diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..00ec607 --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local +.eslintcache + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/README.md b/README.md index 1ff100f..9fcbf83 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,49 @@ # Instructions -## CDN +This project walks through the features of TailwindCSS through branches that incrementally build on top of each other. Pull this repo down locally and checkout each branch one-by-one. I.e.: `git checkout step/1-***`, `git checkout step/2-***`, `git checkout step/3-***`, and so on. -## CLI +Eventually you will run NPM to build you bundle and run the project. So the latest Node and NPM are required. -- `npx tailwindcss-cli build styles/app.css -o build/app.css` +## Step 1 Hello World -- TailwindCSS via CDN -### Notes +The simplest way to get going with Tailwind is through the CDN. However, this is not for production use mostly because of the large file size. Though, it works for out demo. -- You may have an issue with node on your first try. Make sure you version of Node is greater than 11. +First, create an HTML page with a boilerplate HTML5 structure. Then add the following: +`` -## Build tool +You can start playing around with the styles, but you won't get far without referring to the [documentation](https://tailwindcss.com/docs). If you are using Visual Studio Code, there is an easier way. Install the [TailwindCSS intellisense tool](https://tailwindcss.com/docs/intellisense) for autocomplete, syntax highlighting, and linting. -### Notes -- Favor PostCSS -- you can use SASS, but native CSS is powerful enough on its own. -- Install `tailwindcss` `postcss` `autoprefixer` -- Setup tailwind with `npx tailwindcss init -p` +## Step 2 TailwindCSS PostCSS plugin in your build process + +TailwindCSS will drop in easily to most modern project stacks. If you're using [Laravel](https://tailwindcss.com/docs/guides/laravel), React, Vue, or [Ruby on Rails](https://github.com/rails/tailwindcss-rails) you can find step-by-step [installation guides](https://tailwindcss.com/docs/installation). Using Tailwind with PostCSS and a preprocessor like SASS is possible, but not strongly recommended. + +Start by installing the dependencies: + +`npm install -D tailwindcss@latest postcss@latest autoprefixer@latest` + +Add a configuration file for PostCSS: +```js +// postcss.config.js +module.exports = { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + } +} +``` + +Along with the `tailwindcss@latest` package you installed there is also a CLI tool. We can use that to generate a Tailwind config file now: + +`npx tailwindcss init -p` + +Next, you'll need to include Tailwind in a CSS file: + +```css +/* ./your-css-folder/styles.css */ +@tailwind base; +@tailwind components; +@tailwind utilities; +``` + +Now build your styles: +`npx tailwindcss-cli build styles/app.css -o build/app.css` diff --git a/index.html b/index.html index e821f5a..4d1d9d6 100644 --- a/index.html +++ b/index.html @@ -1,20 +1,20 @@ - - - - - - + + + + + + - Document - + Document + - -
- Logo Ipsum -
- + +
+ Logo Ipsum +
+ diff --git a/node_modules/.bin/esbuild b/node_modules/.bin/esbuild deleted file mode 120000 index c83ac07..0000000 --- a/node_modules/.bin/esbuild +++ /dev/null @@ -1 +0,0 @@ -../esbuild/bin/esbuild \ No newline at end of file diff --git a/node_modules/.bin/rollup b/node_modules/.bin/rollup deleted file mode 120000 index 5939621..0000000 --- a/node_modules/.bin/rollup +++ /dev/null @@ -1 +0,0 @@ -../rollup/dist/bin/rollup \ No newline at end of file diff --git a/node_modules/.bin/vite b/node_modules/.bin/vite deleted file mode 120000 index 6d1e3be..0000000 --- a/node_modules/.bin/vite +++ /dev/null @@ -1 +0,0 @@ -../vite/bin/vite.js \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 800dbda..e048229 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -398,16 +398,6 @@ "integrity": "sha512-LolItk2/ikSGQ7SN8UkuKVNMBZp3RG7Itgaxj1npsHRzQobj9JjMneZOZfLhtwlYBe5fCJ75k+cVCiDFUs23oA==", "dev": true }, - "node_modules/esbuild": { - "version": "0.9.7", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.9.7.tgz", - "integrity": "sha512-VtUf6aQ89VTmMLKrWHYG50uByMF4JQlVysb8dmg6cOgW8JnFCipmz7p+HNBl+RR3LLCuBxFGVauAe2wfnF9bLg==", - "dev": true, - "hasInstallScript": true, - "bin": { - "esbuild": "bin/esbuild" - } - }, "node_modules/escalade": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", @@ -1209,21 +1199,6 @@ "node": ">=0.10.0" } }, - "node_modules/rollup": { - "version": "2.44.0", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.44.0.tgz", - "integrity": "sha512-rGSF4pLwvuaH/x4nAS+zP6UNn5YUDWf/TeEU5IoXSZKBbKRNTCI3qMnYXKZgrC0D2KzS2baiOZt1OlqhMu5rnQ==", - "dev": true, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=10.0.0" - }, - "optionalDependencies": { - "fsevents": "~2.3.1" - } - }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -1356,27 +1331,6 @@ "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", "dev": true }, - "node_modules/vite": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-2.1.5.tgz", - "integrity": "sha512-tYU5iaYeUgQYvK/CNNz3tiJ8vYqPWfCE9IQ7K0iuzYovWw7lzty7KRYGWwV3CQPh0NKxWjOczAqiJsCL0Xb+Og==", - "dev": true, - "dependencies": { - "esbuild": "^0.9.3", - "postcss": "^8.2.1", - "resolve": "^1.19.0", - "rollup": "^2.38.5" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": ">=12.0.0" - }, - "optionalDependencies": { - "fsevents": "~2.3.1" - } - }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", diff --git a/node_modules/.vite/_metadata.json b/node_modules/.vite/_metadata.json deleted file mode 100644 index b154efd..0000000 --- a/node_modules/.vite/_metadata.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "hash": "2b4d25fc", - "browserHash": "3806fe38", - "optimized": {} -} \ No newline at end of file diff --git a/node_modules/esbuild/README.md b/node_modules/esbuild/README.md deleted file mode 100644 index 93863d1..0000000 --- a/node_modules/esbuild/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# esbuild - -This is a JavaScript bundler and minifier. See https://github.com/evanw/esbuild and the [JavaScript API documentation](https://esbuild.github.io/api/) for details. diff --git a/node_modules/esbuild/bin/esbuild b/node_modules/esbuild/bin/esbuild deleted file mode 100755 index 110742c..0000000 Binary files a/node_modules/esbuild/bin/esbuild and /dev/null differ diff --git a/node_modules/esbuild/install.js b/node_modules/esbuild/install.js deleted file mode 100644 index 6876bea..0000000 --- a/node_modules/esbuild/install.js +++ /dev/null @@ -1,252 +0,0 @@ -var __defProp = Object.defineProperty; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __getOwnPropSymbols = Object.getOwnPropertySymbols; -var __propIsEnum = Object.prototype.propertyIsEnumerable; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {enumerable: true, configurable: true, writable: true, value}) : obj[key] = value; -var __assign = (a, b) => { - for (var prop in b || (b = {})) - if (__hasOwnProp.call(b, prop)) - __defNormalProp(a, prop, b[prop]); - if (__getOwnPropSymbols) - for (var prop of __getOwnPropSymbols(b)) { - if (__propIsEnum.call(b, prop)) - __defNormalProp(a, prop, b[prop]); - } - return a; -}; -const fs = require("fs"); -const os = require("os"); -const path = require("path"); -const zlib = require("zlib"); -const https = require("https"); -const child_process = require("child_process"); -const version = "0.9.7"; -const binPath = path.join(__dirname, "bin", "esbuild"); -async function installBinaryFromPackage(name, fromPath, toPath) { - const cachePath = getCachePath(name); - try { - fs.copyFileSync(cachePath, toPath); - fs.chmodSync(toPath, 493); - validateBinaryVersion(toPath); - const now = new Date(); - fs.utimesSync(cachePath, now, now); - return; - } catch (e) { - } - let buffer; - let didFail = false; - try { - buffer = installUsingNPM(name, fromPath); - } catch (err) { - didFail = true; - console.error(`Trying to install "${name}" using npm`); - console.error(`Failed to install "${name}" using npm: ${err && err.message || err}`); - } - if (!buffer) { - const url = `https://registry.npmjs.org/${name}/-/${name}-${version}.tgz`; - console.error(`Trying to download ${JSON.stringify(url)}`); - try { - buffer = extractFileFromTarGzip(await fetch(url), fromPath); - } catch (err) { - console.error(`Failed to download ${JSON.stringify(url)}: ${err && err.message || err}`); - } - } - if (!buffer) { - console.error(`Install unsuccessful`); - process.exit(1); - } - fs.writeFileSync(toPath, buffer, {mode: 493}); - try { - validateBinaryVersion(toPath); - } catch (err) { - console.error(`The version of the downloaded binary is incorrect: ${err && err.message || err}`); - console.error(`Install unsuccessful`); - process.exit(1); - } - try { - fs.mkdirSync(path.dirname(cachePath), { - recursive: true, - mode: 448 - }); - fs.copyFileSync(toPath, cachePath); - cleanCacheLRU(cachePath); - } catch (e) { - } - if (didFail) - console.error(`Install successful`); -} -function validateBinaryVersion(binaryPath) { - const stdout = child_process.execFileSync(binaryPath, ["--version"]).toString().trim(); - if (stdout !== version) { - throw new Error(`Expected ${JSON.stringify(version)} but got ${JSON.stringify(stdout)}`); - } -} -function getCachePath(name) { - const home = os.homedir(); - const common = ["esbuild", "bin", `${name}@${version}`]; - if (process.platform === "darwin") - return path.join(home, "Library", "Caches", ...common); - if (process.platform === "win32") - return path.join(home, "AppData", "Local", "Cache", ...common); - const XDG_CACHE_HOME = process.env.XDG_CACHE_HOME; - if (process.platform === "linux" && XDG_CACHE_HOME && path.isAbsolute(XDG_CACHE_HOME)) - return path.join(XDG_CACHE_HOME, ...common); - return path.join(home, ".cache", ...common); -} -function cleanCacheLRU(fileToKeep) { - const dir = path.dirname(fileToKeep); - const entries = []; - for (const entry of fs.readdirSync(dir)) { - const entryPath = path.join(dir, entry); - try { - const stats = fs.statSync(entryPath); - entries.push({path: entryPath, mtime: stats.mtime}); - } catch (e) { - } - } - entries.sort((a, b) => +b.mtime - +a.mtime); - for (const entry of entries.slice(5)) { - try { - fs.unlinkSync(entry.path); - } catch (e) { - } - } -} -function fetch(url) { - return new Promise((resolve, reject) => { - https.get(url, (res) => { - if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location) - return fetch(res.headers.location).then(resolve, reject); - if (res.statusCode !== 200) - return reject(new Error(`Server responded with ${res.statusCode}`)); - let chunks = []; - res.on("data", (chunk) => chunks.push(chunk)); - res.on("end", () => resolve(Buffer.concat(chunks))); - }).on("error", reject); - }); -} -function extractFileFromTarGzip(buffer, file) { - try { - buffer = zlib.unzipSync(buffer); - } catch (err) { - throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`); - } - let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, ""); - let offset = 0; - file = `package/${file}`; - while (offset < buffer.length) { - let name = str(offset, 100); - let size = parseInt(str(offset + 124, 12), 8); - offset += 512; - if (!isNaN(size)) { - if (name === file) - return buffer.subarray(offset, offset + size); - offset += size + 511 & ~511; - } - } - throw new Error(`Could not find ${JSON.stringify(file)} in archive`); -} -function installUsingNPM(name, file) { - const installDir = path.join(os.tmpdir(), "esbuild-" + Math.random().toString(36).slice(2)); - fs.mkdirSync(installDir, {recursive: true}); - fs.writeFileSync(path.join(installDir, "package.json"), "{}"); - const env = __assign(__assign({}, process.env), {npm_config_global: void 0}); - child_process.execSync(`npm install --loglevel=error --prefer-offline --no-audit --progress=false ${name}@${version}`, {cwd: installDir, stdio: "pipe", env}); - const buffer = fs.readFileSync(path.join(installDir, "node_modules", name, file)); - try { - removeRecursive(installDir); - } catch (e) { - } - return buffer; -} -function removeRecursive(dir) { - for (const entry of fs.readdirSync(dir)) { - const entryPath = path.join(dir, entry); - let stats; - try { - stats = fs.lstatSync(entryPath); - } catch (e) { - continue; - } - if (stats.isDirectory()) - removeRecursive(entryPath); - else - fs.unlinkSync(entryPath); - } - fs.rmdirSync(dir); -} -function isYarnBerryOrNewer() { - const {npm_config_user_agent} = process.env; - if (npm_config_user_agent) { - const match = npm_config_user_agent.match(/yarn\/(\d+)/); - if (match && match[1]) { - return parseInt(match[1], 10) >= 2; - } - } - return false; -} -function installDirectly(name) { - if (process.env.ESBUILD_BINARY_PATH) { - fs.copyFileSync(process.env.ESBUILD_BINARY_PATH, binPath); - validateBinaryVersion(binPath); - } else { - const tempBinPath = binPath + "__"; - installBinaryFromPackage(name, "bin/esbuild", tempBinPath).then(() => fs.renameSync(tempBinPath, binPath)).catch((e) => setImmediate(() => { - throw e; - })); - } -} -function installWithWrapper(name, fromPath, toPath) { - fs.writeFileSync(binPath, `#!/usr/bin/env node -const path = require('path'); -const esbuild_exe = path.join(__dirname, '..', ${JSON.stringify(toPath)}); -const child_process = require('child_process'); -const { status } = child_process.spawnSync(esbuild_exe, process.argv.slice(2), { stdio: 'inherit' }); -process.exitCode = status === null ? 1 : status; -`); - const absToPath = path.join(__dirname, toPath); - if (process.env.ESBUILD_BINARY_PATH) { - fs.copyFileSync(process.env.ESBUILD_BINARY_PATH, absToPath); - validateBinaryVersion(absToPath); - } else { - installBinaryFromPackage(name, fromPath, absToPath).catch((e) => setImmediate(() => { - throw e; - })); - } -} -function installOnUnix(name) { - if (isYarnBerryOrNewer()) { - installWithWrapper(name, "bin/esbuild", "esbuild"); - } else { - installDirectly(name); - } -} -function installOnWindows(name) { - installWithWrapper(name, "esbuild.exe", "esbuild.exe"); -} -const platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; -const knownWindowsPackages = { - "win32 ia32 LE": "esbuild-windows-32", - "win32 x64 LE": "esbuild-windows-64" -}; -const knownUnixlikePackages = { - "android arm64 LE": "esbuild-android-arm64", - "darwin arm64 LE": "esbuild-darwin-arm64", - "darwin x64 LE": "esbuild-darwin-64", - "freebsd arm64 LE": "esbuild-freebsd-arm64", - "freebsd x64 LE": "esbuild-freebsd-64", - "linux arm LE": "esbuild-linux-arm", - "linux arm64 LE": "esbuild-linux-arm64", - "linux ia32 LE": "esbuild-linux-32", - "linux mips64el LE": "esbuild-linux-mips64le", - "linux ppc64 LE": "esbuild-linux-ppc64le", - "linux x64 LE": "esbuild-linux-64" -}; -if (platformKey in knownWindowsPackages) { - installOnWindows(knownWindowsPackages[platformKey]); -} else if (platformKey in knownUnixlikePackages) { - installOnUnix(knownUnixlikePackages[platformKey]); -} else { - console.error(`Unsupported platform: ${platformKey}`); - process.exit(1); -} diff --git a/node_modules/esbuild/lib/main.d.ts b/node_modules/esbuild/lib/main.d.ts deleted file mode 100644 index 3601996..0000000 --- a/node_modules/esbuild/lib/main.d.ts +++ /dev/null @@ -1,352 +0,0 @@ -export type Platform = 'browser' | 'node' | 'neutral'; -export type Format = 'iife' | 'cjs' | 'esm'; -export type Loader = 'js' | 'jsx' | 'ts' | 'tsx' | 'css' | 'json' | 'text' | 'base64' | 'file' | 'dataurl' | 'binary' | 'default'; -export type LogLevel = 'info' | 'warning' | 'error' | 'silent'; -export type Charset = 'ascii' | 'utf8'; -export type TreeShaking = true | 'ignore-annotations'; - -interface CommonOptions { - sourcemap?: boolean | 'inline' | 'external' | 'both'; - sourcesContent?: boolean; - - format?: Format; - globalName?: string; - target?: string | string[]; - - minify?: boolean; - minifyWhitespace?: boolean; - minifyIdentifiers?: boolean; - minifySyntax?: boolean; - charset?: Charset; - treeShaking?: TreeShaking; - - jsxFactory?: string; - jsxFragment?: string; - define?: { [key: string]: string }; - pure?: string[]; - keepNames?: boolean; - - color?: boolean; - logLevel?: LogLevel; - logLimit?: number; -} - -export interface BuildOptions extends CommonOptions { - bundle?: boolean; - splitting?: boolean; - preserveSymlinks?: boolean; - outfile?: string; - metafile?: boolean; - outdir?: string; - outbase?: string; - platform?: Platform; - external?: string[]; - loader?: { [ext: string]: Loader }; - resolveExtensions?: string[]; - mainFields?: string[]; - conditions?: string[]; - write?: boolean; - tsconfig?: string; - outExtension?: { [ext: string]: string }; - publicPath?: string; - entryNames?: string; - chunkNames?: string; - assetNames?: string; - inject?: string[]; - banner?: { [type: string]: string }; - footer?: { [type: string]: string }; - incremental?: boolean; - entryPoints?: string[]; - stdin?: StdinOptions; - plugins?: Plugin[]; - absWorkingDir?: string; - nodePaths?: string[]; // The "NODE_PATH" variable from Node.js - watch?: boolean | WatchMode; -} - -export interface WatchMode { - onRebuild?: (error: BuildFailure | null, result: BuildResult | null) => void; -} - -export interface StdinOptions { - contents: string; - resolveDir?: string; - sourcefile?: string; - loader?: Loader; -} - -export interface Message { - text: string; - location: Location | null; - notes: Note[]; - - // Optional user-specified data that is passed through unmodified. You can - // use this to stash the original error, for example. - detail: any; -} - -export interface Note { - text: string; - location: Location | null; -} - -export interface Location { - file: string; - namespace: string; - line: number; // 1-based - column: number; // 0-based, in bytes - length: number; // in bytes - lineText: string; -} - -export interface OutputFile { - path: string; - contents: Uint8Array; // "text" as bytes - text: string; // "contents" as text -} - -export interface BuildInvalidate { - (): Promise; - dispose(): void; -} - -export interface BuildIncremental extends BuildResult { - rebuild: BuildInvalidate; -} - -export interface BuildResult { - warnings: Message[]; - outputFiles?: OutputFile[]; // Only when "write: false" - rebuild?: BuildInvalidate; // Only when "incremental: true" - stop?: () => void; // Only when "watch: true" - metafile?: Metafile; // Only when "metafile: true" -} - -export interface BuildFailure extends Error { - errors: Message[]; - warnings: Message[]; -} - -export interface ServeOptions { - port?: number; - host?: string; - servedir?: string; - onRequest?: (args: ServeOnRequestArgs) => void; -} - -export interface ServeOnRequestArgs { - remoteAddress: string; - method: string; - path: string; - status: number; - timeInMS: number; // The time to generate the response, not to send it -} - -export interface ServeResult { - port: number; - host: string; - wait: Promise; - stop: () => void; -} - -export interface TransformOptions extends CommonOptions { - tsconfigRaw?: string | { - compilerOptions?: { - jsxFactory?: string, - jsxFragmentFactory?: string, - useDefineForClassFields?: boolean, - importsNotUsedAsValues?: 'remove' | 'preserve' | 'error', - }, - }; - - sourcefile?: string; - loader?: Loader; - banner?: string; - footer?: string; -} - -export interface TransformResult { - code: string; - map: string; - warnings: Message[]; -} - -export interface TransformFailure extends Error { - errors: Message[]; - warnings: Message[]; -} - -export interface Plugin { - name: string; - setup: (build: PluginBuild) => void; -} - -export interface PluginBuild { - initialOptions: BuildOptions; - onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) => - (OnResolveResult | null | undefined | Promise)): void; - onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) => - (OnLoadResult | null | undefined | Promise)): void; -} - -export interface OnResolveOptions { - filter: RegExp; - namespace?: string; -} - -export interface OnResolveArgs { - path: string; - importer: string; - namespace: string; - resolveDir: string; - kind: ImportKind; - pluginData: any; -} - -export type ImportKind = - | 'entry-point' - - // JS - | 'import-statement' - | 'require-call' - | 'dynamic-import' - | 'require-resolve' - - // CSS - | 'import-rule' - | 'url-token' - -export interface OnResolveResult { - pluginName?: string; - - errors?: PartialMessage[]; - warnings?: PartialMessage[]; - - path?: string; - external?: boolean; - namespace?: string; - pluginData?: any; -} - -export interface OnLoadOptions { - filter: RegExp; - namespace?: string; -} - -export interface OnLoadArgs { - path: string; - namespace: string; - pluginData: any; -} - -export interface OnLoadResult { - pluginName?: string; - - errors?: PartialMessage[]; - warnings?: PartialMessage[]; - - contents?: string | Uint8Array; - resolveDir?: string; - loader?: Loader; - pluginData?: any; -} - -export interface PartialMessage { - text?: string; - location?: Partial | null; - notes?: PartialNote[]; - detail?: any; -} - -export interface PartialNote { - text?: string; - location?: Partial | null; -} - -export interface Metafile { - inputs: { - [path: string]: { - bytes: number - imports: { - path: string - kind: ImportKind - }[] - } - } - outputs: { - [path: string]: { - bytes: number - inputs: { - [path: string]: { - bytesInOutput: number - } - } - imports: { - path: string - kind: ImportKind - }[] - exports: string[] - entryPoint?: string - } - } -} - -// This function invokes the "esbuild" command-line tool for you. It returns a -// promise that either resolves with a "BuildResult" object or rejects with a -// "BuildFailure" object. -// -// Works in node: yes -// Works in browser: no -export declare function build(options: BuildOptions & { write: false }): Promise; -export declare function build(options: BuildOptions & { incremental: true }): Promise; -export declare function build(options: BuildOptions): Promise; - -// This function is similar to "build" but it serves the resulting files over -// HTTP on a localhost address with the specified port. -// -// Works in node: yes -// Works in browser: no -export declare function serve(serveOptions: ServeOptions, buildOptions: BuildOptions): Promise; - -// This function transforms a single JavaScript file. It can be used to minify -// JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript -// to older JavaScript. It returns a promise that is either resolved with a -// "TransformResult" object or rejected with a "TransformFailure" object. -// -// Works in node: yes -// Works in browser: no -export declare function transform(input: string, options?: TransformOptions): Promise; - -// A synchronous version of "build". -// -// Works in node: yes -// Works in browser: no -export declare function buildSync(options: BuildOptions & { write: false }): BuildResult & { outputFiles: OutputFile[] }; -export declare function buildSync(options: BuildOptions): BuildResult; - -// A synchronous version of "transform". -// -// Works in node: yes -// Works in browser: no -export declare function transformSync(input: string, options?: TransformOptions): TransformResult; - -// This configures the browser-based version of esbuild. It is necessary to -// call this first and wait for the returned promise to be resolved before -// making other API calls when using esbuild in the browser. -// -// Works in node: yes -// Works in browser: yes ("options" is required) -export declare function initialize(options: InitializeOptions): Promise; - -export interface InitializeOptions { - // The URL of the "esbuild.wasm" file. This must be provided when running - // esbuild in the browser. - wasmURL?: string - - // By default esbuild runs the WebAssembly-based browser API in a web worker - // to avoid blocking the UI thread. This can be disabled by setting "worker" - // to false. - worker?: boolean -} - -export let version: string; diff --git a/node_modules/esbuild/lib/main.js b/node_modules/esbuild/lib/main.js deleted file mode 100644 index e21d245..0000000 --- a/node_modules/esbuild/lib/main.js +++ /dev/null @@ -1,1619 +0,0 @@ -var __defProp = Object.defineProperty; -var __markAsModule = (target) => __defProp(target, "__esModule", {value: true}); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, {get: all[name], enumerable: true}); -}; - -// lib/node.ts -__markAsModule(exports); -__export(exports, { - build: () => build, - buildSync: () => buildSync, - initialize: () => initialize, - serve: () => serve, - transform: () => transform, - transformSync: () => transformSync, - version: () => version -}); - -// lib/stdio_protocol.ts -function encodePacket(packet) { - let visit = (value) => { - if (value === null) { - bb.write8(0); - } else if (typeof value === "boolean") { - bb.write8(1); - bb.write8(+value); - } else if (typeof value === "number") { - bb.write8(2); - bb.write32(value | 0); - } else if (typeof value === "string") { - bb.write8(3); - bb.write(encodeUTF8(value)); - } else if (value instanceof Uint8Array) { - bb.write8(4); - bb.write(value); - } else if (value instanceof Array) { - bb.write8(5); - bb.write32(value.length); - for (let item of value) { - visit(item); - } - } else { - let keys = Object.keys(value); - bb.write8(6); - bb.write32(keys.length); - for (let key of keys) { - bb.write(encodeUTF8(key)); - visit(value[key]); - } - } - }; - let bb = new ByteBuffer(); - bb.write32(0); - bb.write32(packet.id << 1 | +!packet.isRequest); - visit(packet.value); - writeUInt32LE(bb.buf, bb.len - 4, 0); - return bb.buf.subarray(0, bb.len); -} -function decodePacket(bytes) { - let visit = () => { - switch (bb.read8()) { - case 0: - return null; - case 1: - return !!bb.read8(); - case 2: - return bb.read32(); - case 3: - return decodeUTF8(bb.read()); - case 4: - return bb.read(); - case 5: { - let count = bb.read32(); - let value2 = []; - for (let i = 0; i < count; i++) { - value2.push(visit()); - } - return value2; - } - case 6: { - let count = bb.read32(); - let value2 = {}; - for (let i = 0; i < count; i++) { - value2[decodeUTF8(bb.read())] = visit(); - } - return value2; - } - default: - throw new Error("Invalid packet"); - } - }; - let bb = new ByteBuffer(bytes); - let id = bb.read32(); - let isRequest = (id & 1) === 0; - id >>>= 1; - let value = visit(); - if (bb.ptr !== bytes.length) { - throw new Error("Invalid packet"); - } - return {id, isRequest, value}; -} -var ByteBuffer = class { - constructor(buf = new Uint8Array(1024)) { - this.buf = buf; - this.len = 0; - this.ptr = 0; - } - _write(delta) { - if (this.len + delta > this.buf.length) { - let clone = new Uint8Array((this.len + delta) * 2); - clone.set(this.buf); - this.buf = clone; - } - this.len += delta; - return this.len - delta; - } - write8(value) { - let offset = this._write(1); - this.buf[offset] = value; - } - write32(value) { - let offset = this._write(4); - writeUInt32LE(this.buf, value, offset); - } - write(bytes) { - let offset = this._write(4 + bytes.length); - writeUInt32LE(this.buf, bytes.length, offset); - this.buf.set(bytes, offset + 4); - } - _read(delta) { - if (this.ptr + delta > this.buf.length) { - throw new Error("Invalid packet"); - } - this.ptr += delta; - return this.ptr - delta; - } - read8() { - return this.buf[this._read(1)]; - } - read32() { - return readUInt32LE(this.buf, this._read(4)); - } - read() { - let length = this.read32(); - let bytes = new Uint8Array(length); - let ptr = this._read(bytes.length); - bytes.set(this.buf.subarray(ptr, ptr + length)); - return bytes; - } -}; -var encodeUTF8; -var decodeUTF8; -if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") { - let encoder = new TextEncoder(); - let decoder = new TextDecoder(); - encodeUTF8 = (text) => encoder.encode(text); - decodeUTF8 = (bytes) => decoder.decode(bytes); -} else if (typeof Buffer !== "undefined") { - encodeUTF8 = (text) => { - let buffer = Buffer.from(text); - if (!(buffer instanceof Uint8Array)) { - buffer = new Uint8Array(buffer); - } - return buffer; - }; - decodeUTF8 = (bytes) => Buffer.from(bytes).toString(); -} else { - throw new Error("No UTF-8 codec found"); -} -function readUInt32LE(buffer, offset) { - return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24; -} -function writeUInt32LE(buffer, value, offset) { - buffer[offset++] = value; - buffer[offset++] = value >> 8; - buffer[offset++] = value >> 16; - buffer[offset++] = value >> 24; -} - -// lib/common.ts -function validateTarget(target) { - target += ""; - if (target.indexOf(",") >= 0) - throw new Error(`Invalid target: ${target}`); - return target; -} -var canBeAnything = () => null; -var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean"; -var mustBeBooleanOrObject = (value) => typeof value === "boolean" || typeof value === "object" && !Array.isArray(value) ? null : "a boolean or an object"; -var mustBeString = (value) => typeof value === "string" ? null : "a string"; -var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object"; -var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer"; -var mustBeFunction = (value) => typeof value === "function" ? null : "a function"; -var mustBeArray = (value) => Array.isArray(value) ? null : "an array"; -var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object"; -var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null"; -var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean"; -var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object"; -var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array"; -var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array"; -function getFlag(object, keys, key, mustBeFn) { - let value = object[key]; - keys[key + ""] = true; - if (value === void 0) - return void 0; - let mustBe = mustBeFn(value); - if (mustBe !== null) - throw new Error(`"${key}" must be ${mustBe}`); - return value; -} -function checkForInvalidFlags(object, keys, where) { - for (let key in object) { - if (!(key in keys)) { - throw new Error(`Invalid option ${where}: "${key}"`); - } - } -} -function validateInitializeOptions(options) { - let keys = Object.create(null); - let wasmURL = getFlag(options, keys, "wasmURL", mustBeString); - let worker = getFlag(options, keys, "worker", mustBeBoolean); - checkForInvalidFlags(options, keys, "in startService() call"); - return { - wasmURL, - worker - }; -} -function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) { - let color = getFlag(options, keys, "color", mustBeBoolean); - let logLevel = getFlag(options, keys, "logLevel", mustBeString); - let logLimit = getFlag(options, keys, "logLimit", mustBeInteger); - if (color) - flags.push(`--color=${color}`); - else if (isTTY2) - flags.push(`--color=true`); - flags.push(`--log-level=${logLevel || logLevelDefault}`); - flags.push(`--log-limit=${logLimit || 0}`); -} -function pushCommonFlags(flags, options, keys) { - let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean); - let target = getFlag(options, keys, "target", mustBeStringOrArray); - let format = getFlag(options, keys, "format", mustBeString); - let globalName = getFlag(options, keys, "globalName", mustBeString); - let minify = getFlag(options, keys, "minify", mustBeBoolean); - let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean); - let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean); - let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean); - let charset = getFlag(options, keys, "charset", mustBeString); - let treeShaking = getFlag(options, keys, "treeShaking", mustBeStringOrBoolean); - let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString); - let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString); - let define = getFlag(options, keys, "define", mustBeObject); - let pure = getFlag(options, keys, "pure", mustBeArray); - let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean); - if (sourcesContent !== void 0) - flags.push(`--sources-content=${sourcesContent}`); - if (target) { - if (Array.isArray(target)) - flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`); - else - flags.push(`--target=${validateTarget(target)}`); - } - if (format) - flags.push(`--format=${format}`); - if (globalName) - flags.push(`--global-name=${globalName}`); - if (minify) - flags.push("--minify"); - if (minifySyntax) - flags.push("--minify-syntax"); - if (minifyWhitespace) - flags.push("--minify-whitespace"); - if (minifyIdentifiers) - flags.push("--minify-identifiers"); - if (charset) - flags.push(`--charset=${charset}`); - if (treeShaking !== void 0 && treeShaking !== true) - flags.push(`--tree-shaking=${treeShaking}`); - if (jsxFactory) - flags.push(`--jsx-factory=${jsxFactory}`); - if (jsxFragment) - flags.push(`--jsx-fragment=${jsxFragment}`); - if (define) { - for (let key in define) { - if (key.indexOf("=") >= 0) - throw new Error(`Invalid define: ${key}`); - flags.push(`--define:${key}=${define[key]}`); - } - } - if (pure) - for (let fn of pure) - flags.push(`--pure:${fn}`); - if (keepNames) - flags.push(`--keep-names`); -} -function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) { - var _a; - let flags = []; - let keys = Object.create(null); - let stdinContents = null; - let stdinResolveDir = null; - let watchMode = null; - pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); - pushCommonFlags(flags, options, keys); - let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); - let bundle = getFlag(options, keys, "bundle", mustBeBoolean); - let watch = getFlag(options, keys, "watch", mustBeBooleanOrObject); - let splitting = getFlag(options, keys, "splitting", mustBeBoolean); - let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean); - let metafile = getFlag(options, keys, "metafile", mustBeBoolean); - let outfile = getFlag(options, keys, "outfile", mustBeString); - let outdir = getFlag(options, keys, "outdir", mustBeString); - let outbase = getFlag(options, keys, "outbase", mustBeString); - let platform = getFlag(options, keys, "platform", mustBeString); - let tsconfig = getFlag(options, keys, "tsconfig", mustBeString); - let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray); - let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray); - let mainFields = getFlag(options, keys, "mainFields", mustBeArray); - let conditions = getFlag(options, keys, "conditions", mustBeArray); - let external = getFlag(options, keys, "external", mustBeArray); - let loader = getFlag(options, keys, "loader", mustBeObject); - let outExtension = getFlag(options, keys, "outExtension", mustBeObject); - let publicPath = getFlag(options, keys, "publicPath", mustBeString); - let entryNames = getFlag(options, keys, "entryNames", mustBeString); - let chunkNames = getFlag(options, keys, "chunkNames", mustBeString); - let assetNames = getFlag(options, keys, "assetNames", mustBeString); - let inject = getFlag(options, keys, "inject", mustBeArray); - let banner = getFlag(options, keys, "banner", mustBeObject); - let footer = getFlag(options, keys, "footer", mustBeObject); - let entryPoints = getFlag(options, keys, "entryPoints", mustBeArray); - let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString); - let stdin = getFlag(options, keys, "stdin", mustBeObject); - let write = (_a = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a : writeDefault; - let incremental = getFlag(options, keys, "incremental", mustBeBoolean) === true; - keys.plugins = true; - checkForInvalidFlags(options, keys, `in ${callName}() call`); - if (sourcemap) - flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`); - if (bundle) - flags.push("--bundle"); - if (watch) { - flags.push("--watch"); - if (typeof watch === "boolean") { - watchMode = {}; - } else { - let watchKeys = Object.create(null); - let onRebuild = getFlag(watch, watchKeys, "onRebuild", mustBeFunction); - checkForInvalidFlags(watch, watchKeys, `on "watch" in ${callName}() call`); - watchMode = {onRebuild}; - } - } - if (splitting) - flags.push("--splitting"); - if (preserveSymlinks) - flags.push("--preserve-symlinks"); - if (metafile) - flags.push(`--metafile`); - if (outfile) - flags.push(`--outfile=${outfile}`); - if (outdir) - flags.push(`--outdir=${outdir}`); - if (outbase) - flags.push(`--outbase=${outbase}`); - if (platform) - flags.push(`--platform=${platform}`); - if (tsconfig) - flags.push(`--tsconfig=${tsconfig}`); - if (resolveExtensions) { - let values = []; - for (let value of resolveExtensions) { - value += ""; - if (value.indexOf(",") >= 0) - throw new Error(`Invalid resolve extension: ${value}`); - values.push(value); - } - flags.push(`--resolve-extensions=${values.join(",")}`); - } - if (publicPath) - flags.push(`--public-path=${publicPath}`); - if (entryNames) - flags.push(`--entry-names=${entryNames}`); - if (chunkNames) - flags.push(`--chunk-names=${chunkNames}`); - if (assetNames) - flags.push(`--asset-names=${assetNames}`); - if (mainFields) { - let values = []; - for (let value of mainFields) { - value += ""; - if (value.indexOf(",") >= 0) - throw new Error(`Invalid main field: ${value}`); - values.push(value); - } - flags.push(`--main-fields=${values.join(",")}`); - } - if (conditions) { - let values = []; - for (let value of conditions) { - value += ""; - if (value.indexOf(",") >= 0) - throw new Error(`Invalid condition: ${value}`); - values.push(value); - } - flags.push(`--conditions=${values.join(",")}`); - } - if (external) - for (let name of external) - flags.push(`--external:${name}`); - if (banner) { - for (let type in banner) { - if (type.indexOf("=") >= 0) - throw new Error(`Invalid banner file type: ${type}`); - flags.push(`--banner:${type}=${banner[type]}`); - } - } - if (footer) { - for (let type in footer) { - if (type.indexOf("=") >= 0) - throw new Error(`Invalid footer file type: ${type}`); - flags.push(`--footer:${type}=${footer[type]}`); - } - } - if (inject) - for (let path2 of inject) - flags.push(`--inject:${path2}`); - if (loader) { - for (let ext in loader) { - if (ext.indexOf("=") >= 0) - throw new Error(`Invalid loader extension: ${ext}`); - flags.push(`--loader:${ext}=${loader[ext]}`); - } - } - if (outExtension) { - for (let ext in outExtension) { - if (ext.indexOf("=") >= 0) - throw new Error(`Invalid out extension: ${ext}`); - flags.push(`--out-extension:${ext}=${outExtension[ext]}`); - } - } - if (entryPoints) { - for (let entryPoint of entryPoints) { - entryPoint += ""; - if (entryPoint.startsWith("-")) - throw new Error(`Invalid entry point: ${entryPoint}`); - flags.push(entryPoint); - } - } - if (stdin) { - let stdinKeys = Object.create(null); - let contents = getFlag(stdin, stdinKeys, "contents", mustBeString); - let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString); - let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString); - let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString); - checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object'); - if (sourcefile) - flags.push(`--sourcefile=${sourcefile}`); - if (loader2) - flags.push(`--loader=${loader2}`); - if (resolveDir) - stdinResolveDir = resolveDir + ""; - stdinContents = contents ? contents + "" : ""; - } - let nodePaths = []; - if (nodePathsInput) { - for (let value of nodePathsInput) { - value += ""; - nodePaths.push(value); - } - } - return { - flags, - write, - stdinContents, - stdinResolveDir, - absWorkingDir, - incremental, - nodePaths, - watch: watchMode - }; -} -function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) { - let flags = []; - let keys = Object.create(null); - pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); - pushCommonFlags(flags, options, keys); - let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); - let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject); - let sourcefile = getFlag(options, keys, "sourcefile", mustBeString); - let loader = getFlag(options, keys, "loader", mustBeString); - let banner = getFlag(options, keys, "banner", mustBeString); - let footer = getFlag(options, keys, "footer", mustBeString); - checkForInvalidFlags(options, keys, `in ${callName}() call`); - if (sourcemap) - flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`); - if (tsconfigRaw) - flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`); - if (sourcefile) - flags.push(`--sourcefile=${sourcefile}`); - if (loader) - flags.push(`--loader=${loader}`); - if (banner) - flags.push(`--banner=${banner}`); - if (footer) - flags.push(`--footer=${footer}`); - return flags; -} -function createChannel(streamIn) { - let responseCallbacks = new Map(); - let pluginCallbacks = new Map(); - let watchCallbacks = new Map(); - let serveCallbacks = new Map(); - let nextServeID = 0; - let isClosed = false; - let nextRequestID = 0; - let nextBuildKey = 0; - let stdout = new Uint8Array(16 * 1024); - let stdoutUsed = 0; - let readFromStdout = (chunk) => { - let limit = stdoutUsed + chunk.length; - if (limit > stdout.length) { - let swap = new Uint8Array(limit * 2); - swap.set(stdout); - stdout = swap; - } - stdout.set(chunk, stdoutUsed); - stdoutUsed += chunk.length; - let offset = 0; - while (offset + 4 <= stdoutUsed) { - let length = readUInt32LE(stdout, offset); - if (offset + 4 + length > stdoutUsed) { - break; - } - offset += 4; - handleIncomingPacket(stdout.subarray(offset, offset + length)); - offset += length; - } - if (offset > 0) { - stdout.copyWithin(0, offset, stdoutUsed); - stdoutUsed -= offset; - } - }; - let afterClose = () => { - isClosed = true; - for (let callback of responseCallbacks.values()) { - callback("The service was stopped", null); - } - responseCallbacks.clear(); - for (let callbacks of serveCallbacks.values()) { - callbacks.onWait("The service was stopped"); - } - serveCallbacks.clear(); - for (let callback of watchCallbacks.values()) { - try { - callback(new Error("The service was stopped"), null); - } catch (e) { - console.error(e); - } - } - watchCallbacks.clear(); - }; - let sendRequest = (refs, value, callback) => { - if (isClosed) - return callback("The service is no longer running", null); - let id = nextRequestID++; - responseCallbacks.set(id, (error, response) => { - try { - callback(error, response); - } finally { - if (refs) - refs.unref(); - } - }); - if (refs) - refs.ref(); - streamIn.writeToStdin(encodePacket({id, isRequest: true, value})); - }; - let sendResponse = (id, value) => { - if (isClosed) - throw new Error("The service is no longer running"); - streamIn.writeToStdin(encodePacket({id, isRequest: false, value})); - }; - let handleRequest = async (id, request) => { - try { - switch (request.command) { - case "ping": { - sendResponse(id, {}); - break; - } - case "resolve": { - let callback = pluginCallbacks.get(request.key); - if (!callback) - sendResponse(id, {}); - else - sendResponse(id, await callback(request)); - break; - } - case "load": { - let callback = pluginCallbacks.get(request.key); - if (!callback) - sendResponse(id, {}); - else - sendResponse(id, await callback(request)); - break; - } - case "serve-request": { - let callbacks = serveCallbacks.get(request.serveID); - if (callbacks && callbacks.onRequest) - callbacks.onRequest(request.args); - sendResponse(id, {}); - break; - } - case "serve-wait": { - let callbacks = serveCallbacks.get(request.serveID); - if (callbacks) - callbacks.onWait(request.error); - sendResponse(id, {}); - break; - } - case "watch-rebuild": { - let callback = watchCallbacks.get(request.watchID); - try { - if (callback) - callback(null, request.args); - } catch (err) { - console.error(err); - } - sendResponse(id, {}); - break; - } - default: - throw new Error(`Invalid command: ` + request.command); - } - } catch (e) { - sendResponse(id, {errors: [extractErrorMessageV8(e, streamIn, null, void 0)]}); - } - }; - let isFirstPacket = true; - let handleIncomingPacket = (bytes) => { - if (isFirstPacket) { - isFirstPacket = false; - let binaryVersion = String.fromCharCode(...bytes); - if (binaryVersion !== "0.9.7") { - throw new Error(`Cannot start service: Host version "${"0.9.7"}" does not match binary version ${JSON.stringify(binaryVersion)}`); - } - return; - } - let packet = decodePacket(bytes); - if (packet.isRequest) { - handleRequest(packet.id, packet.value); - } else { - let callback = responseCallbacks.get(packet.id); - responseCallbacks.delete(packet.id); - if (packet.value.error) - callback(packet.value.error, {}); - else - callback(null, packet.value); - } - }; - let handlePlugins = (initialOptions, plugins, buildKey, stash) => { - if (streamIn.isSync) - throw new Error("Cannot use plugins in synchronous API calls"); - let onResolveCallbacks = {}; - let onLoadCallbacks = {}; - let nextCallbackID = 0; - let i = 0; - let requestPlugins = []; - plugins = [...plugins]; - for (let item of plugins) { - let keys = {}; - if (typeof item !== "object") - throw new Error(`Plugin at index ${i} must be an object`); - let name = getFlag(item, keys, "name", mustBeString); - let setup = getFlag(item, keys, "setup", mustBeFunction); - if (typeof name !== "string" || name === "") - throw new Error(`Plugin at index ${i} is missing a name`); - if (typeof setup !== "function") - throw new Error(`[${name}] Plugin is missing a setup function`); - checkForInvalidFlags(item, keys, `on plugin ${JSON.stringify(name)}`); - let plugin = { - name, - onResolve: [], - onLoad: [] - }; - i++; - setup({ - initialOptions, - onResolve(options, callback2) { - let registeredText = `This error came from the "onResolve" callback registered here`; - let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve"); - let keys2 = {}; - let filter = getFlag(options, keys2, "filter", mustBeRegExp); - let namespace = getFlag(options, keys2, "namespace", mustBeString); - checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${JSON.stringify(name)}`); - if (filter == null) - throw new Error(`[${plugin.name}] onResolve() call is missing a filter`); - let id = nextCallbackID++; - onResolveCallbacks[id] = {name, callback: callback2, note: registeredNote}; - plugin.onResolve.push({id, filter: filter.source, namespace: namespace || ""}); - }, - onLoad(options, callback2) { - let registeredText = `This error came from the "onLoad" callback registered here`; - let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad"); - let keys2 = {}; - let filter = getFlag(options, keys2, "filter", mustBeRegExp); - let namespace = getFlag(options, keys2, "namespace", mustBeString); - checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${JSON.stringify(name)}`); - if (filter == null) - throw new Error(`[${plugin.name}] onLoad() call is missing a filter`); - let id = nextCallbackID++; - onLoadCallbacks[id] = {name, callback: callback2, note: registeredNote}; - plugin.onLoad.push({id, filter: filter.source, namespace: namespace || ""}); - } - }); - requestPlugins.push(plugin); - } - const callback = async (request) => { - switch (request.command) { - case "resolve": { - let response = {}, name, callback2, note; - for (let id of request.ids) { - try { - ({name, callback: callback2, note} = onResolveCallbacks[id]); - let result = await callback2({ - path: request.path, - importer: request.importer, - namespace: request.namespace, - resolveDir: request.resolveDir, - kind: request.kind, - pluginData: stash.load(request.pluginData) - }); - if (result != null) { - if (typeof result !== "object") - throw new Error(`Expected onResolve() callback in plugin ${JSON.stringify(name)} to return an object`); - let keys = {}; - let pluginName = getFlag(result, keys, "pluginName", mustBeString); - let path2 = getFlag(result, keys, "path", mustBeString); - let namespace = getFlag(result, keys, "namespace", mustBeString); - let external = getFlag(result, keys, "external", mustBeBoolean); - let pluginData = getFlag(result, keys, "pluginData", canBeAnything); - let errors = getFlag(result, keys, "errors", mustBeArray); - let warnings = getFlag(result, keys, "warnings", mustBeArray); - checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${JSON.stringify(name)}`); - response.id = id; - if (pluginName != null) - response.pluginName = pluginName; - if (path2 != null) - response.path = path2; - if (namespace != null) - response.namespace = namespace; - if (external != null) - response.external = external; - if (pluginData != null) - response.pluginData = stash.store(pluginData); - if (errors != null) - response.errors = sanitizeMessages(errors, "errors", stash); - if (warnings != null) - response.warnings = sanitizeMessages(warnings, "warnings", stash); - break; - } - } catch (e) { - return {id, errors: [extractErrorMessageV8(e, streamIn, stash, note && note())]}; - } - } - return response; - } - case "load": { - let response = {}, name, callback2, note; - for (let id of request.ids) { - try { - ({name, callback: callback2, note} = onLoadCallbacks[id]); - let result = await callback2({ - path: request.path, - namespace: request.namespace, - pluginData: stash.load(request.pluginData) - }); - if (result != null) { - if (typeof result !== "object") - throw new Error(`Expected onLoad() callback in plugin ${JSON.stringify(name)} to return an object`); - let keys = {}; - let pluginName = getFlag(result, keys, "pluginName", mustBeString); - let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array); - let resolveDir = getFlag(result, keys, "resolveDir", mustBeString); - let pluginData = getFlag(result, keys, "pluginData", canBeAnything); - let loader = getFlag(result, keys, "loader", mustBeString); - let errors = getFlag(result, keys, "errors", mustBeArray); - let warnings = getFlag(result, keys, "warnings", mustBeArray); - checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${JSON.stringify(name)}`); - response.id = id; - if (pluginName != null) - response.pluginName = pluginName; - if (contents instanceof Uint8Array) - response.contents = contents; - else if (contents != null) - response.contents = encodeUTF8(contents); - if (resolveDir != null) - response.resolveDir = resolveDir; - if (pluginData != null) - response.pluginData = stash.store(pluginData); - if (loader != null) - response.loader = loader; - if (errors != null) - response.errors = sanitizeMessages(errors, "errors", stash); - if (warnings != null) - response.warnings = sanitizeMessages(warnings, "warnings", stash); - break; - } - } catch (e) { - return {id, errors: [extractErrorMessageV8(e, streamIn, stash, note && note())]}; - } - } - return response; - } - default: - throw new Error(`Invalid command: ` + request.command); - } - }; - let refCount = 0; - return [requestPlugins, { - ref() { - if (++refCount === 1) - pluginCallbacks.set(buildKey, callback); - }, - unref() { - if (--refCount === 0) - pluginCallbacks.delete(buildKey); - } - }]; - }; - let buildServeData = (refs, options, request) => { - let keys = {}; - let port = getFlag(options, keys, "port", mustBeInteger); - let host = getFlag(options, keys, "host", mustBeString); - let servedir = getFlag(options, keys, "servedir", mustBeString); - let onRequest = getFlag(options, keys, "onRequest", mustBeFunction); - let serveID = nextServeID++; - let onWait; - let wait = new Promise((resolve, reject) => { - onWait = (error) => { - serveCallbacks.delete(serveID); - if (error !== null) - reject(new Error(error)); - else - resolve(); - }; - }); - request.serve = {serveID}; - checkForInvalidFlags(options, keys, `in serve() call`); - if (port !== void 0) - request.serve.port = port; - if (host !== void 0) - request.serve.host = host; - if (servedir !== void 0) - request.serve.servedir = servedir; - serveCallbacks.set(serveID, { - onRequest, - onWait - }); - return { - wait, - stop() { - sendRequest(refs, {command: "serve-stop", serveID}, () => { - }); - } - }; - }; - return { - readFromStdout, - afterClose, - service: { - buildOrServe(callName, callerRefs, serveOptions, options, isTTY2, defaultWD2, callback) { - let pluginRefs; - const details = createObjectStash(); - const logLevelDefault = "warning"; - const refs = { - ref() { - if (pluginRefs) - pluginRefs.ref(); - if (callerRefs) - callerRefs.ref(); - }, - unref() { - if (pluginRefs) - pluginRefs.unref(); - if (callerRefs) - callerRefs.unref(); - } - }; - try { - let key = nextBuildKey++; - let writeDefault = !streamIn.isBrowser; - let plugins; - let requestPlugins; - if (typeof options === "object") { - let value = options.plugins; - if (value !== void 0) { - if (!Array.isArray(value)) - throw new Error(`"plugins" must be an array`); - plugins = value; - } - } - if (plugins && plugins.length > 0) { - [requestPlugins, pluginRefs] = handlePlugins(options, plugins, key, details); - } - let { - flags, - write, - stdinContents, - stdinResolveDir, - absWorkingDir, - incremental, - nodePaths, - watch - } = flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault); - let request = { - command: "build", - key, - flags, - write, - stdinContents, - stdinResolveDir, - absWorkingDir: absWorkingDir || defaultWD2, - incremental, - nodePaths, - hasOnRebuild: !!(watch && watch.onRebuild) - }; - if (requestPlugins) - request.plugins = requestPlugins; - let serve2 = serveOptions && buildServeData(refs, serveOptions, request); - let rebuild; - let stop; - let buildResponseToResult = (response, callback2) => { - let errors = replaceDetailsInMessages(response.errors, details); - let warnings = replaceDetailsInMessages(response.warnings, details); - if (errors.length > 0) - return callback2(failureErrorWithLog("Build failed", errors, warnings), null); - let result = {warnings}; - if (response.outputFiles) - result.outputFiles = response.outputFiles.map(convertOutputFiles); - if (response.metafile) - result.metafile = JSON.parse(response.metafile); - if (response.writeToStdout !== void 0) - console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, "")); - if (response.rebuildID !== void 0) { - if (!rebuild) { - let isDisposed = false; - rebuild = () => new Promise((resolve, reject) => { - if (isDisposed || isClosed) - throw new Error("Cannot rebuild"); - sendRequest(refs, {command: "rebuild", rebuildID: response.rebuildID}, (error2, response2) => { - if (error2) - return callback2(new Error(error2), null); - buildResponseToResult(response2, (error3, result3) => { - if (error3) - reject(error3); - else - resolve(result3); - }); - }); - }); - refs.ref(); - rebuild.dispose = () => { - if (isDisposed) - return; - isDisposed = true; - sendRequest(refs, {command: "rebuild-dispose", rebuildID: response.rebuildID}, () => { - }); - refs.unref(); - }; - } - result.rebuild = rebuild; - } - if (response.watchID !== void 0) { - if (!stop) { - let isStopped = false; - refs.ref(); - stop = () => { - if (isStopped) - return; - isStopped = true; - watchCallbacks.delete(response.watchID); - sendRequest(refs, {command: "watch-stop", watchID: response.watchID}, () => { - }); - refs.unref(); - }; - if (watch && watch.onRebuild) { - watchCallbacks.set(response.watchID, (serviceStopError, watchResponse) => { - if (serviceStopError) - return watch.onRebuild(serviceStopError, null); - let errors2 = replaceDetailsInMessages(watchResponse.errors, details); - let warnings2 = replaceDetailsInMessages(watchResponse.warnings, details); - if (errors2.length > 0) - return watch.onRebuild(failureErrorWithLog("Build failed", errors2, warnings2), null); - let result2 = {warnings: warnings2}; - if (watchResponse.outputFiles) - result2.outputFiles = watchResponse.outputFiles.map(convertOutputFiles); - if (watchResponse.rebuildID !== void 0) - result2.rebuild = rebuild; - result2.stop = stop; - watch.onRebuild(null, result2); - }); - } - } - result.stop = stop; - } - return callback2(null, result); - }; - if (write && streamIn.isBrowser) - throw new Error(`Cannot enable "write" in the browser`); - if (incremental && streamIn.isSync) - throw new Error(`Cannot use "incremental" with a synchronous build`); - sendRequest(refs, request, (error, response) => { - if (error) - return callback(new Error(error), null); - if (serve2) { - let serveResponse = response; - let isStopped = false; - refs.ref(); - let result = { - port: serveResponse.port, - host: serveResponse.host, - wait: serve2.wait, - stop() { - if (isStopped) - return; - isStopped = true; - serve2.stop(); - refs.unref(); - } - }; - refs.ref(); - serve2.wait.then(refs.unref, refs.unref); - return callback(null, result); - } - return buildResponseToResult(response, callback); - }); - } catch (e) { - let flags = []; - try { - pushLogFlags(flags, options, {}, isTTY2, logLevelDefault); - } catch (e2) { - } - const error = extractErrorMessageV8(e, streamIn, details, void 0); - sendRequest(refs, {command: "error", flags, error}, () => { - error.detail = details.load(error.detail); - callback(failureErrorWithLog("Build failed", [error], []), null); - }); - } - }, - transform(callName, refs, input, options, isTTY2, fs2, callback) { - const details = createObjectStash(); - const logLevelDefault = "silent"; - let start = (inputPath) => { - try { - if (typeof input !== "string") - throw new Error('The input to "transform" must be a string'); - let flags = flagsForTransformOptions(callName, options, isTTY2, logLevelDefault); - let request = { - command: "transform", - flags, - inputFS: inputPath !== null, - input: inputPath !== null ? inputPath : input - }; - sendRequest(refs, request, (error, response) => { - if (error) - return callback(new Error(error), null); - let errors = replaceDetailsInMessages(response.errors, details); - let warnings = replaceDetailsInMessages(response.warnings, details); - let outstanding = 1; - let next = () => --outstanding === 0 && callback(null, {warnings, code: response.code, map: response.map}); - if (errors.length > 0) - return callback(failureErrorWithLog("Transform failed", errors, warnings), null); - if (response.codeFS) { - outstanding++; - fs2.readFile(response.code, (err, contents) => { - if (err !== null) { - callback(err, null); - } else { - response.code = contents; - next(); - } - }); - } - if (response.mapFS) { - outstanding++; - fs2.readFile(response.map, (err, contents) => { - if (err !== null) { - callback(err, null); - } else { - response.map = contents; - next(); - } - }); - } - next(); - }); - } catch (e) { - let flags = []; - try { - pushLogFlags(flags, options, {}, isTTY2, logLevelDefault); - } catch (e2) { - } - const error = extractErrorMessageV8(e, streamIn, details, void 0); - sendRequest(refs, {command: "error", flags, error}, () => { - error.detail = details.load(error.detail); - callback(failureErrorWithLog("Transform failed", [error], []), null); - }); - } - }; - if (typeof input === "string" && input.length > 1024 * 1024) { - let next = start; - start = () => fs2.writeFile(input, next); - } - start(null); - } - } - }; -} -function createObjectStash() { - const map = new Map(); - let nextID = 0; - return { - load(id) { - return map.get(id); - }, - store(value) { - if (value === void 0) - return -1; - const id = nextID++; - map.set(id, value); - return id; - } - }; -} -function extractCallerV8(e, streamIn, ident) { - let note; - let tried = false; - return () => { - if (tried) - return note; - tried = true; - try { - let lines = (e.stack + "").split("\n"); - lines.splice(1, 1); - let location = parseStackLinesV8(streamIn, lines, ident); - if (location) { - note = {text: e.message, location}; - return note; - } - } catch (e2) { - } - }; -} -function extractErrorMessageV8(e, streamIn, stash, note) { - let text = "Internal error"; - let location = null; - try { - text = (e && e.message || e) + ""; - } catch (e2) { - } - try { - location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), ""); - } catch (e2) { - } - return {text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1}; -} -function parseStackLinesV8(streamIn, lines, ident) { - let at = " at "; - if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) { - for (let i = 1; i < lines.length; i++) { - let line = lines[i]; - if (!line.startsWith(at)) - continue; - line = line.slice(at.length); - while (true) { - let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line); - if (match) { - line = match[1]; - continue; - } - match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line); - if (match) { - line = match[1]; - continue; - } - match = /^(\S+):(\d+):(\d+)$/.exec(line); - if (match) { - let contents; - try { - contents = streamIn.readFileSync(match[1], "utf8"); - } catch (e) { - break; - } - let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || ""; - let column = +match[3] - 1; - let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0; - return { - file: match[1], - namespace: "file", - line: +match[2], - column: encodeUTF8(lineText.slice(0, column)).length, - length: encodeUTF8(lineText.slice(column, column + length)).length, - lineText: lineText + "\n" + lines.slice(1).join("\n") - }; - } - break; - } - } - } - return null; -} -function failureErrorWithLog(text, errors, warnings) { - let limit = 5; - let summary = errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => { - if (i === limit) - return "\n..."; - if (!e.location) - return ` -error: ${e.text}`; - let {file, line, column} = e.location; - return ` -${file}:${line}:${column}: error: ${e.text}`; - }).join(""); - let error = new Error(`${text}${summary}`); - error.errors = errors; - error.warnings = warnings; - return error; -} -function replaceDetailsInMessages(messages, stash) { - for (const message of messages) { - message.detail = stash.load(message.detail); - } - return messages; -} -function sanitizeLocation(location, where) { - if (location == null) - return null; - let keys = {}; - let file = getFlag(location, keys, "file", mustBeString); - let namespace = getFlag(location, keys, "namespace", mustBeString); - let line = getFlag(location, keys, "line", mustBeInteger); - let column = getFlag(location, keys, "column", mustBeInteger); - let length = getFlag(location, keys, "length", mustBeInteger); - let lineText = getFlag(location, keys, "lineText", mustBeString); - checkForInvalidFlags(location, keys, where); - return { - file: file || "", - namespace: namespace || "", - line: line || 0, - column: column || 0, - length: length || 0, - lineText: lineText || "" - }; -} -function sanitizeMessages(messages, property, stash) { - let messagesClone = []; - let index = 0; - for (const message of messages) { - let keys = {}; - let text = getFlag(message, keys, "text", mustBeString); - let location = getFlag(message, keys, "location", mustBeObjectOrNull); - let notes = getFlag(message, keys, "notes", mustBeArray); - let detail = getFlag(message, keys, "detail", canBeAnything); - let where = `in element ${index} of "${property}"`; - checkForInvalidFlags(message, keys, where); - let notesClone = []; - if (notes) { - for (const note of notes) { - let noteKeys = {}; - let noteText = getFlag(note, noteKeys, "text", mustBeString); - let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull); - checkForInvalidFlags(note, noteKeys, where); - notesClone.push({ - text: noteText || "", - location: sanitizeLocation(noteLocation, where) - }); - } - } - messagesClone.push({ - text: text || "", - location: sanitizeLocation(location, where), - notes: notesClone, - detail: stash.store(detail) - }); - index++; - } - return messagesClone; -} -function convertOutputFiles({path: path2, contents}) { - let text = null; - return { - path: path2, - contents, - get text() { - if (text === null) - text = decodeUTF8(contents); - return text; - } - }; -} - -// lib/node.ts -var child_process = require("child_process"); -var crypto = require("crypto"); -var path = require("path"); -var fs = require("fs"); -var os = require("os"); -var tty = require("tty"); -var worker_threads; -if (process.env.ESBUILD_WORKER_THREADS) { - try { - worker_threads = require("worker_threads"); - } catch (e) { - } -} -var esbuildCommandAndArgs = () => { - if (process.env.ESBUILD_BINARY_PATH) { - return [path.resolve(process.env.ESBUILD_BINARY_PATH), []]; - } - if (false) { - return ["node", [path.join(__dirname, "..", "bin", "esbuild")]]; - } - if (process.platform === "win32") { - return [path.join(__dirname, "..", "esbuild.exe"), []]; - } - let pathForYarn2 = path.join(__dirname, "..", "esbuild"); - if (fs.existsSync(pathForYarn2)) { - return [pathForYarn2, []]; - } - return [path.join(__dirname, "..", "bin", "esbuild"), []]; -}; -var isTTY = () => tty.isatty(2); -var version = "0.9.7"; -var build = (options) => ensureServiceIsRunning().build(options); -var serve = (serveOptions, buildOptions) => ensureServiceIsRunning().serve(serveOptions, buildOptions); -var transform = (input, options) => ensureServiceIsRunning().transform(input, options); -var buildSync = (options) => { - if (worker_threads) { - if (!workerThreadService) - workerThreadService = startWorkerThreadService(worker_threads); - return workerThreadService.buildSync(options); - } - let result; - runServiceSync((service) => service.buildOrServe("buildSync", null, null, options, isTTY(), defaultWD, (err, res) => { - if (err) - throw err; - result = res; - })); - return result; -}; -var transformSync = (input, options) => { - if (worker_threads) { - if (!workerThreadService) - workerThreadService = startWorkerThreadService(worker_threads); - return workerThreadService.transformSync(input, options); - } - let result; - runServiceSync((service) => service.transform("transformSync", null, input, options || {}, isTTY(), { - readFile(tempFile, callback) { - try { - let contents = fs.readFileSync(tempFile, "utf8"); - try { - fs.unlinkSync(tempFile); - } catch (e) { - } - callback(null, contents); - } catch (err) { - callback(err, null); - } - }, - writeFile(contents, callback) { - try { - let tempFile = randomFileName(); - fs.writeFileSync(tempFile, contents); - callback(tempFile); - } catch (e) { - callback(null); - } - } - }, (err, res) => { - if (err) - throw err; - result = res; - })); - return result; -}; -var initializeWasCalled = false; -var initialize = (options) => { - options = validateInitializeOptions(options || {}); - if (options.wasmURL) - throw new Error(`The "wasmURL" option only works in the browser`); - if (options.worker) - throw new Error(`The "worker" option only works in the browser`); - if (initializeWasCalled) - throw new Error('Cannot call "initialize" more than once'); - ensureServiceIsRunning(); - initializeWasCalled = true; - return Promise.resolve(); -}; -var defaultWD = process.cwd(); -var longLivedService; -var ensureServiceIsRunning = () => { - if (longLivedService) - return longLivedService; - let [command, args] = esbuildCommandAndArgs(); - let child = child_process.spawn(command, args.concat(`--service=${"0.9.7"}`, "--ping"), { - windowsHide: true, - stdio: ["pipe", "pipe", "inherit"], - cwd: defaultWD - }); - let {readFromStdout, afterClose, service} = createChannel({ - writeToStdin(bytes) { - child.stdin.write(bytes); - }, - readFileSync: fs.readFileSync, - isSync: false, - isBrowser: false - }); - const stdin = child.stdin; - const stdout = child.stdout; - stdout.on("data", readFromStdout); - stdout.on("end", afterClose); - let refCount = 0; - child.unref(); - if (stdin.unref) { - stdin.unref(); - } - if (stdout.unref) { - stdout.unref(); - } - const refs = { - ref() { - if (++refCount === 1) - child.ref(); - }, - unref() { - if (--refCount === 0) - child.unref(); - } - }; - longLivedService = { - build: (options) => { - return new Promise((resolve, reject) => { - service.buildOrServe("build", refs, null, options, isTTY(), defaultWD, (err, res) => { - if (err) { - reject(err); - } else { - resolve(res); - } - }); - }); - }, - serve: (serveOptions, buildOptions) => { - if (serveOptions === null || typeof serveOptions !== "object") - throw new Error("The first argument must be an object"); - return new Promise((resolve, reject) => service.buildOrServe("serve", refs, serveOptions, buildOptions, isTTY(), defaultWD, (err, res) => { - if (err) { - reject(err); - } else { - resolve(res); - } - })); - }, - transform: (input, options) => { - return new Promise((resolve, reject) => service.transform("transform", refs, input, options || {}, isTTY(), { - readFile(tempFile, callback) { - try { - fs.readFile(tempFile, "utf8", (err, contents) => { - try { - fs.unlink(tempFile, () => callback(err, contents)); - } catch (e) { - callback(err, contents); - } - }); - } catch (err) { - callback(err, null); - } - }, - writeFile(contents, callback) { - try { - let tempFile = randomFileName(); - fs.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile)); - } catch (e) { - callback(null); - } - } - }, (err, res) => err ? reject(err) : resolve(res))); - } - }; - return longLivedService; -}; -var runServiceSync = (callback) => { - let [command, args] = esbuildCommandAndArgs(); - let stdin = new Uint8Array(); - let {readFromStdout, afterClose, service} = createChannel({ - writeToStdin(bytes) { - if (stdin.length !== 0) - throw new Error("Must run at most one command"); - stdin = bytes; - }, - isSync: true, - isBrowser: false - }); - callback(service); - let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.9.7"}`), { - cwd: defaultWD, - windowsHide: true, - input: stdin, - maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024 - }); - readFromStdout(stdout); - afterClose(); -}; -var randomFileName = () => { - return path.join(os.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`); -}; -var workerThreadService = null; -var startWorkerThreadService = (worker_threads2) => { - let {port1: mainPort, port2: workerPort} = new worker_threads2.MessageChannel(); - let worker = new worker_threads2.Worker(__filename, { - workerData: {workerPort, defaultWD}, - transferList: [workerPort], - execArgv: [] - }); - let nextID = 0; - let wasStopped = false; - let validateBuildSyncOptions = (options) => { - if (!options) - return; - let plugins = options.plugins; - let incremental = options.incremental; - if (plugins && plugins.length > 0) - throw new Error(`Cannot use plugins in synchronous API calls`); - if (incremental) - throw new Error(`Cannot use "incremental" with a synchronous build`); - }; - let applyProperties = (object, properties) => { - for (let key in properties) { - object[key] = properties[key]; - } - }; - let runCallSync = (command, args) => { - if (wasStopped) - throw new Error("The service was stopped"); - let id = nextID++; - let sharedBuffer = new SharedArrayBuffer(8); - let sharedBufferView = new Int32Array(sharedBuffer); - let msg = {sharedBuffer, id, command, args}; - worker.postMessage(msg); - let status = Atomics.wait(sharedBufferView, 0, 0); - if (status !== "ok" && status !== "not-equal") - throw new Error("Internal error: Atomics.wait() failed: " + status); - let {message: {id: id2, resolve, reject, properties}} = worker_threads2.receiveMessageOnPort(mainPort); - if (id !== id2) - throw new Error(`Internal error: Expected id ${id} but got id ${id2}`); - if (reject) { - applyProperties(reject, properties); - throw reject; - } - return resolve; - }; - worker.unref(); - return { - buildSync(options) { - validateBuildSyncOptions(options); - return runCallSync("build", [options]); - }, - transformSync(input, options) { - return runCallSync("transform", [input, options]); - } - }; -}; -var startSyncServiceWorker = () => { - let workerPort = worker_threads.workerData.workerPort; - let parentPort = worker_threads.parentPort; - let service = ensureServiceIsRunning(); - defaultWD = worker_threads.workerData.defaultWD; - let extractProperties = (object) => { - let properties = {}; - if (object && typeof object === "object") { - for (let key in object) { - properties[key] = object[key]; - } - } - return properties; - }; - parentPort.on("message", (msg) => { - (async () => { - let {sharedBuffer, id, command, args} = msg; - let sharedBufferView = new Int32Array(sharedBuffer); - try { - if (command === "build") { - workerPort.postMessage({id, resolve: await service.build(args[0])}); - } else if (command === "transform") { - workerPort.postMessage({id, resolve: await service.transform(args[0], args[1])}); - } else { - throw new Error(`Invalid command: ${command}`); - } - } catch (reject) { - workerPort.postMessage({id, reject, properties: extractProperties(reject)}); - } - Atomics.add(sharedBufferView, 0, 1); - Atomics.notify(sharedBufferView, 0, Infinity); - })(); - }); -}; -if (worker_threads && !worker_threads.isMainThread) { - startSyncServiceWorker(); -} -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - build, - buildSync, - initialize, - serve, - transform, - transformSync, - version -}); diff --git a/node_modules/esbuild/package.json b/node_modules/esbuild/package.json deleted file mode 100644 index 682afd0..0000000 --- a/node_modules/esbuild/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "esbuild", - "version": "0.9.7", - "description": "An extremely fast JavaScript bundler and minifier.", - "repository": "https://github.com/evanw/esbuild", - "scripts": { - "postinstall": "node install.js" - }, - "main": "lib/main.js", - "types": "lib/main.d.ts", - "bin": { - "esbuild": "bin/esbuild" - }, - "license": "MIT" -} diff --git a/node_modules/rollup/CHANGELOG.md b/node_modules/rollup/CHANGELOG.md deleted file mode 100644 index 3f7c85f..0000000 --- a/node_modules/rollup/CHANGELOG.md +++ /dev/null @@ -1,4475 +0,0 @@ -# rollup changelog - -## 2.44.0 -*2021-03-29* - -### Features -* Add a new option `makeAbsoluteExternalsRelative` to opt out of renormalizing absolute external ids to relative ids (#4021) -* Extend the `resolveId` plugin hook to allow forcing or preventing renormalization of absolute external ids (#4021) -* Make the rendered code of individual modules available in the generated bundle (#4028) - -### Bug Fixes -* Handle objects with `__proto__` properties correctly (#4019) - -### Pull Requests -* [#4019](https://github.com/rollup/rollup/pull/4019): Deoptimize ObjectExpression when a `__proto__` property is present (@marijnh) -* [#4021](https://github.com/rollup/rollup/pull/4021): Improve absolute path handling (@lukastaegert) -* [#4026](https://github.com/rollup/rollup/pull/4026): chore: fix vscode launch config (change tdd to bdd) (@jameslahm) -* [#4027](https://github.com/rollup/rollup/pull/4027): Post comment for PRs from forks (@lukastaegert) -* [#4028](https://github.com/rollup/rollup/pull/4028): Expose rendered module code to generateBundle hook (@btd) - -## 2.43.1 -*2021-03-28* - -### Bug Fixes -* Prevent infinite recursions in certain scenarios when calling object properties (#4025) - -### Pull Requests -* [#4025](https://github.com/rollup/rollup/pull/4025): Handle recursive this mutation detection (@lukastaegert) - -## 2.43.0 -*2021-03-27* - -### Features -* Track side effects of function properties in objects for better tree-shaking (#4011) - -### Pull Requests -* [#4011](https://github.com/rollup/rollup/pull/4011): Disable pessimistic object deoptimization for calls when the called function doesn't ref this (@marijnh) -* [#4012](https://github.com/rollup/rollup/pull/4012): fix `sourcemap` reference in docs (@tjenkinson) -* [#4015](https://github.com/rollup/rollup/pull/4015): Use SIGTERM instead of SIGINT to kill test child processes in tests (@marijnh) - -## 2.42.4 -*2021-03-24* - -### Bug Fixes -* Do not discard plugin return values when using perf option (#4010) - -### Pull Requests -* [#4010](https://github.com/rollup/rollup/pull/4010): Return hook result inside promise with async timer end (@SuperOleg39) - -## 2.42.3 -*2021-03-22* - -### Bug Fixes -* Do not ignore `#__PURE__` comments in front of optional chaining expressions (#4007) - -### Pull Requests -* [#4007](https://github.com/rollup/rollup/pull/4007): Tree-shake pure call expressions with optional chaining (@lukastaegert) - -## 2.42.2 -*2021-03-22* - -### Bug Fixes -* Use correct import.meta.url in relative imports from transpiled config files (#4005) - -### Pull Requests -* [#4005](https://github.com/rollup/rollup/pull/4005): Use correct import.meta.url in config files (@lukastaegert) - -## 2.42.1 -*2021-03-20* - -### Bug Fixes -* Do not produce unhandled Promise rejections when plugins throw while using the `perf` option (#4004) - -### Pull Requests -* [#4004](https://github.com/rollup/rollup/pull/4004): Fixed unhandled promise rejections (@gluck) - -## 2.42.0 -*2021-03-19* - -### Features -* Prevent infinite loops when several plugins are using `this.resolve` in their resolveId hook (#4000) - -### Pull Requests -* [#4000](https://github.com/rollup/rollup/pull/4000): Break infinite loops in this.resolve (@lukastaegert) - -## 2.41.5 -*2021-03-18* - -### Bug Fixes -* Make sure unused property accesses of external namespaces can be tree-shaken (#4001) - -### Pull Requests -* [#4001](https://github.com/rollup/rollup/pull/4001): Do not count accessing members of an external namespace as side-effects (@lukastaegert) - -## 2.41.4 -*2021-03-16* - -### Bug Fixes -* Do not replace external namespace imports with individual named imports to avoid changing behaviour with regard to missing exports (#3999) - -### Pull Requests -* [#3999](https://github.com/rollup/rollup/pull/3999): Allow to safely probe external namespaces (@lukastaegert) - -## 2.41.3 -*2021-03-16* - -### Bug Fixes -* Always retain arguments passed to empty object pattern parameters (#3998) - -### Pull Requests -* [#3998](https://github.com/rollup/rollup/pull/3998): Do not create invalid code if a function argument is an empty object pattern (@lukastaegert) - -## 2.41.3 -*2021-03-16* - -### Bug Fixes -* Always retain arguments passed to empty object pattern parameters (#3998) - -### Pull Requests -* [#3998](https://github.com/rollup/rollup/pull/3998): Do not create invalid code if a function argument is an empty object pattern (@lukastaegert) - -## 2.41.2 -*2021-03-12* - -### Bug Fixes -* Also remove sourcemaps comments if plugins return a pre-made ast (#3987) - -### Pull Requests -* [#3987](https://github.com/rollup/rollup/pull/3987): Change removal of sourcemap comment (@yannayl) - -## 2.41.1 -*2021-03-11* - -### Pull Requests -* [#3990](https://github.com/rollup/rollup/pull/3990): Add browser sourcemap and remove log (@lukastaegert) - -## 2.41.0 -*2021-03-09* - -### Features -* Add option to `treeshake.propertyReadSideEffects` to keep all property accesses (#3985) - -### Bug Fixes -* Also respect pure comment annotations when a plugin provides an AST in the transform hook provided they use this.parse (#3981) - -### Pull Requests -* [#3981](https://github.com/rollup/rollup/pull/3981): Move pure comment annotation to Graph.contextParse (@yannayl) -* [#3985](https://github.com/rollup/rollup/pull/3985): implement --treeshake.propertyReadSideEffects=always to handle getters with side effects (@kzc) - -## 2.40.0 -*2021-02-26* - -### Features -* Make sure that entry point variable names take precedence over variable names in dependencies when deconflicting (#3977) - -### Bug Fixes -* Replace `:` in generated file names to prevent invalid files on Windows (#3972) - -### Pull Requests -* [#3972](https://github.com/rollup/rollup/pull/3972): Don't allow `:` in file names (@lukastaegert) -* [#3976](https://github.com/rollup/rollup/pull/3976): Add soft breaks to guide to improve mobile experience (@lukastaegert) -* [#3977](https://github.com/rollup/rollup/pull/3977): Reverse module deconflicting order (@lukastaegert) - -## 2.39.1 -*2021-02-23* - -### Bug Fixes -* Make sure local variables named Symbol, Object or Promise do not conflict with code generated by Rollup (#3971) - -### Pull Requests -* [#3964](https://github.com/rollup/rollup/pull/3964): Remove extra word (@jamonholmgren) -* [#3971](https://github.com/rollup/rollup/pull/3971): Avoid conflicts with local variables named Symbol, Object, Promise (@lukastaegert) - -## 2.39.0 -*2021-02-12* - -### Features -* Add "validate" option to verify generated chunks are valid JavaScript (#3952) - -### Bug Fixes -* Always add exports properties for uninitialized named exports (#3957) -* Allow using an external namespace reexport together with named exports (#3959) -* Avoid invalid generated code in certain scenarios with SystemJS exports (#3960) - -### Pull Requests -* [#3952](https://github.com/rollup/rollup/pull/3952): implement `validate` output option and `--validate` CLI option (@kzc) -* [#3956](https://github.com/rollup/rollup/pull/3956): Update dependencies, fix fsevents issue (@lukastaegert) -* [#3957](https://github.com/rollup/rollup/pull/3957): Make sure uninitialised exports turn up via .hasOwnProperty for non-ES formats (@lukastaegert) -* [#3959](https://github.com/rollup/rollup/pull/3959): Allow overriding individual exports of reexported external namespaces (@lukastaegert) -* [#3960](https://github.com/rollup/rollup/pull/3960): Make sure system exports are valid JavaScript - (@lukastaegert) - -## 2.38.5 -*2021-02-05* - -### Bug Fixes -* Prevent invalid code when simplifying assignments and delcarations (#3951) -* Prevent behaviour-changing line-breaks when simplifying assignments in return statements (#3951) -* Slightly improve white-space rendering when simplifying certain expressions (#3951) - -### Pull Requests -* [#3951](https://github.com/rollup/rollup/pull/3951): Wrap simplified assignments if necessary (@lukastaegert) - -## 2.38.4 -*2021-02-02* - -### Bug Fixes -* Do not change logic when tree-shaking declarations in if statements or loops (#3947) - -### Pull Requests -* [#3947](https://github.com/rollup/rollup/pull/3947): Do not tear apart declarations in loop or if bodies (@lukastaegert) - -## 2.38.3 -*2021-02-01* - -### Bug Fixes -* Prevent an unexpected live-binding when default exporting a synthetic named export (#3946) - -### Pull Requests -* [#3945](https://github.com/rollup/rollup/pull/3945): Upgrade chokidar and fsevents for Apple M1 compatibility (@threepointone) -* [#3946](https://github.com/rollup/rollup/pull/3946): Make sure default exports snapshot synthetic named exports (@lukastaegert) - -## 2.38.2 -*2021-01-31* - -### Bug Fixes -* Do not generate invalid code for partially tree-shaken declarations in for loops (#3943) -* Always include function bodies of functions in side-effect-free modules (#3944) - -### Pull Requests -* [#3943](https://github.com/rollup/rollup/pull/3943): Do not partially tree-shake unused declarations in for loops (@lukastaegert) -* [#3944](https://github.com/rollup/rollup/pull/3944): Correctly include functions with side effects from side-effect-free modules (@lukastaegert) - -## 2.38.1 -*2021-01-28* - -### Bug Fixes -* Fix internal error when resolving a missing entry point in the browser build (#3935) - -### Pull Requests -* [#3935](https://github.com/rollup/rollup/pull/3935): fix: remove isolated resolve() for compat with browser distribution (@cmorten and @lukastaegert) -* [#3936](https://github.com/rollup/rollup/pull/3936): Ensure test after() callback is always executed (@Benjamin-Dobell) -* [#3937](https://github.com/rollup/rollup/pull/3937): Modernize references to other software (@ludofischer) - -## 2.38.0 -*2021-01-22* - -### Features -* Entirely remove declared variables that only have an initializer side effect (#3933) - -### Pull Requests -* [#3933](https://github.com/rollup/rollup/pull/3933): Tree-shake unused declarations while keeping initializer side-effects (@lukastaegert) - -## 2.37.1 -*2021-01-20* - -### Pull Requests -* [#3929](https://github.com/rollup/rollup/pull/3929): Deduplicate acorn import (@lukastaegert) - -## 2.37.0 -*2021-01-19* - -### Features -* Always check modules for side effects that only indirectly reexport a used variable (#3840) -* Warn if a circular dependency would cause wrong execution order when preserving modules (#3840) - -### Bug Fixes -* Allow consuming synthetic exports via modules that reexport a namespace (#3894) -* Do not crash for circular default reexports (#3840) -* Do not crash for circular synthetic namespaces (#3840) -* Improve circular dependency execution order in certain scenarios (#3840) - -### Pull Requests -* [#3840](https://github.com/rollup/rollup/pull/3840): Improve circular dependency execution order (@lukastaegert) -* [#3894](https://github.com/rollup/rollup/pull/3894): Always respect synthetic namespaces in namespace reexport (@lukastaegert) - -## 2.36.2 -*2021-01-16* - -### Bug Fixes -* Fix an issue where invalid code was generated for unused assignments with side effects (#3926) - -### Pull Requests -* [#3926](https://github.com/rollup/rollup/pull/3926): Correctly simplify assignments with parentheses (@lukastaegert) - -## 2.36.1 -*2021-01-06* - -### Bug Fixes -* Solve issues that result in invalid code when partially removing assignments (#3921) - -### Pull Requests -* [#3921](https://github.com/rollup/rollup/pull/3921): Prevent invalid code when removing assignment target of side-effectful object expression (@lukastaegert) - -## 2.36.0 -*2021-01-05* - -### Features -* Support partial tree-shaking of chained assignments and unused assignment targets (#3919) - -### Pull Requests -* [#3919](https://github.com/rollup/rollup/pull/3919): Treeshake chained assignment expressions (@lukastaegert) - -## 2.35.1 -*2020-12-14* - -### Bug Fixes -* Allow closing the bundle when watching in case of generate errors by adding the bundle to the error event (#3909) -* Automatically close all bundles on generate errors when watching and using the CLI (#3909) -* Try to create remaining bundles when watching and one of them throws (#3909) - -### Pull Requests -* [#3909](https://github.com/rollup/rollup/pull/3909): Forward bundle through watch error events (@lukastaegert) - -## 2.35.0 -*2020-12-14* - -### Features -* Add `closeBundle` hook that is triggered by `bundle.close()` in the JS API (#3883) - -### Pull Requests -* [#3883](https://github.com/rollup/rollup/pull/3883): Revert pattern to folder export (@intrnl) - -## 2.34.2 -*2020-12-06* - -### Bug Fixes -* Revert pattern export change (#3898) - -### Pull Requests -* [#3898](https://github.com/rollup/rollup/pull/3898): Revert pattern to folder export (@lukastaegert) - -## 2.34.1 -*2020-12-03* - -### Bug Fixes -* Avoid Node deprecation warning by using a pattern export for nested Rollup files (#3896) - -### Pull Requests -* [#3887](https://github.com/rollup/rollup/pull/3887): Run memory leak test on all systems (@lukastaegert) -* [#3892](https://github.com/rollup/rollup/pull/3892): Add pull_request to windows github actions (@shellscape) -* [#3893](https://github.com/rollup/rollup/pull/3893): Update dependencies (@lukastaegert) -* [#3896](https://github.com/rollup/rollup/pull/3896): Replace deprecated folder package export with pattern export (@lukastaegert) - -## 2.34.0 -*2020-11-29* - -### Features -* Support RequireJS comaptible AMD ids in code-splitting builds via amd.autoId (#3867) -* Allow adding an AMD id base path (#3867) - -### Bug Fixes -* Warn when using an constant AMD id in a code-splitting build (#3867) - -### Pull Requests -* [#3867](https://github.com/rollup/rollup/pull/3867): Implement amd.autoId/amd.basePath options (@tjenkinson) - -## 2.33.3 -*2020-11-18* - -### Bug Fixes -* Do not use `.js` extension when importing AMD files from a UMD bundle (#3872) - -### Pull Requests -* [#3861](https://github.com/rollup/rollup/pull/3861): Update chat/support links (@shellscape) -* [#3872](https://github.com/rollup/rollup/pull/3872): Also removeExtensionFromRelativeAmdId in UMD finaliser (@tjenkinson) - -## 2.33.2 -*2020-11-14* - -### Bug Fixes -* Fix an issue where statements were ignored after a conditional return in a labeled statement (#3871) - -### Pull Requests -* [#3871](https://github.com/rollup/rollup/pull/3871): Correctly track label usage in try statements (@Amareis) - -## 2.33.1 -*2020-11-02* - -### Bug Fixes -* Add `syntheticNamedExports` to `this.getModuleInfo` to align with documentation (#3847) - -### Pull Requests -* [#3847](https://github.com/rollup/rollup/pull/3847): Expose syntheticNamedExports to ModuleInfo (@Amareis) -* [#3852](https://github.com/rollup/rollup/pull/3852): Fix typo on docs (@jpsc) - -## 2.33.0 -*2020-11-01* - -### Features -* Add parameter to "watchChange" hook to denote if a change was an addition, update or deletion (#3841) -* Add "closeWatcher" hook to allow plugins to clean up resources when the watcher is closed (#3841) -* Add "this.getWatchFiles" function to plugin context to get the current set of watched files (#3841) - -### Pull Requests -* [#3841](https://github.com/rollup/rollup/pull/3841): Improved watcher hooks (@Amareis) -* [#3848](https://github.com/rollup/rollup/pull/3848): Add options hook to asyncpluginhooks (@intrnl) - -## 2.32.1 -*2020-10-21* - -### Bug Fixes -* Print warning location for plugin warnings if only `loc` is supplied (#3824) - -### Pull Requests -* [#3824](https://github.com/rollup/rollup/pull/3824): plugin warnings not showing warning.loc (@luciotato) - -## 2.32.0 -*2020-10-16* - -### Features -* Extend `preserveEntrySignatures` with a value `"exports-only"` to allow extension only if an entry does not have exports (#3823) - -### Pull Requests -* [#3823](https://github.com/rollup/rollup/pull/3823): Add "exports-only" option to preserveSignature (@lukastaegert) - -## 2.31.0 -*2020-10-15* - -### Features -* When using the `output.moduleToStringTag` option, also add the tag to entries with exports and simulated external namespaces (#3822) -* Add the `__esModule` interop marker to IIFE global variables unless `output.esModule` is turned off (#3822) - -### Pull Requests -* [#3822](https://github.com/rollup/rollup/pull/3822): Add module toStringTag to entries and interop namespaces (@lukastaegert) - -## 2.30.0 -*2020-10-13* - -### Features -* Add `moduleParsed` hook that is called for each module once code and AST are available (#3813) -* Include code and AST in `this.getModuleInfo` (#3813) - -### Bug Fixes -* Provide the original Acorn AST instead of the internal one when resolving dynamic imports that contain non-trivial expressions (#3813) - -### Pull Requests -* [#3813](https://github.com/rollup/rollup/pull/3813): Add moduleParsed plugin hook (@lukastaegert) -* [#3815](https://github.com/rollup/rollup/pull/3815): Docs: wile => while (@tjenkinson) -* [#3817](https://github.com/rollup/rollup/pull/3817): Docs: fix code snippet (@codefrau) -* [#3818](https://github.com/rollup/rollup/pull/3818): Update documentation on configuring Babel, removing the section on passing '{"modules": false}' as that is no longer needed since Babel 7 (@Robin-Hoodie) - -## 2.29.0 -*2020-10-08* - -### Features -* Allow passing custom options to other plugins via `this.resolve` (#3807) -* Allow attaching custom meta information to modules when resolving, loading or transforming (#3807) -* Do not throw but return `null` when using `this.getModuleInfo` for an unknown id (#3807) - -### Bug Fixes -* Trigger build in watch mode when files are added to a watched directory (#3812) -* Make `code` optional when transforming modules (#3807) - -### Pull Requests -* [#3807](https://github.com/rollup/rollup/pull/3807): Implement new APIs for inter-plugin communication (@lukastaegert) -* [#3808](https://github.com/rollup/rollup/pull/3808): Document that the default value of --format is 'es' (@jameshfisher) -* [#3812](https://github.com/rollup/rollup/pull/3812): Watch: listen for new files added to a directory (@dmitrage) - -## 2.28.2 -*2020-09-24* - -### Bug Fixes -* Fix a source of possible variable name conflicts when using preserveModules with SystemJS (#3796) - -### Pull Requests -* [#3792](https://github.com/rollup/rollup/pull/3792): add documentation for output.PreserveModulesRoot (@davidroeca) -* [#3796](https://github.com/rollup/rollup/pull/3796): Fix SystemJS default variable conflict (@lukastaegert) - -## 2.28.1 -*2020-09-21* - -### Bug Fixes -* Fix a path slash issue when using the preserveModulesRoot option on Windows (#3791) - -### Pull Requests -* [#3791](https://github.com/rollup/rollup/pull/3791): Fix preserveModulesRoot path on Windows (@lukastaegert) - -## 2.28.0 -*2020-09-21* - -### Features -* Add an option to treat modules at a given path as located at root when preserving modules (#3786) - -### Pull Requests -* [#3786](https://github.com/rollup/rollup/pull/3786): Add preserveModulesRoot config option (@davidroeca) - -## 2.27.1 -*2020-09-17* - -### Bug Fixes -* Do not fail when using ES module imports in symlinked config files (#3783) - -### Pull Requests -* [#3783](https://github.com/rollup/rollup/pull/3783): Handle loading symlinked config files (@lukastaegert) - -## 2.27.0 -*2020-09-16* - -### Features -* Support specifying a file extension when reading from stdin (#3775) - -### Bug Fixes -* Do not break logic if a branch with hoisted variables is tree-shaken in an else-if statement (#3782) - -### Pull Requests -* [#3770](https://github.com/rollup/rollup/pull/3770): Docs: Exception for babel plugin and commonjs plugin (@jsk7) -* [#3775](https://github.com/rollup/rollup/pull/3775): add ability to specify stdin file extension via --stdin=ext (@kzc) -* [#3782](https://github.com/rollup/rollup/pull/3782): Handle hoisted variables in dead branches of nested if statements (@lukastaegert) - -## 2.26.11 -*2020-09-08* - -### Bug Fixes -* Do not fail for unknown nodes as if statement branches (#3769) - -### Pull Requests -* [#3769](https://github.com/rollup/rollup/pull/3769): Handle debugger statements as if-statement branches (@lukastaegert) - -## 2.26.10 -*2020-09-04* - -### Bug Fixes -* Do not create invalid code when simplifying expressions in return statements that contain line comments (#3762) - -### Pull Requests -* [#3757](https://github.com/rollup/rollup/pull/3757): Fix api docs loadconfigfile (@maxwell8888) -* [#3762](https://github.com/rollup/rollup/pull/3762): Handle line-comments when removing line-breaks to prevent ASI (@lukastaegert) - -## 2.26.9 -*2020-09-01* - -### Bug Fixes -* Add regular expression support to watch include/exclude types (#3754) - -### Pull Requests -* [#3754](https://github.com/rollup/rollup/pull/3754): Add RegExp to the include and exclude fields of the WatcherOptions type (@dagda1) -* [#3756](https://github.com/rollup/rollup/pull/3756): Update FAQ: I think it was meant "external" instead of "other-entry.js" (@madacol) - -## 2.26.8 -*2020-08-29* - -### Bug Fixes -* Make sure that both unresolved and resolved ids are passed to the `external` option in all cases (#3753) - -### Pull Requests -* [#3753](https://github.com/rollup/rollup/pull/3753): Also pass resolved ids to external if they use the object for (@lukastaegert) - -## 2.26.7 -*2020-08-28* - -### Bug Fixes -* Avoid invalid code when rendering hoisted variable declarations from dead branches (#3752) -* Mark the `options` parameter of `this.parse` as optional for TypeScript plugins (#3750) - -### Pull Requests -* [#3750](https://github.com/rollup/rollup/pull/3750): Make `options` of `PluginContext#parse` optional (@intrnl) -* [#3752](https://github.com/rollup/rollup/pull/3752): Extract hoisted variables from dead branches (@lukastaegert) - -## 2.26.6 -*2020-08-27* - -### Bug Fixes -* Avoid conflicts between the namespace of synthetic named exports and local variables (#3747) - -### Pull Requests -* [#3747](https://github.com/rollup/rollup/pull/3747): Properly deconflict synthetic named exports (@lukastaegert) - -## 2.26.5 -*2020-08-22* - -### Bug Fixes -* Use correctly deconflicted variable names for reexported namespaces in ES formats (#3742) - -### Pull Requests -* [#3742](https://github.com/rollup/rollup/pull/3742): Avoid variable name conflict when reexporting several namespaces from a chunk (@lukastaegert) - -## 2.26.4 -*2020-08-19* - -### Bug Fixes -* Fix a situation where invalid code was rendered when dynamically importing a module with synthetic named exports when preserving modules (#3738) -* Create a proper namespace object when in a non-es format, a namespace is imported from a chunk with `default` export mode (#3738) -* Use the same variable when in a chunk, a namespace is both imported and reexported as a binding (#3738) -* Do not include the synthetic namespace in static entry points unless it is actually used (#3738) -* Make sure the chunking of one output does not interfere with the namespace objects of another output (#3738) - -### Pull Requests -* [#3738](https://github.com/rollup/rollup/pull/3738): Improve synthetic entry handling (@lukastaegert) - -## 2.26.3 -*2020-08-16* - -### Bug Fixes -* Fix a situation where line-breaks in a nested simplified conditional expression could result in broken code (#3734) - -### Pull Requests -* [#3734](https://github.com/rollup/rollup/pull/3734): Prevent ASI when simplifying a nested logical expression (@lukastaegert) - -## 2.26.2 -*2020-08-16* - -### Bug Fixes -* Fix a situation where line-breaks in a simplified conditional expression could result in broken code (#3732) - -### Pull Requests -* [#3732](https://github.com/rollup/rollup/pull/3732): Prevent unintended ASI for nested conditionals (@lukastaegert) - -## 2.26.1 -*2020-08-16* - -### Bug Fixes -* Correctly render external namespace imports when only generating SystemJS output (#3731) - -### Pull Requests -* [#3731](https://github.com/rollup/rollup/pull/3731): Render system namespace import (@sastan and @lukastaegert) - -## 2.26.0 -*2020-08-15* - -### Features -* Add a new entry `importedBindings` to the bundle information to list bindings per dependency (#3722) - -### Bug Fixes -* Do not render an invalid UMD wrapper when no bindings are imported from a dependency (#3724) -* Avoid situations where removing the `else` branch from an `if` statement might catch the `else` branch from another one (#3725) - -### Pull Requests -* [#3722](https://github.com/rollup/rollup/pull/3722): Add import specifiers to bundle information (@lukastaegert) -* [#3724](https://github.com/rollup/rollup/pull/3724): Fix missing variables for UMD and IIFE builds (@lukastaegert) -* [#3725](https://github.com/rollup/rollup/pull/3725): Do not entirely remove else branch if another else branch might accidentally be referenced (@lukastaegert) - -## 2.25.0 -*2020-08-14* - -### Features -* Add `--failAfterWarnings` CLI flag that will complete builds with warnings but return an error at the end (#3712) - -### Pull Requests -* [#3712](https://github.com/rollup/rollup/pull/3712): Implement `--failAfterWarnings` flag (@tjenkinson) - -## 2.24.0 -*2020-08-13* - -### Features -* Allow defining interop per dependency via a function (#3710) -* Support interop "auto" as a more compatible version of "true" (#3710) -* Support interop "default" and "esModule" to avoid unnecessary interop helpers (#3710) -* Support interop "defaultOnly" for simplified helpers and Node ESM interop compatible output (#3710) -* Respect interop option for external dynamic imports (#3710) -* Support live-bindings for external default imports in non-ES formats unless "externalLiveBindings" is "false" (#3710) -* Use shared default interop helpers for AMD, UMD and IIFE formats (#3710) -* Avoid unnecessarily deconflicted module variables in non-ES formats (#3710) -* Freeze generated interop namespace objects (#3710) -* Always mark interop helpers as pure (#3710) -* Avoid default export interop if there is already an interop namespace object (#3710) -* Sort all `require` statements to the top in CommonJS output for easier back-transpilation to ES modules by other tools (#3710) - -### Bug Fixes -* Handle accessing `super` in static class fields (#3720) -* Deconflict the names of helper variables introduced for interop (#3710) -* Generate proper namespace objects for static namespace imports in non-ES formats (#3710) -* Do not add unused interop helpers when using the renderDynamicImport hook (#3710) - -### Pull Requests -* [#3710](https://github.com/rollup/rollup/pull/3710): Rework interop handling (@lukastaegert) -* [#3720](https://github.com/rollup/rollup/pull/3720): Handle super in static class fields (@lukastaegert) - -## 2.23.1 -*2020-08-07* - -### Bug Fixes -* Fix an issue where dynamically importing an entry point could return a malformed namespace for CJS and AMD formats (#3709) - -### Pull Requests -* [#3709](https://github.com/rollup/rollup/pull/3709): Properly construct namespace when dynamically importing chunks with facades in default export mode (@lukastaegert) - -## 2.23.0 -*2020-07-23* - -### Features -* Handle environments with only globalThis in UMD output (#3691) - -### Pull Requests -* [#3691](https://github.com/rollup/rollup/pull/3691): Check for globalThis in UMD wrapper (@lukastaegert) - -## 2.22.2 -*2020-07-21* - -### Bug Fixes -* Always generate correct exports when an implicit entry is reexporting from another module (#3688) - -### Pull Requests -* [#3688](https://github.com/rollup/rollup/pull/3688): Include all relevant modules to generate reexports for implicit dependencies (@lukastaegert) - -## 2.22.1 -*2020-07-18* - -### Bug Fixes -* Remove unused arguments when calling a conditional expression (#3680) - -### Pull Requests -* [#3680](https://github.com/rollup/rollup/pull/3680): Allow tree-shaking of arguments of functions that are returned by conditional expressions (@lukastaegert) - -## 2.22.0 -*2020-07-18* - -### Features -* Allow resolving synthetic named exports via an arbitrary export name (#3657) -* Display a warning when the user does not explicitly select an export mode and would generate a chunk with default export mode when targeting CommonJS (#3657) - -### Pull Requests -* [#3657](https://github.com/rollup/rollup/pull/3657): Add basic support for using a non-default export for syntheticNamedExports (@lukastaegert) -* [#3659](https://github.com/rollup/rollup/pull/3659): Warn when implicitly using default export mode (@lukastaegert) - -## 2.21.0 -*2020-07-07* - -### Features -* Allow plugins to disable tree-shaking for individual modules to ensure even empty modules are associated with chunks (#3663) - -### Pull Requests -* [#3663](https://github.com/rollup/rollup/pull/3663): Disable treeshaking per module (@lukastaegert) - -## 2.20.0 -*2020-07-06* - -### Features -* Support using a function to generate different chunk and asset naming patterns per chunk or asset (#3658) -* Add `referencedFiles` property to the chunk info in generateBundle to list referenced assets (#3661) - -### Pull Requests -* [#3658](https://github.com/rollup/rollup/pull/3658): Add ability to use a function that returns a pattern string in all places where you could use a pattern string before (@frank-dspeed) -* [#3661](https://github.com/rollup/rollup/pull/3661): Add referenced files to bundle (@lukastaegert) - -## 2.19.0 -*2020-07-05* - -### Features -* Allow plugins to return a Promise in the options hook (#3660) - -### Pull Requests -* [#3660](https://github.com/rollup/rollup/pull/3660): Make options hooks async (@TomerAberbach) - -## 2.18.2 -*2020-07-02* - -### Bug Fixes -* Do not remove spread element args when the corresponding positional parameter is unused (#3652) - -### Pull Requests -* [#3652](https://github.com/rollup/rollup/pull/3652): Do not tree-shake arguments that contain a spread element (@lukastaegert) - -## 2.18.1 -*2020-06-26* - -### Bug Fixes -* Make sure synthetic exports are present when a module is imported dynamically (#3648) -* Strip the `rollup-plugin-` prefix off the plugin name when looking for the plugin export in a CLI plugin without a default export (#3647) -* Convert plugin names with dashes to camel case when looking for the plugin export in a CLI plugin without a default export (#3647) - -### Pull Requests -* [#3647](https://github.com/rollup/rollup/pull/3647): Strip rollup-plugin prefix to find named plugin exports, throw when export cannot be found (@lukastaegert) -* [#3648](https://github.com/rollup/rollup/pull/3648): Always create a dynamic namespace object when a module with synthetic named exports is imported dynamically (@lukastaegert) - -## 2.18.0 -*2020-06-22* - -### Features -* `inlineDynamicImports`, `manualChunks` and `preserveModules` can now be used as output options (#3645) -* Use sourcemaps for certain warnings that reference source code locations (#3645) - -### Bug Fixes -* `this.getFileName` will now always return the correct file name for chunks when multiple outputs are created (#3645) - -### Pull Requests -* [#3645](https://github.com/rollup/rollup/pull/3645): Per output chunking (@lukastaegert) - -## 2.17.1 -*2020-06-19* - -### Bug Fixes -* Properly resolve accessing properties of namespace members again (#3643) - -### Pull Requests -* [#3643](https://github.com/rollup/rollup/pull/3643): Fix accessing nested properties of namespaces (@lukastaegert) - -## 2.17.0 -*2020-06-17* - -### Features -* When importing Rollup via package.exports, always fall back to the browser ESM build for non-Node environments (#3634) -* Create more efficient code when handling namespace mutations (#3637) - -### Bug Fixes -* Fix a severe performance regression when the same module is imported by a lot of modules (#3641) -* Properly escape special characters in imports (#3638) - -### Pull Requests -* [#3634](https://github.com/rollup/rollup/pull/3634): Set browser build in exports (@guybedford) -* [#3637](https://github.com/rollup/rollup/pull/3637): Do not include the whole namespace when illegally mutating a namespace (@lukastaegert) -* [#3638](https://github.com/rollup/rollup/pull/3638): Support backslash escaping, retain exact newline escaping (@guybedford) -* [#3641](https://github.com/rollup/rollup/pull/3641): Fix performance regression when a file is imported by many importers (@lukastaegert) - -## 2.16.1 -*2020-06-13* - -### Bug Fixes -* Do not produce invalid code when an external or chunk id contain quotes or line-breaks (#3632) -* Do not fail but emit a warning when mutating a namespace object (#3633) - -### Pull Requests -* [#3632](https://github.com/rollup/rollup/pull/3632): Handle single quote escaping in ids (@guybedford) -* [#3633](https://github.com/rollup/rollup/pull/3633): Turn namespace assignment error into a warning (@guybedford) - -## 2.16.0 -*2020-06-12* - -### Features -* Add support for numeric separators (#3626) -* Switch to finalized ESTree optional chaining AST (#3628) - -### Pull Requests -* [#3626](https://github.com/rollup/rollup/pull/3626): Support numeric separator (@TrySound) -* [#3628](https://github.com/rollup/rollup/pull/3628): Acorn 7.3.0 upgrade (@guybedford) -* [#3631](https://github.com/rollup/rollup/pull/3631): Improve discoverability of `manualChunks` for code splitting (@zlamma) - -## 2.15.0 -*2020-06-08* - -### Features -* Allow to skip watching some configs via `watch: false` (#3620) -* Provide the resolved sourcemap path to `sourcemapPathTransform` (#3617) - -### Pull Requests -* [#3617](https://github.com/rollup/rollup/pull/3617): Update sourcemapPathTransform to also take the path to the sourcemap file as a second argument (@dgoldstein0) -* [#3620](https://github.com/rollup/rollup/pull/3620): Rollup watch only one config in exported array (@luwol03) - -## 2.14.0 -*2020-06-07* - -### Features -* Make `this.meta.watchMode` available for plugins to detect watch mode (#3616) - -### Bug Fixes -* Handle exporting the same binding with different names in SystemJS (#3575) - -### Pull Requests -* [#3575](https://github.com/rollup/rollup/pull/3575): Handle some cases of duplicate export bindings (@joeljeske) -* [#3616](https://github.com/rollup/rollup/pull/3616): Make watch mode available in plugins (@lukastaegert) - -## 2.13.1 -*2020-06-04* - -### Bug Fixes -* Prevent conflicts in SystemJS when `module` is used as a top-level variable (#3614) - -### Pull Requests -* [#3614](https://github.com/rollup/rollup/pull/3614): Handle system reserved identifier dedupes (@guybedford) - -## 2.13.0 -*2020-06-03* - -### Features -* Allow to specify that an emitted chunk is only loaded after a given module has loaded to improve chunking (#3606) - -### Pull Requests -* [#3606](https://github.com/rollup/rollup/pull/3606): Enable specifying implicit dependencies when emitting chunks (@lukastaegert) - -## 2.12.1 -*2020-06-02* - -### Bug Fixes -* Render valid imports when chunk names correspond to directory names in virtual setups (#3609) - -### Pull Requests -* [#3609](https://github.com/rollup/rollup/pull/3609): Handle imports from chunks with names that correspond to parent directory names of other chunks (@guybedford) - -## 2.12.0 -*2020-05-31* - -### Features -* Add an option `--waitForBundleInput` to let the build wait until all entry point files are available before starting (#3577) - -### Pull Requests -* [#3577](https://github.com/rollup/rollup/pull/3577): Wait for bundle input option (@Heerschop) - -## 2.11.2 -*2020-05-28* - -### Bug Fixes -* Include side-effects in the second argument of `Array.from` (#3604) - -### Pull Requests -* [#3604](https://github.com/rollup/rollup/pull/3604): Mark `Array.from` as side-effectful, use two-argument Array.from when mapping Sets (@lukastaegert) - -## 2.11.1 -*2020-05-28* - -### Bug Fixes -* Also include side-effects in files that are marked as side-effect-free if they contain an included default export that is reexported (#3602) - -### Pull Requests -* [#3602](https://github.com/rollup/rollup/pull/3602): Handle side-effects next to side-effect-free default exports in case the default export is reexported (@lukastaegert) - -## 2.11.0 -*2020-05-27* - -### Features -* Add basic support for optional chaining (#3582) -* Provide a normalized set of options with proper default values to `buildStart` and `renderStart` (#3597) -* Do not count adding properties to the prototype of an unused class as a side-effect (#3598) -* Support providing `null` for empty setters in SystemJS via option (#3592) - -### Bug Fixes -* Do not fail when using a `/*#__PURE__*/` annotation inside a class field (#3599) -* Allow using `--watch` and `--treeshake` together with sub-options such as `--watch.clearScreen` on the command line (#3597) - -### Pull Requests -* [#3582](https://github.com/rollup/rollup/pull/3582): Support optional chaining via acorn fork(@guybedford) -* [#3592](https://github.com/rollup/rollup/pull/3592): System format optional setters(@guybedford) -* [#3597](https://github.com/rollup/rollup/pull/3597): Provide normalized options (@lukastaegert) -* [#3598](https://github.com/rollup/rollup/pull/3598): Treeshake prototype modifications in classes (@lukastaegert) -* [#3599](https://github.com/rollup/rollup/pull/3599): Retain pure annotations in class fields (@lukastaegert) -* [#3601](https://github.com/rollup/rollup/pull/3601): Fix white-space in docs (@tu4mo) - -## 2.10.9 -*2020-05-24* - -### Bug Fixes -* Prevent invalid exports when facades are created (#3590) - -### Pull Requests -* [#3590](https://github.com/rollup/rollup/pull/3590): Prevent unneeded exports when entry facades are created and ensure all exported variables in facades are imported (@lukastaegert) - -## 2.10.8 -*2020-05-23* - -### Bug Fixes -* Fix issues when synthetic named exports are reexported as default exports (#3586) - -### Pull Requests -* [#3584](https://github.com/rollup/rollup/pull/3584): Clarify documentation for `output.paths` (@jacksteamdev) -* [#3585](https://github.com/rollup/rollup/pull/3585): Target Node.js v14 instead of v13 in Windows tests (@mangs) -* [#3586](https://github.com/rollup/rollup/pull/3586): Handle default reexports of synthetic named exports over several stages (@lukastaegert) - -## 2.10.7 -*2020-05-22* - -### Bug Fixes -* Handle modules re-exporting namespaces without further own code (#3576) - -### Pull Requests -* [#3576](https://github.com/rollup/rollup/pull/3576): Fix "cannot read exports of undefined" error (@guybedford) - -## 2.10.6 -*2020-05-22* - -### Bug Fixes -* Fix some issues around class fields (#3580) -* Prevent a maximum call stack error when a called entity references itself in its declaration (#3581) - -### Pull Requests -* [#3580](https://github.com/rollup/rollup/pull/3580): Update acorn class features (@guybedford) -* [#3581](https://github.com/rollup/rollup/pull/3581): Do not fail when including call arguments of recursively defined variables (@lukastaegert) - -## 2.10.5 -*2020-05-19* - -### Bug Fixes -* Do not remove side-effects that may influence an included default export declaration when side-effects are disabled (#3572) - -### Pull Requests -* [#3572](https://github.com/rollup/rollup/pull/3572): Observe side-effects in files containing a default export declaration that reexports a variable (@lukastaegert) - -## 2.10.4 -*2020-05-19* - -### Bug Fixes -* Tree-shake unused classes with fields unless there are side-effects in the field declaration (#3569) - -### Pull Requests -* [#3569](https://github.com/rollup/rollup/pull/3569): Make sure unused classes with fields are tree-shaken if possible (@lukastaegert) - -## 2.10.3 -*2020-05-18* - -### Bug Fixes -* Validate return value of sourcemapPathTransform option (#3561) - -### Pull Requests -* [#3561](https://github.com/rollup/rollup/pull/3561): Throw error if sourcemapPathTransform-option does not return a string (@Simonwep) - -## 2.10.2 -*2020-05-15* - -### Bug Fixes -* Properly include calls to mutating array methods in certain scenarios (#3559) - -### Pull Requests -* [#3559](https://github.com/rollup/rollup/pull/3559): Make sure UnknownFooExpressions are included when referenced as return values in a MultiExpression (@lukastaegert) - -## 2.10.1 -*2020-05-15* - -### Bug Fixes -* Do not throw when "undefined" is used as a default export (#3558) - -### Pull Requests -* [#3558](https://github.com/rollup/rollup/pull/3558): Properly handle default exporting undefined (@lukastaegert) - -## 2.10.0 -*2020-05-13* - -### Features -* Avoid unnecessary empty imports from a facade chunk to the original chunk (#3552) -* Pin facade creation order so that if several user-defined chunks reference the same module, the first always becomes the "actual" chunk while the later ones become facades (#3552) - -### Bug Fixes -* Do not omit reexports from secondary chunks when creating facades for entry points without hoisting transitive dependencies (#3552) - -### Pull Requests -* [#3552](https://github.com/rollup/rollup/pull/3552): Avoid unnecessary facade dependency inlining (@guybedford) - -## 2.9.1 -*2020-05-11* - -### Bug Fixes -* Do not create unintended live-bindings or invalid reexports when reexporting global variables (#3550) - -### Pull Requests -* [#3550](https://github.com/rollup/rollup/pull/3550): Track updates of globals that are exported as default (@lukastaegert) - -## 2.9.0 -*2020-05-10* - -### Features -* Add ids of static and dynamic imports to `this.getModuleInfo` (#3542) -* Provide `getModuleInfo` and `getModuleIds` to `manualChunks` functions (#3542) -* Add nullish coalescing support (#3548) -* Make the rebuild delay in watch mode configurable and set the default to `0` for snappy rebuilds (#3502) -* Add `this.getModuleIds` to the plugin context as future replacement for `this.moduleIds` (#3542) - -### Pull Requests -* [#3502](https://github.com/rollup/rollup/pull/3502): Configurable build delay (@mattdesl) -* [#3542](https://github.com/rollup/rollup/pull/3542): Extend manualChunks API (@lukastaegert) -* [#3548](https://github.com/rollup/rollup/pull/3548): Support nullish coalescing with tree-shaking (@lukastaegert) - -## 2.8.2 -*2020-05-07* - -### Bug Fixes -* Avoid invalid code when simplifying the body of a shorthand arrow function expression (#3540) - -### Pull Requests -* [#3540](https://github.com/rollup/rollup/pull/3540): Wrap object expressions in parentheses if they become children of an arrow function expression (@lukastaegert) - -## 2.8.1 -*2020-05-07* - -### Bug Fixes -* Allow using plugins on CLI that are exported as `exports.default` (#3529) -* Do not fail side-effect detection in nested callbacks of builtins (#3539) - -### Pull Requests -* [#3529](https://github.com/rollup/rollup/pull/3529): Use default named export with plugins (@NotWoods) -* [#3539](https://github.com/rollup/rollup/pull/3539): Track call side-effects both by entity and CallExpression to avoid untracked side-effects in nested calls (@lukastaegert) - -## 2.8.0 -*2020-05-06* - -### Features -* When a dynamically imported chunk contains more exports than the imported module namespace, do not create a facade chunk but an inline namespace (#3535) - -### Bug Fixes -* Do not execute dynamically imported code before synchronous code in the importing module when generating CommonJS (#3535) - -### Pull Requests -* [#3535](https://github.com/rollup/rollup/pull/3535): Avoid dynamic facade chunks (@lukastaegert) - -## 2.7.6 -*2020-04-30* - -### Bug Fixes -* Fix a type issue when a default export references a global variable (#3526) - -### Pull Requests -* [#3526](https://github.com/rollup/rollup/pull/3526): Handles default exporting global variables (@lukastaegert) - -## 2.7.5 -*2020-04-29* - -### Bug Fixes -* Prevent infinite loop when default values of function parameters in a default export contain a slash (#3522) - -### Pull Requests -* [#3522](https://github.com/rollup/rollup/pull/3522): Avoid infinite loop when finding position for id insertion in default export (@lukastaegert) - -## 2.7.4 -*2020-04-29* - -### Bug Fixes -* Fix an issue where wrong variable names were used when preserving modules (#3521) - -### Pull Requests -* [#3521](https://github.com/rollup/rollup/pull/3521): Fix and improve default export alias logic (@lukastaegert) - -## 2.7.3 -*2020-04-27* - -### Bug Fixes -* Do not access `__proto__` when running Rollup (#3518) - -### Pull Requests -* [#3518](https://github.com/rollup/rollup/pull/3518): use acorn-class-fields and acorn-static-class-features from npm (@nitsky) - -## 2.7.2 -*2020-04-22* - -### Bug Fixes -* Prevent an infinite loop when creating separate manual chunks with circular dependencies (#3510) -* Do not fail if "super" is used in the definition of a class field (#3511) -* Throw if a plugin tries to emit a file with an absolute Windows path (#3509) - -### Pull Requests -* [#3509](https://github.com/rollup/rollup/pull/3509): Ban emitFile via absolute paths on Windows OS (@SASUKE40) -* [#3510](https://github.com/rollup/rollup/pull/3510): Do not fail for circular imports between manual chunks (@lukastaegert) -* [#3511](https://github.com/rollup/rollup/pull/3511): Support "super" in class fields (@lukastaegert) - -## 2.7.1 -*2020-04-21* - -### Bug Fixes -* Use correct path for dynamic imports if `output.paths` is used (#3508) - -### Pull Requests -* [#3508](https://github.com/rollup/rollup/pull/3508): Respect output.paths in dynamic imports (@lukastaegert) - -## 2.7.0 -*2020-04-21* - -### Features -* Add `preserveEntrySignatures` option to control how exports of entry points are handled (#3498) -* Add `preserveSignature` flag to `this.emitFile` to control exports of emitted chunks (#3498) -* Add `output.minifyInternalExports` option to control if internal exports are minified (#3498) - -### Pull Requests -* [#3498](https://github.com/rollup/rollup/pull/3498): Add option to configure if entry signatures are preserved (@lukastaegert) - -## 2.6.1 -*2020-04-12* - -### Bug Fixes -* Close watch mode when stdin closes in a non-TTY environment (#3493) - -### Pull Requests -* [#3493](https://github.com/rollup/rollup/pull/3493): Ensure --watch mode exits correctly when stdin is closed (@jakesgordon) - -## 2.6.0 -*2020-04-10* - -### Features -* Allow regular expressions to declare external modules (#3482) - -### Pull Requests -* [#3482](https://github.com/rollup/rollup/pull/3482): Allow regular expressions in config.external (@johannes-z) - -## 2.5.0 -This version is identical to 2.4.0 - -## 2.4.0 -*2020-04-09* - -### Features -* Add support for most private and public class field features (#3488) - -### Bug Fixes -* Do not replace `this` with `undefined` in class field definitions (#3488) - -### Pull Requests -* [#3488](https://github.com/rollup/rollup/pull/3488): Rollup class fields support (@guybedford and @lukastaegert) - -## 2.3.5 -*2020-04-09* - -### Bug Fixes -* Never remove labels when tree-shaking is disabled (#3492) - -### Pull Requests -* [#3492](https://github.com/rollup/rollup/pull/3492): Always use a new inclusion context when including declarations of variables, always inlcude labels when not treeshaking (@lukastaegert) - -## 2.3.4 -*2020-04-07* - -### Bug Fixes -* Handle re-exporting synthetic exports from entry-points (#3319) -* Fix cross-chunk imports of synthetic exports (#3319) -* Handle namespace objects that contain re-exported synthetic namespaces (#3319) - -### Pull Requests -* [#3319](https://github.com/rollup/rollup/pull/3319): Handle re-exports of synthetic named exports (@manucorporat and @lukastaegert) - -## 2.3.3 -*2020-04-04* - -### Bug Fixes -* Add external namespaces to dynamic namespace objects (#3474) - -### Pull Requests -* [#3474](https://github.com/rollup/rollup/pull/3474): Support external star exports on namespace objects (@guybedford) - -## 2.3.2 -*2020-03-31* - -### Bug Fixes -* Only warn but do not fail build when a namespace is called as a function (#3475) -* Make sure pre-existing sourcemap comments are also removed when rebuilding using the cache (#3476) - -### Pull Requests -* [#3475](https://github.com/rollup/rollup/pull/3475): Call namespace error as a warning (@guybedford) -* [#3476](https://github.com/rollup/rollup/pull/3476): Store locations for removed comments in cache (@lukastaegert) - -## 2.3.1 -*2020-03-30* - -### Bug Fixes -* Do not fail if the config file returns an function returning a Promise (#3472) - -### Pull Requests -* [#3472](https://github.com/rollup/rollup/pull/3472): Fix support for async functions as config (@lukastaegert) - -## 2.3.0 -*2020-03-29* - -### Features -* Do not transpile config files with `.mjs` extension in Node 13+ or `.cjs` extension in any Node version and load them appropriately (#3445) -* Extract helper to load a config file the way rollup does it via `rollup/dist/loadConfigFile` (#3445) - -### Bug Fixes -* Keep watching the config file if an error occurs during initial load in watch node (#3445) -* Add a helpful error message when using a transpiled config in a repository with "type": "module" (#3445) - -### Pull Requests -* [#3445](https://github.com/rollup/rollup/pull/3445): Support native ESM configs in Node 13, support untranspiled configs (@lukastaegert) -* [#3468](https://github.com/rollup/rollup/pull/3468): Don't use esm output format alias in the documentation (@vsn4ik) - -## 2.2.0 -*2020-03-24* - -### Features -* Add `renderDynamicImport` hook to rewrite dynamic import expressions (#3449) -* Add information about dynamically imported modules to `this.getModuleInfo` (#3449) - -### Bug Fixes -* Make file emission work with Uin8Array sources when using Rollup in the browser (#3452) -* Fix types to allow watch to accept an array of configs (#3453) -* Do not strip `.js` extensions from AMD imports when the import is a user-supplied replacement for a non-resolvable dynamic import target (#3453) - -### Pull Requests -* [#3449](https://github.com/rollup/rollup/pull/3449): Add hook to rewrite dynamic import expressions (@lukastaegert) -* [#3452](https://github.com/rollup/rollup/pull/3452): Avoid the assumption of Buffer in browser envs (@JoviDeCroock) -* [#3453](https://github.com/rollup/rollup/pull/3453): fix types since watch accepts single or array config (@lukeed) -* [#3456](https://github.com/rollup/rollup/pull/3456): fix SystemJS url in tutorial (@guybedford) - -## 2.1.0 -*2020-03-18* - -### Features -* Allow specifying an importer when emitting files to resolve relative ids (#3442) - -### Pull Requests -* [#3442](https://github.com/rollup/rollup/pull/3442): Add optional `importer` parameter to `this.emitFile` (@lukastaegert) - -## 2.0.6 -*2020-03-13* - -### Bug Fixes -* Do not use file names from different outputs when generating sourcemaps using the `dir` option (#3440) - -### Pull Requests -* [#3440](https://github.com/rollup/rollup/pull/3440): Use correct file names when writing sourcemaps for multiple outputs (@lukastaegert) - -## 2.0.5 -*2020-03-12* - -### Bug Fixes -* Fix an issue where conditional statements would assume they have the wrong test value (#3438) - -### Pull Requests -* [#3438](https://github.com/rollup/rollup/pull/3438): Make sure logical expressions always check the left argument for side-effects (@lukastaegert) - -## 2.0.4 -*2020-03-12* - -### Bug Fixes -* Avoid conflicts between namespace imports when preserving modules (#3435) - -### Pull Requests -* [#3435](https://github.com/rollup/rollup/pull/3435): Deconflict multiple `index` imports for ES format using nested export star statements (@kamranayub) - -## 2.0.3 -*2020-03-10* - -### Bug Fixes -* Add type for this.getCombinedSourcemap to transform context (#3431) - -### Pull Requests -* [#3377](https://github.com/rollup/rollup/pull/3377): Switch to yargs-parser lib (@jamesgeorge007) -* [#3426](https://github.com/rollup/rollup/pull/3426): Use strict types with PluginDriver (@NotWoods) -* [#3431](https://github.com/rollup/rollup/pull/3431): Add missing type declaration for getCombinedSourcemap (@Anidetrix) -* [#3432](https://github.com/rollup/rollup/pull/3432): Detail how return values from `augmentChunkHash` are used (@jakearchibald) - -## 2.0.2 -*2020-03-07* - -### Bug Fixes -* Make sure the ESM import still works (#3430) - -### Pull Requests -* [#3430](https://github.com/rollup/rollup/pull/3430): Fix conditional exports again (@lukastaegert) - -## 2.0.1 -*2020-03-07* - -### Bug Fixes -* Reenable importing rollup in Node 13.0 - 13.7 (#3428) - -### Pull Requests -* [#3428](https://github.com/rollup/rollup/pull/3428): Fix conditional exports in Node 13.0 - 13.7 (@lukastaegert) - -## 2.0.0 -*2020-03-06* - -### Breaking Changes -* Rollup now requires at least Node 10 to run, or a sufficiently modern browser (#3346) -* The file structure of Rollup's ESM builds has changed: - - The main ESM entry point is now at `rollup/dist/es/rollup.js` instead of `rollup/dist/rollup.es.js` - - The ESM browser build is at `rollup/dist/es/rollup.browser.js` instead of `rollup/dist/rollup.browser.es.js` - - In general, the ESM builds now follow the same naming scheme as the CJS builds but are located in the `rollup/dist/es` subfolder instead of `rollup/dist` (#3391) -* The "watch.chokidar" option no longer accepts a `boolean` value but only an object of parameters that is passed to the bundled Chokidar instance. Chokidar installations by the user will be ignored in favour of the bundled instance (#3331) -* Modules that are completely tree-shaken will no longer be listed as part of any chunks in `generateBundle` -* The `experimentalOptimizeChunks` and `chunkGroupingSize` options have been removed -* [acorn](https://github.com/acornjs/acorn) plugins can only be used if they accept a passed-in acorn instance instead of importing it themselves. See https://github.com/acornjs/acorn/pull/870#issuecomment-527339830 for what needs to be done to make plugins compatible that do not support this yet (#3391) -* Emitted chunks now have the TypeScript type `Uint8Array` instead of `Buffer`. A `Buffer` can still be used, though (#3395) -* The TypeScript types no longer use ESTree types for AST nodes but a very generic type that does not contain information specific to certain node types (#3395) -* The signature of the `writeBundle` plugin hook has been changed to match `generateBundle`: The bundle object is now passed as second parameter instead of first and the first parameter is the output options (#3361) -* The following plugin hooks have been removed: - - ongenerate: use `generateBundle` instead - - onwrite: use `writeBundle` instead - - transformBundle: use `renderChunk` instead - - transformChunk: use `renderChunk` instead -* You can no longer access `this.watcher` on the plugin context. -* The `transform` hook can no longer return `dependencies`. -* The `treeshake.pureExternalModules` option will now show a deprecation warning when used: use `treeshake.moduleSideEffects: 'no-external'` instead -* Using `import.meta.ROLLUP_ASSET_URL_<..>` and `import.meta.ROLLUP_CHUNK_URL_<..>` in code will now show warnings: use `import.meta.ROLLUP_FILE_URL_<..>` instead -* The `resolveAssetUrl` hook will now show a deprecation warning when used: use `resolveFileUrl` instead -* The following plugin context functions will show warnings when used: - - `this.emitAsset`: use `this.emitFile` - - `this.emitChunk`: use `this.emitFile` - - `this.getAssetFileName`: use `this.getFileName` - - `this.getChunkFileName`: use `this.getFileName` - - `this.isExternal`: use `this.resolve` - - `this.resolveId`: use `this.resolve` -* Directly adding properties to the bundle object in the `generateBundle` is deprecated will show a warning (removing properties is allowed, though): Use `this.emitFile` -* Accessing `chunk.isAsset` on the bundle is deprecated: Use `chunk.type === 'asset'` instead -* The error code for a missing `name` property when targeting UMD has been changed to `MISSING_NAME_OPTION_FOR_IIFE_EXPORT` to emphasize this is needed for the IIFE part of UMD (#3393) - -### Features -* Rollup now bundles [Chokidar](https://github.com/paulmillr/chokidar) for a better watch experience (#3331) -* Rollup now bundles [acorn](https://github.com/acornjs/acorn) again, removing its only external dependency (#3391) -* Do not consider empty imports from side-effect-free modules for chunking and hoist side-effect imports if necessary (#3369) -* Rollup can now be imported as an ES module in Node via `import {rollup} from 'rollup'`. Note that this relies on Node's experimental [conditional package exports](https://nodejs.org/dist/latest-v13.x/docs/api/esm.html#esm_conditional_exports) feature and is therefore itself experimental (#3391) -* `systemjs` can be used as format alias for `system` (#3381) - -### Bug Fixes -* Unknown output options now trigger a warning when using the JavaScript API (#3352) -* Rollup will no longer introduce Node types into TypeScript projects that do not use them (#3395) -* Generate correct sourcemaps when tree-shaking occurs in a multi-file bundle (#3423) - -### Pull Requests -* [#3331](https://github.com/rollup/rollup/pull/3331): Bundle Chokidar (@lukastaegert) -* [#3343](https://github.com/rollup/rollup/pull/3343): Remove experimentalOptimizeChunks (@lukastaegert) -* [#3346](https://github.com/rollup/rollup/pull/3346): Update minimum required Node version to 10 (@lukastaegert) -* [#3352](https://github.com/rollup/rollup/pull/3352): Remove active deprecations (@lukastaegert) -* [#3361](https://github.com/rollup/rollup/pull/3361): Change writeBundle signature to match generateBundle (@lukastaegert) -* [#3369](https://github.com/rollup/rollup/pull/3369): Avoid empty imports from side-effect-free chunks (@lukastaegert) -* [#3381](https://github.com/rollup/rollup/pull/3381): Rename esm to es everywhere, add systemjs alias (@lukastaegert) -* [#3391](https://github.com/rollup/rollup/pull/3391): Bundle acorn, allow importing Rollup as Node ES module, update dependencies (@lukastaegert) -* [#3393](https://github.com/rollup/rollup/pull/3393): Better error code for name-less umd bundle (@rail44) -* [#3395](https://github.com/rollup/rollup/pull/3395): Remove `@types` dependencies (@lukastaegert) -* [#3423](https://github.com/rollup/rollup/pull/3423): Update magic-string and fix sourcemaps (@lukastaegert) - -## 1.32.1 -*2020-03-06* - -### Bug Fixes -* Handle default export detection for AMD and IIFE externals that do not have a prototype (#3420) -* Handle missing whitespace when the else branch of an if-statement is simplified (#3421) -* Mention the importing module when reporting errors for missing named exports (#3401) -* Add code to warning for missing output.name of IIFE bundles (#3372) - -### Pull Requests -* [#3372](https://github.com/rollup/rollup/pull/3372): Add warning code for missing output.name of IIFE bundle that has export (@rail44) -* [#3401](https://github.com/rollup/rollup/pull/3401): Missing exports errors now print the importing module (@timiyay) -* [#3418](https://github.com/rollup/rollup/pull/3418): Structure lifecycle hooks, add links to build time hooks (@lukastaegert) -* [#3420](https://github.com/rollup/rollup/pull/3420): Update generated code of getInteropBlock() to work with null prototype objects (@jdalton) -* [#3421](https://github.com/rollup/rollup/pull/3421): Avoid invalid code when "else" branch is simplified (@lukastaegert) - -## 1.32.0 -*2020-02-28* - -### Features -* Allow adding plugins on the command line via `--plugin ` (#3379) - -### Pull Requests -* [#3379](https://github.com/rollup/rollup/pull/3379): introduce CLI --plugin support (@kzc) -* [#3390](https://github.com/rollup/rollup/pull/3390): fix typo: this.addWatchfile (@mistlog) -* [#3392](https://github.com/rollup/rollup/pull/3392): Bump codecov from 3.6.1 to 3.6.5 -* [#3404](https://github.com/rollup/rollup/pull/3404): Update resolveFileUrl docs (@jakearchibald) - -## 1.31.1 -*2020-02-14* - -### Bug Fixes -* Make sure errored files are always re-evaluated in watch mode to avoid an issue in the typescript plugin (#3388) - -### Pull Requests -* [#3366](https://github.com/rollup/rollup/pull/3366): Correct spelling minifaction to minification (@VictorHom) -* [#3371](https://github.com/rollup/rollup/pull/3371): Adjust bug template to mention REPL.it (@lukastaegert) -* [#3388](https://github.com/rollup/rollup/pull/3388): Run transform hooks again in watch mode on files that errored (@lukastaegert) - -## 1.31.0 -*2020-01-31* - -### Features -* Always disable tree-shaking for asm.js functions to maintain semantics (#3362) - -### Pull Requests -* [#3362](https://github.com/rollup/rollup/pull/3362): Preserve asm.js code (@lukastaegert) - -## 1.30.1 -*2020-01-27* - -### Bug Fixes -* Do not mistreat static entgry points as dynamic ones when chunking (#3357) -* Resolve a crash when chunking circular dynamic imports (#3357) - -### Pull Requests -* [#3357](https://github.com/rollup/rollup/pull/3357): Resolve issues with circular dynamic entries (@lukastaegert) - -## 1.30.0 -*2020-01-27* - -### Features -* Do not split chunks when dynamically imported modules import modules that are already loaded by all dynamic importers (#3354) -* Add `hoistTransitiveImports` option to disable hoisting imports of static dependencies into entry chunks (#3353) - -### Bug Fixes -* Make sure polyfills are always loaded first when each static entry point contains them as first import (#3354) - -### Pull Requests -* [#3353](https://github.com/rollup/rollup/pull/3353): Add option to avoid hoisting transitive imports (@lukastaegert) -* [#3354](https://github.com/rollup/rollup/pull/3354): Improve chunking algorithm for dynamic imports (@tjenkinson and @lukastaegert) - -## 1.29.1 -*2020-01-21* - -### Bug Fixes -* Avoid crashes for circular reexports when named exports cannot be found (#3350) - -### Pull Requests -* [#3335](https://github.com/rollup/rollup/pull/3335): Fix typo (@robbinworks) -* [#3342](https://github.com/rollup/rollup/pull/3342): Remove ":" from test file names for Windows and update dependencies (@lukastaegert) -* [#3350](https://github.com/rollup/rollup/pull/3350): Properly handle circular reexports (@lukastaegert) - -## 1.29.0 -*2020-01-08* - -### Features -* Enable top-level await by default (#3089) -* Add typings for watch events (#3302) - -### Bug Fixes -* Deconflict files that would conflict only on a case-insensitive OS (#3317) -* Do not fail in certain scenarios where a logical expression inside a sequence expression was being directly included (#3327) - -### Pull Requests -* [#3089](https://github.com/rollup/rollup/pull/3089): Move top-level await out of experimental (@guybedford) -* [#3302](https://github.com/rollup/rollup/pull/3302): Adds type definitions for RollupWatcher events (@NotWoods) -* [#3317](https://github.com/rollup/rollup/pull/3317): Fix module id conflict on a case insensitive OS (@yesmeck) -* [#3327](https://github.com/rollup/rollup/pull/3327): Handle deoptimizations while a node is being included (@lukastaegert) - -## 1.28.0 -*2020-01-04* - -### Features -* Allow piping in stdin via the command line interface (#3312, #3290) -* Allow plugins to mark modules as having syntheticNamedExports for e.g. better CJS interoperability (#3295) -* Ignore variable reassignments in dead code when tree-shaking to remove more unneeded code (#3212) - -### Bug Fixes -* Properly respect tree-shaken code when generating sourcemaps (#3318) - -### Pull Requests -* [#3212](https://github.com/rollup/rollup/pull/3212): Handle assignments in dead code (@tjenkinson) -* [#3290](https://github.com/rollup/rollup/pull/3290): Implement stdin input with optional "-" as the file name (@kzc) -* [#3295](https://github.com/rollup/rollup/pull/3295): Add syntheticNamedExports (@manucorporat) -* [#3300](https://github.com/rollup/rollup/pull/3300): Add note about setting `types` in tsconfig file (@tjenkinson) -* [#3303](https://github.com/rollup/rollup/pull/3303): Use ! to assert not-null in TypeScript (@NotWoods) -* [#3312](https://github.com/rollup/rollup/pull/3312): Implement stdin input (@lukastaegert) -* [#3318](https://github.com/rollup/rollup/pull/3318): Update magic-string and other dependencies (@lukastaegert) - -## 1.27.14 -*2019-12-22* - -### Bug Fixes -* Update references to official rollup plugins in error messages (#3297, #3298) - -### Pull Requests -* [#3286](https://github.com/rollup/rollup/pull/3286): Update link to JavaScript API documentation (@romankaravia) -* [#3294](https://github.com/rollup/rollup/pull/3294): Update deprecated references to the node-resolve plugin in the documentation (@Vlad-Shcherbina) -* [#3297](https://github.com/rollup/rollup/pull/3297): Update references to rollup-plugin-json (@cprecioso) -* [#3298](https://github.com/rollup/rollup/pull/3298): Update references to official rollup plugins (@cprecioso) - -## 1.27.13 -*2019-12-14* - -### Bug Fixes -* Do not truncate environment variable values at the first colon when using the `--environment` option (#3283) - -### Pull Requests -* [#3283](https://github.com/rollup/rollup/pull/3283): Allow environment variables to contain colons (@tlaverdure) - -## 1.27.12 -*2019-12-13* - -### Bug Fixes -* Prevent invalid AMD or SystemJS code when accessing `import.meta` (#3282) - -### Pull Requests -* [#3282](https://github.com/rollup/rollup/pull/3282): Always make "module" available for SystemJS and AMD formats if `import.meta` is accessed directly (@lukastaegert) - -## 1.27.11 -*2019-12-12* - -### Bug Fixes -* Resolve a crash due to an infinite loop (#3280) - -### Pull Requests -* [#3280](https://github.com/rollup/rollup/pull/3280): Prevent infinite deoptimizations (@lukastaegert) - -## 1.27.10 -*2019-12-11* - -### Bug Fixes -* Keep track of function return values in more situations (#3278) - -### Pull Requests -* [#3278](https://github.com/rollup/rollup/pull/3278): Avoid some unnecessary value tracking deoptimizations (@lukastaegert) - -## 1.27.9 -*2019-12-07* - -### Bug Fixes -* Fix an issue where reexports could be missing when preserving modules (#3273) -* Allow turning of color output via NO_COLOR or FORCE_COLOR=0 environment variables (#3272) - -### Pull Requests -* [#3272](https://github.com/rollup/rollup/pull/3272): Support either NO_COLOR or FORCE_COLOR=0 to turn off color (@kikonen) -* [#3273](https://github.com/rollup/rollup/pull/3273): Make sure that indirectly reexported modules also become chunk dependencies when preserving modules(@lukastaegert) - -## 1.27.8 -*2019-12-02* - -### Bug Fixes -* Deoptimize objects when a method is called on them to make sure modifications via "this" are observed (#3266) - -### Pull Requests -* [#3266](https://github.com/rollup/rollup/pull/3266): Workaround for various object literal mutation bugs (@kzc) - -## 1.27.7 -*2019-12-01* - -### Bug Fixes -* Fix a scenario where a reassignments to computed properties were not tracked (#3267) - -### Pull Requests -* [#3267](https://github.com/rollup/rollup/pull/3267): Fix incomplete computed property deoptimization (@lukastaegert) - -## 1.27.6 -*2019-11-30* - -### Bug Fixes -* Use "auto" export mode by default for all modules when preserving modules (#3265) -* Observe "output.exports" when preserving modules and warn for mixed exports if necessary (#3265) - -### Pull Requests -* [#3265](https://github.com/rollup/rollup/pull/3265): Use export mode "auto" by default when preserving modules (@lukastaegert) - -## 1.27.5 -*2019-11-25* - -### Bug Fixes -* Make sure namespaces for inlined dynamic imports are treated as variable accesses when deconflicting (#3256) - -### Pull Requests -* [#3256](https://github.com/rollup/rollup/pull/3256): Avoid name conflicts when inlining dynamic imports nested in functions (@lukastaegert) -* [#3257](https://github.com/rollup/rollup/pull/3257): Update dependencies (@lukastaegert) - -## 1.27.4 -*2019-11-22* - -### Bug Fixes -* Aggregate circular dependency warnings in the CLI (#3249) -* Do not defer non-aggregated handlers in the CLI (#3249) - -### Pull Requests -* [#3249](https://github.com/rollup/rollup/pull/3249): Fix broken Windows CLI tests (@lukastaegert) -* [#3251](https://github.com/rollup/rollup/pull/3251): Add installation as a separate header (@ashrith-kulai) - -## 1.27.3 -*2019-11-20* - -### Bug Fixes -* Provide better warning when empty chunks are created in a code-splitting scenario (#3244) - -### Pull Requests -* [#3244](https://github.com/rollup/rollup/pull/3244): Clearer empty chunk warning (@tjenkinson) - -## 1.27.2 -*2019-11-18* - -### Bug Fixes -* Fix an issue where live bindings were not working correctly when using `+=` in SystemJS (#3242) - -### Pull Requests -* [#3242](https://github.com/rollup/rollup/pull/3242): Export updated assignments when using shorthand update assignment expressions in SystemJS (@lukastaegert) - -## 1.27.1 -*2019-11-18* - -### Bug Fixes -* Fix an issue where code after a switch-statement with removed cases was erroneously not included (#3241) - -### Pull Requests -* [#3237](https://github.com/rollup/rollup/pull/3237): make `acornOptions` optional in `parse()` in docs (@tjenkinson) -* [#3240](https://github.com/rollup/rollup/pull/3240): Update dependencies and fix vulnerability (@lukastaegert) -* [#3241](https://github.com/rollup/rollup/pull/3241): Do not truncate after switch-statement with removed case (@lukastaegert) - -## 1.27.0 -*2019-11-12* - -### Features -* Add support for output-specific plugins (#3218) -* Reenable parallel output processing when using the CLI (#3218) -* Warn if files are emitted that would overwrite previously emitted files (#3218) - -### Bug Fixes -* Do not overwrite files emitted in other builds if outputs are generated in parallel (#3218) - -### Pull Requests -* [#3218](https://github.com/rollup/rollup/pull/3218): Per output plugins (@lukastaegert) - -## 1.26.5 -*2019-11-11* - -### Bug Fixes -* Fix a regression where it was no longer to pass a certain option format to generate (#3223) - -### Pull Requests -* [#3223](https://github.com/rollup/rollup/pull/3223): Allow passing input options to output (@lukastaegert) - -## 1.26.4 -*2019-11-09* - -### Bug Fixes -* Keep watching known files after a plugin error during the initial build (#3219) - -### Pull Requests -* [#3216](https://github.com/rollup/rollup/pull/3216): Fix small typo (@kaisermann) -* [#3217](https://github.com/rollup/rollup/pull/3217): Update dependencies and fix security vulnerability (@lukastaegert) -* [#3219](https://github.com/rollup/rollup/pull/3219): Also recover from plugin errors during the initial build (@lukastaegert) - -## 1.26.3 -*2019-11-02* - -### Bug Fixes -* Work around an incompatibility with rollup-plugin-dts (#3211) - -### Pull Requests -* [#3211](https://github.com/rollup/rollup/pull/3211): Do no fail if the source attribute is `undefined` in an unused named export (@lukastaegert) - -## 1.26.2 -*2019-10-31* - -### Bug Fixes -* Do not create invalid code when using `treeshake: false` and star re-exports (#3209) - -### Pull Requests -* [#3209](https://github.com/rollup/rollup/pull/3209): Also remove export-all declarations when not tree-shaking (@lukastaegert) - -## 1.26.1 -*2019-10-31* - -### Bug Fixes -* Prevent an issue where outputs would overwrite files emitted by other outputs (#3201) -* Do not throw an error if the config file does not have a .js extension (#3204) - -### Pull Requests -* [#3201](https://github.com/rollup/rollup/pull/3201): Make the CLI run generate/output in serial (@marijnh) -* [#3204](https://github.com/rollup/rollup/pull/3204): support all config file extensions (.js,.mjs,...) (@arlac77) - -## 1.26.0 -*2019-10-27* - -### Features -* Only warn when no output is provided for an IIFE bundle but still produce valid code (#3181) -* Support reexporting namespaces as a binding (#3193) -* Switch from hash.js to crypto for hashing in the Node build for better performance and support for very large assets (#3194) - -### Bug Fixes -* Correctly handle chunks reexporting the same namespace as two different bindings (#3193) - -### Pull Requests -* [#3181](https://github.com/rollup/rollup/pull/3181): Remove the need to provide an output name for IIFE bundles (@bterrier) -* [#3193](https://github.com/rollup/rollup/pull/3193): Add support for "export * as name from …" (@lukastaegert) -* [#3194](https://github.com/rollup/rollup/pull/3194): Add support for large assets (> 100 MB) (@SebastianNiemann) - -## 1.25.2 -*2019-10-23* - -### Bug Fixes -* Improve performance of bundled UMD code by adding additional parentheses to enforce eager parsing (#3183) -* Improve types to tolerate passing a Rollup config with multiple outputs to `rollup.rollup` (#3184) - -### Pull Requests -* [#3183](https://github.com/rollup/rollup/pull/3183): Add parentheses to factory function of UMD bundles (@ajihyf) -* [#3184](https://github.com/rollup/rollup/pull/3184): RollupOptions accept output as array (@imcotton) - -## 1.25.1 -*2019-10-20* - -### Bug Fixes -* Handle a situation where code was not included after a switch statement (#3178) -* Handle a situation where code was not included after a do-while loop (#3180) -* Do not fail if different outputs emit the same file (#3175) -* Give access to the original acorn error for parse errors (#3176) - -### Pull Requests -* [#3175](https://github.com/rollup/rollup/pull/3175): Disable errors for duplicate emitted file names (@marijnh) -* [#3176](https://github.com/rollup/rollup/pull/3176): Add original parser error to rollup error; Update tests (@gribnoysup) -* [#3178](https://github.com/rollup/rollup/pull/3178): Fix switch case not being included correctly (@lukastaegert) -* [#3179](https://github.com/rollup/rollup/pull/3179): Update dependencies (@lukastaegert) -* [#3180](https://github.com/rollup/rollup/pull/3180): Handle conditional breaks in do-while loops with unconditional return (@lukastaegert) - -## 1.25.0 -*2019-10-18* - -### Features -* Remove try-catch if there is no side-effect in the try-block (#3166) -* Omit side-effect-free trailing cases in switch-statements (#3166) -* Remove unused labels (#3170) - -### Bug Fixes -* Do not remove code after labeled statements that contain a throw or return if the label is used (#3170) -* Prevent invalid code when expressions are simplified that do not follow a white-space character (#3173) -* Do not remove continue statements inside switch statements (#3166) -* Prevent trailing empty lines when tree-shaking inside switch statements (#3166) - -### Pull Requests -* [#3166](https://github.com/rollup/rollup/pull/3166): Better try statement tree shaking (@lukastaegert) -* [#3170](https://github.com/rollup/rollup/pull/3170): Handle optional control flow in labeled statements, remove unused labels (@lukastaegert) -* [#3173](https://github.com/rollup/rollup/pull/3173): Add missing spaces in certain statements and expressions to avoid invalid code (@lukastaegert) - -## 1.24.0 -*2019-10-15* - -### Features -* Respect `break`, `continue`, `return` and `throw` when tree-shaking to detect dead code (#3153) -* Do treat treat hoisted function declarations as "unknown" when checking for call side-effects (#3153) - -### Bug Fixes -* Make sure that unknown `import.meta` properties produce valid code in SystemJS (#3152) -* Make sure `treeshake.annotations: false` is respected for class instantiation (#3153) -* Check property access side-effects for class instantiation (#3153) -* Do not suppress break statements inside labeled statements (#3153) - -### Pull Requests -* [#3152](https://github.com/rollup/rollup/pull/3152): Allow import.meta.* for systemjs format (@dmail) -* [#3153](https://github.com/rollup/rollup/pull/3153): Get rid of immutable.js and implement tree-shaking for broken control flow (@lukastaegert) - -## 1.23.1 -*2019-10-05* - -### Bug Fixes -* Fix a regression where the node types had a specific minimal version (#3143) - -### Pull Requests -* [#3143](https://github.com/rollup/rollup/pull/3143): Ensure that types packages have star version ranges (@lukastaegert) - -## 1.23.0 -*2019-10-03* - -### Features -* Add placeholders for extensions when preserving modules (#3116) - -### Pull Requests -* [#3116](https://github.com/rollup/rollup/pull/3116): Include extensions in preserveModules output filenames for scriptified assets (@Andarist) -* [#3142](https://github.com/rollup/rollup/pull/3142): Fix typo (@tu4mo) - -## 1.22.0 -*2019-09-29* - -### Features -* Add a new "hidden" sourcemap type that generates the map files but omits the sourcemap comment (#3120) -* Generate more efficient code when using `namespaceToStringTag: true` (#3135) -* Make sure namespace objects do not have a prototype (#3136) - -### Bug Fixes -* Do not ignore side-effectful iterators by always preserving for..of loops for now (#3132) -* Make sure `--context` is observed as a CLI option (#3134) -* Do not require specific versions for @types dependencies (#3131) - -### Pull Requests -* [#3120](https://github.com/rollup/rollup/pull/3120): Generate sourcemaps but omit the comment (@rohitmohan96) -* [#3131](https://github.com/rollup/rollup/pull/3131): Use asterisk for @types/* dependencies (@frenzzy) -* [#3132](https://github.com/rollup/rollup/pull/3132): Preserve empty for...of loops (@imatlopez) -* [#3133](https://github.com/rollup/rollup/pull/3133): Update dependencies (@lukastaegert) -* [#3134](https://github.com/rollup/rollup/pull/3134): Wire up --context CLI flag (@tchetwin) -* [#3135](https://github.com/rollup/rollup/pull/3135): Remove Symbol polyfill in module namespaces (@mkubilayk) -* [#3136](https://github.com/rollup/rollup/pull/3136): Set null prototype on namespace objects (@rpamely) - -## 1.21.4 -*2019-09-16* - -### Bug Fixes -* Recognize common browser globals (#3117) -* Do not treat "typeof " as a side-effect (#3117) - -### Pull Requests -* [#3117](https://github.com/rollup/rollup/pull/3117): Add browser globals to known globals and prevent "typeof" side-effects (@lukastaegert) - -## 1.21.3 -*2019-09-14* - -### Bug Fixes -* Fix a regression where modifying a watched file did not trigger a rebuild (#3112) - -### Pull Requests -* [#3112](https://github.com/rollup/rollup/pull/3112): Fix .addWatchFile() dependencies failing to invalidate in watch mode (@tivac) - -## 1.21.2 -*2019-09-09* - -### Bug Fixes -* Fix wrong deprecation message to direct to `this.emitFile` instead of `this.emitAsset` - -## 1.21.1 -*2019-09-09* - -### Bug Fixes -* Allow legacy plugins to still add assets directly to the bundle object (#3105) - -### Pull Requests -* [#3105](https://github.com/rollup/rollup/pull/3105): Allow legacy plugins to still add assets directly to the bundle object (@lukastaegert) - -## 1.21.0 -*2019-09-08* - -### Features -* Respect `output.entryFileNames` when preserving modules (#3088) -* Make accessing unknown globals a side-effect unless this is deactivated via `treeshake.unknownGlobalSideEffects` (#3068) -* Respect global objects when checking for pure global functions (#3068) -* Introduce a `type` to more easily distinguish chunks and assets in the output bundle (#3080) - -### Bug Fixes -* Recover in watch mode when the initial build fails (#3081) -* Make sure `output.strict` is respected for SystemJS output (#3101) - -### Pull Requests -* [#3068](https://github.com/rollup/rollup/pull/3068): Make accessing unknown globals a side-effect (@lukastaegert) -* [#3080](https://github.com/rollup/rollup/pull/3080): OutputBundle Tagged union with 'type = chunk|asset' (@askbeka) -* [#3081](https://github.com/rollup/rollup/pull/3081): Watch files onbuild, even if build fails (@mhkeller) -* [#3088](https://github.com/rollup/rollup/pull/3088): Add support for entryFileNames pattern used in combination with preserveModules option (@Andarist) -* [#3101](https://github.com/rollup/rollup/pull/3101): Remove 'use strict'; from systemjs when strict=false (@askbeka) - -## 1.20.3 -*2019-08-28* - -### Bug Fixes -* Make sure file hashes change when a change of the naming pattern leads to a file name change of a dependency (#3083) -* Fix several issues where reexporting an external "default" export could lead to invalid or incorrect code (#3084) - -### Pull Requests -* [#3078](https://github.com/rollup/rollup/pull/3078): Add github actions workflow config for windows (@shellscape) -* [#3083](https://github.com/rollup/rollup/pull/3083): Properly reflect dependency file names in hash (@lukastaegert) -* [#3084](https://github.com/rollup/rollup/pull/3084): Fix "default" reexport issues in non ESM/System formats (@lukastaegert) - -## 1.20.2 -*2019-08-25* - -### Bug Fixes -* Avoid an issue where circular namespace reexports would crash Rollup (#3074) - -### Pull Requests -* [#3077](https://github.com/rollup/rollup/pull/3077): Handle namespaces that reexport themselves (@lukastaegert) - -## 1.20.1 -*2019-08-22* - -### Bug Fixes -* Fix an issue where variable names inside dynamic import expressions were not rendered correctly (#3073) -* Fix type definition to allow a single watcher config as well as an array (#3074) - -### Pull Requests -* [#3073](https://github.com/rollup/rollup/pull/3073): Fix wrong variable name in import expression (@lukastaegert) -* [#3074](https://github.com/rollup/rollup/pull/3074): Fixes type definition on watch and Watcher constructor (@MicahZoltu) - -## 1.20.0 -*2019-08-21* - -### Features -* Add augmentChunkHash plugin hook to be able to reflect changes in renderChunk in the chunk hash (#2921) - -### Bug Fixes -* Do not mutate the acorn options object (#3051) -* Make sure the order of emitted chunks always reflects the order in which they were emitted (#3055) -* Do not hang when there are strings containing comment-like syntax in some scenarios (#3069) - -### Pull Requests -* [#2921](https://github.com/rollup/rollup/pull/2921): Add augmentChunkHash plugin hook (@isidrok) -* [#2995](https://github.com/rollup/rollup/pull/2995): Add info on installing locally to docs (@mesqueeb) -* [#3037](https://github.com/rollup/rollup/pull/3037): Refresh pull request labels (@shellscape) -* [#3048](https://github.com/rollup/rollup/pull/3048): Document ROLLUP_WATCH environment variable (@shellscape) -* [#3051](https://github.com/rollup/rollup/pull/3051): Avoid changes to the original options (.acorn) object (@LongTengDao) -* [#3052](https://github.com/rollup/rollup/pull/3052): Minor refactoring: Remove one try-catch (@KSXGitHub) -* [#3053](https://github.com/rollup/rollup/pull/3053): Refactor to use async-await in more places (@KSXGitHub) -* [#3055](https://github.com/rollup/rollup/pull/3055): Provide consistent chunking via a consistent order of entry modules when emitting chunks (@lukastaegert) -* [#3058](https://github.com/rollup/rollup/pull/3058): Remove acorn-bigint and acorn-dynamic-import from bundle (@LongTengDao) -* [#3061](https://github.com/rollup/rollup/pull/3061): Update to acorn@7 (@lukastaegert) -* [#3063](https://github.com/rollup/rollup/pull/3063): Auto-generate license file (@lukastaegert) -* [#3069](https://github.com/rollup/rollup/pull/3069): Prevent infinite loop when scanning for line-breaks and there are comment-like strings (@lukastaegert) - -## 1.19.4 -*2019-08-07* - -### Bug Fixes -* Prevent invalid code when exporting an external namespace (#3034) -* Prevent invalid or non-equivalent code when simplifying expressions in return and throw statements (#3035) - -### Pull Requests -* [#3034](https://github.com/rollup/rollup/pull/3034): Avoid generating .* as export (@LongTengDao) -* [#3035](https://github.com/rollup/rollup/pull/3035): Prevent ASI errors for conditional expressions (@lukastaegert) -* [#3036](https://github.com/rollup/rollup/pull/3036): Fix documents to use https, not http (@giraffate) - -## 1.19.3 -*2019-08-06* - -### Bug Fixes -* Fix wrong URLs in error messages (#3033) - -### Pull Requests -* [#3033](https://github.com/rollup/rollup/pull/3033): Fix wrong URLs in error messages (@giraffate) - -## 1.19.2 -*2019-08-05* - -### Bug Fixes -* Add bin file to package - -## 1.19.1 -*2019-08-05* - -### Bug Fixes -* Remove wrong extension in package.json file (#3031) - -### Pull Requests -* [#3031](https://github.com/rollup/rollup/pull/3031): Fix wrong extension (@lukastaegert) - -## 1.19.0 -*2019-08-05* - -### Features -* Implement a new unified file emission API for assets and chunks with support for explicit file names (#2999) -* Use the id of the last module in a chunk as base for the chunk name if no better name is available (#3025) -* Use the id of the last module in a chunk as base for the variable name of a chunk in some formats if no better name is available (#2999) - -### Bug Fixes -* Do not produce invalid variable names if an empty name is chosen for a virtual module (#3026) -* Fix an issue where a module variable name would conflict with a local variable name in some formats (#3020) - -### Pull Requests -* [#2999](https://github.com/rollup/rollup/pull/2999): Unified file emission api (@lukastaegert) -* [#3020](https://github.com/rollup/rollup/pull/3020): Switch to a code-splitting build and update dependencies (@lukastaegert) -* [#3025](https://github.com/rollup/rollup/pull/3025): Use id of last module in chunk as name base for auto-generated chunks (@lukastaegert) -* [#3026](https://github.com/rollup/rollup/pull/3026): Avoid variable from empty module name be empty (@LongTengDao) - -## 1.18.0 -*2019-08-01* - -### Features -* Add `externalLiveBindings: false` option to optimize code when live bindings are not needed (#3010) - -### Pull Requests -* [#2997](https://github.com/rollup/rollup/pull/2997): Integrate coverage into CI setup (@lukastaegert) -* [#2998](https://github.com/rollup/rollup/pull/2998): Update readme badges (@lukastaegert) -* [#3010](https://github.com/rollup/rollup/pull/3010): Add option to prevent code for external live bindings (@lukastaegert) - -## 1.17.0 -*2019-07-15* - -### Features -* Allow plugins to access current combined sourcemap in transform hook for coverage instrumentation (#2993) - -### Pull Requests -* [#2987](https://github.com/rollup/rollup/pull/2987): Fix code fences for link (@johanholmerin) -* [#2989](https://github.com/rollup/rollup/pull/2989): Bump lodash from 4.17.11 to 4.17.14 (@dependabot) -* [#2993](https://github.com/rollup/rollup/pull/2993): Add getCombinedSourceMap in transform plugin context (@billowz) - -## 1.16.7 -*2019-07-09* - -### Bug Fixes -* Fix an issue where exported import.meta properties would lead to invalid code (#2986) - -### Pull Requests -* [#2985](https://github.com/rollup/rollup/pull/2985): Improve sourcemap types (@jridgewell) -* [#2986](https://github.com/rollup/rollup/pull/2986): Only overwrite content when resolving import.meta properties (@lukastaegert) - -## 1.16.6 -*2019-07-04* - -### Bug Fixes -* Do not pass undefined to resolveDynamicImport for unresolvable template literals (#2984) - -### Pull Requests -* [#2984](https://github.com/rollup/rollup/pull/2984): Always forward AST nodes for unresolvable dynamic imports (@lukastaegert) - -## 1.16.5 -*2019-07-04* - -### Bug Fixes -* onwarn should still be called when --silent is used (#2982) -* Properly clean up watchers for files that are deleted between builds (#2982) - -### Pull Requests -* [#2981](https://github.com/rollup/rollup/pull/2981): Do not skip onwarn handler when --silent is used (@lukastaegert) -* [#2982](https://github.com/rollup/rollup/pull/2982): Make tests run on Node 12, fix watcher cleanup issue (@lukastaegert) - -## 1.16.4 -*2019-07-02* - -### Bug Fixes -* Do not show a TypeScript error when providing a location as number to this.warn and this.error (#2974) -* Use the correct TypeScript type for Sourcemap.version (#2976) - -### Pull Requests -* [#2965](https://github.com/rollup/rollup/pull/2965): Use async readFile in getRollupDefaultPlugin (@kaksmet) -* [#2974](https://github.com/rollup/rollup/pull/2974): Align TS types, docs and implementation for this.warn and this.error (@lukastaegert) -* [#2976](https://github.com/rollup/rollup/pull/2976): Fix sourcemap type and update dependencies (@lukastaegert) - -## 1.16.3 -*2019-06-29* - -### Bug Fixes -* Prevent name conflicts with unused function parameters (#2972) - -### Pull Requests -* [#2972](https://github.com/rollup/rollup/pull/2972): Deconflict unused parameters (@lukastaegert) - -## 1.16.2 -*2019-06-22* - -### Bug Fixes -* Properly wrap dynamic imports in Promises that can be caught when generating CJS output (#2958) - -### Pull Requests -* [#2958](https://github.com/rollup/rollup/pull/2958): Make sure errors from dynamic imports can be caught (@lukastaegert) - -## 1.16.1 -*2019-06-21* - -### Pull Requests -* [#2956](https://github.com/rollup/rollup/pull/2956): Add missing CLI docs for strictDeprecations (@lukastaegert) - -## 1.16.0 -*2019-06-21* - -### Features -* Add strictDeprecations option to throw when currently or upcoming deprecated features are used (#2945) -* Keep annotations and comments when simplifying logical and conditional expressions (#2955) - -### Bug Fixes -* Generate proper namespace objects when dynamically importing external dependencies for AMD or CJS formats (#2954) -* Fix dynamically imported variables not being resolved correctly when importing from an entry chunk with only a default export (#2954) -* Do not reexport default when reexporting a namespace (#2954) - -### Pull Requests -* [#2945](https://github.com/rollup/rollup/pull/2945): Add option to handle use of features marked for deprecation as errors (@lukastaegert) -* [#2954](https://github.com/rollup/rollup/pull/2954): Improve dynamic import interop (@lukastaegert) -* [#2955](https://github.com/rollup/rollup/pull/2955): Keep annotations and comments when simplifying logical and conditional expressions (@lukastaegert) - -## 1.15.6 -*2019-06-16* - -### Bug Fixes -* No longer use an alternate screen in watch mode to allow scrolling (#2942) -* Prioritize non-external imports over external ones when resolving conflicting namespace re-exports (#2893) - -### Pull Requests -* [#2893](https://github.com/rollup/rollup/pull/2893): Improve handling of conflicting namespace exports (@aleclarson) -* [#2942](https://github.com/rollup/rollup/pull/2942): Get rid of alternate screen and simplify screen clearing (@lukastaegert) - -## 1.15.5 -*2019-06-14* - -### Bug Fixes -* Do not include any comments for completely tree-shaken files so that `renderedLength === 0` is a reliable check (#2940) -* Do not cause type errors when returning `null` from `resolveId` (#2941) - -### Pull Requests -* [#2940](https://github.com/rollup/rollup/pull/2940): Completely omit files that do not have any included statements (@lukastaegert) -* [#2941](https://github.com/rollup/rollup/pull/2941): Explicitly allow null as return value for various hooks (@lukastaegert) - -## 1.15.4 -*2019-06-14* - -### Bug Fixes -* Improve how asset and chunk URLs are resolved for UMD, IIFE and CJS output (#2937) - -### Pull Requests -* [#2937](https://github.com/rollup/rollup/pull/2937): Fix URL resolution to work when the current script contains query parameters (@lukastaegert) - -## 1.15.3 -*2019-06-13* - -### Bug Fixes -* Always reemit assets and chunks from cached transform hooks (#2936) - -### Pull Requests -* [#2936](https://github.com/rollup/rollup/pull/2936): Fix repeated re-emission of files emitted from a transform hook (@lukastaegert) - -## 1.15.2 -*2019-06-13* - -### Bug Fixes -* Make sure chunks emitted from transform hooks are also emitted for incremental builds in watch mode (#2933) - -### Pull Requests -* [#2933](https://github.com/rollup/rollup/pull/2933): Reemit chunks emitted from transform hooks (@lukastaegert) - -## 1.15.1 -*2019-06-11* - -### Bug Fixes -* Do not fail when reexporting variables in dynamic entry points from other chunks (#2928) - -### Pull Requests -* [#2928](https://github.com/rollup/rollup/pull/2928): Handle reexports from dynamic entries across chunk (@lukastaegert) - -## 1.15.0 -*2019-06-11* - -### Features -* Tone down try-catch deoptimization while maintaining polyfill support (#2918) - -### Bug Fixes -* Handle feature detection with "typeof" for regular expressios (#2916) -* Deoptimize `'' + variable'` type coercion as expression statement for feature detection (#2917) -* Always observe argument side-effects when tree-shaking (#2924) - -### Pull Requests -* [#2916](https://github.com/rollup/rollup/pull/2916): Deoptimize typeof for regular expression literals to better support es6-shim (@lukastaegert) -* [#2917](https://github.com/rollup/rollup/pull/2917): Support implicit type coercion errors in es5-shim (@lukastaegert) -* [#2918](https://github.com/rollup/rollup/pull/2918): Deoptimize try-catch less radically (@lukastaegert) -* [#2924](https://github.com/rollup/rollup/pull/2924): Do not tree-shake arguments with side-effects (@lukastaegert) - -## 1.14.6 -*2019-06-10* - -### Bug Fixes -* Fix an issue where call arguments were not included in try statements (#2914) - -### Pull Requests -* [#2914](https://github.com/rollup/rollup/pull/2914): Properly include try statements for each pass when deoptimization is deactivated (@lukastaegert) - -## 1.14.5 -*2019-06-09* - -### Bug Fixes -* Keep external ids unmodified when using the object form of resolveId (#2907) -* Cache dynamic import resolutions when using Rollup cache (#2908) -* Keep all necessary parentheses when tree-shaking call arguments (#2911) - -### Pull Requests -* [#2906](https://github.com/rollup/rollup/pull/2906): Update dependencies (@lukastaegert) -* [#2907](https://github.com/rollup/rollup/pull/2907): Do not renormalize external ids when using the object form (@lukastaegert) -* [#2908](https://github.com/rollup/rollup/pull/2908): Cache dynamic ids if possible (@lukastaegert) -* [#2911](https://github.com/rollup/rollup/pull/2911): Fix treeshaken parameters around parentheses (@manucorporat) - -## 1.14.4 -*2019-06-07* - -### Bug Fixes -* Do not omit external re-exports for `moduleSideEffects: false` (#2905) - -### Pull Requests -* [#2905](https://github.com/rollup/rollup/pull/2905): Make sure external re-exports are included for moduleSideEffects: false (@lukastaegert) - -## 1.14.3 -*2019-06-06* - -### Bug Fixes -* Generate correct external imports when importing from a directory that would be above the root of the current working directory (#2902) - -### Pull Requests -* [#2902](https://github.com/rollup/rollup/pull/2902): Use browser relative path algorithm for chunks (@lukastaegert) - -## 1.14.2 -*2019-06-05* - -### Bug Fixes -* Prevent unnecessary inclusion of external namespace import in certain situations (#2900) - -### Pull Requests -* [#2900](https://github.com/rollup/rollup/pull/2900): Handle early bind for member expressions (@lukastaegert) - -## 1.14.1 -*2019-06-05* - -### Bug Fixes -* Fix an issue where try-statements were not included properly when a variable declared inside the statement was accessed outside it (#2898) -* Fix an issue where `await` expressions were not included properly (#2899) - -### Pull Requests -* [#2898](https://github.com/rollup/rollup/pull/2898): Properly include try-catch-statements even if they have already been included in some way (@lukastaegert) -* [#2899](https://github.com/rollup/rollup/pull/2899): Fix unintended early return in await inclusion handling (@lukastaegert) - -## 1.14.0 -*2019-06-05* - -### Features -* Deoptimize code inside and called from try-statements for feature detection (#2892) -* Tree-shake unused call arguments (#2892) - -### Pull Requests -* [#2892](https://github.com/rollup/rollup/pull/2892): Implement try-statement-deoptimization for feature detection, tree-shake unused arguments (@lukastaegert) - - -## 1.13.1 -*2019-06-01* - -### Bug Fixes -* Avoid conflicts between top-level module, require etc. and CommonJS runtimes (#2889) - -### Pull Requests -* [#2888](https://github.com/rollup/rollup/pull/2888): Enable full TypeScript strict mode (@lukastaegert) -* [#2889](https://github.com/rollup/rollup/pull/2889): Protect all module globals for CJS output from being redefined (@lukastaegert) - -## 1.13.0 -*2019-05-31* - -### Features -* Omit `exports` and `module` from SystemJS wrapper if possible (#2880) -* Try to use the first letters of names when mangling exports (#2885) - -### Bug Fixes -* Avoid conflicts with local variables when using format specific globals to render dynamic imports and file URLs (#2880) -* Do not produce undefined reexports when reexporting from entry points (#2885) - -### Pull Requests -* [#2880](https://github.com/rollup/rollup/pull/2880): Deconflict global variables used inside format-specific code (@lukastaegert) -* [#2885](https://github.com/rollup/rollup/pull/2885): Do not produce undefined reexports when reexporting from entry points and refactor chunk linking (@lukastaegert) - -## 1.12.5 -*2019-05-30* - -### Pull Requests -* [#2884](https://github.com/rollup/rollup/pull/2884): Update pluginutils for new micormatch and reduced bundle size (@lukastaegert) - -## 1.12.4 -*2019-05-27* - -### Bug Fixes -* Show correct error stack trace for errors throw in "load" hooks (#2871) - -### Pull Requests -* [#2875](https://github.com/rollup/rollup/pull/2875): Mention subfolders in docs (@lukastaegert) -* [#2871](https://github.com/rollup/rollup/pull/2871): Reserve error stack information (@LongTengDao) - -## 1.12.3 -*2019-05-19* - -### Bug Fixes -* Prevent duplicate imports when exports are reexported as default exports (#2866) - -### Pull Requests -* [#2755](https://github.com/rollup/rollup/pull/2755): Enable TypeScript strictNullChecks (@edsrzf) -* [#2866](https://github.com/rollup/rollup/pull/2866): Properly deduplicate reexported default exports (@lukastaegert) - -## 1.12.2 -*2019-05-17* - -### Bug Fixes -* Do not fail when using clearScreen:false in watchMode (#2858) -* Properly resolve star reexports when preserving modules (#2860) - -### Pull Requests -* [#2858](https://github.com/rollup/rollup/pull/2858): Declare processConfigsErr before use (@humphd) -* [#2860](https://github.com/rollup/rollup/pull/2860): Keep nested exports with preserveModules (@TomCaserta) -* [#2864](https://github.com/rollup/rollup/pull/2864): Cache transitive reexport detection (@lukastaegert) - -## 1.12.1 -*2019-05-16* - -### Bug Fixes -* Extend file name sanitation to also replace "?" and "*" e.g. when preserving modules with the updated commonjs plugin (#2860) -* Do not ignore module transformer that return an empty string (#2861) - -### Pull Requests -* [#2860](https://github.com/rollup/rollup/pull/2860): Update to latest plugins and extend file name sanitation (@lukastaegert) -* [#2861](https://github.com/rollup/rollup/pull/2861): Allow transformers to return an empty string (@lukastaegert) - -## 1.12.0 -*2019-05-15* - -### Features -* Add `treeshake.moduleSideEffects` option to allow removing empty imports without a side-effect check (#2844) -* Extend plugin API to allow marking modules as side-effect-free (#2844) -* Extend `this.resolve` plugin context function with an option to skip the `resolveId` hook of the calling plugin (#2844) -* Add `isEntry` flag to `this.getModuleInfo` plugin context function (#2844) -* Distribute Rollup as optimized ES2015 code (#2851) - -### Pull Requests -* [#2844](https://github.com/rollup/rollup/pull/2844): Add options and hooks to control module side effects (@lukastaegert) -* [#2851](https://github.com/rollup/rollup/pull/2851): Switch to ES2015 output (@lukastaegert) - -## 1.11.3 -*2019-05-05* - -### Bug Fixes -* Quote es3 keywords in namespace objects (#2825) - -### Pull Requests -* [#2825](https://github.com/rollup/rollup/pull/2825): Add es3 support for namespace object import (@sormy) - -## 1.11.2 -*2019-05-04* - -### Bug Fixes -* Prevent a crash when handling circular namespace exports (#2836) - -### Pull Requests -* [#2836](https://github.com/rollup/rollup/pull/2836): Make sure circular `export * from X` does not stack overflow (@Swatinem) - -## 1.11.1 -*2019-05-04* - -### Bug Fixes -* Fix an issue where rendered exports were reported as "removed" in the bundle information (#2835) - -### Pull Requests -* [#2835](https://github.com/rollup/rollup/pull/2835): Fix `removedExports` to correctly track the exported item (@Swatinem) - -## 1.11.0 -*2019-05-03* - -### Features -* Add `emitChunk` plugin context function to emit additional entry chunks that can be referenced from the code (#2809) -* Allow `manualChunks` to be a function (#2831) -* Omit `.js` extensions in AMD imports to make sure an AMD `baseUrl` would work (#2809) -* Automatically use the name of the imported module as a base for dynamically imported chunks (#2809) -* Add `resolveFileUrl` plugin hook to replace `resolveAssetUrl` and handle emitted chunks as well (#2809) -* Add `resolve` plugin hook to replace `resolveId` and `isExternal` that returns an object (#2829) -* Allow `resolveDynamicImport` to return an `{id, external}` object to also resolve unresolvable dynamic imports to a module (#2829) - -### Bug Fixes -* Do not create invalid code if a dynamic import contains nothing but reexports (#2809) -* Do not fail if modules that define a manual chunk depend on each other (#2809) -* Do not fail if a module that defines a manual chunk is the dependency of a module defining a different manual chunk (#2809) -* No longer fail for unnamed duplicate entry points but combine them (#2809) -* Always return `string | null` from `this.resolveId` even if some `resolveId` hooks return objects (#2829) -* Show proper warnings when `resolveDynamicImport` resolves to a non-external module that does not exist (#2829) - -### Pull Requests -* [#2809](https://github.com/rollup/rollup/pull/2809): Add hook for dynamic entry chunk emission (@lukastaegert) -* [#2821](https://github.com/rollup/rollup/pull/2821): Fix syntax error in documentation (@FFxSquall) -* [#2829](https://github.com/rollup/rollup/pull/2829): Improve id resolution (@lukastaegert) -* [#2831](https://github.com/rollup/rollup/pull/2831): Allow manualChunks to be a function (@lukastaegert) -* [#2832](https://github.com/rollup/rollup/pull/2832): Improve `generateBundle` documentation (@lukastaegert) -* [#2833](https://github.com/rollup/rollup/pull/2833): Update dependencies (@lukastaegert) - -## 1.10.1 -*2019-04-19* - -### Bug Fixes -* Invalid options.format values will now trigger a helpful error (#2813) - -### Pull Requests -* [#2812](https://github.com/rollup/rollup/pull/2812): Minor documentation update (@dnalborczyk) -* [#2813](https://github.com/rollup/rollup/pull/2813): Catch invalid options.format values (@marijnh) -* [#2816](https://github.com/rollup/rollup/pull/2816): Update all dependencies to fix security issues (@lukastaegert) - -## 1.10.0 -*2019-04-11* - -### Features -* Improve generated code to polyfill `import.meta.url` (#2785) -* Add plugin hook to configure handling of `import.meta` (#2785) -* Improve generated code when accessing URLs of emitted assets (#2796) -* Add plugin hook to configure the generated code when accessing URLs of emitted assets (#2796) - -### Bug Fixes -* No longer resolve assets to their parent URL in some cases (#2796) - -### Pull Requests -* [#2785](https://github.com/rollup/rollup/pull/2785): Refactor handling of import.meta.url and add option to configure behaviour (@lukastaegert) -* [#2796](https://github.com/rollup/rollup/pull/2796): Improve and fix asset emission (@lukastaegert) - -## 1.9.3 -*2019-04-10* - -### Bug Fixes -* Simplify return expressions that are evaluated before the surrounding function is bound (#2803) - -### Pull Requests -* [#2803](https://github.com/rollup/rollup/pull/2803): Handle out-of-order binding of identifiers to improve tree-shaking (@lukastaegert) - -## 1.9.2 -*2019-04-10* - -### Bug Fixes -* Allowing replacing `output.file` with `output.dir` in the `outputOptions` hook (#2802) - -### Pull Requests -* [#2802](https://github.com/rollup/rollup/pull/2802): Observe modified output options in bundle.write (@lukastaegert) - -## 1.9.1 -*2019-04-10* - -### Bug Fixes -* Make sure inline comments in dynamic imports are preserved (#2797) - -### Pull Requests -* [#2797](https://github.com/rollup/rollup/pull/2797): Emit inline comments inside dynamic import (@manucorporat) - -## 1.9.0 -*2019-04-05* - -### Features -* Add built-in support for bigint (#2789) - -### Pull Requests -* [#2789](https://github.com/rollup/rollup/pull/2789): Ship with bigint support built-in (@danielgindi) -* [#2791](https://github.com/rollup/rollup/pull/2791): Use shared extractAssignedNames from rollup-pluginutils (@lukastaegert) -* [#2792](https://github.com/rollup/rollup/pull/2792): Test that rollup-plugin-commonjs works with preserveModules (@lukastaegert) - -## 1.8.0 -*2019-04-02* - -### Features -* Support `module` as alias for `esm` and `commonjs` for `cjs` to match Node (#2783) - -### Pull Requests -* [#2782](https://github.com/rollup/rollup/pull/2782): Inline interopDefault in config loading (@guybedford) -* [#2783](https://github.com/rollup/rollup/pull/2783): Support Node-style format aliases (@guybedford) - -## 1.7.4 -*2019-03-28* - -### Bug Fixes -* Improve TypeScript type of the treeshaking options (#2779) - -### Pull Requests -* [#2779](https://github.com/rollup/rollup/pull/2779): Make all properties in TreeshakingOptions optional (@ndelangen) - -## 1.7.3 -*2019-03-24* - -### Bug Fixes -* Use getters when re-exporting live-bindings (#2765) - -### Pull Requests -* [#2765](https://github.com/rollup/rollup/pull/2765): Support exporting live-bindings from other chunks or external dependencies (@lukastaegert) - -## 1.7.2 -*2019-03-24* - -### Bug Fixes -* Make sure relative external ids are resolved correctly (#2774) - -### Pull Requests -* [#2774](https://github.com/rollup/rollup/pull/2774): Resolve relative external ids (@lukastaegert) - -## 1.7.1 -*2019-03-24* - -### Bug Fixes -* Prevent invalid code when exporting several hundred identifiers from a chunk (#2768) -* Do not wrongly deconflict labels (#2776) - -### Pull Requests -* [#2768](https://github.com/rollup/rollup/pull/2768): Sanitize shortened internal export names (@lukastaegert) -* [#2769](https://github.com/rollup/rollup/pull/2769): Update dependencies and fix security issue (@lukastaegert) -* [#2776](https://github.com/rollup/rollup/pull/2776): Do not treat break labels as identifiers (@lukastaegert) - -## 1.7.0 -*2019-03-20* - -### Features -* Sort chunk exports by name for greater consistency (#2757) - -### Bug Fixes -* Fix a situation where tree-shakeable code would not be removed in an indeterminate manner (#2757) - -### Pull Requests -* [#2757](https://github.com/rollup/rollup/pull/2757): Sort modules before binding, sort exports (@lukastaegert) - -## 1.6.1 -*2019-03-20* - -### Bug Fixes -* Avoid name clashes of unused default exports when tree-shaking is false (#2758) -* Do not crash when generating SystemJS bundles containing array patterns with member expressions (#2760) - -### Pull Requests -* [#2758](https://github.com/rollup/rollup/pull/2758): Make sure unused default exports are deconflicted when tree-shaking is false (@lukastaegert) -* [#2760](https://github.com/rollup/rollup/pull/2760): Handle member expressions in array patterns (@lukastaegert) - -## 1.6.0 -*2019-03-08* - -### Features -* Add plugin hook to modify output options (#2736) - -### Pull Requests -* [#2736](https://github.com/rollup/rollup/pull/2736): Add hook for modifying OutputOptions (@Comandeer) - -## 1.5.0 -*2019-03-07* - -### Features -* Allow resolving to a different id while marking it as external at the same time (#2734) - -### Pull Requests -* [#2734](https://github.com/rollup/rollup/pull/2734): Allow resolveId to return an object (@lukastaegert) - -## 1.4.2 -*2019-03-07* - -### Bug Fixes -* Respect variable identity of exports when hashing (#2741) -* Resolve a situations where a variable was imported twice with the same name (#2737) - -### Pull Requests -* [#2741](https://github.com/rollup/rollup/pull/2741): Fix hashing when different variable are exported using the same name (@lukastaegert) -* [#2737](https://github.com/rollup/rollup/pull/2737): Fix duplicate imports with conflicting names (@lukastaegert) - -## 1.4.1 -*2019-03-04* - -### Bug Fixes -* Do not treat the import target "" as external by default (#2733) - -### Pull Requests -* [#2733](https://github.com/rollup/rollup/pull/2733): Do not treat the import target "" as external by default (@LongTengDao) - -## 1.4.0 -*2019-03-01* - -### Features -* Add option to change the name of the dynamic import function to allow polyfilling it (#2723) - -### Pull Requests -* [#2723](https://github.com/rollup/rollup/pull/2723): Add dynamicImportFunction option (@keithamus) - -## 1.3.3 -*2019-03-01* - -### Bug Fixes -* Fix performance regression when handling long chains of calls to property methods (#2732) - -### Pull Requests -* [#2730](https://github.com/rollup/rollup/pull/2730): Order types, interfaces, classes, and object members (@lukastaegert) -* [#2732](https://github.com/rollup/rollup/pull/2732): Take chunk export mode into account when reexporting default (@lukastaegert) - -## 1.3.2 -*2019-02-27* - -### Bug Fixes -* Allow ids of default exported classes to be exported separately (#2728) - -### Pull Requests -* [#2728](https://github.com/rollup/rollup/pull/2728): Update dependencies (@lukastaegert) - -## 1.3.1 -*2019-02-27* - -### Bug Fixes -* Correctly reexport the default export from entry chunks (#2727) - -### Pull Requests -* [#2727](https://github.com/rollup/rollup/pull/2727): Take chunk export mode into account when reexporting default (@lukastaegert) - -## 1.3.0 -*2019-02-26* - -### Features -* Treeshake call expressions prefixed with UglifyJS style `@__PURE__` annotations (#2429) - -### Pull Requests -* [#2429](https://github.com/rollup/rollup/pull/2429): Add support for /*#__PURE__*/ comments (@conartist6 and @lukastaegert) - -## 1.2.5 -*2019-02-26* - -### Bug Fixes -* Store external ids reported by plugins in watch mode (#2718) - -### Pull Requests -* [#2718](https://github.com/rollup/rollup/pull/2718): Incremental external (@andreas-karlsson) - -## 1.2.4 -*2019-02-26* - -### Bug Fixes -* Fix an issue where a variable was imported twice under the same name (#2715) - -### Pull Requests -* [#2715](https://github.com/rollup/rollup/pull/2715): Deduplicate imports referencing default exports and their original variables (@lukastaegert) - -## 1.2.3 -*2019-02-23* - -### Bug Fixes -* Use correct path when rendering dynamic imports where the entry module is empty (#2714) - -### Pull Requests -* [#2714](https://github.com/rollup/rollup/pull/2714): Properly render dynamic imports when imported module is empty (@lukastaegert) - -## 1.2.2 -*2019-02-19* - -### Bug Fixes -* Fix wrong external imports when using the `paths` options only for some outputs (#2706) - -### Pull Requests -* [#2706](https://github.com/rollup/rollup/pull/2706): Always recreate paths for external modules (@lukastaegert) - -## 1.2.1 -*2019-02-17* - -### Bug Fixes -* Fix ESM version of Rollup (#2705) - -### Pull Requests -* [#2705](https://github.com/rollup/rollup/pull/2705): Fix ESM version of Rollup (@lukastaegert) - -## 1.2.0 -*2019-02-17* - -### Features -* Fewer renamed variables due to a completely reimplemented deconflicting logic (#2689) - -### Bug Fixes -* Respect rendered and tree-shaken exports when determining chunk hashes (#2695) -* Fix an error when dynamic imports end up in the same chunk as one of their importees (#2677) -* Do not generate invalid code when expressions containing IIFEs are simplified (#2696) -* Do not throw an error when more than ten bundles are watched (#2700) -* Treat re-exported globals in a spec-compliant way (#2691) -* Fix issues related to wrongly renamed variables (#2689) -* Do not throw an error if config files contain non-default exports (#2673) -* Improve type of `RollupOutput.output` to guarantee at least one chunk (#2679) - -### Pull Requests -* [#2673](https://github.com/rollup/rollup/pull/2673): Allow config files to have non-default exports (@swansontec) -* [#2677](https://github.com/rollup/rollup/pull/2677): Prevent final resolution and facade creation for inlined dynamic imports (@Rich-Harris and @lukastaegert) -* [#2679](https://github.com/rollup/rollup/pull/2679): Improve type of `RollupOutput.output` (@MattiasBuelens) -* [#2689](https://github.com/rollup/rollup/pull/2689): Reimplement variable deconflicting logic (@lukastaegert) -* [#2691](https://github.com/rollup/rollup/pull/2691): Fix CI issues and update acorn dependency (@lukastaegert) -* [#2693](https://github.com/rollup/rollup/pull/2693): Fix typo in export-globals test (@MattiasBuelens) -* [#2695](https://github.com/rollup/rollup/pull/2695): Respect rendered exports when generating chunk hashes (@lukastaegert) -* [#2696](https://github.com/rollup/rollup/pull/2696): Correctly render function expression inside simplified expression statements (@lukastaegert) -* [#2700](https://github.com/rollup/rollup/pull/2700): Add a fix for MaxListenersExceededWarning (@luwes) -* [#2703](https://github.com/rollup/rollup/pull/2703): Update rollup-pluginutils (@lukastaegert) - -## 1.1.2 -*2019-01-21* - -### Bug Fixes -* Tree-shaken dynamic imports no longer leave behind `undefined` entries in the bundle information (#2663) -* Dynamic imports in dynamically imported files could lead to crashes and would not always create new chunks (#2664) - -### Pull Requests -* [#2663](https://github.com/rollup/rollup/pull/2663): Do not include tree-shaken dynamic imports in bundle information (@lukastaegert) -* [#2664](https://github.com/rollup/rollup/pull/2664): Properly handle dynamic imports declared in dynamically imported files (@everdimension) - -## 1.1.1 -*2019-01-19* - -### Bug Fixes -* Make sure object prototype methods are not considered to be falsy when tree-shaking (#2652) - -### Pull Requests -* [#2652](https://github.com/rollup/rollup/pull/2652): Make sure object prototype methods are not considered to be falsy (@lukastaegert) -* [#2654](https://github.com/rollup/rollup/pull/2654): Use correct signature for `this.setAssetSource` in docs (@everdimension) -* [#2656](https://github.com/rollup/rollup/pull/2656): Swap descriptions for `[extname]` and `[ext]` in docs (@tivac) - -## 1.1.0 -*2019-01-09* - -### Features -* Make `this.meta` available from the `options` plugin hook (#2642) -* Add a new `writeBundle` plugin hook that is called *after* all files have been written (#2643) - -### Bug Fixes -* Make sure the `acorn` import of the bundled non-ESM acorn plugins is correctly translated to ESM (#2636) -* Make sure input options are actually passed to the `buildStart` hook (#2642) - -### Pull Requests -* [#2636](https://github.com/rollup/rollup/pull/2636): Improve how acorn is imported, update dependencies (@lukastaegert) -* [#2642](https://github.com/rollup/rollup/pull/2642): Make this.meta available in options hook, pass input options to buildStart (@lukastaegert) -* [#2643](https://github.com/rollup/rollup/pull/2643): Implement writeBundle hook (@lukastaegert) - -## 1.0.2 -*2019-01-05* - -### Bug Fixes -* Make sure the transform hook is always reevaluated when a file watched by the hook changes (#2633) -* Fix a crash when generating hashes for tree-shaken dynamic imports (#2638) -* Fix a crash and some inconsistencies when using the acorn-bigint plugin (#2640) - -### Pull Requests -* [#2633](https://github.com/rollup/rollup/pull/2633): Document `this.addWatchFile` and make sure it also declares transform dependencies (@lukastaegert) -* [#2635](https://github.com/rollup/rollup/pull/2635): Make sure `code` is optional in warning type (@lukastaegert) -* [#2638](https://github.com/rollup/rollup/pull/2638): Do not fail when generating hashes for tree-shaken dynamic imports (@lukastaegert) -* [#2640](https://github.com/rollup/rollup/pull/2640): Always treat bigints as unknown (@lukastaegert) -* [#2641](https://github.com/rollup/rollup/pull/2641): Make sure all CLI options are listed in the summary (@lukastaegert) - -## 1.0.1 -*2019-01-03* - -### Bug Fixes -* Properly handle reexporting an external default export for non-ESM targets when using named exports mode (#2620) -* Do not (wrongly) re-declare input options in the merged `RollupOptions` type (#2622) - -### Pull Requests -* [#2620](https://github.com/rollup/rollup/pull/2620): Fixed issue with reexporting default as default with `{exports: named, interop: true}` options (@Andarist) -* [#2622](https://github.com/rollup/rollup/pull/2622): Simplify RollupOptions (@Kinrany) -* [#2627](https://github.com/rollup/rollup/pull/2627): Show how to skip imports for optional plugins (@chris-morgan) - -## 1.0.0 -*2018-12-28* - -### Breaking Changes -* Several (mostly deprecated) options have been removed or renamed (#2293, #2409): - - banner -> output.banner - - dest -> output.file - - entry -> input - - experimentalCodeSplitting -> now always active - - experimentalDynamicImport -> now always active - - experimentalPreserveModules -> preserveModules - - exports -> output.exports - - extend -> output.extend - - footer -> output.footer - - format -> output.format - - freeze -> output.freeze - - globals -> output.globals - - indent -> output.indent - - interop -> output.interop - - intro -> output.intro - - load -> use plugin API - - moduleName -> output.name - - name -> output.name - - noConflict -> output.noConflict - - output.moduleId -> output.amd.id - - outro -> output.outro - - paths -> output.paths - - preferConst -> output.preferConst - - pureExternalModules -> treeshake.pureExternalModules - - resolveExternal -> use plugin API - - resolveId -> use plugin API - - sourcemap -> output.sourcemap - - sourceMap -> output.sourcemap - - sourceMapFile -> output.sourcemapFile - - strict -> output.strict - - targets -> use output as an array - - transform -> use plugin API - - useStrict -> output.strict -* In general, output options can no longer be used as input options (#2409) -* `bundle.generate` and `bundle.write` now return a new format (#2293) -* Several plugin hooks have become deprecated and will display warnings when used (#2409): - - transformBundle - - transformChunk - - ongenerate - - onwrite -* Plugin transform dependencies are deprecated in favour of using the `this.addWatchFile` plugin context function (#2409) -* Accessing `this.watcher` in plugin hooks is deprecated in favour of the `watchChange` plugin hook and the `this.addWatchFile` plugin context function (#2409) -* Using dynamic import statements will by default create a new chunk unless `inlineDynamicImports` is used (#2293) -* Rollup now uses acorn@6 which means that acorn plugins must be compatible with this version; acorn is now external for non-browser builds to make plugins work (#2293) - -### Features -* The `--dir` ClI option can now be aliased as `-d` (#2293) -* The `--input` option now supports named entry points via `=` (#2293) - -### Bug Fixes -* Both the `--input` option as well as the default CLI option now support named inputs (#2293) - -### Pull Requests -* [#2293](https://github.com/rollup/rollup/pull/2293): Unify code paths for 1.0 relase and update documentation (@guybedford and @lukastaegert) -* [#2409](https://github.com/rollup/rollup/pull/2409): Remove old deprecated features and add new deprecation warnings (@guybedford) -* [#2486](https://github.com/rollup/rollup/pull/2486): Upgrade to acorn 6 (@marijnh) -* [#2611](https://github.com/rollup/rollup/pull/2611): Fix hook's name in test description (@Andarist) -* [#2612](https://github.com/rollup/rollup/pull/2612): Fix a self-contradicting comment in the docs (@LongTengDao) - -## 0.68.2 -*2018-12-23* - -### Bug Fixes -* Do not assume hoisted variables to have been initialized (#2607) - -### Pull Requests -* [#2607](https://github.com/rollup/rollup/pull/2607): Fix an issues where hoisted variables were assumed to have been initialized (@lye) - -## 0.68.1 -*2018-12-19* - -### Bug Fixes -* Fix an issue with UMD wrappers where a variable is used without being defined (#2600) - -### Pull Requests -* [#2600](https://github.com/rollup/rollup/pull/2600): Fix UMD and IIFE wrapper issues and add comprehensive functional wrapper tests (@lukastaegert) - -## 0.68.0 -*2018-12-16* - -### Breaking Changes -* `optimizeChunks` is renamed to `experimentalOptimizeChunks` to reflect this feature is not production-ready yet (#2575) - -### Features -* Plugins can iterate all module ids via `this.moduleIds` (#2565) -* Plugins can get graph information about a module via `this.getModuleInfo(id)` (#2565) -* Plugins and JS API users get more information about the generated chunks: `dynamicImports`, `facadeModuleId`, `isDynamicEntry`, `name` (#2575) -* Tree-shaken dynamic imports will no longer create chunks or influence chunking in any way (#2575) -* Dynamic imports will no longer follow the `entryFileNames` but the `chunkFileNames` property reflecting those are solely internally used (#2575) -* If there are chunk naming conflicts, entry chunks will always take precedence (#2575) -* If an entry facade is created, only the facade chunk is marked as `isEntry` (#2575) -* Dynamic chunks will only be marked as `isEntry` if they are actually entry chunks as well; thus there is now a 1-to-1 correspondence between modules listed in `input` and chunks marked as `isEntry` (#2575) -* Chunks no longer contain imports for variables that are tree-shaken in the chunk but used in other chunks (#2584) -* Chunks will always import re-exported variables directly from the chunk where they are originally exported from (#2584) -* Null characters will be pruned from chunk ids to allow for virtually created chunks and make `rollup-plugin-multi-entry` compatible with code-splitting and thus the upcoming 1.0 version (#2590) -* Simplify the UMD wrapper code as much as possible, especially if there are no exports (#2594) -* The UMD wrapper will now work in strict mode by checking for `self` before `this` when determining the global variable (#2594) - -### Bug Fixes -* If a facade is created for a dynamic entry point, this facade will be imported instead of the facaded chunk (#2575) -* Manual chunks that include multiple entry points will have proper facades created for all entry points if necessary (#2575) -* If missing exports are shimmed, the shim variable will not be global but created on a per-module basis and is deconflicted with variables having the same name (#2584) -* Missing export shims work properly in SystemJS (#2584) -* `preserveModules` now handles dynamic namespace imports (#2584) -* Fix chunk execution order in certain scenarios (#2584) -* Exports and assignments using destructuring syntax will properly update the exported variables when generating SystemJS output (#2587) -* Hashes in chunk names will now also take dynamic imports into account (#2596) - -### Pull Requests -* [#2565](https://github.com/rollup/rollup/pull/2565): Provide module graph information on the plugin context (@samccone) -* [#2575](https://github.com/rollup/rollup/pull/2575): Extend bundle information, tree-shake dynamic imports, fix dynamic import facade creation, support manual chunks with multiple entry points, make `optimizeChunks` experimental (@lukastaegert) -* [#2577](https://github.com/rollup/rollup/pull/2577): Update dependencies (@lukastaegert) -* [#2584](https://github.com/rollup/rollup/pull/2584): Prune tree-shaken chunk imports, fix missing export shimming, support dynamic namespaces when preserving modules, improve chunk execution order (@lukastaegert) -* [#2587](https://github.com/rollup/rollup/pull/2587): Support exports using destructuring declarations and assignments in SystemJS (@lukastaegert) -* [#2590](https://github.com/rollup/rollup/pull/2590): Make sure chunk ids do not contain invalid characters to allow for chunks to correspond to virtual modules (@lukastaegert) -* [#2594](https://github.com/rollup/rollup/pull/2594): Simplify UMD wrapper code and make sure it works in strict mode (@lukastaegert) -* [#2596](https://github.com/rollup/rollup/pull/2596): Take both static and dynamic dependencies into account when calculating hashes (@lukastaegert) - -## 0.67.4 -*2018-12-03* - -### Bug Fixes -* Prevent corrupt source maps for files with very long lines (#2571) - -### Pull Requests -* [#2571](https://github.com/rollup/rollup/pull/2571): Fix an issue with long lines in sourcemaps (@mislav) - -## 0.67.3 -*2018-11-17* - -### Bug Fixes -* Make sure the ESM browser build is actually published to npm (#2560) -* Throw proper error when using `inlineDynamicImports` with `experimentalPreserveModules` (#2560) - -### Pull Requests -* [#2552](https://github.com/rollup/rollup/pull/2552): Properly include ESM browser build in package (@lukastaegert) -* [#2560](https://github.com/rollup/rollup/pull/2560): Show proper error when using `inlineDynamicImports` with `experimentalPreserveModules` (@clarkdo) - -## 0.67.2 -*2018-11-17* - -### Bug Fixes -* Prevent crash when not returning sourcemaps from `renderChunk` plugin hook (#2558) - -### Pull Requests -* [#2558](https://github.com/rollup/rollup/pull/2558): Prevent crash when not returning sourcemaps from `renderChunk` (@kyle1320) - -## 0.67.1 -*2018-11-11* - -### Bug Fixes -* Deconflict CLI entry points with same name but on different paths if no explicit naming is used (#2548) - -### Pull Requests -* [#2548](https://github.com/rollup/rollup/pull/2548): Deconflict CLI entry points with same name but on different paths if no explicit naming is used (@lukastaegert) - -## 0.67.0 -*2018-11-04* - -### Breaking Changes -none - -### Features -* Do not resolve external dynamic imports via plugins to match the logic for static external imports again (#2505) -* Support virtual modules created by plugins when preserving modules (#2511) -* Add new `output.sourcemapExcludeSources` option to exclude the actual sources from sourcemaps (#2531) - -### Bug Fixes -* Fix TypeScript type for sourcemaps (#2507) -* Fix order of external and inter-chunk imports to match the proper execution order (#2508) -* Do not tree-shake children of unknown nodes to e.g. properly handle do-expressions via acorn plugin (#2510) -* Prevent memory leak when using the bundle as cache (#2522) -* Fix mis-placed semicolons for certain SystemJS exports (#2529) - -### Pull Requests -* [#2505](https://github.com/rollup/rollup/pull/2505): Do not resolve external dynamic imports via plugins (@lukastaegert) -* [#2507](https://github.com/rollup/rollup/pull/2507): Fix public sourcemap type (@aMarCruz) -* [#2508](https://github.com/rollup/rollup/pull/2508): Improve execution order of chunks and externals (@lukastaegert) -* [#2510](https://github.com/rollup/rollup/pull/2510): Do not tree-shake children of unknown nodes to e.g. properly handle do-expressions via acorn plugin (@devsnek) -* [#2511](https://github.com/rollup/rollup/pull/2511): Create chunks for virtual modules when preserving modules (@lukastaegert) -* [#2522](https://github.com/rollup/rollup/pull/2522): Prevent memory leak when using the bundle as cache (@kyle1320) -* [#2529](https://github.com/rollup/rollup/pull/2529): Fix mis-placed semicolons for certain SystemJS exports (@kyle1320) -* [#2531](https://github.com/rollup/rollup/pull/2531): add `sourcemapExcludeSources` option to exclude the source content from sourcemaps (@kitsonk) - -## 0.66.6 -*2018-10-10* -* Properly deconflict function and class declaration ids of reassigned default exports ([#2502](https://github.com/rollup/rollup/pull/2502)) - -## 0.66.5 -*2018-10-09* -* Remove cache from memory once no longer needed ([#2496](https://github.com/rollup/rollup/pull/2496)) -* Provide better error message when reexporting external namespace reexports ([#2499](https://github.com/rollup/rollup/pull/2499)) - -## 0.66.4 -*2018-10-04* -* Fix links in warnings and errors ([#2471](https://github.com/rollup/rollup/pull/2471)) - -## 0.66.3 -*2018-10-03* -* Detect side-effects in string.replace function arguments ([#2476](https://github.com/rollup/rollup/pull/2476)) -* Make sure chunk ids are assigned before creating output bundle ([#2483](https://github.com/rollup/rollup/pull/2483)) -* Use proper plugin name in error ([#2470](https://github.com/rollup/rollup/pull/2470)) -* Update TypeScript version and fix type errors ([#2488](https://github.com/rollup/rollup/pull/2488)) - -## 0.66.2 -*2018-09-21* -* Add additional information to parse errors messages in JSON and other non-JS files ([#2466](https://github.com/rollup/rollup/pull/2466)) - -## 0.66.1 -*2018-09-19* -* Ignore falsy plugins ([#2464](https://github.com/rollup/rollup/pull/2464)) -* Switch back to official TypeScript plugin ([#2465](https://github.com/rollup/rollup/pull/2465)) - -## 0.66.0 -*2018-09-16* -* Support ES2019 optional catch bindings ([#2455](https://github.com/rollup/rollup/pull/2455)) -* Add option to transform paths within sourcemaps ([#2430](https://github.com/rollup/rollup/pull/2430)) -* Add renderStart and renderEnd plugin hooks ([#2438](https://github.com/rollup/rollup/pull/2438)) -* Expose ESM browser build and minify browser builds ([#2437](https://github.com/rollup/rollup/pull/2437) -* Associate hoisted variables in function bodys with function parameters ([#2456](https://github.com/rollup/rollup/pull/2456)) -* Fix issue when deconflicting variables used as pattern defaults ([#2446](https://github.com/rollup/rollup/pull/2446)) -* Properly deconflict default exported class and function expressions with ids ([#2458](https://github.com/rollup/rollup/pull/2458)) -* Faster internal test builds ([#2457](https://github.com/rollup/rollup/pull/2457)) -* Switch to rollup-plugin-typescript2 ([#2460](https://github.com/rollup/rollup/pull/2460)) -* Fix internal "perf" script ([#2433](https://github.com/rollup/rollup/pull/2433)) -* Test that errors are passed to the buildEnd hook ([#2450](https://github.com/rollup/rollup/pull/2450)) - -## 0.65.2 -*2018-09-05* -* Prevent watch mode memory leak ([#2441](https://github.com/rollup/rollup/pull/2441)) - -## 0.65.1 -*2018-09-05* -* Prevent globbing when using chokidar ([#2432](https://github.com/rollup/rollup/pull/2432)) - -## 0.65.0 -*2018-08-25* -* Refactor and unify plugin system ([#2382](https://github.com/rollup/rollup/pull/2382)) -* Implement plugin cache API ([#2389](https://github.com/rollup/rollup/pull/2389)) -* Add watchChange plugin hook to watch changed files, deprecate asset dependencies ([#2405](https://github.com/rollup/rollup/pull/2405)) -* Refine asset handling ([#2369](https://github.com/rollup/rollup/pull/2369)) -* Implement `renderChunk` hook to replace `transformChunk` and `transformBundle` hooks ([#2406](https://github.com/rollup/rollup/pull/2406)) -* Add rollup version to plugin context ([#2394](https://github.com/rollup/rollup/pull/2394)) -* Do not resume stdin in watch mode to fix it for Lerna users ([#2410](https://github.com/rollup/rollup/pull/2410)) -* Allow `[format]` placeholder for id generation ([#2387](https://github.com/rollup/rollup/pull/2387)) -* Always log error stacks even when a code frame is given ([#2417](https://github.com/rollup/rollup/pull/2417)) -* Do not test module ids starting with `\0` as external ([#2400](https://github.com/rollup/rollup/pull/2400)) -* Fix tracing of namespace variables ([#2408](https://github.com/rollup/rollup/pull/2408)) -* Fix re-tracing of namespace variables ([#2420](https://github.com/rollup/rollup/pull/2420)) -* Properly wrap comment annotations in SystemJS exports ([#2408](https://github.com/rollup/rollup/pull/2408)) -* Fix renaming of destructured parameters ([#2419](https://github.com/rollup/rollup/pull/2419)) -* Do not display version in watch mode when using `--silent` ([#2392](https://github.com/rollup/rollup/pull/2392)) -* Make `cacheExpiry` an experimental option for now ([#2401](https://github.com/rollup/rollup/pull/2401)) -* Lint test configs on commit ([#2402](https://github.com/rollup/rollup/pull/2402)) -* Add code of conduct ([#2388](https://github.com/rollup/rollup/pull/2388)) -* Move to CircleCI ([#2390](https://github.com/rollup/rollup/pull/2390)) -* Update pull request template ([#2404](https://github.com/rollup/rollup/pull/2404)) - -## 0.64.1 -*2018-08-07* -* Do not render initializers of hoisted variables in dead branches ([#2384](https://github.com/rollup/rollup/pull/2384)) - -## 0.64.0 -*2018-08-07* -* Print memory consumption together with performance timings ([#2370](https://github.com/rollup/rollup/pull/2370)) -* Enable plugins to mark imports as external by returning false for resolveId ([#2351](https://github.com/rollup/rollup/pull/2351)) -* Always retain empty manual chunks ([#2362](https://github.com/rollup/rollup/pull/2362)) -* Ensure CLI warnings are shown on errors and add error for external id collisions ([#2334](https://github.com/rollup/rollup/pull/2334)) -* Remove unnecessary dependency, update dependencies, fix linting of test config ([#2376](https://github.com/rollup/rollup/pull/2376)) -* Add targeted Github issue templates ([#2356](https://github.com/rollup/rollup/pull/2356)) - -## 0.63.5 -*2018-08-01* -* Ensure onwrite plugin hooks execute in sequence ([#2364](https://github.com/rollup/rollup/pull/2364)) -* Always warn when no name is provided for a global module ([#2359](https://github.com/rollup/rollup/pull/2359)) -* Add utility type for user created plugins ([#2355](https://github.com/rollup/rollup/pull/2355)) -* Remove deprecated es6 format from types ([#2349](https://github.com/rollup/rollup/pull/2349)) -* Mark inlineDynamicImports as optional in types ([#2348](https://github.com/rollup/rollup/pull/2348)) - -## 0.63.4 -*2018-07-20* -* Use turbocolor instead of chalk ([#2339](https://github.com/rollup/rollup/pull/2339)) - -## 0.63.3 -*2018-07-20* -* Handle expressions where "in" and "instanceof" are applied to primitive values ([#2344](https://github.com/rollup/rollup/pull/2344)) - -## 0.63.2 -*2018-07-18* -* Fix bind order in for-of loops ([#2338](https://github.com/rollup/rollup/pull/2338)) - -## 0.63.1 -*2018-07-18* - -## 0.63.0 -*2018-07-17* -* Fix many tree-shaking related issues ([#2315](https://github.com/rollup/rollup/pull/2315)) -* Add experimental support for top-level await ([#2235](https://github.com/rollup/rollup/pull/2235)) -* Prevent duplicate version printout in watch mode ([#2325](https://github.com/rollup/rollup/pull/2325)) -* Respect error frames provided by plugins ([#2309](https://github.com/rollup/rollup/pull/2309)) -* Add `esm` format alias to types ([#2327](https://github.com/rollup/rollup/pull/2327)) -* Further unify internal test setup ([#2329](https://github.com/rollup/rollup/pull/2329)) - -## 0.62.0 -*2018-06-27* -* Add option to automatically shim missing exports ([#2118](https://github.com/rollup/rollup/pull/2118)) -* Inline dynamic imports that are also imported statically and only used in a single chunk ([#2295](https://github.com/rollup/rollup/pull/2295)) -* Handle caching and invalidation of assets ([#2267](https://github.com/rollup/rollup/pull/2267)) -* Fix plugin related types ([#2299](https://github.com/rollup/rollup/pull/2299)) - -## 0.61.2 -*2018-06-23* -* Improve watcher error handling, only rebuild invalidated outputs ([#2296](https://github.com/rollup/rollup/pull/2296)) -* Update dependencies, make watcher more stable ([#2297](https://github.com/rollup/rollup/pull/2297)) - -## 0.61.1 -*2018-06-21* -* Do not try to deconflict "undefined" ([#2291](https://github.com/rollup/rollup/pull/2291)) -* Properly track values for loop interator declarations and reassigned namespaces, add smoke test ([#2292](https://github.com/rollup/rollup/pull/2292)) - -## 0.61.0 -*2018-06-20* -* Declare file dependencies via transform plugin hooks ([#2259](https://github.com/rollup/rollup/pull/2259)) -* Handle undefined values when evaluating conditionals ([#2264](https://github.com/rollup/rollup/pull/2264)) -* Handle known undefined properties when evaluating conditionals ([#2265](https://github.com/rollup/rollup/pull/2265)) -* Access watch events via the plugin context ([#2261](https://github.com/rollup/rollup/pull/2261)) -* Add option to suppress `__esModule` flag in output ([#2287](https://github.com/rollup/rollup/pull/2287)) -* Fix issue when re-declaring variables, track reassignments in more cases ([#2279](https://github.com/rollup/rollup/pull/2279)) -* Add VSCode debug settings ([#2276](https://github.com/rollup/rollup/pull/2276)) - -## 0.60.7 -*2018-06-14* -* Fix typing issue ([#2269](https://github.com/rollup/rollup/pull/2269)) - -## 0.60.6 -*2018-06-14* -* Track mutations of included virtual arrays ([#2263](https://github.com/rollup/rollup/pull/2263)) -* Update readme ([#2266](https://github.com/rollup/rollup/pull/2266)) - -## 0.60.5 -*2018-06-14* -* Track deep reassignments of global and exported variables and improve performance ([#2254](https://github.com/rollup/rollup/pull/2254)) - -## 0.60.4 -*2018-06-13* -* Properly handle initially uninitialized exports and exports of globals in SystemJS output ([#2258](https://github.com/rollup/rollup/pull/2258)) - -## 0.60.3 -*2018-06-13* -* Fix types to allow watching an array of outputs ([#2262](https://github.com/rollup/rollup/pull/2262)) - -## 0.60.2 -*2018-06-11* -* Permit setting an asset's source in `generateBundle` ([#2256](https://github.com/rollup/rollup/pull/2256)) -* Add automatic linting ([#2242](https://github.com/rollup/rollup/pull/2242)) - -## 0.60.1 -*2018-06-07* -* Fix plugin regressions ([#2246](https://github.com/rollup/rollup/pull/2246)) -* Avoid conflicts for large numbers of variables ([#2244](https://github.com/rollup/rollup/pull/2244)) - -## 0.60.0 -*2018-06-06* -* New plugin hooks: transformChunk, buildStart, buildEnd; extended plugin context with warn, error, resolveId, isExternal, emitAsset, setAssetSource and getAssetFileName available to any hook ([#2208](https://github.com/rollup/rollup/pull/2208)) -* [BREAKING] Deprecate the `legacy` option and thus IE8 support ([#2141](https://github.com/rollup/rollup/pull/2141)) -* Detect more known extensions and load .mjs without extension ([#2211](https://github.com/rollup/rollup/pull/2211)) -* Add compact output mode ([#2151](https://github.com/rollup/rollup/pull/2151)) -* Significantly improve sourcemap generation performance ([#2228](https://github.com/rollup/rollup/pull/2228)) -* Enable naming SystemJS modules ([#2028](https://github.com/rollup/rollup/pull/2028)) -* Do not use alternate screen if clearScreen is set in watch mode ([#2125](https://github.com/rollup/rollup/pull/2125)) -* Allow object input form for code-splitting in watch mode ([#2217](https://github.com/rollup/rollup/pull/2217)) -* Track reassignments of methods of exports from outside ([#2240](https://github.com/rollup/rollup/pull/2240)) -* Preserve id of default exported functions and classes ([#2234](https://github.com/rollup/rollup/pull/2234)) -* Add semicolons after default exports ([#2209](https://github.com/rollup/rollup/pull/2209)) -* Fix build problems on Windows ([#2232](https://github.com/rollup/rollup/pull/2232)) -* Display install size in readme ([#2196](https://github.com/rollup/rollup/pull/2196)) -* Improve preserve modules test ([#2236](https://github.com/rollup/rollup/pull/2236)) - -## 0.59.4 -*2018-05-28* -* Fix performance regression when many return statements are used ([#2218](https://github.com/rollup/rollup/pull/2218)) - -## 0.59.3 -*2018-05-24* -* Fix reassignment tracking for constructor parameters ([#2214](https://github.com/rollup/rollup/pull/2214)) - -## 0.59.2 -*2018-05-21* -* Fix reassignment tracking in for-in loops ([#2205](https://github.com/rollup/rollup/pull/2205)) - -## 0.59.1 -*2018-05-16* -* Fix infinite recursion when determining literal values of circular structures ([#2193](https://github.com/rollup/rollup/pull/2193)) -* Fix invalid code when simplifying expressions without spaces ([#2194](https://github.com/rollup/rollup/pull/2194)) - -## 0.59.0 -*2018-05-15* -* Tree-shake statically analysable dynamic conditionals ([#2167](https://github.com/rollup/rollup/pull/2167)) -* Do not emit empty chunks when code-splitting or empty files when preserving modules ([#2128](https://github.com/rollup/rollup/pull/2128)) -* Support `import.meta.url` ([#2164](https://github.com/rollup/rollup/pull/2164)) -* Add `esm` format alias ([#2102](https://github.com/rollup/rollup/pull/2102)) -* Use alphanumeric base64 characters when deconflicting variables ([#2188](https://github.com/rollup/rollup/pull/2188)) -* Improve handling of external modules imported as both default and named imports ([#2136](https://github.com/rollup/rollup/pull/2136)) -* Properly deconflict named imports from other chunks ([#2177](https://github.com/rollup/rollup/pull/2177)) -* Fix an issue with namespaces containing reexports ([#2157](https://github.com/rollup/rollup/pull/2157)) -* Fix an issue with with incorrectly mapped default exports when code-splitting CJS or AMD modules ([#2178](https://github.com/rollup/rollup/pull/2178)) -* Fix an issue with wrong paths of relative external imports ([#2160](https://github.com/rollup/rollup/pull/2160)) -* Fix an issue when using default exports and `interop: false` ([#2149](https://github.com/rollup/rollup/pull/2149)) -* Fix in issue with invalid syntax in SystemJS output ([#2187](https://github.com/rollup/rollup/pull/2187)) -* Fix an issue when tree-shaking call expressions and reassigned variables ([#2186](https://github.com/rollup/rollup/pull/2186)) -* Fix file paths in source maps ([#2161](https://github.com/rollup/rollup/pull/2161)) -* Fix wrong file name in error message ([#2137](https://github.com/rollup/rollup/pull/2137)) -* Always use npm 5 on CI ([#2185](https://github.com/rollup/rollup/pull/2185)) - -## 0.58.2 -*2018-04-23* -* Fix rendering of certain statically resolvable if statements ([#2146](https://github.com/rollup/rollup/pull/2146)) - -## 0.58.1 -*2018-04-18* -* Fix comment detection ([#2129](https://github.com/rollup/rollup/pull/2129)) - -## 0.58.0 -*2018-04-16* -* Support individual chunk names with optional content hashes ([#2068](https://github.com/rollup/rollup/pull/2068)) -* Support manually created chunks ([#2084](https://github.com/rollup/rollup/pull/2084)) -* Automatically import deep dependencies when code splitting for better performance ([#2073](https://github.com/rollup/rollup/pull/2073)) -* Automatically minify internal export/import names for esm and system output ([#2087](https://github.com/rollup/rollup/pull/2087)) -* Add option to automatically merge small chunks ([#2090](https://github.com/rollup/rollup/pull/2090)) -* Significantly improve tree-shaking performance ([#2119](https://github.com/rollup/rollup/pull/2119)) -* Enable tree-shaking for logical expressions ([#2098](https://github.com/rollup/rollup/pull/2098)) -* Rework external types and reduce type related dependencies ([#2108](https://github.com/rollup/rollup/pull/2108)) -* Support parallel dependency resolution ([#2116](https://github.com/rollup/rollup/pull/2116)) -* Improve deprecation handling ([#2076](https://github.com/rollup/rollup/pull/2076)) -* Enable `--perf` timings in watch mode ([#2065](https://github.com/rollup/rollup/pull/2065)) -* Improve performance timers ([#2111](https://github.com/rollup/rollup/pull/2111)) -* Improve error handling for plugins ([#2100](https://github.com/rollup/rollup/pull/2100)) -* Improve error when using `--dir` in a single file build ([#2123](https://github.com/rollup/rollup/pull/2123)) -* Do not warn for external imports that are unused due to tree-shaking ([#2124](https://github.com/rollup/rollup/pull/2124)) -* Update mixed export warning message ([#2107](https://github.com/rollup/rollup/pull/2107)) -* Remove duplicate badges from readme ([#2083](https://github.com/rollup/rollup/pull/2083)) -* Update readme examples ([#2086](https://github.com/rollup/rollup/pull/2086)) - -## 0.57.1 -*2018-03-17* -* Improve sourcemap generation performance ([#2062](https://github.com/rollup/rollup/pull/2062)) -* Add reserved config option namespace and improve CLI interface ([#2063](https://github.com/rollup/rollup/pull/2063)) -* Fix issue with default exported function and class expressions ([#2059](https://github.com/rollup/rollup/pull/2059)) -* Replace `forEach` with faster `for` loops in some places ([#2064](https://github.com/rollup/rollup/pull/2064)) - -## 0.57.0 -*2018-03-15* -* Add option to preserve the module structure instead of bundling ([#1922](https://github.com/rollup/rollup/pull/1922)) -* Enable watch mode when code-splitting ([#2035](https://github.com/rollup/rollup/pull/2035)) -* Optionally pass CLI commands to config file ([#1926](https://github.com/rollup/rollup/pull/1926)) -* Option to add correct `.toString` tags to namespaces ([#2041](https://github.com/rollup/rollup/pull/2041)) -* Option and scripts to display performance timings ([#2045](https://github.com/rollup/rollup/pull/2045)) -* Fixes for exported or early accessed namespaces + improved namespace indentation ([#2041](https://github.com/rollup/rollup/pull/2041)) -* Include missing TypeScript dependencies ([#1965](https://github.com/rollup/rollup/pull/1965)) -* Add #_PURE annotation to frozen namespaces ([#2044](https://github.com/rollup/rollup/pull/2044)) -* Improve sourcemap and tree-shaking performance ([#2052](https://github.com/rollup/rollup/pull/2052)) -* Inline sourcemap lookups and make rollup smaller ([#2055](https://github.com/rollup/rollup/pull/2055)) -* Use updated magic-string types ([#2057](https://github.com/rollup/rollup/pull/2057)) -* [BREAKING] Revert class id preservation from #2025 ([#2048](https://github.com/rollup/rollup/pull/2048)) -* [BREAKING] Refactor missing export plugin hook ([#1987](https://github.com/rollup/rollup/pull/1987)) - -## 0.56.5 -*2018-03-07* -* Preserve ids when deconflicting classes ([#2025](https://github.com/rollup/rollup/pull/2025)) -* Fix an issue with re-exported namespace imports ([#2034](https://github.com/rollup/rollup/pull/2034)) -* Prevent an infinite loop when binding member expressions ([#1963](https://github.com/rollup/rollup/pull/1963)) -* Convert code style via prettier ([#2031](https://github.com/rollup/rollup/pull/2031)) -* Fix links in documentation ([#2026](https://github.com/rollup/rollup/pull/2026)) - -## 0.56.4 -*2018-03-05* -* Make rollup builds reproducible ([#2024](https://github.com/rollup/rollup/pull/2024)) -* Improve error handling for source maps ([#2012](https://github.com/rollup/rollup/pull/2012)) -* Properly handle SystemJS default exports without semicolons ([#2019](https://github.com/rollup/rollup/pull/2019)) -* Properly handle importing the same variable several times when code-splitting ([#2020](https://github.com/rollup/rollup/pull/2020)) -* Improve re-export tracing ([#2021](https://github.com/rollup/rollup/pull/2021)) -* Apply "prettier" on commit ([#2017](https://github.com/rollup/rollup/pull/2017)) -* Automatically clean up outdated tests ([#2009](https://github.com/rollup/rollup/pull/2009)) -* Add SystemJS output to form tests ([#2022](https://github.com/rollup/rollup/pull/2022)) -* Improve internal build configuration ([#2016](https://github.com/rollup/rollup/pull/2016)) - -## 0.56.3 -*2018-02-25* -* Fix issues around default exports and module facades ([#2001](https://github.com/rollup/rollup/pull/2001)) -* Improve and fix internal chunk interface ([#1994](https://github.com/rollup/rollup/pull/1994)) -* Fix superfluous semicolons added after declarations ([#1999](https://github.com/rollup/rollup/pull/1999)) -* Improve code-splitting tests ([#1990](https://github.com/rollup/rollup/pull/1990)) - -## 0.56.2 -*2018-02-19* -* Fix handling of reassigned default exports ([#1975](https://github.com/rollup/rollup/pull/1975)) -* Fix handling of renamed exports in entry points ([#1977](https://github.com/rollup/rollup/pull/1977)) -* Update internal TypeScript version ([#1980](https://github.com/rollup/rollup/pull/1980)) -* Omit compiled source files from published types ([#1981](https://github.com/rollup/rollup/pull/1981)) -* Fix example in readme file ([#1984](https://github.com/rollup/rollup/pull/1984)) -* Fix non-replaced dynamic imports in non-ESM output ([#1985](https://github.com/rollup/rollup/pull/1985)) - -## 0.56.1 -*2018-02-16* -* Fix regression when rendering switch statements ([#1971](https://github.com/rollup/rollup/pull/1971)) - -## 0.56.0 -*2018-02-15* -* Update to ECMAScript 2018 ([#1953](https://github.com/rollup/rollup/pull/1953)) -* Rework tree-shaking rendering algorithm ([#1949](https://github.com/rollup/rollup/pull/1949)) -* Tree-shake pure prototype calls on literals ([#1916](https://github.com/rollup/rollup/pull/1916)) -* Expose AST parser to plugins ([#1945](https://github.com/rollup/rollup/pull/1945)) -* Fix namespace re-export deconflicting ([#1960](https://github.com/rollup/rollup/pull/1960)) -* Allow globals to be re-exported ([#1959](https://github.com/rollup/rollup/pull/1959)) -* Fix internal performance timers ([#1966](https://github.com/rollup/rollup/pull/1966)) - -## 0.55.5 -*2018-02-10* -* Remove OpenCollective dependency ([#1915](https://github.com/rollup/rollup/pull/1915)) - -## 0.55.4 -*2018-02-09* -* Improve name deconflicting of external variables ([#1930](https://github.com/rollup/rollup/pull/1930)) -* Improve re-export handling ([#1947](https://github.com/rollup/rollup/pull/1947)) -* Mark preserveSymlinks option as optional ([#1939](https://github.com/rollup/rollup/pull/1939)) -* Enable code-splitting tests to check directory structures ([#1924](https://github.com/rollup/rollup/pull/1924)) -* Improve TypeScript definition test ([#1954](https://github.com/rollup/rollup/pull/1954)) - -## 0.55.3 -*2018-02-01* -* Remove OpenCollective dependency ([#1915](https://github.com/rollup/rollup/pull/1915)) - -## 0.55.2 -*2018-02-01* -* Add option to not follow symlinks ([#1819](https://github.com/rollup/rollup/pull/1819)) -* Fix crash in windows shell ([#1928](https://github.com/rollup/rollup/pull/1928)) -* Fix and test for external TypeScript errors ([#1903](https://github.com/rollup/rollup/pull/1903)) -* Activate OpenCollective ([#1915](https://github.com/rollup/rollup/pull/1915)) -* Optimize CI scripts ([#1921](https://github.com/rollup/rollup/pull/1921)) - -## 0.55.1 -*2018-01-26* -* Improve dynamic import workflow ([#1907](https://github.com/rollup/rollup/pull/1907)) -* Properly handle multiple dynamic imports of the same module ([#1911](https://github.com/rollup/rollup/pull/1911)) -* Fix import specifier deshadowing ([#1912](https://github.com/rollup/rollup/pull/1912)) -* Allow plugin load hook to return an empty string ([#1908](https://github.com/rollup/rollup/pull/1908)) -* Let onwarn handler accept strings ([#1905](https://github.com/rollup/rollup/pull/1905)) - -## 0.55.0 -*2018-01-23* -* Support code splitting ([#1841](https://github.com/rollup/rollup/pull/1841)) -* Support SystemJS as output format ([#1897](https://github.com/rollup/rollup/pull/1897)) -* Allow injecting acorn plugins ([#1857](https://github.com/rollup/rollup/pull/1857)) -* Add `missingExport` plugin hook ([#1845](https://github.com/rollup/rollup/pull/1845)) -* No longer parse config files via bublé ([#1899](https://github.com/rollup/rollup/pull/1899)) -* Use externally maintained dynamic import acorn plugin ([#1891](https://github.com/rollup/rollup/pull/1891)) -* Fix an error message ([#1886](https://github.com/rollup/rollup/pull/1886)) -* Refactor internal rendering options ([#1900](https://github.com/rollup/rollup/pull/1900)) -* Extract internal path resolution ([#1879](https://github.com/rollup/rollup/pull/1879)) -* Extract internal bundle option handling ([#1880](https://github.com/rollup/rollup/pull/1880)) -* Add import description type ([#1884](https://github.com/rollup/rollup/pull/1884)) -* Clean up watch options types ([#1860](https://github.com/rollup/rollup/pull/1860)) -* Clean up some tests ([#1888](https://github.com/rollup/rollup/pull/1888)) - -## 0.54.1 -*2018-01-17* -* Fix TypeScript errors in emitted type definitions ([#1871](https://github.com/rollup/rollup/pull/1871)) - -## 0.54.0 -*2018-01-12* -* Automatically inline locally resolvable dynamic imports ([#1816](https://github.com/rollup/rollup/pull/1816)) -* Preserve directives in function bodies ([#1856](https://github.com/rollup/rollup/pull/1856)) -* Refactor an error notification ([#1846](https://github.com/rollup/rollup/pull/1846)) -* Refactor a wrong import ([#1863](https://github.com/rollup/rollup/pull/1863)) -* Improve emitted TypeScript definitions ([#1864](https://github.com/rollup/rollup/pull/1864)) -* Refactor unused import ([#1866](https://github.com/rollup/rollup/pull/1866)) - -## 0.53.4 -*2018-01-10* -* More type cleanup ([#1858](https://github.com/rollup/rollup/pull/1858)) -* Use chalks internal helper to detect if colors should be used ([#1853](https://github.com/rollup/rollup/pull/1853)) -* Refactor entity handling to use interfaces ([#1840](https://github.com/rollup/rollup/pull/1840)) -* Use immutable.js internal types ([#1844](https://github.com/rollup/rollup/pull/1844)) -* Ship `TypeScript` declaration files ([#1837](https://github.com/rollup/rollup/pull/1837)) - -## 0.53.3 -*2018-01-02* -* Use correct name when re-exporting from external modules ([#1794](https://github.com/rollup/rollup/pull/1794)) -* Disable warnings when `resolveId` returns false ([#1825](https://github.com/rollup/rollup/pull/1825)) - -## 0.53.2 -*2017-12-30* -* Properly handle output arrays in the JavaScript API ([#1827](https://github.com/rollup/rollup/pull/1827)) - -## 0.53.1 -*2017-12-28* -* Properly deprecate more config options ([#1812](https://github.com/rollup/rollup/pull/1812)) -* Pass output options to `transformBundle` plugin hook ([#1813](https://github.com/rollup/rollup/pull/1813)) - -## 0.53.0 -*2017-12-22* -* Experimental dynamic import support ([#1790](https://github.com/rollup/rollup/pull/1790)) -* Unify config validation ([#1805](https://github.com/rollup/rollup/pull/1805)) - -## 0.52.3 -*2017-12-19* -* Properly hoist default exported functions in more situations ([#1799](https://github.com/rollup/rollup/pull/1799)) -* Allow plugin transformations to not overwrite source maps by returning null ([#1797](https://github.com/rollup/rollup/pull/1797)) -* Provide more parameters to "external" handler ([#1792](https://github.com/rollup/rollup/pull/1792)) - -## 0.52.2 -*2017-12-15* -* No longer ignore side-effects in JSON.parse and JSON.stringify ([#1785](https://github.com/rollup/rollup/pull/1785)) -* Updated links in warnings ([#1776](https://github.com/rollup/rollup/pull/1776)) -* No longer prevent self-imports ([#1777](https://github.com/rollup/rollup/pull/1777)) -* Properly hoist default exported functions ([#1787](https://github.com/rollup/rollup/pull/1787)) -* Prevent corruption when re-exporting default exports ([#1765](https://github.com/rollup/rollup/pull/1765)) - -## 0.52.1 -*2017-12-05* -* Improve deprecation warnings ([#1765](https://github.com/rollup/rollup/pull/1765)) -* Properly use stdin ([#1774](https://github.com/rollup/rollup/pull/1774)) -* Let --environment be used multiple times ([#1768](https://github.com/rollup/rollup/pull/1768)) -* Always transpile config files ([#1759](https://github.com/rollup/rollup/pull/1759)) -* Respect globals option in headers of UMD and IIFE files ([#1747](https://github.com/rollup/rollup/pull/1747)) - -## 0.52.0 -*2017-11-25* -* Accept config as promise ([#1731](https://github.com/rollup/rollup/pull/1731)) -* Accept promises for intro/outro/banner/footer ([#1253](https://github.com/rollup/rollup/pull/1253)) -* Option to prevent freezing of namespace imports ([#1696](https://github.com/rollup/rollup/pull/1696)) -* Option to retain all output in watch mode ([#1688](https://github.com/rollup/rollup/pull/1688)) -* Options to fine-tune treeshaking ([#1760](https://github.com/rollup/rollup/pull/1760)) - -## 0.51.8 -*2017-11-19* -* Fix speed problems by simplifying treeshaking reassignment handling ([#1740](https://github.com/rollup/rollup/pull/1740)) -* Update dependencies ([#1742](https://github.com/rollup/rollup/pull/1742)) - -## 0.51.7 -*2017-11-17* -* Keep "this"-context when calling sequence expressions ([#1724](https://github.com/rollup/rollup/pull/1724)) - -## 0.51.6 -*2017-11-16* -* Use sourcemaps to determine error locations ([#1728](https://github.com/rollup/rollup/pull/1728)) - -## 0.51.5 -*2017-11-11* -* Fix regressions with uninitialised conditional expressions ([#1720](https://github.com/rollup/rollup/pull/1720)) - -## 0.51.4 -*2017-11-11* -* Fix regressions preventing builds ([#1725](https://github.com/rollup/rollup/pull/1725)) - -## 0.51.3 -*2017-11-10* -* Fix regression when treeshaking sequence expressions ([#1717](https://github.com/rollup/rollup/pull/1717)) - -## 0.51.2 -*2017-11-09* -* Fix treeshaking regression when labels are used inside functions ([#1712](https://github.com/rollup/rollup/pull/1712)) - -## 0.51.1 -*2017-11-08* -* Fix an issue with empty return statements ([#1704](https://github.com/rollup/rollup/pull/1704)) - -## 0.51.0 -*2017-11-08* -* Massive improvements to the treeshaking algorithm ([#1667](https://github.com/rollup/rollup/pull/1667)) - -## 0.50.1 -*2017-11-08* -* Fix treeshaking regression ([#1695](https://github.com/rollup/rollup/pull/1695)) -* Treeshaking improvements ([#1650](https://github.com/rollup/rollup/pull/1650)) -* Enable installation from Github ([#1670](https://github.com/rollup/rollup/pull/1670)) -* Update documentation ([#1660](https://github.com/rollup/rollup/pull/1660)) - -## 0.50.0 -*2017-09-16* -* Many treeshaking improvements ([#1624](https://github.com/rollup/rollup/pull/1624)) -* Show finish time in watch mode ([#1620](https://github.com/rollup/rollup/pull/1620)) - -## 0.49.3 -*2017-09-08* -* Respect `watch` options ([#1596](https://github.com/rollup/rollup/issues/1596)) -* Fix treeshaking regressions ([#1604](https://github.com/rollup/rollup/pull/1604)) -* Allow `-o` to work with `output.format` ([#1606](https://github.com/rollup/rollup/pull/1606)) - -## 0.49.2 -*2017-08-29* -* Fix treeshaking regressions ([#1591](https://github.com/rollup/rollup/pull/1591)) - -## 0.49.1 -*2017-08-28* -* Fix treeshaking regressions ([#1586](https://github.com/rollup/rollup/pull/1586)) - -## 0.49.0 -*2017-08-27* -* Completely update the treeshaking algorithm ([#1582](https://github.com/rollup/rollup/pull/1582)) -* Only flip screen buffer if appropriate ([#1574](https://github.com/rollup/rollup/pull/1574)) -* Guard against two instances creating the same dir ([#1576](https://github.com/rollup/rollup/pull/1576)) - -## 0.48.2 - -* Paths is an output option ([#1569](https://github.com/rollup/rollup/pull/1569)) - -## 0.48.1 - -* Print deprecation warnings in watch mode, and fix options when watcher restarts ([#1568](https://github.com/rollup/rollup/pull/1568)) - -## 0.48.0 - -* Numerous changes to the `options` object and CLI arguments ([#1479](https://github.com/rollup/rollup/issues/1479)). See [this gist](https://gist.github.com/Rich-Harris/d472c50732dab03efeb37472b08a3f32) for a rundown. - -## 0.47.6 - -* Set `process.env.ROLLUP_WATCH` *before* loading config file - -## 0.47.5 - -* Fix broken multi-bundle configs with `rollup.watch` ([#1532](https://github.com/rollup/rollup/issues/1532)) - -## 0.47.4 - -* Delete cached config file before reloading in watch mode - -## 0.47.3 - -* Deshadow aliased imports ([#1550](https://github.com/rollup/rollup/issues/1550)) - -## 0.47.2 - -* Rebuild with dependency that npm randomly deleted - -## 0.47.1 - -* Ignore external namespace imports when deshadowing ([#1547](https://github.com/rollup/rollup/issues/1547)) - -## 0.47.0 - -* Watch config file, restart `rollup.watch` on change ([#1535](https://github.com/rollup/rollup/issues/1535)) -* Correctly render `export { foo } from` declarations in `es` output ([#1543](https://github.com/rollup/rollup/pull/1543)) -* Reinstate missing `rollup.VERSION` - -## 0.46.3 - -* init for/for-of loop section head with correct scopes ([#1538](https://github.com/rollup/rollup/issues/1538), [#1539](https://github.com/rollup/rollup/issues/1539)) -* Fix namespace imports and re-exports in `es` output ([#1511](https://github.com/rollup/rollup/issues/1511)) -* Deshadow indirectly imported namespaces ([#1488](https://github.com/rollup/rollup/issues/1488), [#1505](https://github.com/rollup/rollup/issues/1505)) - -## 0.46.2 - -* Pass options to `bundle.write` correctly in `rollup.watch` ([#1533](https://github.com/rollup/rollup/issues/1533)) -* init for-in loop section head with correct scopes ([#1480](https://github.com/rollup/rollup/issues/1480)) -* support `--no-interop` flag ([#1524](https://github.com/rollup/rollup/issues/1524)) - -## 0.46.1 - -* Remove `rollup.watch` from browser build ([#1530](https://github.com/rollup/rollup/issues/1530)) -* Remove `source-map-support` dependency ([#1528](https://github.com/rollup/rollup/issues/1528)) - -## 0.46.0 - -* `options.format` is now required ([#1491](https://github.com/rollup/rollup/pull/1491)) -* if `options.format` is `es6`, it will now throw an error (should be `es`) ([#1491](https://github.com/rollup/rollup/pull/1491)) -* Add experimental `rollup.watch` method, replacing [rollup-watch](https://github.com/rollup/rollup-watch) ([#1491](https://github.com/rollup/rollup/pull/1491)) -* Batch warnings together in CLI output ([#1491](https://github.com/rollup/rollup/pull/1491)) -* Clear screen between rebuilds in `--watch` mode ([#1491](https://github.com/rollup/rollup/pull/1491)) -* `onwarn` function's second argument is the default handler, allowing easier filtering without reimplementing any logic ([#1491](https://github.com/rollup/rollup/pull/1491)) -* Prevent semi-colon removal after variable declaration that is for loop body ([#1275](https://github.com/rollup/rollup/issues/1275)) -* Return `exports` for namespaced but non-extended IIFE bundles ([#1492](https://github.com/rollup/rollup/issues/1492)) -* Fix scoping in switch statements ([#1498](https://github.com/rollup/rollup/pull/1498)) -* Handle side-effects in tagged template expressions ([#1508](https://github.com/rollup/rollup/pull/1508)) -* More descriptive error for missing options.format ([#1510](https://github.com/rollup/rollup/pull/1510)) -* Refactor scope handling ([#1517](https://github.com/rollup/rollup/pull/1517)) -* Handle failure of a config in multi-config build ([#1513](https://github.com/rollup/rollup/issues/1513)) - - -## 0.45.2 - -* Fix interop when import is a string ([#1486](https://github.com/rollup/rollup/issues/1486)) -* Separate `resolvedIds` from `resolvedExternalIds` ([#1490](https://github.com/rollup/rollup/pull/1490)) -* Add `--extend` flag to CLI ([#1482](https://github.com/rollup/rollup/pull/1482)) - -## 0.45.1 - -* Remove `weak` from `optionalDependencies` ([#1483](https://github.com/rollup/rollup/issues/1483)) - -## 0.45.0 - -* [BREAKING] `bundle.generate(...)` returns a Promise, so that `transformBundle` plugin hooks can be asynchronous ([#1474](https://github.com/rollup/rollup/issues/1474)) - -## 0.44.0 - -* [BREAKING] Don't extend existing globals, unless `options.extend` is true ([#827](https://github.com/rollup/rollup/issues/827)) -* Fix handling of catch clause parameters ([#1462](https://github.com/rollup/rollup/issues/1462)) - -## 0.43.1 - -* Fix memory leak on incremental rebuilds ([#883](https://github.com/rollup/rollup/issues/883)) -* Allow `this.warn` and `this.error` to accept a `{line, column}` object as an alternative to a character index ([#1265](https://github.com/rollup/rollup/issues/1265)) -* Print more useful error if entry module is 'external' ([#1264](https://github.com/rollup/rollup/issues/1264)) -* Catch errors in `bundle.generate` options ([#1463](https://github.com/rollup/rollup/pull/1463)) -* Fix magic-string deprecation warning ([#1445](https://github.com/rollup/rollup/pull/1445)) - -## 0.43.0 - -* Allow config files to import JSON ([#1426](https://github.com/rollup/rollup/issues/1426)) -* Allow undefined imports in interop block ([#1341](https://github.com/rollup/rollup/issues/1341)) -* Add `process.env.ROLLUP_WATCH = 'true'` in watch mode ([#1429](https://github.com/rollup/rollup/issues/1429)) -* Add `pureExternalModules` option ([#1352](https://github.com/rollup/rollup/issues/1352)) -* Allow plugins to specify `options.entry` ([#1270](https://github.com/rollup/rollup/issues/1270)) -* Update dependencies - -## 0.42.0 - -* Deprecate `options.moduleId` in favour of `options.amd.id` ([#1365](https://github.com/rollup/rollup/pull/1365)) -* Add `options.amd.define` option to specify name of AMD `define` function ([#1365](https://github.com/rollup/rollup/pull/1365)) -* Fix incorrect class removal with `treeshake: false` ([#1375](https://github.com/rollup/rollup/pull/1375)) -* Deconflict module exports imported as namespaces ([#1384](https://github.com/rollup/rollup/issues/1384)) -* Handle bare self-imports ([#1274](https://github.com/rollup/rollup/issues/1274)) -* Allow config file to export an array of multiple configs ([#1389](https://github.com/rollup/rollup/pull/1389)) -* Handle exponentiation operator, and fail gracefully on unknown operators ([#1416](https://github.com/rollup/rollup/issues/1416)) -* Add `watch` option ([#1424](https://github.com/rollup/rollup/pull/1424)) - -## 0.41.6 - -* Preserve `originalSourceMap` on incremental rebuilds for loaders with sourcemaps ([#1336](https://github.com/rollup/rollup/issues/1336)) - -## 0.41.5 - -* Wrap ternary consequent/alternate sequences in parens ([#1273](https://github.com/rollup/rollup/issues/1273)) -* Fix erroneous warning on multiple `export * from` declarations with defaults ([#1278](https://github.com/rollup/rollup/issues/1278)) -* Prevent variable conflicts with `treeshake: false` ([#1268](https://github.com/rollup/rollup/issues/1268)) -* Allow missing `source` when collapsing sourcemaps ([#1254](https://github.com/rollup/rollup/issues/1254)) -* Allow plugins to log with strings ([#1316](https://github.com/rollup/rollup/pull/1316)) - -## 0.41.4 - -* Fix cases of multiple `export * from 'external'` declarations ([#1252](https://github.com/rollup/rollup/issues/1252)) -* Fix 'TODO' error message ([#1257](https://github.com/rollup/rollup/issues/1257)) - -## 0.41.3 - -* Don't treat `this.foo` as possible namespace ([#1258](https://github.com/rollup/rollup/issues/1258)) - -## 0.41.2 - -* Optimize `namespace['foo']` references ([#1240](https://github.com/rollup/rollup/pull/1240)) - -## 0.41.1 - -* Include `new` expressions where callee is a class with side-effects ([#980](https://github.com/rollup/rollup/issues/980) [#1233](https://github.com/rollup/rollup/issues/1233)) - -## 0.41.0 - -* Add `this.warn(...)` and `this.error(...)` methods to plugin `transform` hook contexts ([#1140](https://github.com/rollup/rollup/issues/1140)) -* `throw` always considered to be a side effect ([#1227](https://github.com/rollup/rollup/pull/1227)) - -## 0.40.2 - -* Add `file` property to sourcemaps for bundles with plugins ([#986](https://github.com/rollup/rollup/issues/986)) -* Don't require globals for empty imports ([#1217](https://github.com/rollup/rollup/issues/1217)) - -## 0.40.1 - -* Allow missing space between `export default` and declaration ([#1218](https://github.com/rollup/rollup/pull/1218)) - -## 0.40.0 - -* [BREAKING] Better, more consistent error logging ([#1212](https://github.com/rollup/rollup/pull/1212)) -* Don't use colours and emojis for non-TTY stderr ([#1201](https://github.com/rollup/rollup/issues/1201)) - -## 0.39.2 - -* Prevent mutation of cached ASTs (fixes stack overflow with rollup-watch) ([#1205](https://github.com/rollup/rollup/pull/1205)) - -## 0.39.1 - -* Ignore `var` initialisers in dead branches ([#1198](https://github.com/rollup/rollup/issues/1198)) - -## 0.39.0 - -* [BREAKING] Warnings are objects, rather than strings ([#1194](https://github.com/rollup/rollup/issues/1194)) - -## 0.38.3 - -* More informative warning for implicit external dependencies ([#1051](https://github.com/rollup/rollup/issues/1051)) -* Warn when creating browser bundle with external dependencies on Node built-ins ([#1051](https://github.com/rollup/rollup/issues/1051)) -* Statically analyse LogicalExpression nodes, for better dead code removal ([#1061](https://github.com/rollup/rollup/issues/1061)) - -## 0.38.2 - -* Preserve `var` declarations in dead branches ([#997](https://github.com/rollup/rollup/issues/997)) -* Warn if exporting a call expression that looks like a function declaration ([#1011](https://github.com/rollup/rollup/issues/1011)) -* Wrap function expressions in parentheses if necessary ([#1011](https://github.com/rollup/rollup/issues/1011)) - -## 0.38.1 - -* Fix sourcemap comment removal ([#1104](https://github.com/rollup/rollup/issues/1104)) -* Warn if empty bundle is generated ([#444](https://github.com/rollup/rollup/issues/444)) -* Support ES2017 syntax ([#492](https://github.com/rollup/rollup/issues/492)) -* Remove unused imports from external modules ([#595](https://github.com/rollup/rollup/issues/595)) -* Remove unused function and class declarations inside function bodies ([#1108](https://github.com/rollup/rollup/issues/1108), [#1178](https://github.com/rollup/rollup/issues/1178)) -* Deconflict function expression IDs ([#1176](https://github.com/rollup/rollup/issues/1176)) - -## 0.38.0 - -* [BREAKING] `export { foo as default }` creates live binding ([#1078](https://github.com/rollup/rollup/issues/1078)) -* Prevent sourceMappingURL removal edge case ([#988](https://github.com/rollup/rollup/issues/988)) -* Bind function expression IDs to the correct scope ([#1083](https://github.com/rollup/rollup/issues/1083)) -* Correctly deshadow destructured parameters with assignments ([#1008](https://github.com/rollup/rollup/issues/1008)) - -## 0.37.2 - -* Remove unused `new` expressions without side-effects ([#179](https://github.com/rollup/rollup/issues/179)) -* Only remove valid sourceMappingURL comments ([#1132](https://github.com/rollup/rollup/issues/1132)) -* Ensure blocks containing activated `var` declarations are included in output ([#1113](https://github.com/rollup/rollup/issues/1113)) -* Support plugin outros ([#1116](https://github.com/rollup/rollup/issues/1116)) - -## 0.37.1 - -* Follow symlinks ([#447](https://github.com/rollup/rollup/issues/447)) -* Fix tree-shaking of recursive functions and other cases ([#1120](https://github.com/rollup/rollup/issues/1120), [#1142](https://github.com/rollup/rollup/issues/1142)) -* Support module names that require quotes ([#582](https://github.com/rollup/rollup/issues/582), [#584](https://github.com/rollup/rollup/issues/584)) -* Fix [#957](https://github.com/rollup/rollup/issues/957) - -## 0.37.0 - -* [BREAKING] Default exports are not included in reified namespaces ([#1028](https://github.com/rollup/rollup/issues/1028)) -* Parentheses do not defeat tree-shaking ([#1101](https://github.com/rollup/rollup/issues/1101), [#1128](https://github.com/rollup/rollup/issues/1128)) -* More `legacy` fixes: do not create getters ([#1069](https://github.com/rollup/rollup/pull/1069)), do not include `__esModule` ([#1068](https://github.com/rollup/rollup/pull/1068)), quote reserved property names ([#1057](https://github.com/rollup/rollup/pull/1057)) -* Fix missing namespace member warnings ([#1045](https://github.com/rollup/rollup/issues/1045)) -* Fix TypeError in arrow function without braces returning a function ([#1062](https://github.com/rollup/rollup/pull/1062)) - -## 0.36.4 - -* Only depend on program-level call expressions ([#977](https://github.com/rollup/rollup/issues/977)) - -## 0.36.3 - -* Add `legacy` option for IE8 support ([#989](https://github.com/rollup/rollup/pull/989)) - -## 0.36.2 - -* Insert semicolons where necessary to fix broken code ([#1004](https://github.com/rollup/rollup/issues/1004)) -* Include module ID and location when warning about top-level `this` ([#1012](https://github.com/rollup/rollup/pull/1012)) -* More informative error for missing exports ([#1033](https://github.com/rollup/rollup/issues/1033)) -* `options.moduleContext` for per-module context overrides ([#1023](https://github.com/rollup/rollup/pull/1023)) - -## 0.36.1 - -* Include naked block statements ([#981](https://github.com/rollup/rollup/issues/981)) -* Correctly include falsy alternate statements in optimised if blocks ([#973](https://github.com/rollup/rollup/issues/973)) -* Prevent omission of default exports that are only used by the exporting module ([#967](https://github.com/rollup/rollup/pull/967)) -* Prevent warning on `auto` exports with ES output ([#966](https://github.com/rollup/rollup/pull/966)) - -## 0.36.0 - -* `export { foo as default }` no longer creates a live binding ([#860](https://github.com/rollup/rollup/issues/860)) - -## 0.35.15 - -* Warn on missing unused imports in deshadowing phase ([#928](https://github.com/rollup/rollup/issues/928)) -* Always add a newline to the end of bundles ([#958](https://github.com/rollup/rollup/issues/958)) - -## 0.35.14 - -* Include all parent statements of expression with effects, up to function boundary ([#930](https://github.com/rollup/rollup/issues/930)) - -## 0.35.13 - -* Include superclasses when including their subclasses ([#932](https://github.com/rollup/rollup/issues/932)) - -## 0.35.12 - -* Add `interop: false` option to disable unwrapping of external imports ([#939](https://github.com/rollup/rollup/issues/939)) - -## 0.35.11 - -* Deconflict reified namespaces with other declarations ([#910](https://github.com/rollup/rollup/issues/910)) - -## 0.35.10 - -* Only remove EmptyStatement nodes directly inside blocks ([#913](https://github.com/rollup/rollup/issues/931)) - -## 0.35.9 - -* Support Node 0.12 ([#909](https://github.com/rollup/rollup/issues/909)) - -## 0.35.8 - -* Correctly deshadow re-assigned module functions ([#910](https://github.com/rollup/rollup/issues/910)) - -## 0.35.7 - -* Refactor `flushTime.js` ([#922](https://github.com/rollup/rollup/pull/922)) - -## 0.35.6 - -* Fix browser build - -## 0.35.5 - -* Allow empty for loop heads ([#919](https://github.com/rollup/rollup/issues/919)) - -## 0.35.4 - -* Preserve effects in for-of and for-in loops ([#870](https://github.com/rollup/rollup/issues/870)) -* Remove empty statements ([#918](https://github.com/rollup/rollup/pull/918)) - -## 0.35.3 - -* Render identifiers inside template literals - -## 0.35.2 - -* Fix broken build caused by out of date locally installed dependencies - -## 0.35.1 - -* Rewrite deconflicted class identifiers ([#915](https://github.com/rollup/rollup/pull/915)) -* Include `dependencies` in `bundle.modules` objects ([#903](https://github.com/rollup/rollup/issues/903)) -* Update to Acorn 4 ([#914](https://github.com/rollup/rollup/pull/914)) - -## 0.35.0 - -* Rewrite analysis/tree-shaking code ([#902](https://github.com/rollup/rollup/pull/902)) -* Include conditional mutations of global objects ([#901](https://github.com/rollup/rollup/issues/901)) -* Only reify namespaces if necessary ([#898](https://github.com/rollup/rollup/issues/898)) -* Track mutations of aliased globals ([#893](https://github.com/rollup/rollup/issues/893)) -* Include duplicated var declarations ([#716](https://github.com/rollup/rollup/issues/716)) - -## 0.34.13 - -* Pass `{ format }` through to `transformBundle` ([#867](https://github.com/rollup/rollup/issues/867)) - -## 0.34.12 - -* Fix `rollup --watch` ([#887](https://github.com/rollup/rollup/issues/887)) -* Case-sensitive paths ([#862](https://github.com/rollup/rollup/issues/862)) - -## 0.34.11 - -* Prevent leaky state when `bundle` is reused ([#875](https://github.com/rollup/rollup/issues/875)) -* Ensure `intro` appears before interop block ([#880](https://github.com/rollup/rollup/issues/880)) - -## 0.34.10 - -* Allow custom `options.context` to replace top-level `this` ([#851](https://github.com/rollup/rollup/issues/851)) -* Fix `noConflict` when used via `rollup --config` ([#846](https://github.com/rollup/rollup/issues/846)) -* Place `outro` block *after* export block ([#852](https://github.com/rollup/rollup/issues/852)) - -## 0.34.9 - -* Disable indentation by default, for faster bundle generation ([#812](https://github.com/rollup/rollup/pull/812)) -* More helpful error on missing entry file ([#802](https://github.com/rollup/rollup/issues/802)) -* Preserve comments before import declarations ([#815](https://github.com/rollup/rollup/pull/815)) - -## 0.34.8 - -* Wrap UMD factory function in parens to avoid lazy parsing ([#774](https://github.com/rollup/rollup/pull/774)) - -## 0.34.7 - -* Leave it up to resolveId to normalize the entry path ([#835](https://github.com/rollup/rollup/pull/835)) -* Cache decoded mappings ([#834](https://github.com/rollup/rollup/pull/834)) - -## 0.34.5 - -* Fix circular export ([#813](https://github.com/rollup/rollup/issues/813)) - -## 0.34.4 - -* Module render performance tweak ([#823](https://github.com/rollup/rollup/pull/823)) - -## 0.34.3 - -* Avoid infinite recursion in `Bundle.sort()` ([#800](https://github.com/rollup/rollup/pull/800)) - -## 0.34.2 - -* resolveId calls are cached now to improve incremental build -* Fixed error message recursion in plugins - -## 0.34.1 - -* Support `paths` config ([#754](https://github.com/rollup/rollup/issues/754)) -* Allow `export *` from external module, internally - -## 0.34.0 - -* Use resolved IDs for relative imports that are also external modules, to allow `options.globals` to work with them ([#763](https://github.com/rollup/rollup/issues/763)) -* Ensure reassigned exports are declared in an ES bundle, and remove empty `exports.foo;` statements ([#755](https://github.com/rollup/rollup/issues/755)) -* Add newline after sourcemap comment ([#756](https://github.com/rollup/rollup/issues/756)) - -## 0.33.2 - -* Add `bundle` as second argument to `ongenerate` and `onwrite` hooks ([#773](https://github.com/rollup/rollup/pull/773)) -* Warn on top-level `this` ([#770](https://github.com/rollup/rollup/issues/770)) - -## 0.33.1 - -* Fix `--no-strict` option ([#751](https://github.com/rollup/rollup/pull/751)) -* Fix Windows edge case with case-sensitive paths ([#760](https://github.com/rollup/rollup/pull/760)) - -## 0.33.0 - -* Downgrade missing transformer sourcemap to a warning, not an error, and print the name of the offending plugin if possible ([#746](https://github.com/rollup/rollup/issues/746)) -* Warn if same name is re-exported from two modules ([#722](https://github.com/rollup/rollup/issues/722)) - -## 0.32.4 - -* Add `ongenerate` and `onwrite` plugin hooks ([#742](https://github.com/rollup/rollup/pull/742)) - -## 0.32.3 - -* Generated correct sourcemaps with reified namespaces ([#668](https://github.com/rollup/rollup/issues/668)) -* Exclude plugin helper modules from sourcemaps ([#747](https://github.com/rollup/rollup/pull/747)) - -## 0.32.2 - -* Allow `--globals` to work with `--external` or `options.external` in whatever configuration ([#743](https://github.com/rollup/rollup/issues/743)) - -## 0.32.1 - -* Preserve side-effects to default exports that coincide with used named exports ([#733](https://github.com/rollup/rollup/issues/733)) -* Support `rollup -c node:pkgname` ([#736](https://github.com/rollup/rollup/issues/736)) - -## 0.32.0 - -* Deprecate `es6` format in favour of `es` ([#468](https://github.com/rollup/rollup/issues/468)) -* Add correct `jsnext:main` build ([#726](https://github.com/rollup/rollup/pull/726)) - -## 0.31.2 - -* Allow `load` plugins to provide sourcemap ([#715](https://github.com/rollup/rollup/pull/715)) -* Allow `sourceMapFile` in config options ([#717](https://github.com/rollup/rollup/issues/717)) - -## 0.31.1 - -* Logging for errors emitted by `rollup-watch` ([#712](https://github.com/rollup/rollup/issues/712)) - -## 0.31.0 - -* Rewrite top-level `this` as `undefined` ([#707](https://github.com/rollup/rollup/pull/707)) -* Pass `options.acorn` to Acorn ([#564](https://github.com/rollup/rollup/issues/564)) - -## 0.30.0 - -* Bundle CLI ([#700](https://github.com/rollup/rollup/issues/700)) -* Ensure absolute paths are normalised ([#704](https://github.com/rollup/rollup/issues/704)) -* Allow `rollup --watch` to work with targets - -## 0.29.1 - -* Merge `target` options with main options ([#701](https://github.com/rollup/rollup/issues/701)) -* Update magic-string ([#690](https://github.com/rollup/rollup/issues/690)) - -## 0.29.0 - -* `rollup --watch` ([#284](https://github.com/rollup/rollup/issues/284)) - -## 0.28.0 - -* Experimental support for incremental rebuilds ([#658](https://github.com/rollup/rollup/pull/658)) - -## 0.27.1 - -* Ensure names exported from a module are not replaced with reserved words ([#696](https://github.com/rollup/rollup/pull/696)) -* Revert ([#692](https://github.com/rollup/rollup/pull/692)) – resolved IDs must be strings - -## 0.27.0 - -* Use native promises instead of `es6-promise` ([#689](https://github.com/rollup/rollup/issues/689)) -* Support multiple targets in config files ([#655](https://github.com/rollup/rollup/issues/655)) -* Allow `resolveId` plugin functions to return non-strings ([#692](https://github.com/rollup/rollup/pull/692)) - -## 0.26.7 - -* Distinguish between default and namespace imports of external module ([#637](https://github.com/rollup/rollup/issues/637)) -* Add `__esModule` property to named exports in AMD, CJS and UMD modes ([#650](https://github.com/rollup/rollup/issues/650)) - -## 0.26.6 - -* Deconflict named imports from external modules in ES bundles ([#659](https://github.com/rollup/rollup/issues/659)) -* Support `options.preferConst` to generate `const` declarations for exports rather than `var` declarations ([#653](https://github.com/rollup/rollup/issues/653)) - -## 0.26.5 - -* Preserve `debugger` statements ([#664](https://github.com/rollup/rollup/issues/664)) -* Allow `options.external` to be a function ([#522](https://github.com/rollup/rollup/issues/522)) - -## 0.26.4 - -* Prevent plugin-provided external IDs being normalised ([#630](https://github.com/rollup/rollup/issues/630), [#633](https://github.com/rollup/rollup/issues/633)) -* Throw if module exports/re-exports the same name twice, or has multiple default exports ([#679](https://github.com/rollup/rollup/issues/679)) -* Warn about `eval` security issue ([#675]((https://github.com/rollup/rollup/issues/675))) - - -## 0.26.3 - -* Ensure reference is not incorrectly marked as a reassignment ([#648](https://github.com/rollup/rollup/issues/648)) - -## 0.26.2 - -* Sanity check output of `load` hook ([#607](https://github.com/rollup/rollup/issues/607)) -* Correct scoping for ID class expressions ([#626](https://github.com/rollup/rollup/issues/626)) -* Warn if named and default exports are used together in auto mode ([#587](https://github.com/rollup/rollup/issues/587)) -* Allow variable initialisers to be rewritten if necessary ([#632](https://github.com/rollup/rollup/issues/632)) -* Prevent double `var` with no-treeshake option ([#639](https://github.com/rollup/rollup/pull/639)) - -## 0.26.1 - -* Add `treeshake: false`/`--no-treeshake` option for debugging ([#505](https://github.com/rollup/rollup/issues/505)) -* Update build process to use Bublé ([#620](https://github.com/rollup/rollup/pull/620)) - -## 0.26.0 - -* Add `noConflict`/`--no-conflict` option for UMD builds ([#580](https://github.com/rollup/rollup/pull/580)) -* Normalise relative external paths ([#591](https://github.com/rollup/rollup/pull/591)) -* Report files causing transform errors ([#609](https://github.com/rollup/rollup/pull/609)) -* Handle sourcemap segments with a single member ([#619](https://github.com/rollup/rollup/pull/619)) -* Update dependencies - -## 0.25.8 - -* Unixize entry path ([#586](https://github.com/rollup/rollup/pull/586)) - -## 0.25.7 - -* Expand deshadowed shorthand properties ([#575](https://github.com/rollup/rollup/issues/575)) -* Allow external files to be non-existent ([#532](https://github.com/rollup/rollup/issues/532)) - -## 0.25.6 - -* Fix a regression introduced by #566 ([#569](https://github.com/rollup/rollup/issues/569)) -* Prune dead conditional expressions more carefully ([#567](https://github.com/rollup/rollup/issues/567)) - -## 0.25.5 - -* Make sure shorthand destructuring assignments don't break ([#528](https://github.com/rollup/rollup/issues/528)) -* Allow 'exports' key ([#542](https://github.com/rollup/rollup/issues/542)) -* Ensure `foo. bar` where `foo` is a namespace import is rewritten correctly ([#566](https://github.com/rollup/rollup/issues/566)) -* Fix an edge case for exported globals (e.g. `export { document }`) ([#562](https://github.com/rollup/rollup/issues/562)) - -## 0.25.4 - -* Fix misnamed exports of default imports in ES bundles ([#513](https://github.com/rollup/rollup/issues/513)) -* CLI: warn on missing config ([#515](https://github.com/rollup/rollup/pull/515)) -* Detect side-effects in non-top-level member expression assignment ([#476](https://github.com/rollup/rollup/issues/476)) -* Don't remove computed property class keys ([#504](https://github.com/rollup/rollup/issues/504)) -* Augment existing global object rather than replacing ([#493](https://github.com/rollup/rollup/issues/493)) -* Don't fail on `export {}`, warn instead ([#486](https://github.com/rollup/rollup/issues/486)) - -## 0.25.3 - -* Handle non-objects and `null` in `_interopDefault` ([#474](https://github.com/rollup/rollup/issues/474)) - -## 0.25.2 - -* Skip dead branches of a conditional expression (#[465](https://github.com/rollup/rollup/pull/465)) -* Allow globals to be exported ([#472](https://github.com/rollup/rollup/pull/472)) -* Ensure reassigned exports are exported ([#484](https://github.com/rollup/rollup/issues/484)) - -## 0.25.1 - -* Throw error if namespace is called ([#446](https://github.com/rollup/rollup/issues/446)) -* Prevent shadowing bug in ES6 output ([#441](https://github.com/rollup/rollup/pull/441)) -* Prevent `var exports.foo` ([#426](https://github.com/rollup/rollup/issues/426)) -* Prevent double export of aliased symbols ([#438](https://github.com/rollup/rollup/issues/438)) -* Provide more informative error if Rollup is used in-browser without appropriate `resolveId`/`load` hooks ([#275](https://github.com/rollup/rollup/issues/275)) -* Use `_interopDefault` function to DRY out code with many external dependencies, in CommonJS output ([#458](https://github.com/rollup/rollup/pull/458)) - -## 0.25.0 - -* **breaking** Module order is determined according to spec, rather than in a way designed to prevent runtime errors. Rollup will warn if it detects runtime errors are likely ([#435](https://github.com/rollup/rollup/issues/435)) -* Prevent overly aggressive tree-shaking with complex call expressions ([#440](https://github.com/rollup/rollup/issues/440)) - -## 0.24.1 - -* Handle calls to default exports other that are not function expressions or references to function declarations ([#421](https://github.com/rollup/rollup/issues/421)) -* Ensure namespace blocks are created for chained imports ([#430](https://github.com/rollup/rollup/issues/430)) -* Include references in computed property keys ([#434](https://github.com/rollup/rollup/issues/434)) -* Use CLI `--external` option correctly ([#417](https://github.com/rollup/rollup/pull/417)) -* Allow relative imports to be treated as external, if absolute paths are provided in `options.external` ([#410](https://github.com/rollup/rollup/issues/410)) -* Make IIFE output adhere to Crockford style ([#415](https://github.com/rollup/rollup/pull/415)) - -## 0.24.0 - -* No longer attempts to resolve IDs in `options.external` ([#407](https://github.com/rollup/rollup/issues/407)) -* Fix broken sourcemap resolution in cases where some modules are transformed and others aren't ([#404](https://github.com/rollup/rollup/issues/404)) - -## 0.23.2 - -* Ensure `dest` or `sourceMapFile` is resolved against CWD for purposes of sourcemap generation ([#344](https://github.com/rollup/rollup/issues/344)) -* Support `banner`, `footer`, `intro` and `outro` options via CLI ([#330](https://github.com/rollup/rollup/issues/330)) -* Allow `options.global` to be a function rather than an object, and warn on missing names ([#293](https://github.com/rollup/rollup/issues/293)) -* Ensure side-effects are captured in cyclical call expressions ([#397](https://github.com/rollup/rollup/issues/397)) -* Fix parse error with body-less arrow function expressions ([#403](https://github.com/rollup/rollup/issues/403)) - -## 0.23.1 - -* Reinstate missing fix from ([#392](https://github.com/rollup/rollup/pull/392)) - -## 0.23.0 - -* Add `bundleTransform` plugin hook and option ([#387](https://github.com/rollup/rollup/pull/387)) -* Correctly store names in sourcemaps, regardless of transformers -* Add `--environment` option to CLI ([#388](https://github.com/rollup/rollup/pull/388)) -* Handle destructuring in exports ([#374](https://github.com/rollup/rollup/issues/374)) -* Fix UMD global exports bug introduced in 0.22.1 ([#392](https://github.com/rollup/rollup/pull/392)) - -## 0.22.2 - -* Prevent lost `var` keywords ([#390](https://github.com/rollup/rollup/issues/390)) - -## 0.22.1 - -* Update expected option keys ([#379](https://github.com/rollup/rollup/issues/379)) -* Handle transformers that return stringified sourcemaps ([#377](https://github.com/rollup/rollup/issues/377)) -* Automatically create missing namespaces if `moduleName` contains dots ([#378](https://github.com/rollup/rollup/issues/378)) -* Ignore external dependency warnings coming from config file ([#333](https://github.com/rollup/rollup/issues/333)) -* Update to latest magic-string for performance boost - -## 0.22.0 - -* Duplicate warnings are squelched ([#362](https://github.com/rollup/rollup/issues/362)) -* Plugins can manipulate or override the `options` object ([#371](https://github.com/rollup/rollup/pull/371)) - -## 0.21.3 - -* Validate option keys ([#348](https://github.com/rollup/rollup/pull/348)) -* Allow namespaces imports to sit alongside named imports ([#355](https://github.com/rollup/rollup/issues/355)) -* Count references inside destructured objects ([#364](https://github.com/rollup/rollup/issues/364)) -* Preserve top-level `delete` statements ([#352](https://github.com/rollup/rollup/issues/352)) - -## 0.21.2 - -* Missing relative imports are an error, not a warning ([#321](https://github.com/rollup/rollup/issues/321)) -* Fixed incorrectly renamed default exports in ES6 bundles ([#339](https://github.com/rollup/rollup/issues/339)) -* Fixed infinite recursion bug ([#341](https://github.com/rollup/rollup/issues/341)) - -## 0.21.1 - -* Remove `aggressive: true` (was too aggressive) ([#309](https://github.com/rollup/rollup/pull/309)) -* Handle top-level block statements ([#326](https://github.com/rollup/rollup/issues/326)) -* Optimise namespaces with default exports ([#314](https://github.com/rollup/rollup/issues/314)) - -## 0.21.0 - -* Only include statements whose side-effects are relevant (i.e. contribute to exports or affect global state) ([#253](https://github.com/rollup/rollup/pull/253)) ([#253](https://github.com/rollup/rollup/pull/253)) -* Exclude dead branches from analysis and inclusion ([#249](https://github.com/rollup/rollup/pull/249)) -* Add `aggressive: true` option to eliminate all side-effects outside entry module -* More informative error when re-exporting non-existent binding ([#274](https://github.com/rollup/rollup/issues/274)) -* Fix infinite recursion bug ([#291](https://github.com/rollup/rollup/issues/291)) -* Log errors when using `rollup --config` ([#288](https://github.com/rollup/rollup/pull/288)) -* Return rejected promises on startup instead of throwing error, if options are invalid ([#303](https://github.com/rollup/rollup/pull/303)) - -## 0.20.5 - -* Ensure re-exports don't create a local binding ([#270](https://github.com/rollup/rollup/pull/270)) - -## 0.20.4 - -* Check file exists at resolve time, to allow filenames with non-extension dots in them ([#250](https://github.com/rollup/rollup/pull/250)) -* Import `Promise` where used, for Node 0.10 support ([#254](https://github.com/rollup/rollup/issues/254)) -* Allow asynchronous transformer plugins ([#260](https://github.com/rollup/rollup/issues/260)) -* Don't assume re-exported bindings are globals when deconflicting ([#267](https://github.com/rollup/rollup/issues/267)) - - -## 0.20.3 - -* Fix bug where multiple `export *` declarations caused error ([#244](https://github.com/rollup/rollup/pulls/244)) -* Missing namespace exports are a warning, not an error ([#244](https://github.com/rollup/rollup/pulls/244)) -* Plugins can provide `banner` and `footer` options (string, or function that returns a string) ([#235](https://github.com/rollup/rollup/issues/235)) -* Warn on encountering `eval` ([#186](https://github.com/rollup/rollup/issues/186)) - -## 0.20.2 - -* Handle errors in build config file -* More robust deconflicting, in cases where e.g. `foo$1` already exists -* Use Rollup CLI for own build process - -## 0.20.1 - -* Support `--config` file to enable plugins with CLI ([#226](https://github.com/rollup/rollup/pulls/226)) -* Prevent `default` being used as variable name ([#215](https://github.com/rollup/rollup/issues/215)) -* Update deps - -## 0.20.0 - -* Support for [plugins](https://github.com/rollup/rollup/wiki/Plugins) ([#207](https://github.com/rollup/rollup/pulls/207)) -* BREAKING – `options.transform`, `options.load`, `options.resolveId`, `options.resolveExternal` and `options.external` are no longer supported, and should be handled by plugins. [More info](https://github.com/rollup/rollup/wiki/Plugins) -* BREAKING – the .js extension is only added if it looks like there's no extension, allowing e.g. `import data from 'data.json'` (with the appropriate transformer). For safety, always include the file extension – import `./foo.js`, not `./foo` - -## 0.19.2 - -* Fix exporting namespaces to include all of their exports ([#204](https://github.com/rollup/rollup/issues/204)) -* Namespace exotic objects are frozen to ensure that its properties cannot be modified, reconfigured, redefined or deleted ([#203](https://github.com/rollup/rollup/pulls/203)) -* Fix `ReferenceError: Promise is not defined` in node v0.10 ([#189](https://github.com/rollup/rollup/issues/189)) - -## 0.19.1 - -* Fix `module.basename()` when used with custom `resolveId` function -* Use [rollup-babel](https://github.com/rollup/rollup-babel) to build self -* Exposed the version string through the API: `require( 'rollup' ).VERSION` - -## 0.19.0 - -* **breaking** The `transform` option is no longer passed through to custom loaders. Loaders should only concern themselves with providing source code; transformation will *always* take place -* `options.transform` functions can return a string, or a `{code, map, ast}` object. Where possible, sourcemap chains will be flattened ([#175](https://github.com/rollup/rollup/pull/175)) -* `options.resolveId`, `options.resolveExternal` and `options.load` can each be a function or an array of functions. If an array, the first non-null/undefined return value is used. In both cases, failed resolution/loading will fall back to the defaults, unless an error is thrown. ([#174](https://github.com/rollup/rollup/pull/174)) -* New `intro` and `outro` options – similar to `banner` and `footer` except inserted *inside* any format-specific wrapper -* Multiple var declarations in an export block (e.g. `export let a = 1, b = 2`) are split up to facilitate tree-shaking ([#171](https://github.com/rollup/rollup/issues/171)) -* More informative error when using a missing namespace property ([#169](https://github.com/rollup/rollup/pull/169)) -* Update various dependencies - -## 0.18.5 - -* Allow namespaces to be assigned to variables ([#168](https://github.com/rollup/rollup/issues/168)) -* Promote `chalk` and `source-map-support` to `dependencies`, as they're used by the CLI ([#167](https://github.com/rollup/rollup/pull/167)) - -## 0.18.4 - -* Make external modules configurable (i.e. `external.config.foo = 'bar'`) without erroring - -## 0.18.3 - -* Crop indent exclusion ranges to exclude enclosing quotes ([#166](https://github.com/rollup/rollup/issues/166)) - -## 0.18.2 - -* Include definitions of namespace members that are exported as defaults - -## 0.18.1 - -* Include `acorn.parse` in bundle, remove `sander` from dependencies, simplify build - -## 0.18.0 - -* Internal rewrite -* Reinstate statically-analysable namespace imports -* Avoid using getters in namespace blocks where possible ([#144](https://github.com/rollup/rollup/issues/144)) -* Track variable aliases ([#96](https://github.com/rollup/rollup/issues/96)) -* Prevent multiline strings being indented ([#164](https://github.com/rollup/rollup/issues/164)) - -## 0.17.4 - -* Allow imports from hidden directories (replay of [#133](https://github.com/rollup/rollup/issues/133)) - -## 0.17.3 - -* Handle parenthesised default exports ([#136](https://github.com/rollup/rollup/issues/136)) - -## 0.17.2 - -* Allow use of scoped npm packages ([#131](https://github.com/rollup/rollup/issues/131)) - -## 0.17.1 - -* Allow namespaces to be passed to a function ([#149](https://github.com/rollup/rollup/issues/149)) - -## 0.17.0 - -* Roll back to 0.15.0 and reapply subsequent fixes pending resolution of ([#132](https://github.com/rollup/rollup/issues/132)) and related issues - -## 0.16.4 - -* Fix import paths with `.` ([#133](https://github.com/rollup/rollup/issues/133)) -* Prevent sourceMappingURL confusion leading to broken sourcemap -* Add code coverage reporting [#130](https://github.com/rollup/rollup/pull/130)) -* Add `modules` property to user-facing `bundle` – an array with `{id}` objects ([#128](https://github.com/rollup/rollup/issues/128)) - -## 0.16.3 - -* Prevent adjacent blocks of multiple var declarations causing magic-string failure ([#105](https://github.com/rollup/rollup/issues/105)) - -## 0.16.2 - -* Top-level function calls and assignments to globals are treated as side-effects, and always included -* Import files from subdirectories of external packages, e.g. `import mod from 'foo/sub/mod'` ([#126](https://github.com/rollup/rollup/issues/126)) - -## 0.16.1 - -* Handle assignment patterns, and destructured/rest parameters, when analysing scopes -* Fix bug preventing project from self-building (make base `Identifier` class markable) - -## 0.16.0 - -* Internal refactoring ([#99](https://github.com/rollup/rollup/pull/99)) -* Optimisation for statically-analysable namespace imports ([#99](https://github.com/rollup/rollup/pull/99)) -* Windows support (theoretically!) ([#117](https://github.com/rollup/rollup/pull/117) / [#119](https://github.com/rollup/rollup/pull/119)) - -## 0.15.0 - -* Load all modules specified by `import` statements, and do tree-shaking synchronously once loading is complete. This results in simpler and faster code, and enables future improvements ([#97](https://github.com/rollup/rollup/pull/97)) -* Only rewrite `foo` as `exports.foo` when it makes sense to ([#92](https://github.com/rollup/rollup/issues/92)) -* Fix bug with shadowed variables that are eventually exported ([#91](https://github.com/rollup/rollup/issues/91)) -* Exclude unused function declarations that happen to modify a used name ([#90](https://github.com/rollup/rollup/pull/90)) -* Simplify internal `Scope` model – scopes always attach to blocks, never function expressions/declarations - -## 0.14.1 - -* `export { name } from './other'` does not create a local binding ([#16](https://github.com/rollup/rollup/issues/16)) -* A single binding can be exported under multiple names ([#18](https://github.com/rollup/rollup/issues/18)) -* `useStrict` option exposed to CLI as `--strict`/`--no-strict` ([#81](https://github.com/rollup/rollup/issues/81)) -* Neater exports from ES6 bundles - -## 0.14.0 - -* Internal refactoring -* Correctly deconflict generated default export names ([#72](https://github.com/rollup/rollup/issues/72)) -* Handle `export { x } from 'y'` declarations ([#74](https://github.com/rollup/rollup/issues/74)) -* Dedupe named imports from external modules in ES6 bundles ([#77](https://github.com/rollup/rollup/issues/77)) - -## 0.13.0 - -* Support `banner` and `footer` options ([#66](https://github.com/rollup/rollup/pull/66)) -* Remove pre-existing sourcemap comments ([#66](https://github.com/rollup/rollup/pull/66)) -* Deconflict external imports ([#66](https://github.com/rollup/rollup/pull/66)) -* Use existing AST, if provided ([#66](https://github.com/rollup/rollup/pull/66)) -* Rename internal namespace exports as appropriate ([#66](https://github.com/rollup/rollup/pull/66)) -* Remove uninitialised var declarations that get exported ([#66](https://github.com/rollup/rollup/pull/66)) -* Rename variables named `exports` to avoid conflicts ([#66](https://github.com/rollup/rollup/pull/66)) - -## 0.12.1 - -* Don't attempt to mark statements belonging to external modules ([#68](https://github.com/rollup/rollup/issues/68)) -* Correctly deshadow variables that conflict with imports ([#68](https://github.com/rollup/rollup/issues/68)) - -## 0.12.0 - -* Internal re-architecting, resulting in more efficient bundling with reduced memory usage -* Shorthand properties are expanded if necessary ([#61](https://github.com/rollup/rollup/issues/61)) -* Fixed various bugs with bundle external dependencies, particularly when generating ES6 bundles ([#59](https://github.com/rollup/rollup/issues/59)) -* Add `--globals` option to CLI ([#60](https://github.com/rollup/rollup/pull/60)) -* Allow imports of external modules for side-effects ([#55](https://github.com/rollup/rollup/pull/55)) -* Prevent Rollup hanging on non-existent external module ([#54](https://github.com/rollup/rollup/pull/54)) - -## 0.11.4 - -* Side-effect preservation applies to internal default exports ([#43](https://github.com/rollup/rollup/issues/43)) - -## 0.11.3 - -* Class methods are not incorrectly renamed ([#42](https://github.com/rollup/rollup/issues/42)) -* External modules are assigned names before canonical names are determined ([#42](https://github.com/rollup/rollup/issues/42)) - -## 0.11.2 - -* Correctly handle computed properties (e.g. `foo[bar]`) when discovering dependencies ([#47](https://github.com/rollup/rollup/pull/47)) - -## 0.11.1 - -* Support for `export * from '..'` ([#46](https://github.com/rollup/rollup/pull/46)) - -## 0.11.0 - -* Experimental browser-friendly build (`dist/rollup.browser.js`) ([#25](https://github.com/rollup/rollup/issues/25)) -* Internal re-architecting to make discovery process simpler and more performant -* Preservation of side-effects that happen in a separate module to the affected definition ([#39](https://github.com/rollup/rollup/issues/39)) - -## 0.10.0 - -* Better sorting algorithm – sorting happens at the module level, rather than the statement level. This avoids certain edge cases -* IIFEs are ignored for the purposes of distinguishing between 'strong' and 'weak' dependencies -* Empty `var` declarations for exported bindings are omitted - -## 0.9.1 - -* Much faster statement insertion (fixes major 0.9.0 performance regression) - -## 0.9.0 - -* BREAKING - `resolvePath` is now `resolveId`. The returned `id` (which by default is a filepath) is passed to the `load` function, which can optionally be overridden, and which is applied to all modules including the entry module. This allows custom resolver and loading logic for integration with third party systems (e.g. JSPM) or, eventually, in-browser usage ([#30](https://github.com/rollup/rollup/issues/30)) -* A statement cannot appear after later statements from the same bundle ([#34](https://github.com/rollup/rollup/issues/34)) -* Tricky cyclical dependencies are handled ([#36](https://github.com/rollup/rollup/issues/36)) -* `sourcemap` option is used by CLI (was omitted previously) - -## 0.8.3 - -* Correctly rename functions that have arguments with the same name ([#32](https://github.com/rollup/rollup/issues/32)) -* Ensure unused default exports are given a legal name ([#33](https://github.com/rollup/rollup/issues/33)) - -## 0.8.2 - -* Support `moduleId` and `moduleName` via CLI ([#24](https://github.com/rollup/rollup/issues/24)) - -## 0.8.1 - -* Anonymous functions that are exported as default are converted to named function declarations for correct hoisting, rather than being bound to functions ([#29](https://github.com/rollup/rollup/issues/29)) -* Automatically-generated default export names are deconflicted with local definitions ([#29](https://github.com/rollup/rollup/issues/29)) - -## 0.8.0 - -* Top-level variable declarations with multiple declarators are split up, to avoid unnecessary code importing and incorrectly-ordered statements ([#26](https://github.com/rollup/rollup/issues/26)) -* `this` at the top level is `undefined` ([#28](https://github.com/rollup/rollup/issues/28)) - -## 0.7.8 - -* Avoid using `path.parse` - unsupported in node 0.10 - -## 0.7.7 - -* Promise `source-map-support` from `devDependencies` to `dependencies` ([#23](https://github.com/rollup/rollup/issues/23)) - -## 0.7.6 - -* Better placement of `export default` statements ([#21](https://github.com/rollup/rollup/issues/21)) -* Prevent function calls and property assignments from being treated as rebinding for sake of unbound default exports -* Add `--external foo,bar,baz` option to CLI (equivalent to `external: ['foo', 'bar', 'baz']`) -* Add CLI tests - -## 0.7.5 - -* Prevent accidental conflicts with the global namespace ([#20](https://github.com/rollup/rollup/issues/20)) - -## 0.7.4 - -* More precise statement re-ordering to satisfy `export default` constraint (fixes bug introduced in 0.7.3) - -## 0.7.3 - -* Default exports are not bound. To enable this, statements within a module are sorted to retain their original order ([#15](https://github.com/rollup/rollup/issues/15)) -* Better positioning of comments ([#14](https://github.com/rollup/rollup/issues/14)) -* Various fixes to get Travis-CI rigged up - -## 0.7.2 - -* Fix sourcemap paths on Windows ([#6](https://github.com/rollup/rollup/pull/6)) - -## 0.7.1 - -* Named functions can be used as default exports from a bundle -* Method calls are assumed to mutate the owner (i.e. `foo.bar()` mutates `foo`) ([#13](https://github.com/rollup/rollup/issues/13)) -* `options.indent` can be used to control indentation of resulting bundle. `options.true` (default) means 'auto', `options.false` means empty string. Alternatively specify whitespace e.g. `' '` or `'\t'` ([#5](https://github.com/rollup/rollup/issues/5)) - -## 0.7.0 - -* Ensure statements are always separated by a newline ([#9](https://github.com/rollup/rollup/pull/9)) -* Use CommonJS `exports` correctly (UMD exports) -* Throw error if `moduleName` is required but missing (UMD exports) -* Attach IIFE global to `this` rather than `window` -* Allow names inside bundle to the the names of `Object.prototype` properties ([#12](https://github.com/rollup/rollup/pull/12)) -* Keep exports live ([#11](https://github.com/rollup/rollup/pull/11)) - -## 0.6.5 - -* Add sourceMappingURL comment to code, as appropriate -* Higher resolution sourcemaps - -## 0.6.4 - -* Fix CJS bundling with default export - -## 0.6.3 - -* Fix exports and external module imports with some output formats -* Fix endless cycle bug on Windows ([#3](https://github.com/rollup/rollup/pull/3)) - thanks @Bobris - -## 0.6.2 - -* Permit assignments to properties of imported bindings - -## 0.6.1 - -* Support for basic transformers - -## 0.6.0 - -* BREAKING - `rollup.rollup` and `bundle.write` both take a single options argument -* BREAKING - external modules must be declared upfront with `options.external: [...]` -* Non-relative module paths will be resolved by looking for `jsnext:main` fields in the appropriate `package.json` files. This behaviour can be overridden by passing an alternative `resolveExternal` function -* Fix sourcemap options -* Include CLI files in npm package (duh) - -## 0.5.0 - -* Command line interface -* Sourcemap generation -* Correct behaviour with `export { x as y } from 'z'` - -## 0.4.1 - -* More import name deconflicting - -## 0.4.0 - -* Self-hosting! `rollup.rollup` now rolls up rollup -* Fix bug with comments inside a statement later being appended to it -* Prevent shadowing of external modules -* Rewrite computed property identifiers where necessary -* Preserve original statement order where possible -* Internal refactoring - -## 0.3.1 - -* Saner deconflicting -* Rename namespace imports from external modules correctly - -## 0.3.0 - -* Basic functionality present, mostly spec-compliant - -## 0.2.1 - -* Include dist files in npm package (duh) - -## 0.2.0 - -* First release capable of doing anything useful -* Still lots of basic functionality missing - -## 0.1.0 - -* Initial experiment diff --git a/node_modules/rollup/LICENSE.md b/node_modules/rollup/LICENSE.md deleted file mode 100644 index 03e865a..0000000 --- a/node_modules/rollup/LICENSE.md +++ /dev/null @@ -1,762 +0,0 @@ -# Rollup core license -Rollup is released under the MIT license: - -The MIT License (MIT) - -Copyright (c) 2017 [these people](https://github.com/rollup/rollup/graphs/contributors) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -# Licenses of bundled dependencies -The published Rollup artifact additionally contains code with the following licenses: -MIT, ISC - -# Bundled dependencies: -## acorn -License: MIT -By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine -Repository: https://github.com/acornjs/acorn.git - -> MIT License -> -> Copyright (C) 2012-2020 by various contributors (see AUTHORS) -> -> 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. - ---------------------------------------- - -## acorn-class-fields -License: MIT -By: Adrian Heine -Repository: https://github.com/acornjs/acorn-class-fields - -> Copyright (C) 2017-2018 by Adrian Heine -> -> 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. - ---------------------------------------- - -## acorn-private-class-elements -License: MIT -By: Adrian Heine -Repository: https://github.com/acornjs/acorn-private-class-elements - -> Copyright (C) 2017-2018 by Adrian Heine -> -> 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. - ---------------------------------------- - -## acorn-static-class-features -License: MIT -By: Adrian Heine -Repository: https://github.com/acornjs/acorn-static-class-features - -> Copyright (C) 2017-2018 by Adrian Heine -> -> 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. - ---------------------------------------- - -## acorn-walk -License: MIT -By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine -Repository: https://github.com/acornjs/acorn.git - -> MIT License -> -> Copyright (C) 2012-2020 by various contributors (see AUTHORS) -> -> 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. - ---------------------------------------- - -## anymatch -License: ISC -By: Elan Shanker -Repository: https://github.com/micromatch/anymatch - -> The ISC License -> -> Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) -> -> Permission to use, copy, modify, and/or distribute this software for any -> purpose with or without fee is hereby granted, provided that the above -> copyright notice and this permission notice appear in all copies. -> -> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - ---------------------------------------- - -## binary-extensions -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/binary-extensions - ---------------------------------------- - -## braces -License: MIT -By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm -Repository: micromatch/braces - -> The MIT License (MIT) -> -> Copyright (c) 2014-2018, Jon Schlinkert. -> -> 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. - ---------------------------------------- - -## chokidar -License: MIT -By: Paul Miller, Elan Shanker -Repository: git+https://github.com/paulmillr/chokidar.git - -> The MIT License (MIT) -> -> Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker -> -> 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. - ---------------------------------------- - -## colorette -License: MIT -By: Jorge Bucaran -Repository: jorgebucaran/colorette - -> Copyright © Jorge Bucaran <> -> -> 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. - ---------------------------------------- - -## date-time -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/date-time - ---------------------------------------- - -## fill-range -License: MIT -By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling -Repository: jonschlinkert/fill-range - -> The MIT License (MIT) -> -> Copyright (c) 2014-present, Jon Schlinkert. -> -> 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. - ---------------------------------------- - -## glob-parent -License: ISC -By: Gulp Team, Elan Shanker, Blaine Bublitz -Repository: gulpjs/glob-parent - -> The ISC License -> -> Copyright (c) 2015, 2019 Elan Shanker -> -> Permission to use, copy, modify, and/or distribute this software for any -> purpose with or without fee is hereby granted, provided that the above -> copyright notice and this permission notice appear in all copies. -> -> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - ---------------------------------------- - -## hash.js -License: MIT -By: Fedor Indutny -Repository: git@github.com:indutny/hash.js - ---------------------------------------- - -## inherits -License: ISC -Repository: git://github.com/isaacs/inherits - -> The ISC License -> -> Copyright (c) Isaac Z. Schlueter -> -> Permission to use, copy, modify, and/or distribute this software for any -> purpose with or without fee is hereby granted, provided that the above -> copyright notice and this permission notice appear in all copies. -> -> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -> REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -> FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -> INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -> LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -> OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -> PERFORMANCE OF THIS SOFTWARE. - ---------------------------------------- - -## is-binary-path -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/is-binary-path - ---------------------------------------- - -## is-extglob -License: MIT -By: Jon Schlinkert -Repository: jonschlinkert/is-extglob - -> The MIT License (MIT) -> -> Copyright (c) 2014-2016, Jon Schlinkert -> -> 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. - ---------------------------------------- - -## is-glob -License: MIT -By: Jon Schlinkert, Brian Woodward, Daniel Perez -Repository: micromatch/is-glob - -> The MIT License (MIT) -> -> Copyright (c) 2014-2017, Jon Schlinkert. -> -> 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. - ---------------------------------------- - -## is-number -License: MIT -By: Jon Schlinkert, Olsten Larck, Rouven Weßling -Repository: jonschlinkert/is-number - -> The MIT License (MIT) -> -> Copyright (c) 2014-present, Jon Schlinkert. -> -> 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. - ---------------------------------------- - -## is-reference -License: MIT -By: Rich Harris -Repository: git+https://github.com/Rich-Harris/is-reference.git - ---------------------------------------- - -## locate-character -License: MIT -By: Rich Harris -Repository: Rich-Harris/locate-character - ---------------------------------------- - -## magic-string -License: MIT -By: Rich Harris -Repository: https://github.com/rich-harris/magic-string - -> Copyright 2018 Rich Harris -> -> 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. - ---------------------------------------- - -## micromatch -License: MIT -By: Jon Schlinkert, Amila Welihinda, Bogdan Chadkin, Brian Woodward, Devon Govett, Elan Shanker, Fabrício Matté, Martin Kolárik, Olsten Larck, Paul Miller, Tom Byrer, Tyler Akins, Peter Bright -Repository: micromatch/micromatch - -> The MIT License (MIT) -> -> Copyright (c) 2014-present, Jon Schlinkert. -> -> 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. - ---------------------------------------- - -## minimalistic-assert -License: ISC -Repository: https://github.com/calvinmetcalf/minimalistic-assert.git - -> Copyright 2015 Calvin Metcalf -> -> Permission to use, copy, modify, and/or distribute this software for any purpose -> with or without fee is hereby granted, provided that the above copyright notice -> and this permission notice appear in all copies. -> -> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -> REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -> FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -> INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -> LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -> OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -> PERFORMANCE OF THIS SOFTWARE. - ---------------------------------------- - -## normalize-path -License: MIT -By: Jon Schlinkert, Blaine Bublitz -Repository: jonschlinkert/normalize-path - -> The MIT License (MIT) -> -> Copyright (c) 2014-2018, Jon Schlinkert. -> -> 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. - ---------------------------------------- - -## parse-ms -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/parse-ms - ---------------------------------------- - -## picomatch -License: MIT -By: Jon Schlinkert -Repository: micromatch/picomatch - -> The MIT License (MIT) -> -> Copyright (c) 2017-present, Jon Schlinkert. -> -> 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. - ---------------------------------------- - -## pretty-bytes -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/pretty-bytes - ---------------------------------------- - -## pretty-ms -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/pretty-ms - ---------------------------------------- - -## readdirp -License: MIT -By: Thorsten Lorenz, Paul Miller -Repository: git://github.com/paulmillr/readdirp.git - -> MIT License -> -> Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com) -> -> 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. - ---------------------------------------- - -## require-relative -License: MIT -By: Valerio Proietti -Repository: git://github.com/kamicane/require-relative.git - ---------------------------------------- - -## rollup-pluginutils -License: MIT -By: Rich Harris -Repository: rollup/rollup-pluginutils - ---------------------------------------- - -## signal-exit -License: ISC -By: Ben Coe -Repository: https://github.com/tapjs/signal-exit.git - -> The ISC License -> -> Copyright (c) 2015, Contributors -> -> Permission to use, copy, modify, and/or distribute this software -> for any purpose with or without fee is hereby granted, provided -> that the above copyright notice and this permission notice -> appear in all copies. -> -> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES -> OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE -> LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES -> OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -> WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -> ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - ---------------------------------------- - -## sourcemap-codec -License: MIT -By: Rich Harris -Repository: https://github.com/Rich-Harris/sourcemap-codec - -> The MIT License -> -> Copyright (c) 2015 Rich Harris -> -> 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. - ---------------------------------------- - -## time-zone -License: MIT -By: Sindre Sorhus -Repository: sindresorhus/time-zone - ---------------------------------------- - -## to-regex-range -License: MIT -By: Jon Schlinkert, Rouven Weßling -Repository: micromatch/to-regex-range - -> The MIT License (MIT) -> -> Copyright (c) 2015-present, Jon Schlinkert. -> -> 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. - ---------------------------------------- - -## yargs-parser -License: ISC -By: Ben Coe -Repository: https://github.com/yargs/yargs-parser.git - -> Copyright (c) 2016, Contributors -> -> Permission to use, copy, modify, and/or distribute this software -> for any purpose with or without fee is hereby granted, provided -> that the above copyright notice and this permission notice -> appear in all copies. -> -> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES -> OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE -> LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES -> OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -> WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, -> ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/rollup/README.md b/node_modules/rollup/README.md deleted file mode 100644 index be9df6a..0000000 --- a/node_modules/rollup/README.md +++ /dev/null @@ -1,138 +0,0 @@ -# Rollup - -

- - npm version - - - install size - - - code coverage - - - backers - - - sponsors - - - license - - - dependency status - - - Join the chat at https://is.gd/rollup_chat - -

- - -## Overview - -Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the standardized ES module format for code, instead of previous idiosyncratic solutions such as CommonJS and AMD. ES modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries. Rollup can optimize ES modules for faster native loading in modern browsers, or output a legacy module format allowing ES module workflows today. - -## Quick Start Guide - -Install with `npm install --global rollup`. Rollup can be used either through a [command line interface](https://rollupjs.org/#command-line-reference) with an optional configuration file, or else through its [JavaScript API](https://rollupjs.org/guide/en/#javascript-api). Run `rollup --help` to see the available options and parameters. The starter project templates, [rollup-starter-lib](https://github.com/rollup/rollup-starter-lib) and [rollup-starter-app](https://github.com/rollup/rollup-starter-app), demonstrate common configuration options, and more detailed instructions are available throughout the [user guide](https://rollupjs.org/). - -### Commands - -These commands assume the entry point to your application is named main.js, and that you'd like all imports compiled into a single file named bundle.js. - -For browsers: - -```bash -# compile to a - js += `\nimport "${id}?html-proxy&index=${inlineModuleIndex}.js"`; - shouldRemove = true; - } - } - } - // For asset references in index.html, also generate an import - // statement for each - this will be handled by the asset plugin - const assetAttrs = assetAttrsConfig[node.tag]; - if (assetAttrs) { - for (const p of node.props) { - if (p.type === 6 /* ATTRIBUTE */ && - p.value && - assetAttrs.includes(p.name)) { - const url = p.value.content; - if (!isExcludedUrl(url)) { - if (node.tag === 'link' && isCSSRequest(url)) { - // CSS references, convert to import - js += `\nimport ${JSON.stringify(url)}`; - shouldRemove = true; - } - else { - assetUrls.push(p); - } - } - else if (checkPublicFile(url, config)) { - s.overwrite(p.value.loc.start.offset, p.value.loc.end.offset, `"${config.base + url.slice(1)}"`); - } - } - } - } - if (shouldRemove) { - // remove the script tag from the html. we are going to inject new - // ones in the end. - s.remove(node.loc.start.offset, node.loc.end.offset); - } - }); - // for each encountered asset url, rewrite original html so that it - // references the post-build location. - for (const attr of assetUrls) { - const value = attr.value; - try { - const url = attr.name === 'srcset' - ? await processSrcSet(value.content, ({ url }) => urlToBuiltUrl(url, id, config, this)) - : await urlToBuiltUrl(value.content, id, config, this); - s.overwrite(value.loc.start.offset, value.loc.end.offset, `"${url}"`); - } - catch (e) { - // #1885 preload may be pointing to urls that do not exist - // locally on disk - if (e.code !== 'ENOENT') { - throw e; - } - } - } - processedHtml.set(id, s.toString()); - // inject dynamic import polyfill - if (config.build.polyfillDynamicImport) { - js = `import "${polyfillId}";\n${js}`; - } - return js; - } - }, - async generateBundle(_, bundle) { - const getPreloadLinksForChunk = (chunk, seen = new Set()) => { - const tags = []; - chunk.imports.forEach((file) => { - const importee = bundle[file]; - if (importee && importee.type === 'chunk' && !seen.has(file)) { - seen.add(file); - tags.push({ - tag: 'link', - attrs: { - rel: 'modulepreload', - href: toPublicPath(file, config) - } - }); - tags.push(...getPreloadLinksForChunk(importee, seen)); - } - }); - return tags; - }; - const getCssTagsForChunk = (chunk, seen = new Set()) => { - const tags = []; - chunk.imports.forEach((file) => { - const importee = bundle[file]; - if (importee && importee.type === 'chunk') { - tags.push(...getCssTagsForChunk(importee, seen)); - } - }); - const cssFiles = chunkToEmittedCssFileMap.get(chunk); - if (cssFiles) { - cssFiles.forEach((file) => { - if (!seen.has(file)) { - seen.add(file); - tags.push({ - tag: 'link', - attrs: { - rel: 'stylesheet', - href: toPublicPath(file, config) - } - }); - } - }); - } - return tags; - }; - for (const [id, html] of processedHtml) { - // resolve asset url references - let result = html.replace(assetUrlRE, (_, fileHash, postfix = '') => { - return config.base + getAssetFilename(fileHash, config) + postfix; - }); - // find corresponding entry chunk - const chunk = Object.values(bundle).find((chunk) => chunk.type === 'chunk' && - chunk.isEntry && - chunk.facadeModuleId === id); - // inject chunk asset links - if (chunk) { - const assetTags = [ - // js entry chunk for this page - { - tag: 'script', - attrs: { - type: 'module', - crossorigin: true, - src: toPublicPath(chunk.fileName, config) - } - }, - // preload for imports - ...getPreloadLinksForChunk(chunk), - ...getCssTagsForChunk(chunk) - ]; - result = injectToHead(result, assetTags); - } - // inject css link when cssCodeSplit is false - if (!config.build.cssCodeSplit) { - const cssChunk = Object.values(bundle).find((chunk) => chunk.type === 'asset' && chunk.name === 'style.css'); - if (cssChunk) { - result = injectToHead(result, [ - { - tag: 'link', - attrs: { - rel: 'stylesheet', - href: toPublicPath(cssChunk.fileName, config) - } - } - ]); - } - } - const shortEmitName = path__default.posix.relative(config.root, id); - result = await applyHtmlTransforms(result, '/' + shortEmitName, id, postHooks, undefined, bundle, chunk); - this.emitFile({ - type: 'asset', - fileName: shortEmitName, - source: result - }); - } - } - }; -} -function resolveHtmlTransforms(plugins) { - const preHooks = []; - const postHooks = []; - for (const plugin of plugins) { - const hook = plugin.transformIndexHtml; - if (hook) { - if (typeof hook === 'function') { - postHooks.push(hook); - } - else if (hook.enforce === 'pre') { - preHooks.push(hook.transform); - } - else { - postHooks.push(hook.transform); - } - } - } - return [preHooks, postHooks]; -} -async function applyHtmlTransforms(html, path, filename, hooks, server, bundle, chunk) { - const headTags = []; - const headPrependTags = []; - const bodyTags = []; - const bodyPrependTags = []; - const ctx = { - path, - filename, - server, - bundle, - chunk - }; - for (const hook of hooks) { - const res = await hook(html, ctx); - if (!res) { - continue; - } - if (typeof res === 'string') { - html = res; - } - else { - let tags; - if (Array.isArray(res)) { - tags = res; - } - else { - html = res.html || html; - tags = res.tags; - } - for (const tag of tags) { - if (tag.injectTo === 'body') { - bodyTags.push(tag); - } - else if (tag.injectTo === 'body-prepend') { - bodyPrependTags.push(tag); - } - else if (tag.injectTo === 'head') { - headTags.push(tag); - } - else { - headPrependTags.push(tag); - } - } - } - } - // inject tags - if (headPrependTags.length) { - html = injectToHead(html, headPrependTags, true); - } - if (headTags.length) { - html = injectToHead(html, headTags); - } - if (bodyPrependTags.length) { - html = injectToBody(html, bodyPrependTags, true); - } - if (bodyTags.length) { - html = injectToBody(html, bodyTags); - } - return html; -} -function toPublicPath(filename, config) { - return isExternalUrl(filename) ? filename : config.base + filename; -} -const headInjectRE = /<\/head>/; -const headPrependInjectRE = [//, //i]; -function injectToHead(html, tags, prepend = false) { - const tagsHtml = serializeTags(tags); - if (prepend) { - // inject after head or doctype - for (const re of headPrependInjectRE) { - if (re.test(html)) { - return html.replace(re, `$&\n${tagsHtml}`); - } - } - } - else { - // inject before head close - if (headInjectRE.test(html)) { - return html.replace(headInjectRE, `${tagsHtml}\n$&`); - } - } - // if no tag is present, just prepend - return tagsHtml + `\n` + html; -} -const bodyInjectRE = /<\/body>/; -const bodyPrependInjectRE = //; -function injectToBody(html, tags, prepend = false) { - if (prepend) { - // inject after body open - const tagsHtml = `\n` + serializeTags(tags); - if (bodyPrependInjectRE.test(html)) { - return html.replace(bodyPrependInjectRE, `$&\n${tagsHtml}`); - } - // if no body, prepend - return tagsHtml + `\n` + html; - } - else { - // inject before body close - const tagsHtml = `\n` + serializeTags(tags); - if (bodyInjectRE.test(html)) { - return html.replace(bodyInjectRE, `${tagsHtml}\n$&`); - } - // if no body, append - return html + `\n` + tagsHtml; - } -} -const unaryTags = new Set(['link', 'meta', 'base']); -function serializeTag({ tag, attrs, children }) { - if (unaryTags.has(tag)) { - return `<${tag}${serializeAttrs(attrs)}>`; - } - else { - return `<${tag}${serializeAttrs(attrs)}>${serializeTags(children)}`; - } -} -function serializeTags(tags) { - if (typeof tags === 'string') { - return tags; - } - else if (tags) { - return tags.map(serializeTag).join(`\n `); - } - return ''; -} -function serializeAttrs(attrs) { - let res = ''; - for (const key in attrs) { - if (typeof attrs[key] === 'boolean') { - res += attrs[key] ? ` ${key}` : ``; - } - else { - res += ` ${key}=${JSON.stringify(attrs[key])}`; - } - } - return res; -} - -const debug$a = createDebugger('vite:esbuild'); -async function transformWithEsbuild(code, filename, options, inMap) { - // if the id ends with a valid ext, use it (e.g. vue blocks) - // otherwise, cleanup the query before checking the ext - const ext = path__default.extname(/\.\w+$/.test(filename) ? filename : cleanUrl(filename)); - let loader = ext.slice(1); - if (loader === 'cjs' || loader === 'mjs') { - loader = 'js'; - } - const resolvedOptions = { - loader: loader, - sourcemap: true, - // ensure source file name contains full query - sourcefile: filename, - ...options - }; - delete resolvedOptions.include; - delete resolvedOptions.exclude; - delete resolvedOptions.jsxInject; - try { - const result = await esbuild.transform(code, resolvedOptions); - if (inMap) { - const nextMap = JSON.parse(result.map); - nextMap.sourcesContent = []; - return { - ...result, - map: combineSourcemaps(filename, [ - nextMap, - inMap - ]) - }; - } - else { - return { - ...result, - map: JSON.parse(result.map) - }; - } - } - catch (e) { - debug$a(`esbuild error with options used: `, resolvedOptions); - // patch error information - if (e.errors) { - e.frame = ''; - e.errors.forEach((m) => { - e.frame += `\n` + prettifyMessage(m, code); - }); - e.loc = e.errors[0].location; - } - throw e; - } -} -function esbuildPlugin(options = {}) { - const filter = createFilter$1(options.include || /\.(tsx?|jsx)$/, options.exclude || /\.js$/); - return { - name: 'vite:esbuild', - async transform(code, id) { - if (filter(id) || filter(cleanUrl(id))) { - const result = await transformWithEsbuild(code, id, options); - if (result.warnings.length) { - result.warnings.forEach((m) => { - this.warn(prettifyMessage(m, code)); - }); - } - if (options.jsxInject && /\.(?:j|t)sx\b/.test(id)) { - result.code = options.jsxInject + ';' + result.code; - } - return { - code: result.code, - map: result.map - }; - } - } - }; -} -const buildEsbuildPlugin = (config) => { - return { - name: 'vite:esbuild-transpile', - async renderChunk(code, chunk, opts) { - // @ts-ignore injected by @vitejs/plugin-legacy - if (opts.__vite_skip_esbuild__) { - return null; - } - const target = config.build.target; - const minify = config.build.minify === 'esbuild'; - if (!target && !minify) { - return null; - } - return transformWithEsbuild(code, chunk.fileName, { - target: target || undefined, - minify - }); - } - }; -}; -function prettifyMessage(m, code) { - let res = source.yellow(m.text); - if (m.location) { - const lines = code.split(/\r?\n/g); - const line = Number(m.location.line); - const column = Number(m.location.column); - const offset = lines - .slice(0, line - 1) - .map((l) => l.length) - .reduce((total, l) => total + l + 1, 0) + column; - res += `\n` + generateCodeFrame(code, offset, offset + 1); - } - return res + `\n`; -} - -var dist = createCommonjsModule(function (module, exports) { -var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Worker = void 0; -const os_1 = __importDefault(os__default); - -class Worker { - constructor(fn, options = {}) { - this.code = genWorkerCode(fn); - this.max = options.max || Math.max(1, os_1.default.cpus().length - 1); - this.pool = []; - this.idlePool = []; - this.queue = []; - } - async run(...args) { - const worker = await this._getAvailableWorker(); - return new Promise((resolve, reject) => { - worker.currentResolve = resolve; - worker.currentReject = reject; - worker.postMessage(args); - }); - } - stop() { - this.pool.forEach((w) => w.unref()); - this.queue.forEach(([_, reject]) => reject(new Error('Main worker pool stopped before a worker was available.'))); - this.pool = []; - this.idlePool = []; - this.queue = []; - } - async _getAvailableWorker() { - // has idle one? - if (this.idlePool.length) { - return this.idlePool.shift(); - } - // can spawn more? - if (this.pool.length < this.max) { - const worker = new worker_threads_1__default.Worker(this.code, { eval: true }); - worker.on('message', (res) => { - worker.currentResolve && worker.currentResolve(res); - worker.currentResolve = null; - this._assignDoneWorker(worker); - }); - worker.on('error', (err) => { - worker.currentReject && worker.currentReject(err); - worker.currentReject = null; - }); - worker.on('exit', (code) => { - const i = this.pool.indexOf(worker); - if (i > -1) - this.pool.splice(i, 1); - if (code !== 0 && worker.currentReject) { - worker.currentReject(new Error(`Wroker stopped with non-0 exit code ${code}`)); - worker.currentReject = null; - } - }); - this.pool.push(worker); - return worker; - } - // no one is available, we have to wait - let resolve; - let reject; - const onWorkerAvailablePromise = new Promise((r, rj) => { - resolve = r; - reject = rj; - }); - this.queue.push([resolve, reject]); - return onWorkerAvailablePromise; - } - _assignDoneWorker(worker) { - // someone's waiting already? - if (this.queue.length) { - const [resolve] = this.queue.shift(); - resolve(worker); - return; - } - // take a rest. - this.idlePool.push(worker); - } -} -exports.Worker = Worker; -function genWorkerCode(fn) { - return ` -const doWork = ${fn.toString()} - -const { parentPort } = require('worker_threads') - -parentPort.on('message', async (args) => { - const res = await doWork(...args) - parentPort.postMessage(res) -}) - `; -} -}); - -function terserPlugin(options) { - const worker = new dist.Worker((basedir, code, options) => { - // when vite is linked, the worker thread won't share the same resolve - // root with vite itself, so we have to pass in the basedir and resolve - // terser first. - // eslint-disable-next-line - const terserPath = require.resolve('vite/dist/node/terser', { - paths: [basedir] - }); - return require(terserPath).minify(code, options); - }); - return { - name: 'vite:terser', - async renderChunk(code, _chunk, outputOptions) { - const res = await worker.run(__dirname, code, { - ...options, - sourceMap: !!outputOptions.sourcemap, - module: outputOptions.format.startsWith('es'), - toplevel: outputOptions.format === 'cjs', - safari10: true - }); - return { - code: res.code, - map: res.map - }; - }, - closeBundle() { - worker.stop(); - } - }; -} - -function manifestPlugin(config) { - const manifest = {}; - let outputCount = 0; - return { - name: 'vite:manifest', - generateBundle({ format }, bundle) { - var _a; - function getChunkName(chunk) { - if (chunk.facadeModuleId) { - let name = normalizePath$2(path__default.relative(config.root, chunk.facadeModuleId)); - if (format === 'system' && !chunk.name.includes('-legacy')) { - const ext = path__default.extname(name); - name = name.slice(0, -ext.length) + `-legacy` + ext; - } - return name; - } - else { - return `_` + path__default.basename(chunk.fileName); - } - } - function getInternalImports(imports) { - const filteredImports = []; - for (const file of imports) { - if (bundle[file] === undefined) { - continue; - } - filteredImports.push(getChunkName(bundle[file])); - } - return filteredImports; - } - function createChunk(chunk) { - const manifestChunk = { - file: chunk.fileName - }; - if (chunk.facadeModuleId) { - manifestChunk.src = getChunkName(chunk); - } - if (chunk.isEntry) { - manifestChunk.isEntry = true; - } - if (chunk.isDynamicEntry) { - manifestChunk.isDynamicEntry = true; - } - if (chunk.imports.length) { - const internalImports = getInternalImports(chunk.imports); - if (internalImports.length > 0) { - manifestChunk.imports = internalImports; - } - } - if (chunk.dynamicImports.length) { - const internalImports = getInternalImports(chunk.dynamicImports); - if (internalImports.length > 0) { - manifestChunk.dynamicImports = internalImports; - } - } - const cssFiles = chunkToEmittedCssFileMap.get(chunk); - if (cssFiles) { - manifestChunk.css = [...cssFiles]; - } - const assets = chunkToEmittedAssetsMap.get(chunk); - if (assets) - [(manifestChunk.assets = [...assets])]; - return manifestChunk; - } - for (const file in bundle) { - const chunk = bundle[file]; - if (chunk.type === 'chunk') { - manifest[getChunkName(chunk)] = createChunk(chunk); - } - } - outputCount++; - const output = (_a = config.build.rollupOptions) === null || _a === void 0 ? void 0 : _a.output; - const outputLength = Array.isArray(output) ? output.length : 1; - if (outputCount >= outputLength) { - this.emitFile({ - fileName: `manifest.json`, - type: 'asset', - source: JSON.stringify(manifest, null, 2) - }); - } - } - }; -} - -function walk$2(ast, { enter, leave }) { - return visit(ast, null, enter, leave); -} - -let should_skip = false; -let should_remove = false; -let replacement = null; -const context = { - skip: () => should_skip = true, - remove: () => should_remove = true, - replace: (node) => replacement = node -}; - -function replace(parent, prop, index, node) { - if (parent) { - if (index !== null) { - parent[prop][index] = node; - } else { - parent[prop] = node; - } - } -} - -function remove(parent, prop, index) { - if (parent) { - if (index !== null) { - parent[prop].splice(index, 1); - } else { - delete parent[prop]; - } - } -} - -function visit( - node, - parent, - enter, - leave, - prop, - index -) { - if (node) { - if (enter) { - const _should_skip = should_skip; - const _should_remove = should_remove; - const _replacement = replacement; - should_skip = false; - should_remove = false; - replacement = null; - - enter.call(context, node, parent, prop, index); - - if (replacement) { - node = replacement; - replace(parent, prop, index, node); - } - - if (should_remove) { - remove(parent, prop, index); - } - - const skipped = should_skip; - const removed = should_remove; - - should_skip = _should_skip; - should_remove = _should_remove; - replacement = _replacement; - - if (skipped) return node; - if (removed) return null; - } - - for (const key in node) { - const value = (node )[key]; - - if (typeof value !== 'object') { - continue; - } - - else if (Array.isArray(value)) { - for (let j = 0, k = 0; j < value.length; j += 1, k += 1) { - if (value[j] !== null && typeof value[j].type === 'string') { - if (!visit(value[j], node, enter, leave, key, k)) { - // removed - j--; - } - } - } - } - - else if (value !== null && typeof value.type === 'string') { - visit(value, node, enter, leave, key, null); - } - } - - if (leave) { - const _replacement = replacement; - const _should_remove = should_remove; - replacement = null; - should_remove = false; - - leave.call(context, node, parent, prop, index); - - if (replacement) { - node = replacement; - replace(parent, prop, index, node); - } - - if (should_remove) { - remove(parent, prop, index); - } - - const removed = should_remove; - - replacement = _replacement; - should_remove = _should_remove; - - if (removed) return null; - } - } - - return node; -} - -const extractors = { - ArrayPattern(names, param) { - for (const element of param.elements) { - if (element) - extractors[element.type](names, element); - } - }, - AssignmentPattern(names, param) { - extractors[param.left.type](names, param.left); - }, - Identifier(names, param) { - names.push(param.name); - }, - MemberExpression() { }, - ObjectPattern(names, param) { - for (const prop of param.properties) { - // @ts-ignore Typescript reports that this is not a valid type - if (prop.type === 'RestElement') { - extractors.RestElement(names, prop); - } - else { - extractors[prop.value.type](names, prop.value); - } - } - }, - RestElement(names, param) { - extractors[param.argument.type](names, param.argument); - } -}; -const extractAssignedNames = function extractAssignedNames(param) { - const names = []; - extractors[param.type](names, param); - return names; -}; - -const blockDeclarations = { - const: true, - let: true -}; -class Scope$1 { - constructor(options = {}) { - this.parent = options.parent; - this.isBlockScope = !!options.block; - this.declarations = Object.create(null); - if (options.params) { - options.params.forEach((param) => { - extractAssignedNames(param).forEach((name) => { - this.declarations[name] = true; - }); - }); - } - } - addDeclaration(node, isBlockDeclaration, isVar) { - if (!isBlockDeclaration && this.isBlockScope) { - // it's a `var` or function node, and this - // is a block scope, so we need to go up - this.parent.addDeclaration(node, isBlockDeclaration, isVar); - } - else if (node.id) { - extractAssignedNames(node.id).forEach((name) => { - this.declarations[name] = true; - }); - } - } - contains(name) { - return this.declarations[name] || (this.parent ? this.parent.contains(name) : false); - } -} -const attachScopes = function attachScopes(ast, propertyName = 'scope') { - let scope = new Scope$1(); - walk$2(ast, { - enter(n, parent) { - const node = n; - // function foo () {...} - // class Foo {...} - if (/(Function|Class)Declaration/.test(node.type)) { - scope.addDeclaration(node, false, false); - } - // var foo = 1 - if (node.type === 'VariableDeclaration') { - const { kind } = node; - const isBlockDeclaration = blockDeclarations[kind]; - // don't add const/let declarations in the body of a for loop #113 - const parentType = parent ? parent.type : ''; - if (!(isBlockDeclaration && /ForOfStatement/.test(parentType))) { - node.declarations.forEach((declaration) => { - scope.addDeclaration(declaration, isBlockDeclaration, true); - }); - } - } - let newScope; - // create new function scope - if (/Function/.test(node.type)) { - const func = node; - newScope = new Scope$1({ - parent: scope, - block: false, - params: func.params - }); - // named function expressions - the name is considered - // part of the function's scope - if (func.type === 'FunctionExpression' && func.id) { - newScope.addDeclaration(func, false, false); - } - } - // create new block scope - if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) { - newScope = new Scope$1({ - parent: scope, - block: true - }); - } - // catch clause has its own block scope - if (node.type === 'CatchClause') { - newScope = new Scope$1({ - parent: scope, - params: node.param ? [node.param] : [], - block: true - }); - } - if (newScope) { - Object.defineProperty(node, propertyName, { - value: newScope, - configurable: true - }); - scope = newScope; - } - }, - leave(n) { - const node = n; - if (node[propertyName]) - scope = scope.parent; - } - }); - return scope; -}; - -// Helper since Typescript can't detect readonly arrays with Array.isArray -function isArray$2(arg) { - return Array.isArray(arg); -} -function ensureArray(thing) { - if (isArray$2(thing)) - return thing; - if (thing == null) - return []; - return [thing]; -} - -function getMatcherString(id, resolutionBase) { - if (resolutionBase === false) { - return id; - } - // resolve('') is valid and will default to process.cwd() - const basePath = path$1.resolve(resolutionBase || '') - .split(path$1.sep) - .join('/') - // escape all possible (posix + win) path characters that might interfere with regex - .replace(/[-^$*+?.()|[\]{}]/g, '\\$&'); - // Note that we use posix.join because: - // 1. the basePath has been normalized to use / - // 2. the incoming glob (id) matcher, also uses / - // otherwise Node will force backslash (\) on windows - return path$1.posix.join(basePath, id); -} -const createFilter = function createFilter(include, exclude, options) { - const resolutionBase = options && options.resolve; - const getMatcher = (id) => id instanceof RegExp - ? id - : { - test: (what) => { - // this refactor is a tad overly verbose but makes for easy debugging - const pattern = getMatcherString(id, resolutionBase); - const fn = picomatch(pattern, { dot: true }); - const result = fn(what); - return result; - } - }; - const includeMatchers = ensureArray(include).map(getMatcher); - const excludeMatchers = ensureArray(exclude).map(getMatcher); - return function result(id) { - if (typeof id !== 'string') - return false; - if (/\0/.test(id)) - return false; - const pathId = id.split(path$1.sep).join('/'); - for (let i = 0; i < excludeMatchers.length; ++i) { - const matcher = excludeMatchers[i]; - if (matcher.test(pathId)) - return false; - } - for (let i = 0; i < includeMatchers.length; ++i) { - const matcher = includeMatchers[i]; - if (matcher.test(pathId)) - return true; - } - return !includeMatchers.length; - }; -}; - -const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'; -const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'; -const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins}`.split(' ')); -forbiddenIdentifiers.add(''); -const makeLegalIdentifier = function makeLegalIdentifier(str) { - let identifier = str - .replace(/-(\w)/g, (_, letter) => letter.toUpperCase()) - .replace(/[^$_a-zA-Z0-9]/g, '_'); - if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) { - identifier = `_${identifier}`; - } - return identifier || '_'; -}; - -var commondir = function (basedir, relfiles) { - if (relfiles) { - var files = relfiles.map(function (r) { - return path__default.resolve(basedir, r); - }); - } - else { - var files = basedir; - } - - var res = files.slice(1).reduce(function (ps, file) { - if (!file.match(/^([A-Za-z]:)?\/|\\/)) { - throw new Error('relative path without a basedir'); - } - - var xs = file.split(/\/+|\\+/); - for ( - var i = 0; - ps[i] === xs[i] && i < Math.min(ps.length, xs.length); - i++ - ); - return ps.slice(0, i); - }, files[0].split(/\/+|\\+/)); - - // Windows correctly handles paths with forward-slashes - return res.length > 1 ? res.join('/') : '/' -}; - -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var isWindows$3 = process.platform === 'win32'; - - -// JavaScript implementation of realpath, ported from node pre-v6 - -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); - -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; - - return callback; - - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); - } - } - - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } - } - } -} - -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); -} - -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows$3) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; -} - -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows$3) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; -} - -var realpathSync$1 = function realpathSync(p, cache) { - // make p is absolute - p = path__default.resolve(p); - - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; - } - - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); - - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; - - // On windows, check that the root exists. On unix there is no need. - if (isWindows$3 && !knownHard[base]) { - fs__default.lstatSync(base); - knownHard[base] = true; - } - } - - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; - } - - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs__default.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } - - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows$3) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; - } - } - if (linkTarget === null) { - fs__default.statSync(base); - linkTarget = fs__default.readlinkSync(base); - } - resolvedLink = path__default.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows$3) seenLinks[id] = linkTarget; - } - - // resolve the link, then start over - p = path__default.resolve(resolvedLink, p.slice(pos)); - start(); - } - - if (cache) cache[original] = p; - - return p; -}; - - -var realpath$3 = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; - } - - // make p is absolute - p = path__default.resolve(p); - - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); - } - - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); - - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; - - // On windows, check that the root exists. On unix there is no need. - if (isWindows$3 && !knownHard[base]) { - fs__default.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); - } else { - process.nextTick(LOOP); - } - } - - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); - } - - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); - } - - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); - } - - return fs__default.lstat(base, gotStat); - } - - function gotStat(err, stat) { - if (err) return cb(err); - - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); - } - - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows$3) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); - } - } - fs__default.stat(base, function(err) { - if (err) return cb(err); - - fs__default.readlink(base, function(err, target) { - if (!isWindows$3) seenLinks[id] = target; - gotTarget(err, target); - }); - }); - } - - function gotTarget(err, target, base) { - if (err) return cb(err); - - var resolvedLink = path__default.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); - } - - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = path__default.resolve(resolvedLink, p.slice(pos)); - start(); - } -}; - -var old = { - realpathSync: realpathSync$1, - realpath: realpath$3 -}; - -var fs_realpath = realpath$2; -realpath$2.realpath = realpath$2; -realpath$2.sync = realpathSync; -realpath$2.realpathSync = realpathSync; -realpath$2.monkeypatch = monkeypatch; -realpath$2.unmonkeypatch = unmonkeypatch; - - -var origRealpath = fs__default.realpath; -var origRealpathSync = fs__default.realpathSync; - -var version$1 = process.version; -var ok = /^v[0-5]\./.test(version$1); - - -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) -} - -function realpath$2 (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) - } - - if (typeof cache === 'function') { - cb = cache; - cache = null; - } - origRealpath(p, cache, function (er, result) { - if (newError(er)) { - old.realpath(p, cache, cb); - } else { - cb(er, result); - } - }); -} - -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) - } - - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er - } - } -} - -function monkeypatch () { - fs__default.realpath = realpath$2; - fs__default.realpathSync = realpathSync; -} - -function unmonkeypatch () { - fs__default.realpath = origRealpath; - fs__default.realpathSync = origRealpathSync; -} - -var concatMap = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray$1(x)) res.push.apply(res, x); - else res.push(x); - } - return res; -}; - -var isArray$1 = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -var balancedMatch = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - - var r = range(a, b, str); - - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} - -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} - -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; - - if (ai >= 0 && bi > 0) { - begs = []; - left = str.length; - - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } - - bi = str.indexOf(b, i + 1); - } - - i = ai < bi && ai >= 0 ? ai : bi; - } - - if (begs.length) { - result = [ left, right ]; - } - } - - return result; -} - -var braceExpansion = expandTop; - -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; - -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} - -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} - - -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; - - var parts = []; - var m = balancedMatch('{', '}', str); - - if (!m) - return str.split(','); - - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); - - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); - } - - parts.push.apply(parts, p); - - return parts; -} - -function expandTop(str) { - if (!str) - return []; - - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } - - return expand(escapeBraces(str), true).map(unescapeBraces); -} - -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} - -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} - -function expand(str, isTop) { - var expansions = []; - - var m = balancedMatch('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; - - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } - - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } - - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. - - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; - - var N; - - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length); - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); - - N = []; - - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } - - return expansions; -} - -var minimatch_1 = minimatch; -minimatch.Minimatch = Minimatch$1; - -var path = { sep: '/' }; -try { - path = path__default; -} catch (er) {} - -var GLOBSTAR$1 = minimatch.GLOBSTAR = Minimatch$1.GLOBSTAR = {}; - - -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } -}; - -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]'; - -// * => any number of characters -var star = qmark + '*?'; - -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; - -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; - -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!'); - -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true; - return set - }, {}) -} - -// normalizes slashes. -var slashSplit = /\/+/; - -minimatch.filter = filter; -function filter (pattern, options) { - options = options || {}; - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} - -function ext (a, b) { - a = a || {}; - b = b || {}; - var t = {}; - Object.keys(b).forEach(function (k) { - t[k] = b[k]; - }); - Object.keys(a).forEach(function (k) { - t[k] = a[k]; - }); - return t -} - -minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return minimatch - - var orig = minimatch; - - var m = function minimatch (p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)) - }; - - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - }; - - return m -}; - -Minimatch$1.defaults = function (def) { - if (!def || !Object.keys(def).length) return Minimatch$1 - return minimatch.defaults(def).Minimatch -}; - -function minimatch (p, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } - - if (!options) options = {}; - - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } - - // "" only matches "" - if (pattern.trim() === '') return p === '' - - return new Minimatch$1(pattern, options).match(p) -} - -function Minimatch$1 (pattern, options) { - if (!(this instanceof Minimatch$1)) { - return new Minimatch$1(pattern, options) - } - - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } - - if (!options) options = {}; - pattern = pattern.trim(); - - // windows support: need to use /, not \ - if (path.sep !== '/') { - pattern = pattern.split(path.sep).join('/'); - } - - this.options = options; - this.set = []; - this.pattern = pattern; - this.regexp = null; - this.negate = false; - this.comment = false; - this.empty = false; - - // make the set of regexps etc. - this.make(); -} - -Minimatch$1.prototype.debug = function () {}; - -Minimatch$1.prototype.make = make; -function make () { - // don't do it more than once. - if (this._made) return - - var pattern = this.pattern; - var options = this.options; - - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true; - return - } - if (!pattern) { - this.empty = true; - return - } - - // step 1: figure out negation, etc. - this.parseNegate(); - - // step 2: expand braces - var set = this.globSet = this.braceExpand(); - - if (options.debug) this.debug = console.error; - - this.debug(this.pattern, set); - - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }); - - this.debug(this.pattern, set); - - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this); - - this.debug(this.pattern, set); - - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }); - - this.debug(this.pattern, set); - - this.set = set; -} - -Minimatch$1.prototype.parseNegate = parseNegate; -function parseNegate () { - var pattern = this.pattern; - var negate = false; - var options = this.options; - var negateOffset = 0; - - if (options.nonegate) return - - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate; - negateOffset++; - } - - if (negateOffset) this.pattern = pattern.substr(negateOffset); - this.negate = negate; -} - -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -}; - -Minimatch$1.prototype.braceExpand = braceExpand; - -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch$1) { - options = this.options; - } else { - options = {}; - } - } - - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern; - - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') - } - - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } - - return braceExpansion(pattern) -} - -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch$1.prototype.parse = parse$c; -var SUBPARSE = {}; -function parse$c (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } - - var options = this.options; - - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR$1 - if (pattern === '') return '' - - var re = ''; - var hasMagic = !!options.nocase; - var escaping = false; - // ? => one single character - var patternListStack = []; - var negativeLists = []; - var stateChar; - var inClass = false; - var reClassStart = -1; - var classStart = -1; - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)'; - var self = this; - - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star; - hasMagic = true; - break - case '?': - re += qmark; - hasMagic = true; - break - default: - re += '\\' + stateChar; - break - } - self.debug('clearStateChar %j %j', stateChar, re); - stateChar = false; - } - } - - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c); - - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c; - escaping = false; - continue - } - - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - - case '\\': - clearStateChar(); - escaping = true; - continue - - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class'); - if (c === '!' && i === classStart + 1) c = '^'; - re += c; - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar); - clearStateChar(); - stateChar = c; - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar(); - continue - - case '(': - if (inClass) { - re += '('; - continue - } - - if (!stateChar) { - re += '\\('; - continue - } - - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }); - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:'; - this.debug('plType %j %j', stateChar, re); - stateChar = false; - continue - - case ')': - if (inClass || !patternListStack.length) { - re += '\\)'; - continue - } - - clearStateChar(); - hasMagic = true; - var pl = patternListStack.pop(); - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close; - if (pl.type === '!') { - negativeLists.push(pl); - } - pl.reEnd = re.length; - continue - - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|'; - escaping = false; - continue - } - - clearStateChar(); - re += '|'; - continue - - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar(); - - if (inClass) { - re += '\\' + c; - continue - } - - inClass = true; - classStart = i; - reClassStart = re.length; - re += c; - continue - - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c; - escaping = false; - continue - } - - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i); - try { - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE); - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'; - hasMagic = hasMagic || sp[1]; - inClass = false; - continue - } - } - - // finish up the class. - hasMagic = true; - inClass = false; - re += c; - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar(); - - if (escaping) { - // no need - escaping = false; - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\'; - } - - re += c; - - } // switch - } // for - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1); - sp = this.parse(cs, SUBPARSE); - re = re.substr(0, reClassStart) + '\\[' + sp[0]; - hasMagic = hasMagic || sp[1]; - } - - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length); - this.debug('setting tail', re, pl); - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\'; - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }); - - this.debug('tail=%j\n %s', tail, tail, pl, re); - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type; - - hasMagic = true; - re = re.slice(0, pl.reStart) + t + '\\(' + tail; - } - - // handle trailing things that only matter at the very end. - clearStateChar(); - if (escaping) { - // trailing \\ - re += '\\\\'; - } - - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false; - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true; - } - - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n]; - - var nlBefore = re.slice(0, nl.reStart); - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8); - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd); - var nlAfter = re.slice(nl.reEnd); - - nlLast += nlAfter; - - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1; - var cleanAfter = nlAfter; - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); - } - nlAfter = cleanAfter; - - var dollar = ''; - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$'; - } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast; - re = newRe; - } - - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re; - } - - if (addPatternStart) { - re = patternStart + re; - } - - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } - - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } - - var flags = options.nocase ? 'i' : ''; - try { - var regExp = new RegExp('^' + re + '$', flags); - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } - - regExp._glob = pattern; - regExp._src = re; - - return regExp -} - -minimatch.makeRe = function (pattern, options) { - return new Minimatch$1(pattern, options || {}).makeRe() -}; - -Minimatch$1.prototype.makeRe = makeRe; -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp - - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set; - - if (!set.length) { - this.regexp = false; - return this.regexp - } - var options = this.options; - - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot; - var flags = options.nocase ? 'i' : ''; - - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR$1) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|'); - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$'; - - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$'; - - try { - this.regexp = new RegExp(re, flags); - } catch (ex) { - this.regexp = false; - } - return this.regexp -} - -minimatch.match = function (list, pattern, options) { - options = options || {}; - var mm = new Minimatch$1(pattern, options); - list = list.filter(function (f) { - return mm.match(f) - }); - if (mm.options.nonull && !list.length) { - list.push(pattern); - } - return list -}; - -Minimatch$1.prototype.match = match; -function match (f, partial) { - this.debug('match', f, this.pattern); - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' - - if (f === '/' && partial) return true - - var options = this.options; - - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/'); - } - - // treat the test path as a set of pathparts. - f = f.split(slashSplit); - this.debug(this.pattern, 'split', f); - - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. - - var set = this.set; - this.debug(this.pattern, 'set', set); - - // Find the basename of the path by looking for the last non-empty segment - var filename; - var i; - for (i = f.length - 1; i >= 0; i--) { - filename = f[i]; - if (filename) break - } - - for (i = 0; i < set.length; i++) { - var pattern = set[i]; - var file = f; - if (options.matchBase && pattern.length === 1) { - file = [filename]; - } - var hit = this.matchOne(file, pattern, partial); - if (hit) { - if (options.flipNegate) return true - return !this.negate - } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} - -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch$1.prototype.matchOne = function (file, pattern, partial) { - var options = this.options; - - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }); - - this.debug('matchOne', file.length, pattern.length); - - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop'); - var p = pattern[pi]; - var f = file[fi]; - - this.debug(pattern, p, f); - - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false - - if (p === GLOBSTAR$1) { - this.debug('GLOBSTAR', [pattern, p, f]); - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi; - var pr = pi + 1; - if (pr === pl) { - this.debug('** at the end'); - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr]; - - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); - - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee); - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr); - break - } - - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue'); - fr++; - } - } - - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr); - if (fr === fl) return true - } - return false - } - - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit; - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase(); - } else { - hit = f === p; - } - this.debug('string match', p, f, hit); - } else { - hit = f.match(p); - this.debug('pattern match', p, f, hit); - } - - if (!hit) return false - } - - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === ''); - return emptyFileEnd - } - - // should be unreachable. - throw new Error('wtf?') -}; - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} - -var inherits_browser = createCommonjsModule(function (module) { -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - }; -} -}); - -var inherits = createCommonjsModule(function (module) { -try { - var util = util__default; - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = inherits_browser; -} -}); - -function posix(path) { - return path.charAt(0) === '/'; -} - -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); - - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} - -var pathIsAbsolute = process.platform === 'win32' ? win32 : posix; -var posix_1 = posix; -var win32_1 = win32; -pathIsAbsolute.posix = posix_1; -pathIsAbsolute.win32 = win32_1; - -var alphasort_1 = alphasort; -var alphasorti_1 = alphasorti; -var setopts_1 = setopts$2; -var ownProp_1 = ownProp$2; -var makeAbs_1 = makeAbs; -var finish_1 = finish; -var mark_1 = mark; -var isIgnored_1 = isIgnored$2; -var childrenIgnored_1 = childrenIgnored$2; - -function ownProp$2 (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) -} - - - - -var Minimatch = minimatch_1.Minimatch; - -function alphasorti (a, b) { - return a.toLowerCase().localeCompare(b.toLowerCase()) -} - -function alphasort (a, b) { - return a.localeCompare(b) -} - -function setupIgnores (self, options) { - self.ignore = options.ignore || []; - - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore]; - - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap); - } -} - -// ignore patterns are always in dot:true mode. -function ignoreMap (pattern) { - var gmatcher = null; - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, ''); - gmatcher = new Minimatch(gpattern, { dot: true }); - } - - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher - } -} - -function setopts$2 (self, pattern, options) { - if (!options) - options = {}; - - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") - } - pattern = "**/" + pattern; - } - - self.silent = !!options.silent; - self.pattern = pattern; - self.strict = options.strict !== false; - self.realpath = !!options.realpath; - self.realpathCache = options.realpathCache || Object.create(null); - self.follow = !!options.follow; - self.dot = !!options.dot; - self.mark = !!options.mark; - self.nodir = !!options.nodir; - if (self.nodir) - self.mark = true; - self.sync = !!options.sync; - self.nounique = !!options.nounique; - self.nonull = !!options.nonull; - self.nosort = !!options.nosort; - self.nocase = !!options.nocase; - self.stat = !!options.stat; - self.noprocess = !!options.noprocess; - self.absolute = !!options.absolute; - - self.maxLength = options.maxLength || Infinity; - self.cache = options.cache || Object.create(null); - self.statCache = options.statCache || Object.create(null); - self.symlinks = options.symlinks || Object.create(null); - - setupIgnores(self, options); - - self.changedCwd = false; - var cwd = process.cwd(); - if (!ownProp$2(options, "cwd")) - self.cwd = cwd; - else { - self.cwd = path__default.resolve(options.cwd); - self.changedCwd = self.cwd !== cwd; - } - - self.root = options.root || path__default.resolve(self.cwd, "/"); - self.root = path__default.resolve(self.root); - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/"); - - // TODO: is an absolute `cwd` supposed to be resolved against `root`? - // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') - self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd); - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/"); - self.nomount = !!options.nomount; - - // disable comments and negation in Minimatch. - // Note that they are not supported in Glob itself anyway. - options.nonegate = true; - options.nocomment = true; - - self.minimatch = new Minimatch(pattern, options); - self.options = self.minimatch.options; -} - -function finish (self) { - var nou = self.nounique; - var all = nou ? [] : Object.create(null); - - for (var i = 0, l = self.matches.length; i < l; i ++) { - var matches = self.matches[i]; - if (!matches || Object.keys(matches).length === 0) { - if (self.nonull) { - // do like the shell, and spit out the literal glob - var literal = self.minimatch.globSet[i]; - if (nou) - all.push(literal); - else - all[literal] = true; - } - } else { - // had matches - var m = Object.keys(matches); - if (nou) - all.push.apply(all, m); - else - m.forEach(function (m) { - all[m] = true; - }); - } - } - - if (!nou) - all = Object.keys(all); - - if (!self.nosort) - all = all.sort(self.nocase ? alphasorti : alphasort); - - // at *some* point we statted all of these - if (self.mark) { - for (var i = 0; i < all.length; i++) { - all[i] = self._mark(all[i]); - } - if (self.nodir) { - all = all.filter(function (e) { - var notDir = !(/\/$/.test(e)); - var c = self.cache[e] || self.cache[makeAbs(self, e)]; - if (notDir && c) - notDir = c !== 'DIR' && !Array.isArray(c); - return notDir - }); - } - } - - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored$2(self, m) - }); - - self.found = all; -} - -function mark (self, p) { - var abs = makeAbs(self, p); - var c = self.cache[abs]; - var m = p; - if (c) { - var isDir = c === 'DIR' || Array.isArray(c); - var slash = p.slice(-1) === '/'; - - if (isDir && !slash) - m += '/'; - else if (!isDir && slash) - m = m.slice(0, -1); - - if (m !== p) { - var mabs = makeAbs(self, m); - self.statCache[mabs] = self.statCache[abs]; - self.cache[mabs] = self.cache[abs]; - } - } - - return m -} - -// lotta situps... -function makeAbs (self, f) { - var abs = f; - if (f.charAt(0) === '/') { - abs = path__default.join(self.root, f); - } else if (pathIsAbsolute(f) || f === '') { - abs = f; - } else if (self.changedCwd) { - abs = path__default.resolve(self.cwd, f); - } else { - abs = path__default.resolve(f); - } - - if (process.platform === 'win32') - abs = abs.replace(/\\/g, '/'); - - return abs -} - - -// Return true, if pattern ends with globstar '**', for the accompanying parent directory. -// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents -function isIgnored$2 (self, path) { - if (!self.ignore.length) - return false - - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} - -function childrenIgnored$2 (self, path) { - if (!self.ignore.length) - return false - - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) -} - -var common = { - alphasort: alphasort_1, - alphasorti: alphasorti_1, - setopts: setopts_1, - ownProp: ownProp_1, - makeAbs: makeAbs_1, - finish: finish_1, - mark: mark_1, - isIgnored: isIgnored_1, - childrenIgnored: childrenIgnored_1 -}; - -var sync$8 = globSync; -globSync.GlobSync = GlobSync$1; -var setopts$1 = common.setopts; -var ownProp$1 = common.ownProp; -var childrenIgnored$1 = common.childrenIgnored; -var isIgnored$1 = common.isIgnored; - -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') - - return new GlobSync$1(pattern, options).found -} - -function GlobSync$1 (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') - - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') - - if (!(this instanceof GlobSync$1)) - return new GlobSync$1(pattern, options) - - setopts$1(this, pattern, options); - - if (this.noprocess) - return this - - var n = this.minimatch.set.length; - this.matches = new Array(n); - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false); - } - this._finish(); -} - -GlobSync$1.prototype._finish = function () { - assert__default(this instanceof GlobSync$1); - if (this.realpath) { - var self = this; - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null); - for (var p in matchset) { - try { - p = self._makeAbs(p); - var real = fs_realpath.realpathSync(p, self.realpathCache); - set[real] = true; - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true; - else - throw er - } - } - }); - } - common.finish(this); -}; - - -GlobSync$1.prototype._process = function (pattern, index, inGlobStar) { - assert__default(this instanceof GlobSync$1); - - // Get the first [n] parts of pattern that are all strings. - var n = 0; - while (typeof pattern[n] === 'string') { - n ++; - } - // now n is the index of the first one that is *not* a string. - - // See if there's anything else - var prefix; - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index); - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null; - break - - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/'); - break - } - - var remain = pattern.slice(n); - - // get the list of entries. - var read; - if (prefix === null) - read = '.'; - else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) { - if (!prefix || !pathIsAbsolute(prefix)) - prefix = '/' + prefix; - read = prefix; - } else - read = prefix; - - var abs = this._makeAbs(read); - - //if ignored, skip processing - if (childrenIgnored$1(this, read)) - return - - var isGlobStar = remain[0] === minimatch_1.GLOBSTAR; - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar); - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar); -}; - - -GlobSync$1.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar); - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return - - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0]; - var negate = !!this.minimatch.negate; - var rawGlob = pn._glob; - var dotOk = this.dot || rawGlob.charAt(0) === '.'; - - var matchedEntries = []; - for (var i = 0; i < entries.length; i++) { - var e = entries[i]; - if (e.charAt(0) !== '.' || dotOk) { - var m; - if (negate && !prefix) { - m = !e.match(pn); - } else { - m = e.match(pn); - } - if (m) - matchedEntries.push(e); - } - } - - var len = matchedEntries.length; - // If there are no matched entries, then nothing matches. - if (len === 0) - return - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null); - - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i]; - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e; - else - e = prefix + e; - } - - if (e.charAt(0) === '/' && !this.nomount) { - e = path__default.join(this.root, e); - } - this._emitMatch(index, e); - } - // This was the last one, and no stats were needed - return - } - - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift(); - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i]; - var newPattern; - if (prefix) - newPattern = [prefix, e]; - else - newPattern = [e]; - this._process(newPattern.concat(remain), index, inGlobStar); - } -}; - - -GlobSync$1.prototype._emitMatch = function (index, e) { - if (isIgnored$1(this, e)) - return - - var abs = this._makeAbs(e); - - if (this.mark) - e = this._mark(e); - - if (this.absolute) { - e = abs; - } - - if (this.matches[index][e]) - return - - if (this.nodir) { - var c = this.cache[abs]; - if (c === 'DIR' || Array.isArray(c)) - return - } - - this.matches[index][e] = true; - - if (this.stat) - this._stat(e); -}; - - -GlobSync$1.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) - - var entries; - var lstat; - try { - lstat = fs__default.lstatSync(abs); - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null - } - } - - var isSym = lstat && lstat.isSymbolicLink(); - this.symlinks[abs] = isSym; - - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE'; - else - entries = this._readdir(abs, false); - - return entries -}; - -GlobSync$1.prototype._readdir = function (abs, inGlobStar) { - - if (inGlobStar && !ownProp$1(this.symlinks, abs)) - return this._readdirInGlobStar(abs) - - if (ownProp$1(this.cache, abs)) { - var c = this.cache[abs]; - if (!c || c === 'FILE') - return null - - if (Array.isArray(c)) - return c - } - - try { - return this._readdirEntries(abs, fs__default.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er); - return null - } -}; - -GlobSync$1.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i]; - if (abs === '/') - e = abs + e; - else - e = abs + '/' + e; - this.cache[e] = true; - } - } - - this.cache[abs] = entries; - - // mark and cache dir-ness - return entries -}; - -GlobSync$1.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f); - this.cache[abs] = 'FILE'; - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd); - error.path = this.cwd; - error.code = er.code; - throw error - } - break - - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false; - break - - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false; - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er); - break - } -}; - -GlobSync$1.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { - - var entries = this._readdir(abs, inGlobStar); - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return - - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1); - var gspref = prefix ? [ prefix ] : []; - var noGlobStar = gspref.concat(remainWithoutGlobStar); - - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false); - - var len = entries.length; - var isSym = this.symlinks[abs]; - - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return - - for (var i = 0; i < len; i++) { - var e = entries[i]; - if (e.charAt(0) === '.' && !this.dot) - continue - - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar); - this._process(instead, index, true); - - var below = gspref.concat(entries[i], remain); - this._process(below, index, true); - } -}; - -GlobSync$1.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix); - - if (!this.matches[index]) - this.matches[index] = Object.create(null); - - // If it doesn't exist, then just mark the lack of results - if (!exists) - return - - if (prefix && pathIsAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix); - if (prefix.charAt(0) === '/') { - prefix = path__default.join(this.root, prefix); - } else { - prefix = path__default.resolve(this.root, prefix); - if (trail) - prefix += '/'; - } - } - - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/'); - - // Mark this as a match - this._emitMatch(index, prefix); -}; - -// Returns either 'DIR', 'FILE', or false -GlobSync$1.prototype._stat = function (f) { - var abs = this._makeAbs(f); - var needDir = f.slice(-1) === '/'; - - if (f.length > this.maxLength) - return false - - if (!this.stat && ownProp$1(this.cache, abs)) { - var c = this.cache[abs]; - - if (Array.isArray(c)) - c = 'DIR'; - - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c - - if (needDir && c === 'FILE') - return false - - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } - var stat = this.statCache[abs]; - if (!stat) { - var lstat; - try { - lstat = fs__default.lstatSync(abs); - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false; - return false - } - } - - if (lstat && lstat.isSymbolicLink()) { - try { - stat = fs__default.statSync(abs); - } catch (er) { - stat = lstat; - } - } else { - stat = lstat; - } - } - - this.statCache[abs] = stat; - - var c = true; - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE'; - - this.cache[abs] = this.cache[abs] || c; - - if (needDir && c === 'FILE') - return false - - return c -}; - -GlobSync$1.prototype._mark = function (p) { - return common.mark(this, p) -}; - -GlobSync$1.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -}; - -// Returns a wrapper function that returns a wrapped callback -// The wrapper function should do some stuff, and return a -// presumably different callback function. -// This makes sure that own properties are retained, so that -// decorations and such are not lost along the way. -var wrappy_1 = wrappy; -function wrappy (fn, cb) { - if (fn && cb) return wrappy(fn)(cb) - - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') - - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k]; - }); - - return wrapper - - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - var ret = fn.apply(this, args); - var cb = args[args.length-1]; - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k]; - }); - } - return ret - } -} - -var once_1 = wrappy_1(once); -var strict = wrappy_1(onceStrict); - -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }); - - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }); -}); - -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true; - return f.value = fn.apply(this, arguments) - }; - f.called = false; - return f -} - -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true; - return f.value = fn.apply(this, arguments) - }; - var name = fn.name || 'Function wrapped with `once`'; - f.onceError = name + " shouldn't be called more than once"; - f.called = false; - return f -} -once_1.strict = strict; - -var reqs = Object.create(null); - - -var inflight_1 = wrappy_1(inflight); - -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb); - return null - } else { - reqs[key] = [cb]; - return makeres(key) - } -} - -function makeres (key) { - return once_1(function RES () { - var cbs = reqs[key]; - var len = cbs.length; - var args = slice(arguments); - - // XXX It's somewhat ambiguous whether a new callback added in this - // pass should be queued for later execution if something in the - // list of callbacks throws, or if it should just be discarded. - // However, it's such an edge case that it hardly matters, and either - // choice is likely as surprising as the other. - // As it happens, we do go ahead and schedule it for later execution. - try { - for (var i = 0; i < len; i++) { - cbs[i].apply(null, args); - } - } finally { - if (cbs.length > len) { - // added more in the interim. - // de-zalgo, just in case, but don't call again. - cbs.splice(0, len); - process.nextTick(function () { - RES.apply(null, args); - }); - } else { - delete reqs[key]; - } - } - }) -} - -function slice (args) { - var length = args.length; - var array = []; - - for (var i = 0; i < length; i++) array[i] = args[i]; - return array -} - -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern, false) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern, inGlobStar) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// -// If inGlobStar and PREFIX is symlink and points to dir -// set ENTRIES = [] -// else readdir(PREFIX) as ENTRIES -// If fail, END -// -// with ENTRIES -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// // Mark that this entry is a globstar match -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. - -var glob_1 = glob; - -var EE$1 = require$$0__default$1.EventEmitter; -var setopts = common.setopts; -var ownProp = common.ownProp; - - -var childrenIgnored = common.childrenIgnored; -var isIgnored = common.isIgnored; - - - -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {}; - if (!options) options = {}; - - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return sync$8(pattern, options) - } - - return new Glob(pattern, options, cb) -} - -glob.sync = sync$8; -var GlobSync = glob.GlobSync = sync$8.GlobSync; - -// old api surface -glob.glob = glob; - -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin - } - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin -} - -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_); - options.noprocess = true; - - var g = new Glob(pattern, options); - var set = g.minimatch.set; - - if (!pattern) - return false - - if (set.length > 1) - return true - - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true - } - - return false -}; - -glob.Glob = Glob; -inherits(Glob, EE$1); -function Glob (pattern, options, cb) { - if (typeof options === 'function') { - cb = options; - options = null; - } - - if (options && options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return new GlobSync(pattern, options) - } - - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) - - setopts(this, pattern, options); - this._didRealPath = false; - - // process each pattern in the minimatch set - var n = this.minimatch.set.length; - - // The matches are stored as {: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n); - - if (typeof cb === 'function') { - cb = once_1(cb); - this.on('error', cb); - this.on('end', function (matches) { - cb(null, matches); - }); - } - - var self = this; - this._processing = 0; - - this._emitQueue = []; - this._processQueue = []; - this.paused = false; - - if (this.noprocess) - return this - - if (n === 0) - return done() - - var sync = true; - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done); - } - sync = false; - - function done () { - --self._processing; - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish(); - }); - } else { - self._finish(); - } - } - } -} - -Glob.prototype._finish = function () { - assert__default(this instanceof Glob); - if (this.aborted) - return - - if (this.realpath && !this._didRealpath) - return this._realpath() - - common.finish(this); - this.emit('end', this.found); -}; - -Glob.prototype._realpath = function () { - if (this._didRealpath) - return - - this._didRealpath = true; - - var n = this.matches.length; - if (n === 0) - return this._finish() - - var self = this; - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next); - - function next () { - if (--n === 0) - self._finish(); - } -}; - -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index]; - if (!matchset) - return cb() - - var found = Object.keys(matchset); - var self = this; - var n = found.length; - - if (n === 0) - return cb() - - var set = this.matches[index] = Object.create(null); - found.forEach(function (p, i) { - // If there's a problem with the stat, then it means that - // one or more of the links in the realpath couldn't be - // resolved. just return the abs value in that case. - p = self._makeAbs(p); - fs_realpath.realpath(p, self.realpathCache, function (er, real) { - if (!er) - set[real] = true; - else if (er.syscall === 'stat') - set[p] = true; - else - self.emit('error', er); // srsly wtf right here - - if (--n === 0) { - self.matches[index] = set; - cb(); - } - }); - }); -}; - -Glob.prototype._mark = function (p) { - return common.mark(this, p) -}; - -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -}; - -Glob.prototype.abort = function () { - this.aborted = true; - this.emit('abort'); -}; - -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true; - this.emit('pause'); - } -}; - -Glob.prototype.resume = function () { - if (this.paused) { - this.emit('resume'); - this.paused = false; - if (this._emitQueue.length) { - var eq = this._emitQueue.slice(0); - this._emitQueue.length = 0; - for (var i = 0; i < eq.length; i ++) { - var e = eq[i]; - this._emitMatch(e[0], e[1]); - } - } - if (this._processQueue.length) { - var pq = this._processQueue.slice(0); - this._processQueue.length = 0; - for (var i = 0; i < pq.length; i ++) { - var p = pq[i]; - this._processing--; - this._process(p[0], p[1], p[2], p[3]); - } - } - } -}; - -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert__default(this instanceof Glob); - assert__default(typeof cb === 'function'); - - if (this.aborted) - return - - this._processing++; - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]); - return - } - - //console.error('PROCESS %d', this._processing, pattern) - - // Get the first [n] parts of pattern that are all strings. - var n = 0; - while (typeof pattern[n] === 'string') { - n ++; - } - // now n is the index of the first one that is *not* a string. - - // see if there's anything else - var prefix; - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index, cb); - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null; - break - - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/'); - break - } - - var remain = pattern.slice(n); - - // get the list of entries. - var read; - if (prefix === null) - read = '.'; - else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) { - if (!prefix || !pathIsAbsolute(prefix)) - prefix = '/' + prefix; - read = prefix; - } else - read = prefix; - - var abs = this._makeAbs(read); - - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() - - var isGlobStar = remain[0] === minimatch_1.GLOBSTAR; - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb); - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb); -}; - -Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this; - this._readdir(abs, inGlobStar, function (er, entries) { - return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }); -}; - -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() - - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0]; - var negate = !!this.minimatch.negate; - var rawGlob = pn._glob; - var dotOk = this.dot || rawGlob.charAt(0) === '.'; - - var matchedEntries = []; - for (var i = 0; i < entries.length; i++) { - var e = entries[i]; - if (e.charAt(0) !== '.' || dotOk) { - var m; - if (negate && !prefix) { - m = !e.match(pn); - } else { - m = e.match(pn); - } - if (m) - matchedEntries.push(e); - } - } - - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) - - var len = matchedEntries.length; - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null); - - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i]; - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e; - else - e = prefix + e; - } - - if (e.charAt(0) === '/' && !this.nomount) { - e = path__default.join(this.root, e); - } - this._emitMatch(index, e); - } - // This was the last one, and no stats were needed - return cb() - } - - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift(); - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i]; - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e; - else - e = prefix + e; - } - this._process([e].concat(remain), index, inGlobStar, cb); - } - cb(); -}; - -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return - - if (isIgnored(this, e)) - return - - if (this.paused) { - this._emitQueue.push([index, e]); - return - } - - var abs = pathIsAbsolute(e) ? e : this._makeAbs(e); - - if (this.mark) - e = this._mark(e); - - if (this.absolute) - e = abs; - - if (this.matches[index][e]) - return - - if (this.nodir) { - var c = this.cache[abs]; - if (c === 'DIR' || Array.isArray(c)) - return - } - - this.matches[index][e] = true; - - var st = this.statCache[abs]; - if (st) - this.emit('stat', e, st); - - this.emit('match', e); -}; - -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return - - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) - - var lstatkey = 'lstat\0' + abs; - var self = this; - var lstatcb = inflight_1(lstatkey, lstatcb_); - - if (lstatcb) - fs__default.lstat(abs, lstatcb); - - function lstatcb_ (er, lstat) { - if (er && er.code === 'ENOENT') - return cb() - - var isSym = lstat && lstat.isSymbolicLink(); - self.symlinks[abs] = isSym; - - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) { - self.cache[abs] = 'FILE'; - cb(); - } else - self._readdir(abs, false, cb); - } -}; - -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return - - cb = inflight_1('readdir\0'+abs+'\0'+inGlobStar, cb); - if (!cb) - return - - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) - - if (ownProp(this.cache, abs)) { - var c = this.cache[abs]; - if (!c || c === 'FILE') - return cb() - - if (Array.isArray(c)) - return cb(null, c) - } - fs__default.readdir(abs, readdirCb(this, abs, cb)); -}; - -function readdirCb (self, abs, cb) { - return function (er, entries) { - if (er) - self._readdirError(abs, er, cb); - else - self._readdirEntries(abs, entries, cb); - } -} - -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return - - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i]; - if (abs === '/') - e = abs + e; - else - e = abs + '/' + e; - this.cache[e] = true; - } - } - - this.cache[abs] = entries; - return cb(null, entries) -}; - -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return - - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f); - this.cache[abs] = 'FILE'; - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd); - error.path = this.cwd; - error.code = er.code; - this.emit('error', error); - this.abort(); - } - break - - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false; - break - - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false; - if (this.strict) { - this.emit('error', er); - // If the error is handled, then we abort - // if not, we threw out of here - this.abort(); - } - if (!this.silent) - console.error('glob error', er); - break - } - - return cb() -}; - -Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this; - this._readdir(abs, inGlobStar, function (er, entries) { - self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb); - }); -}; - - -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) - - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() - - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1); - var gspref = prefix ? [ prefix ] : []; - var noGlobStar = gspref.concat(remainWithoutGlobStar); - - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb); - - var isSym = this.symlinks[abs]; - var len = entries.length; - - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() - - for (var i = 0; i < len; i++) { - var e = entries[i]; - if (e.charAt(0) === '.' && !this.dot) - continue - - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar); - this._process(instead, index, true, cb); - - var below = gspref.concat(entries[i], remain); - this._process(below, index, true, cb); - } - - cb(); -}; - -Glob.prototype._processSimple = function (prefix, index, cb) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var self = this; - this._stat(prefix, function (er, exists) { - self._processSimple2(prefix, index, er, exists, cb); - }); -}; -Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { - - //console.error('ps2', prefix, exists) - - if (!this.matches[index]) - this.matches[index] = Object.create(null); - - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() - - if (prefix && pathIsAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix); - if (prefix.charAt(0) === '/') { - prefix = path__default.join(this.root, prefix); - } else { - prefix = path__default.resolve(this.root, prefix); - if (trail) - prefix += '/'; - } - } - - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/'); - - // Mark this as a match - this._emitMatch(index, prefix); - cb(); -}; - -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f); - var needDir = f.slice(-1) === '/'; - - if (f.length > this.maxLength) - return cb() - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs]; - - if (Array.isArray(c)) - c = 'DIR'; - - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) - - if (needDir && c === 'FILE') - return cb() - - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } - var stat = this.statCache[abs]; - if (stat !== undefined) { - if (stat === false) - return cb(null, stat) - else { - var type = stat.isDirectory() ? 'DIR' : 'FILE'; - if (needDir && type === 'FILE') - return cb() - else - return cb(null, type, stat) - } - } - - var self = this; - var statcb = inflight_1('stat\0' + abs, lstatcb_); - if (statcb) - fs__default.lstat(abs, statcb); - - function lstatcb_ (er, lstat) { - if (lstat && lstat.isSymbolicLink()) { - // If it's a symlink, then treat it as the target, unless - // the target does not exist, then treat it as a file. - return fs__default.stat(abs, function (er, stat) { - if (er) - self._stat2(f, abs, null, lstat, cb); - else - self._stat2(f, abs, er, stat, cb); - }) - } else { - self._stat2(f, abs, er, lstat, cb); - } - } -}; - -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false; - return cb() - } - - var needDir = f.slice(-1) === '/'; - this.statCache[abs] = stat; - - if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) - return cb(null, false, stat) - - var c = true; - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE'; - this.cache[abs] = this.cache[abs] || c; - - if (needDir && c === 'FILE') - return cb() - - return cb(null, c, stat) -}; - -// @ts-check -/** @typedef { import('estree').BaseNode} BaseNode */ - -/** @typedef {{ - skip: () => void; - remove: () => void; - replace: (node: BaseNode) => void; -}} WalkerContext */ - -class WalkerBase { - constructor() { - /** @type {boolean} */ - this.should_skip = false; - - /** @type {boolean} */ - this.should_remove = false; - - /** @type {BaseNode | null} */ - this.replacement = null; - - /** @type {WalkerContext} */ - this.context = { - skip: () => (this.should_skip = true), - remove: () => (this.should_remove = true), - replace: (node) => (this.replacement = node) - }; - } - - /** - * - * @param {any} parent - * @param {string} prop - * @param {number} index - * @param {BaseNode} node - */ - replace(parent, prop, index, node) { - if (parent) { - if (index !== null) { - parent[prop][index] = node; - } else { - parent[prop] = node; - } - } - } - - /** - * - * @param {any} parent - * @param {string} prop - * @param {number} index - */ - remove(parent, prop, index) { - if (parent) { - if (index !== null) { - parent[prop].splice(index, 1); - } else { - delete parent[prop]; - } - } - } -} - -// @ts-check - -/** @typedef { import('estree').BaseNode} BaseNode */ -/** @typedef { import('./walker.js').WalkerContext} WalkerContext */ - -/** @typedef {( - * this: WalkerContext, - * node: BaseNode, - * parent: BaseNode, - * key: string, - * index: number - * ) => void} SyncHandler */ - -class SyncWalker extends WalkerBase { - /** - * - * @param {SyncHandler} enter - * @param {SyncHandler} leave - */ - constructor(enter, leave) { - super(); - - /** @type {SyncHandler} */ - this.enter = enter; - - /** @type {SyncHandler} */ - this.leave = leave; - } - - /** - * - * @param {BaseNode} node - * @param {BaseNode} parent - * @param {string} [prop] - * @param {number} [index] - * @returns {BaseNode} - */ - visit(node, parent, prop, index) { - if (node) { - if (this.enter) { - const _should_skip = this.should_skip; - const _should_remove = this.should_remove; - const _replacement = this.replacement; - this.should_skip = false; - this.should_remove = false; - this.replacement = null; - - this.enter.call(this.context, node, parent, prop, index); - - if (this.replacement) { - node = this.replacement; - this.replace(parent, prop, index, node); - } - - if (this.should_remove) { - this.remove(parent, prop, index); - } - - const skipped = this.should_skip; - const removed = this.should_remove; - - this.should_skip = _should_skip; - this.should_remove = _should_remove; - this.replacement = _replacement; - - if (skipped) return node; - if (removed) return null; - } - - for (const key in node) { - const value = node[key]; - - if (typeof value !== "object") { - continue; - } else if (Array.isArray(value)) { - for (let i = 0; i < value.length; i += 1) { - if (value[i] !== null && typeof value[i].type === 'string') { - if (!this.visit(value[i], node, key, i)) { - // removed - i--; - } - } - } - } else if (value !== null && typeof value.type === "string") { - this.visit(value, node, key, null); - } - } - - if (this.leave) { - const _replacement = this.replacement; - const _should_remove = this.should_remove; - this.replacement = null; - this.should_remove = false; - - this.leave.call(this.context, node, parent, prop, index); - - if (this.replacement) { - node = this.replacement; - this.replace(parent, prop, index, node); - } - - if (this.should_remove) { - this.remove(parent, prop, index); - } - - const removed = this.should_remove; - - this.replacement = _replacement; - this.should_remove = _should_remove; - - if (removed) return null; - } - } - - return node; - } -} - -// @ts-check - -/** @typedef { import('estree').BaseNode} BaseNode */ -/** @typedef { import('./sync.js').SyncHandler} SyncHandler */ -/** @typedef { import('./async.js').AsyncHandler} AsyncHandler */ - -/** - * - * @param {BaseNode} ast - * @param {{ - * enter?: SyncHandler - * leave?: SyncHandler - * }} walker - * @returns {BaseNode} - */ -function walk$1(ast, { enter, leave }) { - const instance = new SyncWalker(enter, leave); - return instance.visit(ast, null); -} - -function isReference(node, parent) { - if (node.type === 'MemberExpression') { - return !node.computed && isReference(node.object, node); - } - if (node.type === 'Identifier') { - if (!parent) - return true; - switch (parent.type) { - // disregard `bar` in `foo.bar` - case 'MemberExpression': return parent.computed || node === parent.object; - // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}` - case 'MethodDefinition': return parent.computed; - // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}` - case 'FieldDefinition': return parent.computed || node === parent.value; - // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }` - case 'Property': return parent.computed || node === parent.value; - // disregard the `bar` in `export { foo as bar }` or - // the foo in `import { foo as bar }` - case 'ExportSpecifier': - case 'ImportSpecifier': return node === parent.local; - // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}` - case 'LabeledStatement': - case 'BreakStatement': - case 'ContinueStatement': return false; - default: return true; - } - } - return false; -} - -var peerDependencies = { - rollup: "^2.30.0" -}; - -function tryParse(parse, code, id) { - try { - return parse(code, { allowReturnOutsideFunction: true }); - } catch (err) { - err.message += ` in ${id}`; - throw err; - } -} - -const firstpassGlobal = /\b(?:require|module|exports|global)\b/; - -const firstpassNoGlobal = /\b(?:require|module|exports)\b/; - -function hasCjsKeywords(code, ignoreGlobal) { - const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal; - return firstpass.test(code); -} - -/* eslint-disable no-underscore-dangle */ - -function analyzeTopLevelStatements(parse, code, id) { - const ast = tryParse(parse, code, id); - - let isEsModule = false; - let hasDefaultExport = false; - let hasNamedExports = false; - - for (const node of ast.body) { - switch (node.type) { - case 'ExportDefaultDeclaration': - isEsModule = true; - hasDefaultExport = true; - break; - case 'ExportNamedDeclaration': - isEsModule = true; - if (node.declaration) { - hasNamedExports = true; - } else { - for (const specifier of node.specifiers) { - if (specifier.exported.name === 'default') { - hasDefaultExport = true; - } else { - hasNamedExports = true; - } - } - } - break; - case 'ExportAllDeclaration': - isEsModule = true; - if (node.exported && node.exported.name === 'default') { - hasDefaultExport = true; - } else { - hasNamedExports = true; - } - break; - case 'ImportDeclaration': - isEsModule = true; - break; - } - } - - return { isEsModule, hasDefaultExport, hasNamedExports, ast }; -} - -const isWrappedId = (id, suffix) => id.endsWith(suffix); -const wrapId = (id, suffix) => `\0${id}${suffix}`; -const unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length); - -const PROXY_SUFFIX = '?commonjs-proxy'; -const REQUIRE_SUFFIX = '?commonjs-require'; -const EXTERNAL_SUFFIX = '?commonjs-external'; - -const DYNAMIC_REGISTER_SUFFIX = '?commonjs-dynamic-register'; -const DYNAMIC_JSON_PREFIX = '\0commonjs-dynamic-json:'; -const DYNAMIC_PACKAGES_ID = '\0commonjs-dynamic-packages'; - -const HELPERS_ID = '\0commonjsHelpers.js'; - -// `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers. -// Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled. -// This will no longer be necessary once Rollup switches to ES6 output, likely -// in Rollup 3 - -const HELPERS = ` -export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -export function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -export function getDefaultExportFromNamespaceIfPresent (n) { - return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; -} - -export function getDefaultExportFromNamespaceIfNotNamed (n) { - return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; -} - -export function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var a = Object.defineProperty({}, '__esModule', {value: true}); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; -} -`; - -const HELPER_NON_DYNAMIC = ` -export function createCommonjsModule(fn) { - var module = { exports: {} } - return fn(module, module.exports), module.exports; -} - -export function commonjsRequire (target) { - throw new Error('Could not dynamically require "' + target + '". Please configure the dynamicRequireTargets option of @rollup/plugin-commonjs appropriately for this require call to behave properly.'); -} -`; - -const HELPERS_DYNAMIC = ` -export function createCommonjsModule(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function (path, base) { - return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); - } - }, fn(module, module.exports), module.exports; -} - -export function commonjsRegister (path, loader) { - DYNAMIC_REQUIRE_LOADERS[path] = loader; -} - -const DYNAMIC_REQUIRE_LOADERS = Object.create(null); -const DYNAMIC_REQUIRE_CACHE = Object.create(null); -const DEFAULT_PARENT_MODULE = { - id: '<' + 'rollup>', exports: {}, parent: undefined, filename: null, loaded: false, children: [], paths: [] -}; -const CHECKED_EXTENSIONS = ['', '.js', '.json']; - -function normalize (path) { - path = path.replace(/\\\\/g, '/'); - const parts = path.split('/'); - const slashed = parts[0] === ''; - for (let i = 1; i < parts.length; i++) { - if (parts[i] === '.' || parts[i] === '') { - parts.splice(i--, 1); - } - } - for (let i = 1; i < parts.length; i++) { - if (parts[i] !== '..') continue; - if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') { - parts.splice(--i, 2); - i--; - } - } - path = parts.join('/'); - if (slashed && path[0] !== '/') - path = '/' + path; - else if (path.length === 0) - path = '.'; - return path; -} - -function join () { - if (arguments.length === 0) - return '.'; - let joined; - for (let i = 0; i < arguments.length; ++i) { - let arg = arguments[i]; - if (arg.length > 0) { - if (joined === undefined) - joined = arg; - else - joined += '/' + arg; - } - } - if (joined === undefined) - return '.'; - - return joined; -} - -function isPossibleNodeModulesPath (modulePath) { - let c0 = modulePath[0]; - if (c0 === '/' || c0 === '\\\\') return false; - let c1 = modulePath[1], c2 = modulePath[2]; - if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) || - (c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false; - if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) - return false; - return true; -} - -function dirname (path) { - if (path.length === 0) - return '.'; - - let i = path.length - 1; - while (i > 0) { - const c = path.charCodeAt(i); - if ((c === 47 || c === 92) && i !== path.length - 1) - break; - i--; - } - - if (i > 0) - return path.substr(0, i); - - if (path.chartCodeAt(0) === 47 || path.chartCodeAt(0) === 92) - return path.charAt(0); - - return '.'; -} - -export function commonjsResolveImpl (path, originalModuleDir, testCache) { - const shouldTryNodeModules = isPossibleNodeModulesPath(path); - path = normalize(path); - let relPath; - if (path[0] === '/') { - originalModuleDir = '/'; - } - while (true) { - if (!shouldTryNodeModules) { - relPath = originalModuleDir ? normalize(originalModuleDir + '/' + path) : path; - } else if (originalModuleDir) { - relPath = normalize(originalModuleDir + '/node_modules/' + path); - } else { - relPath = normalize(join('node_modules', path)); - } - - if (relPath.endsWith('/..')) { - break; // Travelled too far up, avoid infinite loop - } - - for (let extensionIndex = 0; extensionIndex < CHECKED_EXTENSIONS.length; extensionIndex++) { - const resolvedPath = relPath + CHECKED_EXTENSIONS[extensionIndex]; - if (DYNAMIC_REQUIRE_CACHE[resolvedPath]) { - return resolvedPath; - }; - if (DYNAMIC_REQUIRE_LOADERS[resolvedPath]) { - return resolvedPath; - }; - } - if (!shouldTryNodeModules) break; - const nextDir = normalize(originalModuleDir + '/..'); - if (nextDir === originalModuleDir) break; - originalModuleDir = nextDir; - } - return null; -} - -export function commonjsResolve (path, originalModuleDir) { - const resolvedPath = commonjsResolveImpl(path, originalModuleDir); - if (resolvedPath !== null) { - return resolvedPath; - } - return require.resolve(path); -} - -export function commonjsRequire (path, originalModuleDir) { - const resolvedPath = commonjsResolveImpl(path, originalModuleDir, true); - if (resolvedPath !== null) { - let cachedModule = DYNAMIC_REQUIRE_CACHE[resolvedPath]; - if (cachedModule) return cachedModule.exports; - const loader = DYNAMIC_REQUIRE_LOADERS[resolvedPath]; - if (loader) { - DYNAMIC_REQUIRE_CACHE[resolvedPath] = cachedModule = { - id: resolvedPath, - filename: resolvedPath, - path: dirname(resolvedPath), - exports: {}, - parent: DEFAULT_PARENT_MODULE, - loaded: false, - children: [], - paths: [], - require: function (path, base) { - return commonjsRequire(path, (base === undefined || base === null) ? cachedModule.path : base); - } - }; - try { - loader.call(commonjsGlobal, cachedModule, cachedModule.exports); - } catch (error) { - delete DYNAMIC_REQUIRE_CACHE[resolvedPath]; - throw error; - } - cachedModule.loaded = true; - return cachedModule.exports; - }; - } - return require(path); -} - -commonjsRequire.cache = DYNAMIC_REQUIRE_CACHE; -commonjsRequire.resolve = commonjsResolve; -`; - -function getHelpersModule(isDynamicRequireModulesEnabled) { - return `${HELPERS}${isDynamicRequireModulesEnabled ? HELPERS_DYNAMIC : HELPER_NON_DYNAMIC}`; -} - -/* eslint-disable import/prefer-default-export */ - -function deconflict(scope, globals, identifier) { - let i = 1; - let deconflicted = makeLegalIdentifier(identifier); - - while (scope.contains(deconflicted) || globals.has(deconflicted)) { - deconflicted = makeLegalIdentifier(`${identifier}_${i}`); - i += 1; - } - // eslint-disable-next-line no-param-reassign - scope.declarations[deconflicted] = true; - - return deconflicted; -} - -function getName(id) { - const name = makeLegalIdentifier(path$1.basename(id, path$1.extname(id))); - if (name !== 'index') { - return name; - } - const segments = path$1.dirname(id).split(path$1.sep); - return makeLegalIdentifier(segments[segments.length - 1]); -} - -function normalizePathSlashes(path) { - return path.replace(/\\/g, '/'); -} - -const VIRTUAL_PATH_BASE = '/$$rollup_base$$'; -const getVirtualPathForDynamicRequirePath = (path, commonDir) => { - const normalizedPath = normalizePathSlashes(path); - return normalizedPath.startsWith(commonDir) - ? VIRTUAL_PATH_BASE + normalizedPath.slice(commonDir.length) - : normalizedPath; -}; - -function getPackageEntryPoint(dirPath) { - let entryPoint = 'index.js'; - - try { - if (fs$2.existsSync(path$1.join(dirPath, 'package.json'))) { - entryPoint = - JSON.parse(fs$2.readFileSync(path$1.join(dirPath, 'package.json'), { encoding: 'utf8' })).main || - entryPoint; - } - } catch (ignored) { - // ignored - } - - return entryPoint; -} - -function getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir) { - let code = `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');`; - for (const dir of dynamicRequireModuleDirPaths) { - const entryPoint = getPackageEntryPoint(dir); - - code += `\ncommonjsRegister(${JSON.stringify( - getVirtualPathForDynamicRequirePath(dir, commonDir) - )}, function (module, exports) { - module.exports = require(${JSON.stringify(normalizePathSlashes(path$1.join(dir, entryPoint)))}); -});`; - } - return code; -} - -function getDynamicPackagesEntryIntro( - dynamicRequireModuleDirPaths, - dynamicRequireModuleSet -) { - let dynamicImports = Array.from( - dynamicRequireModuleSet, - (dynamicId) => `require(${JSON.stringify(wrapModuleRegisterProxy(dynamicId))});` - ).join('\n'); - - if (dynamicRequireModuleDirPaths.length) { - dynamicImports += `require(${JSON.stringify(wrapModuleRegisterProxy(DYNAMIC_PACKAGES_ID))});`; - } - - return dynamicImports; -} - -function wrapModuleRegisterProxy(id) { - return wrapId(id, DYNAMIC_REGISTER_SUFFIX); -} - -function unwrapModuleRegisterProxy(id) { - return unwrapId(id, DYNAMIC_REGISTER_SUFFIX); -} - -function isModuleRegisterProxy(id) { - return isWrappedId(id, DYNAMIC_REGISTER_SUFFIX); -} - -function isDynamicModuleImport(id, dynamicRequireModuleSet) { - const normalizedPath = normalizePathSlashes(id); - return dynamicRequireModuleSet.has(normalizedPath) && !normalizedPath.endsWith('.json'); -} - -function isDirectory(path) { - try { - if (fs$2.statSync(path).isDirectory()) return true; - } catch (ignored) { - // Nothing to do here - } - return false; -} - -function getDynamicRequirePaths(patterns) { - const dynamicRequireModuleSet = new Set(); - for (const pattern of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) { - const isNegated = pattern.startsWith('!'); - const modifySet = Set.prototype[isNegated ? 'delete' : 'add'].bind(dynamicRequireModuleSet); - for (const path of glob_1.sync(isNegated ? pattern.substr(1) : pattern)) { - modifySet(normalizePathSlashes(path$1.resolve(path))); - if (isDirectory(path)) { - modifySet(normalizePathSlashes(path$1.resolve(path$1.join(path, getPackageEntryPoint(path))))); - } - } - } - const dynamicRequireModuleDirPaths = Array.from(dynamicRequireModuleSet.values()).filter((path) => - isDirectory(path) - ); - return { dynamicRequireModuleSet, dynamicRequireModuleDirPaths }; -} - -const isCjsPromises = new Map(); - -function getIsCjsPromise(id) { - let isCjsPromise = isCjsPromises.get(id); - if (isCjsPromise) return isCjsPromise.promise; - - const promise = new Promise((resolve) => { - isCjsPromise = { - resolve, - promise: null - }; - isCjsPromises.set(id, isCjsPromise); - }); - isCjsPromise.promise = promise; - - return promise; -} - -function setIsCjsPromise(id, resolution) { - const isCjsPromise = isCjsPromises.get(id); - if (isCjsPromise) { - if (isCjsPromise.resolve) { - isCjsPromise.resolve(resolution); - isCjsPromise.resolve = null; - } - } else { - isCjsPromises.set(id, { promise: Promise.resolve(resolution), resolve: null }); - } -} - -// e.g. id === "commonjsHelpers?commonjsRegister" -function getSpecificHelperProxy(id) { - return `export {${id.split('?')[1]} as default} from '${HELPERS_ID}';`; -} - -function getUnknownRequireProxy(id, requireReturnsDefault) { - if (requireReturnsDefault === true || id.endsWith('.json')) { - return `export {default} from ${JSON.stringify(id)};`; - } - const name = getName(id); - const exported = - requireReturnsDefault === 'auto' - ? `import {getDefaultExportFromNamespaceIfNotNamed} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name});` - : requireReturnsDefault === 'preferred' - ? `import {getDefaultExportFromNamespaceIfPresent} from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name});` - : !requireReturnsDefault - ? `import {getAugmentedNamespace} from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name});` - : `export default ${name};`; - return `import * as ${name} from ${JSON.stringify(id)}; ${exported}`; -} - -function getDynamicJsonProxy(id, commonDir) { - const normalizedPath = normalizePathSlashes(id.slice(DYNAMIC_JSON_PREFIX.length)); - return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify( - getVirtualPathForDynamicRequirePath(normalizedPath, commonDir) - )}, function (module, exports) { - module.exports = require(${JSON.stringify(normalizedPath)}); -});`; -} - -function getDynamicRequireProxy(normalizedPath, commonDir) { - return `const commonjsRegister = require('${HELPERS_ID}?commonjsRegister');\ncommonjsRegister(${JSON.stringify( - getVirtualPathForDynamicRequirePath(normalizedPath, commonDir) - )}, function (module, exports) { - ${fs$2.readFileSync(normalizedPath, { encoding: 'utf8' })} -});`; -} - -async function getStaticRequireProxy( - id, - requireReturnsDefault, - esModulesWithDefaultExport, - esModulesWithNamedExports -) { - const name = getName(id); - const isCjs = await getIsCjsPromise(id); - if (isCjs) { - return `import { __moduleExports } from ${JSON.stringify(id)}; export default __moduleExports;`; - } else if (isCjs === null) { - return getUnknownRequireProxy(id, requireReturnsDefault); - } else if (!requireReturnsDefault) { - return `import {getAugmentedNamespace} from "${HELPERS_ID}"; import * as ${name} from ${JSON.stringify( - id - )}; export default /*@__PURE__*/getAugmentedNamespace(${name});`; - } else if ( - requireReturnsDefault !== true && - (requireReturnsDefault === 'namespace' || - !esModulesWithDefaultExport.has(id) || - (requireReturnsDefault === 'auto' && esModulesWithNamedExports.has(id))) - ) { - return `import * as ${name} from ${JSON.stringify(id)}; export default ${name};`; - } - return `export {default} from ${JSON.stringify(id)};`; -} - -/* eslint-disable no-param-reassign, no-undefined */ - -function getCandidatesForExtension(resolved, extension) { - return [resolved + extension, `${resolved}${path$1.sep}index${extension}`]; -} - -function getCandidates(resolved, extensions) { - return extensions.reduce( - (paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)), - [resolved] - ); -} - -function getResolveId(extensions) { - function resolveExtensions(importee, importer) { - // not our problem - if (importee[0] !== '.' || !importer) return undefined; - - const resolved = path$1.resolve(path$1.dirname(importer), importee); - const candidates = getCandidates(resolved, extensions); - - for (let i = 0; i < candidates.length; i += 1) { - try { - const stats = fs$2.statSync(candidates[i]); - if (stats.isFile()) return { id: candidates[i] }; - } catch (err) { - /* noop */ - } - } - - return undefined; - } - - return function resolveId(importee, rawImporter) { - const importer = - rawImporter && isModuleRegisterProxy(rawImporter) - ? unwrapModuleRegisterProxy(rawImporter) - : rawImporter; - - // Proxies are only importing resolved ids, no need to resolve again - if (importer && isWrappedId(importer, PROXY_SUFFIX)) { - return importee; - } - - const isProxyModule = isWrappedId(importee, PROXY_SUFFIX); - const isRequiredModule = isWrappedId(importee, REQUIRE_SUFFIX); - let isModuleRegistration = false; - - if (isProxyModule) { - importee = unwrapId(importee, PROXY_SUFFIX); - } else if (isRequiredModule) { - importee = unwrapId(importee, REQUIRE_SUFFIX); - - isModuleRegistration = isModuleRegisterProxy(importee); - if (isModuleRegistration) { - importee = unwrapModuleRegisterProxy(importee); - } - } - - if ( - importee.startsWith(HELPERS_ID) || - importee === DYNAMIC_PACKAGES_ID || - importee.startsWith(DYNAMIC_JSON_PREFIX) - ) { - return importee; - } - - if (importee.startsWith('\0')) { - return null; - } - - return this.resolve(importee, importer, { - skipSelf: true, - custom: { 'node-resolve': { isRequire: isProxyModule || isRequiredModule } } - }).then((resolved) => { - if (!resolved) { - resolved = resolveExtensions(importee, importer); - } - if (resolved && isProxyModule) { - resolved.id = wrapId(resolved.id, resolved.external ? EXTERNAL_SUFFIX : PROXY_SUFFIX); - resolved.external = false; - } else if (resolved && isModuleRegistration) { - resolved.id = wrapModuleRegisterProxy(resolved.id); - } else if (!resolved && (isProxyModule || isRequiredModule)) { - return { id: wrapId(importee, EXTERNAL_SUFFIX), external: false }; - } - return resolved; - }); - }; -} - -function validateRollupVersion(rollupVersion, peerDependencyVersion) { - const [major, minor] = rollupVersion.split('.').map(Number); - const versionRegexp = /\^(\d+\.\d+)\.\d+/g; - let minMajor = Infinity; - let minMinor = Infinity; - let foundVersion; - // eslint-disable-next-line no-cond-assign - while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) { - const [foundMajor, foundMinor] = foundVersion[1].split('.').map(Number); - if (foundMajor < minMajor) { - minMajor = foundMajor; - minMinor = foundMinor; - } - } - if (major < minMajor || (major === minMajor && minor < minMinor)) { - throw new Error( - `Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minMajor}.${minMinor} but found rollup@${rollupVersion}.` - ); - } -} - -const operators = { - '==': (x) => equals(x.left, x.right, false), - - '!=': (x) => not(operators['=='](x)), - - '===': (x) => equals(x.left, x.right, true), - - '!==': (x) => not(operators['==='](x)), - - '!': (x) => isFalsy(x.argument), - - '&&': (x) => isTruthy(x.left) && isTruthy(x.right), - - '||': (x) => isTruthy(x.left) || isTruthy(x.right) -}; - -function not(value) { - return value === null ? value : !value; -} - -function equals(a, b, strict) { - if (a.type !== b.type) return null; - // eslint-disable-next-line eqeqeq - if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value; - return null; -} - -function isTruthy(node) { - if (!node) return false; - if (node.type === 'Literal') return !!node.value; - if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression); - if (node.operator in operators) return operators[node.operator](node); - return null; -} - -function isFalsy(node) { - return not(isTruthy(node)); -} - -function getKeypath(node) { - const parts = []; - - while (node.type === 'MemberExpression') { - if (node.computed) return null; - - parts.unshift(node.property.name); - // eslint-disable-next-line no-param-reassign - node = node.object; - } - - if (node.type !== 'Identifier') return null; - - const { name } = node; - parts.unshift(name); - - return { name, keypath: parts.join('.') }; -} - -const KEY_COMPILED_ESM = '__esModule'; - -function isDefineCompiledEsm(node) { - const definedProperty = - getDefinePropertyCallName(node, 'exports') || getDefinePropertyCallName(node, 'module.exports'); - if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) { - return isTruthy(definedProperty.value); - } - return false; -} - -function getDefinePropertyCallName(node, targetName) { - const targetNames = targetName.split('.'); - - const { - callee: { object, property } - } = node; - if (!object || object.type !== 'Identifier' || object.name !== 'Object') return; - if (!property || property.type !== 'Identifier' || property.name !== 'defineProperty') return; - if (node.arguments.length !== 3) return; - - const [target, key, value] = node.arguments; - if (targetNames.length === 1) { - if (target.type !== 'Identifier' || target.name !== targetNames[0]) { - return; - } - } - - if (targetNames.length === 2) { - if ( - target.type !== 'MemberExpression' || - target.object.name !== targetNames[0] || - target.property.name !== targetNames[1] - ) { - return; - } - } - - if (value.type !== 'ObjectExpression' || !value.properties) return; - - const valueProperty = value.properties.find((p) => p.key && p.key.name === 'value'); - if (!valueProperty || !valueProperty.value) return; - - // eslint-disable-next-line consistent-return - return { key: key.value, value: valueProperty.value }; -} - -function isLocallyShadowed(name, scope) { - while (scope.parent) { - if (scope.declarations[name]) { - return true; - } - // eslint-disable-next-line no-param-reassign - scope = scope.parent; - } - return false; -} - -function isShorthandProperty(parent) { - return parent && parent.type === 'Property' && parent.shorthand; -} - -function wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath) { - const args = `module${uses.exports ? ', exports' : ''}`; - - magicString - .trim() - .prepend(`var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`) - .append( - `\n}${virtualDynamicRequirePath ? `, ${JSON.stringify(virtualDynamicRequirePath)}` : ''});` - ); -} - -function rewriteExportsAndGetExportsBlock( - magicString, - moduleName, - wrapped, - topLevelModuleExportsAssignments, - topLevelExportsAssignmentsByName, - defineCompiledEsmExpressions, - deconflict, - isRestorableCompiledEsm, - code, - uses, - HELPERS_NAME -) { - const namedExportDeclarations = [`export { ${moduleName} as __moduleExports };`]; - const moduleExportsPropertyAssignments = []; - let deconflictedDefaultExportName; - - if (!wrapped) { - let hasModuleExportsAssignment = false; - const namedExportProperties = []; - - // Collect and rewrite module.exports assignments - for (const { left } of topLevelModuleExportsAssignments) { - hasModuleExportsAssignment = true; - magicString.overwrite(left.start, left.end, `var ${moduleName}`); - } - - // Collect and rewrite named exports - for (const [exportName, node] of topLevelExportsAssignmentsByName) { - const deconflicted = deconflict(exportName); - magicString.overwrite(node.start, node.left.end, `var ${deconflicted}`); - - if (exportName === 'default') { - deconflictedDefaultExportName = deconflicted; - } else { - namedExportDeclarations.push( - exportName === deconflicted - ? `export { ${exportName} };` - : `export { ${deconflicted} as ${exportName} };` - ); - } - - if (hasModuleExportsAssignment) { - moduleExportsPropertyAssignments.push(`${moduleName}.${exportName} = ${deconflicted};`); - } else { - namedExportProperties.push(`\t${exportName}: ${deconflicted}`); - } - } - - // Regenerate CommonJS namespace - if (!hasModuleExportsAssignment) { - const moduleExports = `{\n${namedExportProperties.join(',\n')}\n}`; - magicString - .trim() - .append( - `\n\nvar ${moduleName} = ${ - isRestorableCompiledEsm - ? `/*#__PURE__*/Object.defineProperty(${moduleExports}, '__esModule', {value: true})` - : moduleExports - };` - ); - } - } - - // Generate default export - const defaultExport = []; - if (isRestorableCompiledEsm) { - defaultExport.push(`export default ${deconflictedDefaultExportName || moduleName};`); - } else if ( - (wrapped || deconflictedDefaultExportName) && - (defineCompiledEsmExpressions.length > 0 || code.indexOf('__esModule') >= 0) - ) { - // eslint-disable-next-line no-param-reassign - uses.commonjsHelpers = true; - defaultExport.push( - `export default /*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${moduleName});` - ); - } else { - defaultExport.push(`export default ${moduleName};`); - } - - return `\n\n${defaultExport - .concat(namedExportDeclarations) - .concat(moduleExportsPropertyAssignments) - .join('\n')}`; -} - -function isRequireStatement(node, scope) { - if (!node) return false; - if (node.type !== 'CallExpression') return false; - - // Weird case of `require()` or `module.require()` without arguments - if (node.arguments.length === 0) return false; - - return isRequire(node.callee, scope); -} - -function isRequire(node, scope) { - return ( - (node.type === 'Identifier' && node.name === 'require' && !scope.contains('require')) || - (node.type === 'MemberExpression' && isModuleRequire(node, scope)) - ); -} - -function isModuleRequire({ object, property }, scope) { - return ( - object.type === 'Identifier' && - object.name === 'module' && - property.type === 'Identifier' && - property.name === 'require' && - !scope.contains('module') - ); -} - -function isStaticRequireStatement(node, scope) { - if (!isRequireStatement(node, scope)) return false; - return !hasDynamicArguments(node); -} - -function hasDynamicArguments(node) { - return ( - node.arguments.length > 1 || - (node.arguments[0].type !== 'Literal' && - (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0)) - ); -} - -const reservedMethod = { resolve: true, cache: true, main: true }; - -function isNodeRequirePropertyAccess(parent) { - return parent && parent.property && reservedMethod[parent.property.name]; -} - -function isIgnoredRequireStatement(requiredNode, ignoreRequire) { - return ignoreRequire(requiredNode.arguments[0].value); -} - -function getRequireStringArg(node) { - return node.arguments[0].type === 'Literal' - ? node.arguments[0].value - : node.arguments[0].quasis[0].value.cooked; -} - -function hasDynamicModuleForPath(source, id, dynamicRequireModuleSet) { - if (!/^(?:\.{0,2}[/\\]|[A-Za-z]:[/\\])/.test(source)) { - try { - const resolvedPath = normalizePathSlashes(resolve$4.sync(source, { basedir: path$1.dirname(id) })); - if (dynamicRequireModuleSet.has(resolvedPath)) { - return true; - } - } catch (ex) { - // Probably a node.js internal module - return false; - } - - return false; - } - - for (const attemptExt of ['', '.js', '.json']) { - const resolvedPath = normalizePathSlashes(path$1.resolve(path$1.dirname(id), source + attemptExt)); - if (dynamicRequireModuleSet.has(resolvedPath)) { - return true; - } - } - - return false; -} - -function getRequireHandlers() { - const requiredSources = []; - const requiredBySource = Object.create(null); - const requiredByNode = new Map(); - const requireExpressionsWithUsedReturnValue = []; - - function addRequireStatement(sourceId, node, scope, usesReturnValue) { - const required = getRequired(sourceId); - requiredByNode.set(node, { scope, required }); - if (usesReturnValue) { - required.nodesUsingRequired.push(node); - requireExpressionsWithUsedReturnValue.push(node); - } - } - - function getRequired(sourceId) { - if (!requiredBySource[sourceId]) { - requiredSources.push(sourceId); - - requiredBySource[sourceId] = { - source: sourceId, - name: null, - nodesUsingRequired: [] - }; - } - - return requiredBySource[sourceId]; - } - - function rewriteRequireExpressionsAndGetImportBlock( - magicString, - topLevelDeclarations, - topLevelRequireDeclarators, - reassignedNames, - helpersNameIfUsed, - dynamicRegisterSources - ) { - const removedDeclarators = getDeclaratorsReplacedByImportsAndSetImportNames( - topLevelRequireDeclarators, - requiredByNode, - reassignedNames - ); - setRemainingImportNamesAndRewriteRequires( - requireExpressionsWithUsedReturnValue, - requiredByNode, - magicString - ); - removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString); - const importBlock = `${(helpersNameIfUsed - ? [`import * as ${helpersNameIfUsed} from '${HELPERS_ID}';`] - : [] - ) - .concat( - // dynamic registers first, as the may be required in the other modules - [...dynamicRegisterSources].map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`), - - // now the actual modules so that they are analyzed before creating the proxies; - // no need to do this for virtual modules as we never proxy them - requiredSources - .filter((source) => !source.startsWith('\0')) - .map((source) => `import '${wrapId(source, REQUIRE_SUFFIX)}';`), - - // now the proxy modules - requiredSources.map((source) => { - const { name, nodesUsingRequired } = requiredBySource[source]; - return `import ${nodesUsingRequired.length ? `${name} from ` : ``}'${ - source.startsWith('\0') ? source : wrapId(source, PROXY_SUFFIX) - }';`; - }) - ) - .join('\n')}`; - return importBlock ? `${importBlock}\n\n` : ''; - } - - return { - addRequireStatement, - requiredSources, - rewriteRequireExpressionsAndGetImportBlock - }; -} - -function getDeclaratorsReplacedByImportsAndSetImportNames( - topLevelRequireDeclarators, - requiredByNode, - reassignedNames -) { - const removedDeclarators = new Set(); - for (const declarator of topLevelRequireDeclarators) { - const { required } = requiredByNode.get(declarator.init); - if (!required.name) { - const potentialName = declarator.id.name; - if ( - !reassignedNames.has(potentialName) && - !required.nodesUsingRequired.some((node) => - isLocallyShadowed(potentialName, requiredByNode.get(node).scope) - ) - ) { - required.name = potentialName; - removedDeclarators.add(declarator); - } - } - } - return removedDeclarators; -} - -function setRemainingImportNamesAndRewriteRequires( - requireExpressionsWithUsedReturnValue, - requiredByNode, - magicString -) { - let uid = 0; - for (const requireExpression of requireExpressionsWithUsedReturnValue) { - const { required } = requiredByNode.get(requireExpression); - if (!required.name) { - let potentialName; - const isUsedName = (node) => requiredByNode.get(node).scope.contains(potentialName); - do { - potentialName = `require$$${uid}`; - uid += 1; - } while (required.nodesUsingRequired.some(isUsedName)); - required.name = potentialName; - } - magicString.overwrite(requireExpression.start, requireExpression.end, required.name); - } -} - -function removeDeclaratorsFromDeclarations(topLevelDeclarations, removedDeclarators, magicString) { - for (const declaration of topLevelDeclarations) { - let keepDeclaration = false; - let [{ start }] = declaration.declarations; - for (const declarator of declaration.declarations) { - if (removedDeclarators.has(declarator)) { - magicString.remove(start, declarator.end); - } else if (!keepDeclaration) { - magicString.remove(start, declarator.start); - keepDeclaration = true; - } - start = declarator.end; - } - if (!keepDeclaration) { - magicString.remove(declaration.start, declaration.end); - } - } -} - -/* eslint-disable no-param-reassign, no-shadow, no-underscore-dangle, no-continue */ - -const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/; - -const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/; - -function transformCommonjs( - parse, - code, - id, - isEsModule, - ignoreGlobal, - ignoreRequire, - getIgnoreTryCatchRequireStatementMode, - sourceMap, - isDynamicRequireModulesEnabled, - dynamicRequireModuleSet, - disableWrap, - commonDir, - astCache -) { - const ast = astCache || tryParse(parse, code, id); - const magicString = new MagicString(code); - const uses = { - module: false, - exports: false, - global: false, - require: false, - commonjsHelpers: false - }; - const virtualDynamicRequirePath = - isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath(path$1.dirname(id), commonDir); - let scope = attachScopes(ast, 'scope'); - let lexicalDepth = 0; - let programDepth = 0; - let currentTryBlockEnd = null; - let shouldWrap = false; - const defineCompiledEsmExpressions = []; - - const globals = new Set(); - - // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯ - const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers'); - const dynamicRegisterSources = new Set(); - let hasRemovedRequire = false; - - const { - addRequireStatement, - requiredSources, - rewriteRequireExpressionsAndGetImportBlock - } = getRequireHandlers(); - - // See which names are assigned to. This is necessary to prevent - // illegally replacing `var foo = require('foo')` with `import foo from 'foo'`, - // where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh) - const reassignedNames = new Set(); - const topLevelDeclarations = []; - const topLevelRequireDeclarators = new Set(); - const skippedNodes = new Set(); - const topLevelModuleExportsAssignments = []; - const topLevelExportsAssignmentsByName = new Map(); - - walk$1(ast, { - enter(node, parent) { - if (skippedNodes.has(node)) { - this.skip(); - return; - } - - if (currentTryBlockEnd !== null && node.start > currentTryBlockEnd) { - currentTryBlockEnd = null; - } - - programDepth += 1; - if (node.scope) ({ scope } = node); - if (functionType.test(node.type)) lexicalDepth += 1; - if (sourceMap) { - magicString.addSourcemapLocation(node.start); - magicString.addSourcemapLocation(node.end); - } - - // eslint-disable-next-line default-case - switch (node.type) { - case 'TryStatement': - if (currentTryBlockEnd === null) { - currentTryBlockEnd = node.block.end; - } - return; - case 'AssignmentExpression': - if (node.left.type === 'MemberExpression') { - const flattened = getKeypath(node.left); - if (!flattened || scope.contains(flattened.name)) return; - - const exportsPatternMatch = exportsPattern.exec(flattened.keypath); - if (!exportsPatternMatch || flattened.keypath === 'exports') return; - - const [, exportName] = exportsPatternMatch; - uses[flattened.name] = true; - - // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...` – - if (programDepth > 3) { - shouldWrap = true; - } else if (exportName === KEY_COMPILED_ESM) { - defineCompiledEsmExpressions.push(parent); - } else if (flattened.keypath === 'module.exports') { - topLevelModuleExportsAssignments.push(node); - } else if (!topLevelExportsAssignmentsByName.has(exportName)) { - topLevelExportsAssignmentsByName.set(exportName, node); - } else { - shouldWrap = true; - } - - skippedNodes.add(node.left); - - if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') { - node.right.properties.forEach((prop) => { - if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return; - const { name } = prop.key; - if (name === makeLegalIdentifier(name)) ; - }); - return; - } - } else { - for (const name of extractAssignedNames(node.left)) { - reassignedNames.add(name); - } - } - return; - case 'CallExpression': { - if (isDefineCompiledEsm(node)) { - if (programDepth === 3 && parent.type === 'ExpressionStatement') { - // skip special handling for [module.]exports until we know we render this - skippedNodes.add(node.arguments[0]); - defineCompiledEsmExpressions.push(parent); - } else { - shouldWrap = true; - } - return; - } - - if ( - node.callee.object && - node.callee.object.name === 'require' && - node.callee.property.name === 'resolve' && - hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet) - ) { - const requireNode = node.callee.object; - magicString.appendLeft( - node.end - 1, - `,${JSON.stringify( - path$1.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath - )}` - ); - magicString.overwrite( - requireNode.start, - requireNode.end, - `${HELPERS_NAME}.commonjsRequire`, - { - storeName: true - } - ); - uses.commonjsHelpers = true; - return; - } - - if (!isStaticRequireStatement(node, scope)) return; - if (!isDynamicRequireModulesEnabled) { - skippedNodes.add(node.callee); - } - if (!isIgnoredRequireStatement(node, ignoreRequire)) { - skippedNodes.add(node.callee); - const usesReturnValue = parent.type !== 'ExpressionStatement'; - - let canConvertRequire = true; - let shouldRemoveRequireStatement = false; - - if (currentTryBlockEnd !== null) { - ({ - canConvertRequire, - shouldRemoveRequireStatement - } = getIgnoreTryCatchRequireStatementMode(node.arguments[0].value)); - - if (shouldRemoveRequireStatement) { - hasRemovedRequire = true; - } - } - - let sourceId = getRequireStringArg(node); - const isDynamicRegister = isModuleRegisterProxy(sourceId); - if (isDynamicRegister) { - sourceId = unwrapModuleRegisterProxy(sourceId); - if (sourceId.endsWith('.json')) { - sourceId = DYNAMIC_JSON_PREFIX + sourceId; - } - dynamicRegisterSources.add(wrapModuleRegisterProxy(sourceId)); - } else { - if ( - !sourceId.endsWith('.json') && - hasDynamicModuleForPath(sourceId, id, dynamicRequireModuleSet) - ) { - if (shouldRemoveRequireStatement) { - magicString.overwrite(node.start, node.end, `undefined`); - } else if (canConvertRequire) { - magicString.overwrite( - node.start, - node.end, - `${HELPERS_NAME}.commonjsRequire(${JSON.stringify( - getVirtualPathForDynamicRequirePath(sourceId, commonDir) - )}, ${JSON.stringify( - path$1.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath - )})` - ); - uses.commonjsHelpers = true; - } - return; - } - - if (canConvertRequire) { - addRequireStatement(sourceId, node, scope, usesReturnValue); - } - } - - if (usesReturnValue) { - if (shouldRemoveRequireStatement) { - magicString.overwrite(node.start, node.end, `undefined`); - return; - } - - if ( - parent.type === 'VariableDeclarator' && - !scope.parent && - parent.id.type === 'Identifier' - ) { - // This will allow us to reuse this variable name as the imported variable if it is not reassigned - // and does not conflict with variables in other places where this is imported - topLevelRequireDeclarators.add(parent); - } - } else { - // This is a bare import, e.g. `require('foo');` - - if (!canConvertRequire && !shouldRemoveRequireStatement) { - return; - } - - magicString.remove(parent.start, parent.end); - } - } - return; - } - case 'ConditionalExpression': - case 'IfStatement': - // skip dead branches - if (isFalsy(node.test)) { - skippedNodes.add(node.consequent); - } else if (node.alternate && isTruthy(node.test)) { - skippedNodes.add(node.alternate); - } - return; - case 'Identifier': { - const { name } = node; - if (!(isReference(node, parent) && !scope.contains(name))) return; - switch (name) { - case 'require': - if (isNodeRequirePropertyAccess(parent)) { - if (hasDynamicModuleForPath(id, '/', dynamicRequireModuleSet)) { - if (parent.property.name === 'cache') { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { - storeName: true - }); - uses.commonjsHelpers = true; - } - } - - return; - } - - if (isDynamicRequireModulesEnabled && isRequireStatement(parent, scope)) { - magicString.appendLeft( - parent.end - 1, - `,${JSON.stringify( - path$1.dirname(id) === '.' ? null /* default behavior */ : virtualDynamicRequirePath - )}` - ); - } - if (isShorthandProperty(parent)) { - magicString.appendRight(node.end, `: ${HELPERS_NAME}.commonjsRequire`); - } else { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { - storeName: true - }); - } - - uses.commonjsHelpers = true; - return; - case 'module': - case 'exports': - shouldWrap = true; - uses[name] = true; - return; - case 'global': - uses.global = true; - if (!ignoreGlobal) { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, { - storeName: true - }); - uses.commonjsHelpers = true; - } - return; - case 'define': - magicString.overwrite(node.start, node.end, 'undefined', { storeName: true }); - return; - default: - globals.add(name); - return; - } - } - case 'MemberExpression': - if (!isDynamicRequireModulesEnabled && isModuleRequire(node, scope)) { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, { - storeName: true - }); - uses.commonjsHelpers = true; - skippedNodes.add(node.object); - skippedNodes.add(node.property); - } - return; - case 'ReturnStatement': - // if top-level return, we need to wrap it - if (lexicalDepth === 0) { - shouldWrap = true; - } - return; - case 'ThisExpression': - // rewrite top-level `this` as `commonjsHelpers.commonjsGlobal` - if (lexicalDepth === 0) { - uses.global = true; - if (!ignoreGlobal) { - magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, { - storeName: true - }); - uses.commonjsHelpers = true; - } - } - return; - case 'UnaryExpression': - // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151) - if (node.operator === 'typeof') { - const flattened = getKeypath(node.argument); - if (!flattened) return; - - if (scope.contains(flattened.name)) return; - - if ( - flattened.keypath === 'module.exports' || - flattened.keypath === 'module' || - flattened.keypath === 'exports' - ) { - magicString.overwrite(node.start, node.end, `'object'`, { storeName: false }); - } - } - return; - case 'VariableDeclaration': - if (!scope.parent) { - topLevelDeclarations.push(node); - } - } - }, - - leave(node) { - programDepth -= 1; - if (node.scope) scope = scope.parent; - if (functionType.test(node.type)) lexicalDepth -= 1; - } - }); - - let isRestorableCompiledEsm = false; - if (defineCompiledEsmExpressions.length > 0) { - if (!shouldWrap && defineCompiledEsmExpressions.length === 1) { - isRestorableCompiledEsm = true; - magicString.remove( - defineCompiledEsmExpressions[0].start, - defineCompiledEsmExpressions[0].end - ); - } else { - shouldWrap = true; - uses.exports = true; - } - } - - // We cannot wrap ES/mixed modules - shouldWrap = shouldWrap && !disableWrap && !isEsModule; - uses.commonjsHelpers = uses.commonjsHelpers || shouldWrap; - - if ( - !( - requiredSources.length || - dynamicRegisterSources.size || - uses.module || - uses.exports || - uses.require || - uses.commonjsHelpers || - hasRemovedRequire - ) && - (ignoreGlobal || !uses.global) - ) { - return { meta: { commonjs: { isCommonJS: false } } }; - } - - const moduleName = deconflict(scope, globals, getName(id)); - - let leadingComment = ''; - if (code.startsWith('/*')) { - const commentEnd = code.indexOf('*/', 2) + 2; - leadingComment = `${code.slice(0, commentEnd)}\n`; - magicString.remove(0, commentEnd).trim(); - } - - const exportBlock = isEsModule - ? '' - : rewriteExportsAndGetExportsBlock( - magicString, - moduleName, - shouldWrap, - topLevelModuleExportsAssignments, - topLevelExportsAssignmentsByName, - defineCompiledEsmExpressions, - (name) => deconflict(scope, globals, name), - isRestorableCompiledEsm, - code, - uses, - HELPERS_NAME - ); - - const importBlock = rewriteRequireExpressionsAndGetImportBlock( - magicString, - topLevelDeclarations, - topLevelRequireDeclarators, - reassignedNames, - uses.commonjsHelpers && HELPERS_NAME, - dynamicRegisterSources - ); - - if (shouldWrap) { - wrapCode(magicString, uses, moduleName, HELPERS_NAME, virtualDynamicRequirePath); - } - - magicString - .trim() - .prepend(leadingComment + importBlock) - .append(exportBlock); - - return { - code: magicString.toString(), - map: sourceMap ? magicString.generateMap() : null, - syntheticNamedExports: isEsModule ? false : '__moduleExports', - meta: { commonjs: { isCommonJS: !isEsModule } } - }; -} - -function commonjs(options = {}) { - const extensions = options.extensions || ['.js']; - const filter = createFilter(options.include, options.exclude); - const { - ignoreGlobal, - requireReturnsDefault: requireReturnsDefaultOption, - esmExternals - } = options; - const getRequireReturnsDefault = - typeof requireReturnsDefaultOption === 'function' - ? requireReturnsDefaultOption - : () => requireReturnsDefaultOption; - let esmExternalIds; - const isEsmExternal = - typeof esmExternals === 'function' - ? esmExternals - : Array.isArray(esmExternals) - ? ((esmExternalIds = new Set(esmExternals)), (id) => esmExternalIds.has(id)) - : () => esmExternals; - - const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths( - options.dynamicRequireTargets - ); - const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0; - const commonDir = isDynamicRequireModulesEnabled - ? commondir(null, Array.from(dynamicRequireModuleSet).concat(process.cwd())) - : null; - - const esModulesWithDefaultExport = new Set(); - const esModulesWithNamedExports = new Set(); - - const ignoreRequire = - typeof options.ignore === 'function' - ? options.ignore - : Array.isArray(options.ignore) - ? (id) => options.ignore.includes(id) - : () => false; - - const getIgnoreTryCatchRequireStatementMode = (id) => { - const mode = - typeof options.ignoreTryCatch === 'function' - ? options.ignoreTryCatch(id) - : Array.isArray(options.ignoreTryCatch) - ? options.ignoreTryCatch.includes(id) - : options.ignoreTryCatch || false; - - return { - canConvertRequire: mode !== 'remove' && mode !== true, - shouldRemoveRequireStatement: mode === 'remove' - }; - }; - - const resolveId = getResolveId(extensions); - - const sourceMap = options.sourceMap !== false; - - function transformAndCheckExports(code, id) { - if (isDynamicRequireModulesEnabled && this.getModuleInfo(id).isEntry) { - code = - getDynamicPackagesEntryIntro(dynamicRequireModuleDirPaths, dynamicRequireModuleSet) + code; - } - - const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements( - this.parse, - code, - id - ); - if (hasDefaultExport) { - esModulesWithDefaultExport.add(id); - } - if (hasNamedExports) { - esModulesWithNamedExports.add(id); - } - - if ( - !dynamicRequireModuleSet.has(normalizePathSlashes(id)) && - (!hasCjsKeywords(code, ignoreGlobal) || (isEsModule && !options.transformMixedEsModules)) - ) { - return { meta: { commonjs: { isCommonJS: false } } }; - } - - let disableWrap = false; - - // avoid wrapping in createCommonjsModule, as this is a commonjsRegister call - if (isModuleRegisterProxy(id)) { - disableWrap = true; - id = unwrapModuleRegisterProxy(id); - } - - return transformCommonjs( - this.parse, - code, - id, - isEsModule, - ignoreGlobal || isEsModule, - ignoreRequire, - getIgnoreTryCatchRequireStatementMode, - sourceMap, - isDynamicRequireModulesEnabled, - dynamicRequireModuleSet, - disableWrap, - commonDir, - ast - ); - } - - return { - name: 'commonjs', - - buildStart() { - validateRollupVersion(this.meta.rollupVersion, peerDependencies.rollup); - if (options.namedExports != null) { - this.warn( - 'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.' - ); - } - }, - - resolveId, - - load(id) { - if (id === HELPERS_ID) { - return getHelpersModule(isDynamicRequireModulesEnabled); - } - - if (id.startsWith(HELPERS_ID)) { - return getSpecificHelperProxy(id); - } - - if (isWrappedId(id, EXTERNAL_SUFFIX)) { - const actualId = unwrapId(id, EXTERNAL_SUFFIX); - return getUnknownRequireProxy( - actualId, - isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true - ); - } - - if (id === DYNAMIC_PACKAGES_ID) { - return getDynamicPackagesModule(dynamicRequireModuleDirPaths, commonDir); - } - - if (id.startsWith(DYNAMIC_JSON_PREFIX)) { - return getDynamicJsonProxy(id, commonDir); - } - - if (isDynamicModuleImport(id, dynamicRequireModuleSet)) { - return `export default require(${JSON.stringify(normalizePathSlashes(id))});`; - } - - if (isModuleRegisterProxy(id)) { - return getDynamicRequireProxy( - normalizePathSlashes(unwrapModuleRegisterProxy(id)), - commonDir - ); - } - - if (isWrappedId(id, PROXY_SUFFIX)) { - const actualId = unwrapId(id, PROXY_SUFFIX); - return getStaticRequireProxy( - actualId, - getRequireReturnsDefault(actualId), - esModulesWithDefaultExport, - esModulesWithNamedExports - ); - } - - return null; - }, - - transform(code, rawId) { - let id = rawId; - - if (isModuleRegisterProxy(id)) { - id = unwrapModuleRegisterProxy(id); - } - - const extName = path$1.extname(id); - if ( - extName !== '.cjs' && - id !== DYNAMIC_PACKAGES_ID && - !id.startsWith(DYNAMIC_JSON_PREFIX) && - (!filter(id) || !extensions.includes(extName)) - ) { - return null; - } - - try { - return transformAndCheckExports.call(this, code, rawId); - } catch (err) { - return this.error(err, err.loc); - } - }, - - moduleParsed({ id, meta: { commonjs } }) { - if (commonjs) { - const isCjs = commonjs.isCommonJS; - if (isCjs != null) { - setIsCjsPromise(id, isCjs); - return; - } - } - setIsCjsPromise(id, null); - } - }; -} - -var arrayUnion = (...arguments_) => { - return [...new Set([].concat(...arguments_))]; -}; - -const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; - -const getPath = (filepath, cwd) => { - const pth = filepath[0] === '!' ? filepath.slice(1) : filepath; - return path__default.isAbsolute(pth) ? pth : path__default.join(cwd, pth); -}; - -const addExtensions = (file, extensions) => { - if (path__default.extname(file)) { - return `**/${file}`; - } - - return `**/${file}.${getExtensions(extensions)}`; -}; - -const getGlob = (directory, options) => { - if (options.files && !Array.isArray(options.files)) { - throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``); - } - - if (options.extensions && !Array.isArray(options.extensions)) { - throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``); - } - - if (options.files && options.extensions) { - return options.files.map(x => path__default.posix.join(directory, addExtensions(x, options.extensions))); - } - - if (options.files) { - return options.files.map(x => path__default.posix.join(directory, `**/${x}`)); - } - - if (options.extensions) { - return [path__default.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)]; - } - - return [path__default.posix.join(directory, '**')]; -}; - -var dirGlob = async (input, options) => { - options = { - cwd: process.cwd(), - ...options - }; - - if (typeof options.cwd !== 'string') { - throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); - } - - const globs = await Promise.all([].concat(input).map(async x => { - const isDirectory = await pathType.isDirectory(getPath(x, options.cwd)); - return isDirectory ? getGlob(x, options) : x; - })); - - return [].concat.apply([], globs); // eslint-disable-line prefer-spread -}; - -var sync$7 = (input, options) => { - options = { - cwd: process.cwd(), - ...options - }; - - if (typeof options.cwd !== 'string') { - throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); - } - - const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x); - - return [].concat.apply([], globs); // eslint-disable-line prefer-spread -}; -dirGlob.sync = sync$7; - -// A simple implementation of make-array -function makeArray (subject) { - return Array.isArray(subject) - ? subject - : [subject] -} - -const EMPTY = ''; -const SPACE = ' '; -const ESCAPE = '\\'; -const REGEX_TEST_BLANK_LINE = /^\s+$/; -const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; -const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; -const REGEX_SPLITALL_CRLF = /\r?\n/g; -// /foo, -// ./foo, -// ../foo, -// . -// .. -const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; - -const SLASH$1 = '/'; -const KEY_IGNORE = typeof Symbol !== 'undefined' - ? Symbol.for('node-ignore') - /* istanbul ignore next */ - : 'node-ignore'; - -const define = (object, key, value) => - Object.defineProperty(object, key, {value}); - -const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; - -// Sanitize the range of a regular expression -// The cases are complicated, see test cases for details -const sanitizeRange = range => range.replace( - REGEX_REGEXP_RANGE, - (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) - ? match - // Invalid range (out of order) which is ok for gitignore rules but - // fatal for JavaScript regular expression, so eliminate it. - : EMPTY -); - -// See fixtures #59 -const cleanRangeBackSlash = slashes => { - const {length} = slashes; - return slashes.slice(0, length - length % 2) -}; - -// > If the pattern ends with a slash, -// > it is removed for the purpose of the following description, -// > but it would only find a match with a directory. -// > In other words, foo/ will match a directory foo and paths underneath it, -// > but will not match a regular file or a symbolic link foo -// > (this is consistent with the way how pathspec works in general in Git). -// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' -// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call -// you could use option `mark: true` with `glob` - -// '`foo/`' should not continue with the '`..`' -const REPLACERS = [ - - // > Trailing spaces are ignored unless they are quoted with backslash ("\") - [ - // (a\ ) -> (a ) - // (a ) -> (a) - // (a \ ) -> (a ) - /\\?\s+$/, - match => match.indexOf('\\') === 0 - ? SPACE - : EMPTY - ], - - // replace (\ ) with ' ' - [ - /\\\s/g, - () => SPACE - ], - - // Escape metacharacters - // which is written down by users but means special for regular expressions. - - // > There are 12 characters with special meanings: - // > - the backslash \, - // > - the caret ^, - // > - the dollar sign $, - // > - the period or dot ., - // > - the vertical bar or pipe symbol |, - // > - the question mark ?, - // > - the asterisk or star *, - // > - the plus sign +, - // > - the opening parenthesis (, - // > - the closing parenthesis ), - // > - and the opening square bracket [, - // > - the opening curly brace {, - // > These special characters are often called "metacharacters". - [ - /[\\$.|*+(){^]/g, - match => `\\${match}` - ], - - [ - // > a question mark (?) matches a single character - /(?!\\)\?/g, - () => '[^/]' - ], - - // leading slash - [ - - // > A leading slash matches the beginning of the pathname. - // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". - // A leading slash matches the beginning of the pathname - /^\//, - () => '^' - ], - - // replace special metacharacter slash after the leading slash - [ - /\//g, - () => '\\/' - ], - - [ - // > A leading "**" followed by a slash means match in all directories. - // > For example, "**/foo" matches file or directory "foo" anywhere, - // > the same as pattern "foo". - // > "**/foo/bar" matches file or directory "bar" anywhere that is directly - // > under directory "foo". - // Notice that the '*'s have been replaced as '\\*' - /^\^*\\\*\\\*\\\//, - - // '**/foo' <-> 'foo' - () => '^(?:.*\\/)?' - ], - - // starting - [ - // there will be no leading '/' - // (which has been replaced by section "leading slash") - // If starts with '**', adding a '^' to the regular expression also works - /^(?=[^^])/, - function startingReplacer () { - // If has a slash `/` at the beginning or middle - return !/\/(?!$)/.test(this) - // > Prior to 2.22.1 - // > If the pattern does not contain a slash /, - // > Git treats it as a shell glob pattern - // Actually, if there is only a trailing slash, - // git also treats it as a shell glob pattern - - // After 2.22.1 (compatible but clearer) - // > If there is a separator at the beginning or middle (or both) - // > of the pattern, then the pattern is relative to the directory - // > level of the particular .gitignore file itself. - // > Otherwise the pattern may also match at any level below - // > the .gitignore level. - ? '(?:^|\\/)' - - // > Otherwise, Git treats the pattern as a shell glob suitable for - // > consumption by fnmatch(3) - : '^' - } - ], - - // two globstars - [ - // Use lookahead assertions so that we could match more than one `'/**'` - /\\\/\\\*\\\*(?=\\\/|$)/g, - - // Zero, one or several directories - // should not use '*', or it will be replaced by the next replacer - - // Check if it is not the last `'/**'` - (_, index, str) => index + 6 < str.length - - // case: /**/ - // > A slash followed by two consecutive asterisks then a slash matches - // > zero or more directories. - // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. - // '/**/' - ? '(?:\\/[^\\/]+)*' - - // case: /** - // > A trailing `"/**"` matches everything inside. - - // #21: everything inside but it should not include the current folder - : '\\/.+' - ], - - // intermediate wildcards - [ - // Never replace escaped '*' - // ignore rule '\*' will match the path '*' - - // 'abc.*/' -> go - // 'abc.*' -> skip this rule - /(^|[^\\]+)\\\*(?=.+)/g, - - // '*.js' matches '.js' - // '*.js' doesn't match 'abc' - (_, p1) => `${p1}[^\\/]*` - ], - - [ - // unescape, revert step 3 except for back slash - // For example, if a user escape a '\\*', - // after step 3, the result will be '\\\\\\*' - /\\\\\\(?=[$.|*+(){^])/g, - () => ESCAPE - ], - - [ - // '\\\\' -> '\\' - /\\\\/g, - () => ESCAPE - ], - - [ - // > The range notation, e.g. [a-zA-Z], - // > can be used to match one of the characters in a range. - - // `\` is escaped by step 3 - /(\\)?\[([^\]/]*?)(\\*)($|\])/g, - (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE - // '\\[bar]' -> '\\\\[bar\\]' - ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` - : close === ']' - ? endEscape.length % 2 === 0 - // A normal case, and it is a range notation - // '[bar]' - // '[bar\\\\]' - ? `[${sanitizeRange(range)}${endEscape}]` - // Invalid range notaton - // '[bar\\]' -> '[bar\\\\]' - : '[]' - : '[]' - ], - - // ending - [ - // 'js' will not match 'js.' - // 'ab' will not match 'abc' - /(?:[^*])$/, - - // WTF! - // https://git-scm.com/docs/gitignore - // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) - // which re-fixes #24, #38 - - // > If there is a separator at the end of the pattern then the pattern - // > will only match directories, otherwise the pattern can match both - // > files and directories. - - // 'js*' will not match 'a.js' - // 'js/' will not match 'a.js' - // 'js' will match 'a.js' and 'a.js/' - match => /\/$/.test(match) - // foo/ will not match 'foo' - ? `${match}$` - // foo matches 'foo' and 'foo/' - : `${match}(?=$|\\/$)` - ], - - // trailing wildcard - [ - /(\^|\\\/)?\\\*$/, - (_, p1) => { - const prefix = p1 - // '\^': - // '/*' does not match EMPTY - // '/*' does not match everything - - // '\\\/': - // 'abc/*' does not match 'abc/' - ? `${p1}[^/]+` - - // 'a*' matches 'a' - // 'a*' matches 'aa' - : '[^/]*'; - - return `${prefix}(?=$|\\/$)` - } - ], -]; - -// A simple cache, because an ignore rule only has only one certain meaning -const regexCache = Object.create(null); - -// @param {pattern} -const makeRegex = (pattern, negative, ignorecase) => { - const r = regexCache[pattern]; - if (r) { - return r - } - - // const replacers = negative - // ? NEGATIVE_REPLACERS - // : POSITIVE_REPLACERS - - const source = REPLACERS.reduce( - (prev, current) => prev.replace(current[0], current[1].bind(pattern)), - pattern - ); - - return regexCache[pattern] = ignorecase - ? new RegExp(source, 'i') - : new RegExp(source) -}; - -const isString = subject => typeof subject === 'string'; - -// > A blank line matches no files, so it can serve as a separator for readability. -const checkPattern = pattern => pattern - && isString(pattern) - && !REGEX_TEST_BLANK_LINE.test(pattern) - - // > A line starting with # serves as a comment. - && pattern.indexOf('#') !== 0; - -const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF); - -class IgnoreRule { - constructor ( - origin, - pattern, - negative, - regex - ) { - this.origin = origin; - this.pattern = pattern; - this.negative = negative; - this.regex = regex; - } -} - -const createRule = (pattern, ignorecase) => { - const origin = pattern; - let negative = false; - - // > An optional prefix "!" which negates the pattern; - if (pattern.indexOf('!') === 0) { - negative = true; - pattern = pattern.substr(1); - } - - pattern = pattern - // > Put a backslash ("\") in front of the first "!" for patterns that - // > begin with a literal "!", for example, `"\!important!.txt"`. - .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') - // > Put a backslash ("\") in front of the first hash for patterns that - // > begin with a hash. - .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); - - const regex = makeRegex(pattern, negative, ignorecase); - - return new IgnoreRule( - origin, - pattern, - negative, - regex - ) -}; - -const throwError = (message, Ctor) => { - throw new Ctor(message) -}; - -const checkPath = (path, originalPath, doThrow) => { - if (!isString(path)) { - return doThrow( - `path must be a string, but got \`${originalPath}\``, - TypeError - ) - } - - // We don't know if we should ignore EMPTY, so throw - if (!path) { - return doThrow(`path must not be empty`, TypeError) - } - - // Check if it is a relative path - if (checkPath.isNotRelative(path)) { - const r = '`path.relative()`d'; - return doThrow( - `path should be a ${r} string, but got "${originalPath}"`, - RangeError - ) - } - - return true -}; - -const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path); - -checkPath.isNotRelative = isNotRelative; -checkPath.convert = p => p; - -class Ignore { - constructor ({ - ignorecase = true - } = {}) { - this._rules = []; - this._ignorecase = ignorecase; - define(this, KEY_IGNORE, true); - this._initCache(); - } - - _initCache () { - this._ignoreCache = Object.create(null); - this._testCache = Object.create(null); - } - - _addPattern (pattern) { - // #32 - if (pattern && pattern[KEY_IGNORE]) { - this._rules = this._rules.concat(pattern._rules); - this._added = true; - return - } - - if (checkPattern(pattern)) { - const rule = createRule(pattern, this._ignorecase); - this._added = true; - this._rules.push(rule); - } - } - - // @param {Array | string | Ignore} pattern - add (pattern) { - this._added = false; - - makeArray( - isString(pattern) - ? splitPattern(pattern) - : pattern - ).forEach(this._addPattern, this); - - // Some rules have just added to the ignore, - // making the behavior changed. - if (this._added) { - this._initCache(); - } - - return this - } - - // legacy - addPattern (pattern) { - return this.add(pattern) - } - - // | ignored : unignored - // negative | 0:0 | 0:1 | 1:0 | 1:1 - // -------- | ------- | ------- | ------- | -------- - // 0 | TEST | TEST | SKIP | X - // 1 | TESTIF | SKIP | TEST | X - - // - SKIP: always skip - // - TEST: always test - // - TESTIF: only test if checkUnignored - // - X: that never happen - - // @param {boolean} whether should check if the path is unignored, - // setting `checkUnignored` to `false` could reduce additional - // path matching. - - // @returns {TestResult} true if a file is ignored - _testOne (path, checkUnignored) { - let ignored = false; - let unignored = false; - - this._rules.forEach(rule => { - const {negative} = rule; - if ( - unignored === negative && ignored !== unignored - || negative && !ignored && !unignored && !checkUnignored - ) { - return - } - - const matched = rule.regex.test(path); - - if (matched) { - ignored = !negative; - unignored = negative; - } - }); - - return { - ignored, - unignored - } - } - - // @returns {TestResult} - _test (originalPath, cache, checkUnignored, slices) { - const path = originalPath - // Supports nullable path - && checkPath.convert(originalPath); - - checkPath(path, originalPath, throwError); - - return this._t(path, cache, checkUnignored, slices) - } - - _t (path, cache, checkUnignored, slices) { - if (path in cache) { - return cache[path] - } - - if (!slices) { - // path/to/a.js - // ['path', 'to', 'a.js'] - slices = path.split(SLASH$1); - } - - slices.pop(); - - // If the path has no parent directory, just test it - if (!slices.length) { - return cache[path] = this._testOne(path, checkUnignored) - } - - const parent = this._t( - slices.join(SLASH$1) + SLASH$1, - cache, - checkUnignored, - slices - ); - - // If the path contains a parent directory, check the parent first - return cache[path] = parent.ignored - // > It is not possible to re-include a file if a parent directory of - // > that file is excluded. - ? parent - : this._testOne(path, checkUnignored) - } - - ignores (path) { - return this._test(path, this._ignoreCache, false).ignored - } - - createFilter () { - return path => !this.ignores(path) - } - - filter (paths) { - return makeArray(paths).filter(this.createFilter()) - } - - // @returns {TestResult} - test (path) { - return this._test(path, this._testCache, true) - } -} - -const factory = options => new Ignore(options); - -const returnFalse = () => false; - -const isPathValid = path => - checkPath(path && checkPath.convert(path), path, returnFalse); - -factory.isPathValid = isPathValid; - -// Fixes typescript -factory.default = factory; - -var ignore = factory; - -// Windows -// -------------------------------------------------------------- -/* istanbul ignore if */ -if ( - // Detect `process` so that it can run in browsers. - typeof process !== 'undefined' - && ( - process.env && process.env.IGNORE_TEST_WIN32 - || process.platform === 'win32' - ) -) { - /* eslint no-control-regex: "off" */ - const makePosix = str => /^\\\\\?\\/.test(str) - || /["<>|\u0000-\u001F]+/u.test(str) - ? str - : str.replace(/\\/g, '/'); - - checkPath.convert = makePosix; - - // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' - // 'd:\\foo' - const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; - checkPath.isNotRelative = path => - REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) - || isNotRelative(path); -} - -var slash = path => { - const isExtendedLengthPath = /^\\\\\?\\/.test(path); - const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex - - if (isExtendedLengthPath || hasNonAscii) { - return path; - } - - return path.replace(/\\/g, '/'); -}; - -const {promisify: promisify$6} = util__default; - - - - - - -const DEFAULT_IGNORE = [ - '**/node_modules/**', - '**/flow-typed/**', - '**/coverage/**', - '**/.git' -]; - -const readFileP = promisify$6(fs__default.readFile); - -const mapGitIgnorePatternTo = base => ignore => { - if (ignore.startsWith('!')) { - return '!' + path__default.posix.join(base, ignore.slice(1)); - } - - return path__default.posix.join(base, ignore); -}; - -const parseGitIgnore = (content, options) => { - const base = slash(path__default.relative(options.cwd, path__default.dirname(options.fileName))); - - return content - .split(/\r?\n/) - .filter(Boolean) - .filter(line => !line.startsWith('#')) - .map(mapGitIgnorePatternTo(base)); -}; - -const reduceIgnore = files => { - const ignores = ignore(); - for (const file of files) { - ignores.add(parseGitIgnore(file.content, { - cwd: file.cwd, - fileName: file.filePath - })); - } - - return ignores; -}; - -const ensureAbsolutePathForCwd = (cwd, p) => { - cwd = slash(cwd); - if (path__default.isAbsolute(p)) { - if (slash(p).startsWith(cwd)) { - return p; - } - - throw new Error(`Path ${p} is not in cwd ${cwd}`); - } - - return path__default.join(cwd, p); -}; - -const getIsIgnoredPredecate = (ignores, cwd) => { - return p => ignores.ignores(slash(path__default.relative(cwd, ensureAbsolutePathForCwd(cwd, p.path || p)))); -}; - -const getFile = async (file, cwd) => { - const filePath = path__default.join(cwd, file); - const content = await readFileP(filePath, 'utf8'); - - return { - cwd, - filePath, - content - }; -}; - -const getFileSync = (file, cwd) => { - const filePath = path__default.join(cwd, file); - const content = fs__default.readFileSync(filePath, 'utf8'); - - return { - cwd, - filePath, - content - }; -}; - -const normalizeOptions = ({ - ignore = [], - cwd = slash(process.cwd()) -} = {}) => { - return {ignore, cwd}; -}; - -var gitignore = async options => { - options = normalizeOptions(options); - - const paths = await out('**/.gitignore', { - ignore: DEFAULT_IGNORE.concat(options.ignore), - cwd: options.cwd - }); - - const files = await Promise.all(paths.map(file => getFile(file, options.cwd))); - const ignores = reduceIgnore(files); - - return getIsIgnoredPredecate(ignores, options.cwd); -}; - -var sync$6 = options => { - options = normalizeOptions(options); - - const paths = out.sync('**/.gitignore', { - ignore: DEFAULT_IGNORE.concat(options.ignore), - cwd: options.cwd - }); - - const files = paths.map(file => getFileSync(file, options.cwd)); - const ignores = reduceIgnore(files); - - return getIsIgnoredPredecate(ignores, options.cwd); -}; -gitignore.sync = sync$6; - -const {Transform} = require$$0__default; - -class ObjectTransform extends Transform { - constructor() { - super({ - objectMode: true - }); - } -} - -class FilterStream$1 extends ObjectTransform { - constructor(filter) { - super(); - this._filter = filter; - } - - _transform(data, encoding, callback) { - if (this._filter(data)) { - this.push(data); - } - - callback(); - } -} - -class UniqueStream$1 extends ObjectTransform { - constructor() { - super(); - this._pushed = new Set(); - } - - _transform(data, encoding, callback) { - if (!this._pushed.has(data)) { - this.push(data); - this._pushed.add(data); - } - - callback(); - } -} - -var streamUtils = { - FilterStream: FilterStream$1, - UniqueStream: UniqueStream$1 -}; - -const {FilterStream, UniqueStream} = streamUtils; - -const DEFAULT_FILTER = () => false; - -const isNegative = pattern => pattern[0] === '!'; - -const assertPatternsInput = patterns => { - if (!patterns.every(pattern => typeof pattern === 'string')) { - throw new TypeError('Patterns must be a string or an array of strings'); - } -}; - -const checkCwdOption = (options = {}) => { - if (!options.cwd) { - return; - } - - let stat; - try { - stat = fs__default.statSync(options.cwd); - } catch { - return; - } - - if (!stat.isDirectory()) { - throw new Error('The `cwd` option must be a path to a directory'); - } -}; - -const getPathString = p => p.stats instanceof fs__default.Stats ? p.path : p; - -const generateGlobTasks = (patterns, taskOptions) => { - patterns = arrayUnion([].concat(patterns)); - assertPatternsInput(patterns); - checkCwdOption(taskOptions); - - const globTasks = []; - - taskOptions = { - ignore: [], - expandDirectories: true, - ...taskOptions - }; - - for (const [index, pattern] of patterns.entries()) { - if (isNegative(pattern)) { - continue; - } - - const ignore = patterns - .slice(index) - .filter(pattern => isNegative(pattern)) - .map(pattern => pattern.slice(1)); - - const options = { - ...taskOptions, - ignore: taskOptions.ignore.concat(ignore) - }; - - globTasks.push({pattern, options}); - } - - return globTasks; -}; - -const globDirs = (task, fn) => { - let options = {}; - if (task.options.cwd) { - options.cwd = task.options.cwd; - } - - if (Array.isArray(task.options.expandDirectories)) { - options = { - ...options, - files: task.options.expandDirectories - }; - } else if (typeof task.options.expandDirectories === 'object') { - options = { - ...options, - ...task.options.expandDirectories - }; - } - - return fn(task.pattern, options); -}; - -const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern]; - -const getFilterSync = options => { - return options && options.gitignore ? - gitignore.sync({cwd: options.cwd, ignore: options.ignore}) : - DEFAULT_FILTER; -}; - -const globToTask = task => glob => { - const {options} = task; - if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) { - options.ignore = dirGlob.sync(options.ignore); - } - - return { - pattern: glob, - options - }; -}; - -var globby = async (patterns, options) => { - const globTasks = generateGlobTasks(patterns, options); - - const getFilter = async () => { - return options && options.gitignore ? - gitignore({cwd: options.cwd, ignore: options.ignore}) : - DEFAULT_FILTER; - }; - - const getTasks = async () => { - const tasks = await Promise.all(globTasks.map(async task => { - const globs = await getPattern(task, dirGlob); - return Promise.all(globs.map(globToTask(task))); - })); - - return arrayUnion(...tasks); - }; - - const [filter, tasks] = await Promise.all([getFilter(), getTasks()]); - const paths = await Promise.all(tasks.map(task => out(task.pattern, task.options))); - - return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_))); -}; - -var sync$5 = (patterns, options) => { - const globTasks = generateGlobTasks(patterns, options); - - const tasks = []; - for (const task of globTasks) { - const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); - tasks.push(...newTask); - } - - const filter = getFilterSync(options); - - let matches = []; - for (const task of tasks) { - matches = arrayUnion(matches, out.sync(task.pattern, task.options)); - } - - return matches.filter(path_ => !filter(path_)); -}; - -var stream$2 = (patterns, options) => { - const globTasks = generateGlobTasks(patterns, options); - - const tasks = []; - for (const task of globTasks) { - const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); - tasks.push(...newTask); - } - - const filter = getFilterSync(options); - const filterStream = new FilterStream(p => !filter(p)); - const uniqueStream = new UniqueStream(); - - return merge2_1(tasks.map(task => out.stream(task.pattern, task.options))) - .pipe(filterStream) - .pipe(uniqueStream); -}; - -var generateGlobTasks_1 = generateGlobTasks; - -var hasMagic = (patterns, options) => [] - .concat(patterns) - .some(pattern => out.isDynamicPattern(pattern, options)); - -var gitignore_1 = gitignore; -globby.sync = sync$5; -globby.stream = stream$2; -globby.generateGlobTasks = generateGlobTasks_1; -globby.hasMagic = hasMagic; -globby.gitignore = gitignore_1; - -class VariableDynamicImportError extends Error {} - -/* eslint-disable-next-line no-template-curly-in-string */ -const example = 'For example: import(`./foo/${bar}.js`).'; - -function sanitizeString(str) { - if (str.includes('*')) { - throw new VariableDynamicImportError('A dynamic import cannot contain * characters.'); - } - return str; -} - -function templateLiteralToGlob(node) { - let glob = ''; - - for (let i = 0; i < node.quasis.length; i += 1) { - glob += sanitizeString(node.quasis[i].value.raw); - if (node.expressions[i]) { - glob += expressionToGlob(node.expressions[i]); - } - } - - return glob; -} - -function callExpressionToGlob(node) { - const { callee } = node; - if ( - callee.type === 'MemberExpression' && - callee.property.type === 'Identifier' && - callee.property.name === 'concat' - ) { - return `${expressionToGlob(callee.object)}${node.arguments.map(expressionToGlob).join('')}`; - } - return '*'; -} - -function binaryExpressionToGlob(node) { - if (node.operator !== '+') { - throw new VariableDynamicImportError(`${node.operator} operator is not supported.`); - } - - return `${expressionToGlob(node.left)}${expressionToGlob(node.right)}`; -} - -function expressionToGlob(node) { - switch (node.type) { - case 'TemplateLiteral': - return templateLiteralToGlob(node); - case 'CallExpression': - return callExpressionToGlob(node); - case 'BinaryExpression': - return binaryExpressionToGlob(node); - case 'Literal': { - return sanitizeString(node.value); - } - default: - return '*'; - } -} - -function dynamicImportToGlob(node, sourceString) { - let glob = expressionToGlob(node); - if (!glob.includes('*')) { - return null; - } - glob = glob.replace(/\*\*/g, '*'); - - if (glob.startsWith('*')) { - throw new VariableDynamicImportError( - `invalid import "${sourceString}". It cannot be statically analyzed. Variable dynamic imports must start with ./ and be limited to a specific directory. ${example}` - ); - } - - if (glob.startsWith('/')) { - throw new VariableDynamicImportError( - `invalid import "${sourceString}". Variable absolute imports are not supported, imports must start with ./ in the static part of the import. ${example}` - ); - } - - if (!glob.startsWith('./') && !glob.startsWith('../')) { - throw new VariableDynamicImportError( - `invalid import "${sourceString}". Variable bare imports are not supported, imports must start with ./ in the static part of the import. ${example}` - ); - } - - if (glob.startsWith('./*.')) { - throw new VariableDynamicImportError( - `${`invalid import "${sourceString}". Variable imports cannot import their own directory, ` + - 'place imports in a separate directory or make the import filename more specific. '}${example}` - ); - } - - if (path__default.extname(glob) === '') { - throw new VariableDynamicImportError( - `invalid import "${sourceString}". A file extension must be included in the static part of the import. ${example}` - ); - } - - return glob; -} - -function dynamicImportVariables({ include, exclude, warnOnError } = {}) { - const filter = createFilter(include, exclude); - - return { - name: 'rollup-plugin-dynamic-import-variables', - - transform(code, id) { - if (!filter(id)) { - return null; - } - - const parsed = this.parse(code); - - let dynamicImportIndex = -1; - let ms; - - walk$1(parsed, { - enter: (node) => { - if (node.type !== 'ImportExpression') { - return; - } - dynamicImportIndex += 1; - - try { - // see if this is a variable dynamic import, and generate a glob expression - const glob = dynamicImportToGlob(node.source, code.substring(node.start, node.end)); - - if (!glob) { - // this was not a variable dynamic import - return; - } - - // execute the glob - const result = globby.sync(glob, { cwd: path__default.dirname(id) }); - const paths = result.map((r) => - r.startsWith('./') || r.startsWith('../') ? r : `./${r}` - ); - - // create magic string if it wasn't created already - ms = ms || new MagicString(code); - // unpack variable dynamic import into a function with import statements per file, rollup - // will turn these into chunks automatically - ms.prepend( - `function __variableDynamicImportRuntime${dynamicImportIndex}__(path) { - switch (path) { - ${paths.map((p) => ` case '${p}': return import('${p}');`).join('\n ')} - default: return Promise.reject(new Error("Unknown variable dynamic import: " + path)); - } - }\n\n` - ); - // call the runtime function instead of doing a dynamic import, the import specifier will - // be evaluated at runtime and the correct import will be returned by the injected function - ms.overwrite( - node.start, - node.start + 6, - `__variableDynamicImportRuntime${dynamicImportIndex}__` - ); - } catch (error) { - if (error instanceof VariableDynamicImportError) { - // TODO: line number - if (warnOnError) { - this.warn(error); - } else { - this.error(error); - } - } else { - this.error(error); - } - } - } - }); - - if (ms && dynamicImportIndex !== -1) { - return { - code: ms.toString(), - map: ms.generateMap({ - file: id, - includeContent: true, - hires: true - }) - }; - } - return null; - } - }; -} - -const dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/; -const dataUriPrefix = `/@data-uri/`; -/** - * Build only, since importing from a data URI works natively. - */ -function dataURIPlugin() { - const resolved = {}; - return { - name: 'vite:data-uri', - resolveId(id) { - if (!dataUriRE.test(id)) { - return null; - } - const uri = new url.URL(id); - if (uri.protocol !== 'data:') { - return null; - } - const match = uri.pathname.match(dataUriRE); - if (!match) { - return null; - } - const [, mime, format, data] = match; - if (mime !== 'text/javascript') { - throw new Error(`data URI with non-JavaScript mime type is not supported.`); - } - // decode data - const base64 = format && /base64/i.test(format.substring(1)); - const content = base64 - ? Buffer.from(data, 'base64').toString('utf-8') - : data; - resolved[id] = content; - return dataUriPrefix + id; - }, - load(id) { - if (id.startsWith(dataUriPrefix)) { - id = id.slice(dataUriPrefix.length); - return resolved[id] || null; - } - } - }; -} - -/** - * @param {object} exports - * @param {Set} keys - */ -function loop(exports, keys) { - if (typeof exports === 'string') { - return exports; - } - - if (exports) { - let idx, tmp; - if (Array.isArray(exports)) { - for (idx=0; idx < exports.length; idx++) { - if (tmp = loop(exports[idx], keys)) return tmp; - } - } else { - for (idx in exports) { - if (keys.has(idx)) { - return loop(exports[idx], keys); - } - } - } - } -} - -/** - * @param {string} name The package name - * @param {string} entry The target entry, eg "." - * @param {number} [condition] Unmatched condition? - */ -function bail(name, entry, condition) { - throw new Error( - condition - ? `No known conditions for "${entry}" entry in "${name}" package` - : `Missing "${entry}" export in "${name}" package` - ); -} - -/** - * @param {string} name the package name - * @param {string} entry the target path/import - */ -function toName(name, entry) { - return entry === name ? '.' - : entry[0] === '.' ? entry - : entry.replace(new RegExp('^' + name + '\/'), './'); -} - -/** - * @param {object} pkg package.json contents - * @param {string} [entry] entry name or import path - * @param {object} [options] - * @param {boolean} [options.browser] - * @param {boolean} [options.require] - * @param {string[]} [options.conditions] - */ -function resolve$1(pkg, entry='.', options={}) { - let { name, exports } = pkg; - - if (exports) { - let { browser, require, conditions=[] } = options; - - let target = toName(name, entry); - if (target[0] !== '.') target = './' + target; - - if (typeof exports === 'string') { - return target === '.' ? exports : bail(name, target); - } - - let allows = new Set(['default', ...conditions]); - allows.add(require ? 'require' : 'import'); - allows.add(browser ? 'browser' : 'node'); - - let key, tmp, isSingle=false; - - for (key in exports) { - isSingle = key[0] !== '.'; - break; - } - - if (isSingle) { - return target === '.' - ? loop(exports, allows) || bail(name, target, 1) - : bail(name, target); - } - - if (tmp = exports[target]) { - return loop(tmp, allows) || bail(name, target, 1); - } - - for (key in exports) { - tmp = key[key.length - 1]; - if (tmp === '/' && target.startsWith(key)) { - return (tmp = loop(exports[key], allows)) - ? (tmp + target.substring(key.length)) - : bail(name, target, 1); - } - if (tmp === '*' && target.startsWith(key.slice(0, -1))) { - // do not trigger if no *content* to inject - if (target.substring(key.length - 1).length > 0) { - return (tmp = loop(exports[key], allows)) - ? tmp.replace('*', target.substring(key.length - 1)) - : bail(name, target, 1); - } - } - } - - return bail(name, target); - } -} - -// special id for paths marked with browser: false -// https://github.com/defunctzombie/package-browser-field-spec#ignore-a-module -const browserExternalId = '__vite-browser-external'; -const isDebug$4 = process.env.DEBUG; -const debug$9 = createDebugger('vite:resolve-details', { - onlyWhenFocused: true -}); -function resolvePlugin(baseOptions) { - const { root, isProduction, asSrc, preferRelative = false } = baseOptions; - const requireOptions = { - ...baseOptions, - isRequire: true - }; - let server; - return { - name: 'vite:resolve', - configureServer(_server) { - server = _server; - }, - resolveId(id, importer, resolveOpts, ssr) { - if (id.startsWith(browserExternalId)) { - return id; - } - // fast path for commonjs proxy modules - if (/\?commonjs/.test(id) || id === 'commonjsHelpers.js') { - return; - } - // this is passed by @rollup/plugin-commonjs - const isRequire = resolveOpts && - resolveOpts.custom && - resolveOpts.custom['node-resolve'] && - resolveOpts.custom['node-resolve'].isRequire; - const options = isRequire ? requireOptions : baseOptions; - let res; - // explicit fs paths that starts with /@fs/* - if (asSrc && id.startsWith(FS_PREFIX)) { - const fsPath = fsPathFromId(id); - res = tryFsResolve(fsPath, options); - isDebug$4 && debug$9(`[@fs] ${source.cyan(id)} -> ${source.dim(res)}`); - // always return here even if res doesn't exist since /@fs/ is explicit - // if the file doesn't exist it should be a 404 - return res || fsPath; - } - // URL - // /foo -> /fs-root/foo - if (asSrc && id.startsWith('/')) { - const fsPath = path__default.resolve(root, id.slice(1)); - if ((res = tryFsResolve(fsPath, options))) { - isDebug$4 && debug$9(`[url] ${source.cyan(id)} -> ${source.dim(res)}`); - return res; - } - } - // relative - if (id.startsWith('.') || (preferRelative && /^\w/.test(id))) { - const basedir = importer ? path__default.dirname(importer) : process.cwd(); - let fsPath = path__default.resolve(basedir, id); - // handle browser field mapping for relative imports - if ((res = tryResolveBrowserMapping(fsPath, importer, options, true))) { - return res; - } - if ((res = tryFsResolve(fsPath, options))) { - isDebug$4 && debug$9(`[relative] ${source.cyan(id)} -> ${source.dim(res)}`); - const pkg = importer != null && idToPkgMap.get(importer); - if (pkg) { - idToPkgMap.set(res, pkg); - return { - id: res, - moduleSideEffects: pkg.hasSideEffects(res) - }; - } - return res; - } - } - // absolute fs paths - if (path__default.isAbsolute(id) && (res = tryFsResolve(id, options))) { - isDebug$4 && debug$9(`[fs] ${source.cyan(id)} -> ${source.dim(res)}`); - return res; - } - // external - if (isExternalUrl(id)) { - return { - id, - external: true - }; - } - // data uri: pass through (this only happens during build and will be - // handled by dedicated plugin) - if (isDataUrl(id)) { - return null; - } - // bare package imports, perform node resolve - if (bareImportRE.test(id)) { - if (asSrc && - server && - !ssr && - (res = tryOptimizedResolve(id, server))) { - return res; - } - if ((res = tryResolveBrowserMapping(id, importer, options, false))) { - return res; - } - if ((res = tryNodeResolve(id, importer, options, server))) { - return res; - } - // node built-ins. - // externalize if building for SSR, otherwise redirect to empty module - if (isBuiltin(id)) { - if (ssr) { - return { - id, - external: true - }; - } - else { - if (!asSrc) { - debug$9(`externalized node built-in "${id}" to empty module. ` + - `(imported by: ${source.white.dim(importer)})`); - } - return isProduction - ? browserExternalId - : `${browserExternalId}:${id}`; - } - } - } - isDebug$4 && debug$9(`[fallthrough] ${source.dim(id)}`); - }, - load(id) { - if (id.startsWith(browserExternalId)) { - return isProduction - ? `export default {}` - : `export default new Proxy({}, { - get() { - throw new Error('Module "${id.slice(browserExternalId.length + 1)}" has been externalized for browser compatibility and cannot be accessed in client code.') - } -})`; - } - } - }; -} -function tryFsResolve(fsPath, options, tryIndex = true) { - let file = fsPath; - let postfix = ''; - let postfixIndex = fsPath.indexOf('?'); - if (postfixIndex < 0) { - postfixIndex = fsPath.indexOf('#'); - } - if (postfixIndex > 0) { - file = fsPath.slice(0, postfixIndex); - postfix = fsPath.slice(postfixIndex); - } - let res; - if ((res = tryResolveFile(file, postfix, options, false, options.tryPrefix))) { - return res; - } - for (const ext of options.extensions || DEFAULT_EXTENSIONS) { - if ((res = tryResolveFile(file + ext, postfix, options, false, options.tryPrefix))) { - return res; - } - } - if ((res = tryResolveFile(file, postfix, options, tryIndex, options.tryPrefix))) { - return res; - } -} -function tryResolveFile(file, postfix, options, tryIndex, tryPrefix) { - let isReadable = false; - try { - // #2051 if we don't have read permission on a directory, existsSync() still - // works and will result in massively slow subsequent checks (which are - // unnecessary in the first place) - fs__default.accessSync(file, fs__default.constants.R_OK); - isReadable = true; - } - catch (e) { } - if (isReadable) { - if (!fs__default.statSync(file).isDirectory()) { - return normalizePath$2(ensureVolumeInPath(file)) + postfix; - } - else if (tryIndex) { - const pkgPath = file + '/package.json'; - if (fs__default.existsSync(pkgPath)) { - // path points to a node package - const pkg = loadPackageData(pkgPath); - return resolvePackageEntry(file, pkg, options); - } - const index = tryFsResolve(file + '/index', options); - if (index) - return index + postfix; - } - } - if (tryPrefix) { - const prefixed = `${path__default.dirname(file)}/${tryPrefix}${path__default.basename(file)}`; - return tryResolveFile(prefixed, postfix, options, tryIndex); - } -} -const idToPkgMap = new Map(); -function tryNodeResolve(id, importer, options, server) { - var _a, _b, _c; - const { root, dedupe, isBuild } = options; - const deepMatch = id.match(deepImportRE); - const pkgId = deepMatch ? deepMatch[1] || deepMatch[2] : id; - let basedir; - if (dedupe && dedupe.includes(pkgId)) { - basedir = root; - } - else if (importer && - path__default.isAbsolute(importer) && - fs__default.existsSync(cleanUrl(importer))) { - basedir = path__default.dirname(importer); - } - else { - basedir = root; - } - const pkg = resolvePackageData(pkgId, basedir); - if (!pkg) { - return; - } - let resolved = deepMatch - ? resolveDeepImport(id, pkg, options) - : resolvePackageEntry(id, pkg, options); - if (!resolved) { - return; - } - // link id to pkg for browser field mapping check - idToPkgMap.set(resolved, pkg); - if (isBuild) { - // Resolve package side effects for build so that rollup can better - // perform tree-shaking - return { - id: resolved, - moduleSideEffects: pkg.hasSideEffects(resolved) - }; - } - else { - if (!resolved.includes('node_modules') || // linked - !server || // build - server._isRunningOptimizer || // optimizing - !server._optimizeDepsMetadata) { - return { id: resolved }; - } - // if we reach here, it's a valid dep import that hasn't been optimized. - const isJsType = OPTIMIZABLE_ENTRY_RE.test(resolved); - const exclude = (_a = server.config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.exclude; - if (!isJsType || - (importer === null || importer === void 0 ? void 0 : importer.includes('node_modules')) || - (exclude === null || exclude === void 0 ? void 0 : exclude.includes(pkgId)) || - (exclude === null || exclude === void 0 ? void 0 : exclude.includes(id)) || - SPECIAL_QUERY_RE.test(resolved)) { - // excluded from optimization - // Inject a version query to npm deps so that the browser - // can cache it without re-validation, but only do so for known js types. - // otherwise we may introduce duplicated modules for externalized files - // from pre-bundled deps. - const versionHash = (_b = server._optimizeDepsMetadata) === null || _b === void 0 ? void 0 : _b.browserHash; - if (versionHash && isJsType) { - resolved = injectQuery(resolved, `v=${versionHash}`); - } - } - else { - // this is a missing import. - // queue optimize-deps re-run. - (_c = server._registerMissingImport) === null || _c === void 0 ? void 0 : _c.call(server, id, resolved); - } - return { id: resolved }; - } -} -function tryOptimizedResolve(id, server) { - const cacheDir = server.config.optimizeCacheDir; - const depData = server._optimizeDepsMetadata; - if (cacheDir && depData) { - const isOptimized = depData.optimized[id]; - if (isOptimized) { - return (isOptimized.file + - `?v=${depData.browserHash}${isOptimized.needsInterop ? `&es-interop` : ``}`); - } - } -} -const packageCache = new Map(); -function resolvePackageData(id, basedir) { - const cacheKey = id + basedir; - if (packageCache.has(cacheKey)) { - return packageCache.get(cacheKey); - } - try { - const pkgPath = resolveFrom$2(`${id}/package.json`, basedir); - return loadPackageData(pkgPath, cacheKey); - } - catch (e) { - isDebug$4 && debug$9(`${source.red(`[failed loading package.json]`)} ${id}`); - } -} -function loadPackageData(pkgPath, cacheKey = pkgPath) { - const data = JSON.parse(fs__default.readFileSync(pkgPath, 'utf-8')); - const pkgDir = path__default.dirname(pkgPath); - const { sideEffects } = data; - let hasSideEffects; - if (typeof sideEffects === 'boolean') { - hasSideEffects = () => sideEffects; - } - else if (Array.isArray(sideEffects)) { - hasSideEffects = createFilter$1(sideEffects, null, { resolve: pkgDir }); - } - else { - hasSideEffects = () => true; - } - const pkg = { - dir: pkgDir, - data, - hasSideEffects, - resolvedImports: {} - }; - packageCache.set(cacheKey, pkg); - return pkg; -} -function resolvePackageEntry(id, { resolvedImports, dir, data }, options) { - if (resolvedImports['.']) { - return resolvedImports['.']; - } - let entryPoint; - // resolve exports field with highest priority - // using https://github.com/lukeed/resolve.exports - if (data.exports) { - entryPoint = resolveExports(data, '.', options); - } - // if exports resolved to .mjs, still resolve other fields. - // This is because .mjs files can technically import .cjs files which would - // make them invalid for pure ESM environments - so if other module/browser - // fields are present, prioritize those instead. - if (!entryPoint || entryPoint.endsWith('.mjs')) { - // check browser field - // https://github.com/defunctzombie/package-browser-field-spec - const browserEntry = typeof data.browser === 'string' - ? data.browser - : isObject$3(data.browser) && data.browser['.']; - if (browserEntry) { - // check if the package also has a "module" field. - if (typeof data.module === 'string' && data.module !== browserEntry) { - // if both are present, we may have a problem: some package points both - // to ESM, with "module" targeting Node.js, while some packages points - // "module" to browser ESM and "browser" to UMD. - // the heuristics here is to actually read the browser entry when - // possible and check for hints of UMD. If it is UMD, prefer "module" - // instead; Otherwise, assume it's ESM and use it. - const resolvedBrowserEntry = tryFsResolve(path__default.join(dir, browserEntry), options); - if (resolvedBrowserEntry) { - const content = fs__default.readFileSync(resolvedBrowserEntry, 'utf-8'); - if ((/typeof exports\s*==/.test(content) && - /typeof module\s*==/.test(content)) || - /module\.exports\s*=/.test(content)) { - // likely UMD or CJS(!!! e.g. firebase 7.x), prefer module - entryPoint = data.module; - } - } - } - else { - entryPoint = browserEntry; - } - } - } - if (!entryPoint || entryPoint.endsWith('.mjs')) { - for (const field of options.mainFields || DEFAULT_MAIN_FIELDS) { - if (typeof data[field] === 'string') { - entryPoint = data[field]; - break; - } - } - } - entryPoint = entryPoint || data.main || 'index.js'; - // resolve object browser field in package.json - const { browser: browserField } = data; - if (isObject$3(browserField)) { - entryPoint = mapWithBrowserField(entryPoint, browserField) || entryPoint; - } - entryPoint = path__default.join(dir, entryPoint); - const resolvedEntryPoint = tryFsResolve(entryPoint, options); - if (resolvedEntryPoint) { - isDebug$4 && - debug$9(`[package entry] ${source.cyan(id)} -> ${source.dim(resolvedEntryPoint)}`); - resolvedImports['.'] = resolvedEntryPoint; - return resolvedEntryPoint; - } - else { - throw new Error(`Failed to resolve entry for package "${id}". ` + - `The package may have incorrect main/module/exports specified in its package.json.`); - } -} -function resolveExports(pkg, key, options) { - const conditions = [options.isProduction ? 'production' : 'development']; - if (!options.isRequire) { - conditions.push('module'); - } - if (options.conditions) { - conditions.push(...options.conditions); - } - return resolve$1(pkg, key, { - browser: true, - require: options.isRequire, - conditions - }); -} -function resolveDeepImport(id, { resolvedImports, dir, data }, options) { - id = '.' + id.slice(data.name.length); - if (resolvedImports[id]) { - return resolvedImports[id]; - } - let relativeId = id; - const { exports: exportsField, browser: browserField } = data; - // map relative based on exports data - if (exportsField) { - if (isObject$3(exportsField) && !Array.isArray(exportsField)) { - relativeId = resolveExports(data, relativeId, options); - } - else { - // not exposed - relativeId = undefined; - } - if (!relativeId) { - throw new Error(`Package subpath '${relativeId}' is not defined by "exports" in ` + - `${path__default.join(dir, 'package.json')}.`); - } - } - else if (isObject$3(browserField)) { - const mapped = mapWithBrowserField(relativeId, browserField); - if (mapped) { - relativeId = mapped; - } - else if (mapped === false) { - return (resolvedImports[id] = browserExternalId); - } - } - if (relativeId) { - const resolved = tryFsResolve(path__default.join(dir, relativeId), options, !exportsField // try index only if no exports field - ); - if (resolved) { - isDebug$4 && - debug$9(`[node/deep-import] ${source.cyan(id)} -> ${source.dim(resolved)}`); - return (resolvedImports[id] = resolved); - } - } -} -function tryResolveBrowserMapping(id, importer, options, isFilePath) { - let res; - const pkg = importer && idToPkgMap.get(importer); - if (pkg && isObject$3(pkg.data.browser)) { - const mapId = isFilePath ? './' + slash$2(path__default.relative(pkg.dir, id)) : id; - const browserMappedPath = mapWithBrowserField(mapId, pkg.data.browser); - if (browserMappedPath) { - const fsPath = path__default.join(pkg.dir, browserMappedPath); - if ((res = tryFsResolve(fsPath, options))) { - isDebug$4 && - debug$9(`[browser mapped] ${source.cyan(id)} -> ${source.dim(res)}`); - idToPkgMap.set(res, pkg); - return { - id: res, - moduleSideEffects: pkg.hasSideEffects(res) - }; - } - } - else if (browserMappedPath === false) { - return browserExternalId; - } - } -} -/** - * given a relative path in pkg dir, - * return a relative path in pkg dir, - * mapped with the "map" object - * - * - Returning `undefined` means there is no browser mapping for this id - * - Returning `false` means this id is explicitly externalized for browser - */ -function mapWithBrowserField(relativePathInPkgDir, map) { - const normalizedPath = path__default.posix.normalize(relativePathInPkgDir); - for (const key in map) { - const normalizedKey = path__default.posix.normalize(key); - if (normalizedPath === normalizedKey || - equalWithoutSuffix(normalizedPath, normalizedKey, '.js') || - equalWithoutSuffix(normalizedPath, normalizedKey, '/index.js')) { - return map[key]; - } - } -} -function equalWithoutSuffix(path, key, suffix) { - return key.endsWith(suffix) && key.slice(0, -suffix.length) === path; -} - -/** - * Heuristics for determining whether a dependency should be externalized for - * server-side rendering. - * - * TODO right now externals are imported using require(), we probably need to - * rework this when more libraries ship native ESM distributions for Node. - */ -function resolveSSRExternal(config, knownImports, ssrExternals = new Set()) { - var _a, _b, _c; - const { root } = config; - const pkgContent = lookupFile(root, ['package.json']); - if (!pkgContent) { - return []; - } - const pkg = JSON.parse(pkgContent); - const devDeps = Object.keys(pkg.devDependencies || {}); - const deps = [...knownImports, ...Object.keys(pkg.dependencies || {})]; - for (const id of devDeps) { - ssrExternals.add(id); - } - const resolveOptions = { - root, - isProduction: false, - isBuild: true - }; - for (const id of deps) { - let entry; - let requireEntry; - try { - entry = (_a = tryNodeResolve(id, undefined, resolveOptions)) === null || _a === void 0 ? void 0 : _a.id; - requireEntry = require.resolve(id, { paths: [root] }); - } - catch (e) { - // resolve failed, assume include - continue; - } - if (!entry) { - // no esm entry but has require entry (is this even possible?) - ssrExternals.add(id); - continue; - } - if (!entry.includes('node_modules')) { - // entry is not a node dep, possibly linked - don't externalize - // instead, trace its dependencies. - const depRoot = path__default.dirname(resolveFrom$2(`${id}/package.json`, root)); - resolveSSRExternal({ - ...config, - root: depRoot - }, knownImports, ssrExternals); - continue; - } - if (entry !== requireEntry) { - // has separate esm/require entry, assume require entry is cjs - ssrExternals.add(id); - } - else { - // node resolve and esm resolve resolves to the same file. - if (!/\.m?js$/.test(entry)) { - // entry is not js, cannot externalize - continue; - } - // check if the entry is cjs - const content = fs__default.readFileSync(entry, 'utf-8'); - if (/\bmodule\.exports\b|\bexports[.\[]|\brequire\s*\(/.test(content)) { - ssrExternals.add(id); - } - } - } - if ((_b = config.ssr) === null || _b === void 0 ? void 0 : _b.external) { - config.ssr.external.forEach((id) => ssrExternals.add(id)); - } - let externals = [...ssrExternals]; - if ((_c = config.ssr) === null || _c === void 0 ? void 0 : _c.noExternal) { - externals = externals.filter((id) => !config.ssr.noExternal.includes(id)); - } - return externals.filter((id) => id !== 'vite'); -} -function shouldExternalizeForSSR(id, externals) { - const should = externals.some((e) => { - if (id === e) { - return true; - } - // deep imports, check ext before externalizing - only externalize - // extension-less imports and explicit .js imports - if (id.startsWith(e + '/') && (!path__default.extname(id) || id.endsWith('.js'))) { - return true; - } - }); - return should; -} - -function ssrManifestPlugin(config) { - // module id => preload assets mapping - const ssrManifest = {}; - const base = config.base; - return { - name: 'vite:manifest', - generateBundle(_options, bundle) { - for (const file in bundle) { - const chunk = bundle[file]; - if (chunk.type === 'chunk' && !chunk.isEntry) { - // links for entry chunks are already generated in static HTML - // so we only need to record info for non-entry chunks - // TODO: also include non-CSS assets - const cssFiles = chunkToEmittedCssFileMap.get(chunk); - for (const id in chunk.modules) { - const mappedChunks = ssrManifest[id] || (ssrManifest[id] = []); - mappedChunks.push(base + chunk.fileName); - if (cssFiles) { - cssFiles.forEach((file) => { - mappedChunks.push(base + file); - }); - } - } - } - } - this.emitFile({ - fileName: 'ssr-manifest.json', - type: 'asset', - source: JSON.stringify(ssrManifest, null, 2) - }); - } - }; -} - -// Reserved word lists for various dialects of the language - -var reservedWords = { - 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", - 5: "class enum extends super const export import", - 6: "enum", - strict: "implements interface let package private protected public static yield", - strictBind: "eval arguments" -}; - -// And the keywords - -var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; - -var keywords = { - 5: ecma5AndLessKeywords, - "5module": ecma5AndLessKeywords + " export import", - 6: ecma5AndLessKeywords + " const class extends export import super" -}; - -var keywordRelationalOperator = /^in(stanceof)?$/; - -// ## Character categories - -// Big ugly regular expressions that match characters in the -// whitespace, identifier, and identifier-start categories. These -// are only applied when a character is found to actually have a -// code point above 128. -// Generated by `bin/generate-identifier-regex.js`. -var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; -var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; - -var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); -var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); - -nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; - -// These are a run-length and offset encoded representation of the -// >0xffff code points that are a valid part of identifiers. The -// offset starts at 0x10000, and each pair of numbers represents an -// offset to the next range, and then a size of the range. They were -// generated by bin/generate-identifier-regex.js - -// eslint-disable-next-line comma-spacing -var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938]; - -// eslint-disable-next-line comma-spacing -var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239]; - -// This has a complexity linear to the value of the code. The -// assumption is that looking up astral identifier characters is -// rare. -function isInAstralSet(code, set) { - var pos = 0x10000; - for (var i = 0; i < set.length; i += 2) { - pos += set[i]; - if (pos > code) { return false } - pos += set[i + 1]; - if (pos >= code) { return true } - } -} - -// Test whether a given character code starts an identifier. - -function isIdentifierStart(code, astral) { - if (code < 65) { return code === 36 } - if (code < 91) { return true } - if (code < 97) { return code === 95 } - if (code < 123) { return true } - if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } - if (astral === false) { return false } - return isInAstralSet(code, astralIdentifierStartCodes) -} - -// Test whether a given character is part of an identifier. - -function isIdentifierChar(code, astral) { - if (code < 48) { return code === 36 } - if (code < 58) { return true } - if (code < 65) { return false } - if (code < 91) { return true } - if (code < 97) { return code === 95 } - if (code < 123) { return true } - if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } - if (astral === false) { return false } - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) -} - -// ## Token types - -// The assignment of fine-grained, information-carrying type objects -// allows the tokenizer to store the information it has about a -// token in a way that is very cheap for the parser to look up. - -// All token type variables start with an underscore, to make them -// easy to recognize. - -// The `beforeExpr` property is used to disambiguate between regular -// expressions and divisions. It is set on all token types that can -// be followed by an expression (thus, a slash after them would be a -// regular expression). -// -// The `startsExpr` property is used to check if the token ends a -// `yield` expression. It is set on all token types that either can -// directly start an expression (like a quotation mark) or can -// continue an expression (like the body of a string). -// -// `isLoop` marks a keyword as starting a loop, which is important -// to know when parsing a label, in order to allow or disallow -// continue jumps to that label. - -var TokenType = function TokenType(label, conf) { - if ( conf === void 0 ) conf = {}; - - this.label = label; - this.keyword = conf.keyword; - this.beforeExpr = !!conf.beforeExpr; - this.startsExpr = !!conf.startsExpr; - this.isLoop = !!conf.isLoop; - this.isAssign = !!conf.isAssign; - this.prefix = !!conf.prefix; - this.postfix = !!conf.postfix; - this.binop = conf.binop || null; - this.updateContext = null; -}; - -function binop(name, prec) { - return new TokenType(name, {beforeExpr: true, binop: prec}) -} -var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; - -// Map keyword names to token types. - -var keywords$1 = {}; - -// Succinct definitions of keyword token types -function kw(name, options) { - if ( options === void 0 ) options = {}; - - options.keyword = name; - return keywords$1[name] = new TokenType(name, options) -} - -var types = { - num: new TokenType("num", startsExpr), - regexp: new TokenType("regexp", startsExpr), - string: new TokenType("string", startsExpr), - name: new TokenType("name", startsExpr), - eof: new TokenType("eof"), - - // Punctuation token types. - bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), - bracketR: new TokenType("]"), - braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), - braceR: new TokenType("}"), - parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), - parenR: new TokenType(")"), - comma: new TokenType(",", beforeExpr), - semi: new TokenType(";", beforeExpr), - colon: new TokenType(":", beforeExpr), - dot: new TokenType("."), - question: new TokenType("?", beforeExpr), - questionDot: new TokenType("?."), - arrow: new TokenType("=>", beforeExpr), - template: new TokenType("template"), - invalidTemplate: new TokenType("invalidTemplate"), - ellipsis: new TokenType("...", beforeExpr), - backQuote: new TokenType("`", startsExpr), - dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), - - // Operators. These carry several kinds of properties to help the - // parser use them properly (the presence of these properties is - // what categorizes them as operators). - // - // `binop`, when present, specifies that this operator is a binary - // operator, and will refer to its precedence. - // - // `prefix` and `postfix` mark the operator as a prefix or postfix - // unary operator. - // - // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as - // binary operators with a very low precedence, that should result - // in AssignmentExpression nodes. - - eq: new TokenType("=", {beforeExpr: true, isAssign: true}), - assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), - incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), - prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), - logicalOR: binop("||", 1), - logicalAND: binop("&&", 2), - bitwiseOR: binop("|", 3), - bitwiseXOR: binop("^", 4), - bitwiseAND: binop("&", 5), - equality: binop("==/!=/===/!==", 6), - relational: binop("/<=/>=", 7), - bitShift: binop("<>/>>>", 8), - plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), - modulo: binop("%", 10), - star: binop("*", 10), - slash: binop("/", 10), - starstar: new TokenType("**", {beforeExpr: true}), - coalesce: binop("??", 1), - - // Keyword token types. - _break: kw("break"), - _case: kw("case", beforeExpr), - _catch: kw("catch"), - _continue: kw("continue"), - _debugger: kw("debugger"), - _default: kw("default", beforeExpr), - _do: kw("do", {isLoop: true, beforeExpr: true}), - _else: kw("else", beforeExpr), - _finally: kw("finally"), - _for: kw("for", {isLoop: true}), - _function: kw("function", startsExpr), - _if: kw("if"), - _return: kw("return", beforeExpr), - _switch: kw("switch"), - _throw: kw("throw", beforeExpr), - _try: kw("try"), - _var: kw("var"), - _const: kw("const"), - _while: kw("while", {isLoop: true}), - _with: kw("with"), - _new: kw("new", {beforeExpr: true, startsExpr: true}), - _this: kw("this", startsExpr), - _super: kw("super", startsExpr), - _class: kw("class", startsExpr), - _extends: kw("extends", beforeExpr), - _export: kw("export"), - _import: kw("import", startsExpr), - _null: kw("null", startsExpr), - _true: kw("true", startsExpr), - _false: kw("false", startsExpr), - _in: kw("in", {beforeExpr: true, binop: 7}), - _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), - _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), - _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), - _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) -}; - -// Matches a whole line break (where CRLF is considered a single -// line break). Used to count lines. - -var lineBreak = /\r\n?|\n|\u2028|\u2029/; -var lineBreakG = new RegExp(lineBreak.source, "g"); - -function isNewLine(code, ecma2019String) { - return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) -} - -var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; - -var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; - -var ref = Object.prototype; -var hasOwnProperty$1 = ref.hasOwnProperty; -var toString$1 = ref.toString; - -// Checks if an object has a property. - -function has$1(obj, propName) { - return hasOwnProperty$1.call(obj, propName) -} - -var isArray = Array.isArray || (function (obj) { return ( - toString$1.call(obj) === "[object Array]" -); }); - -function wordsRegexp(words) { - return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") -} - -// These are used when `options.locations` is on, for the -// `startLoc` and `endLoc` properties. - -var Position = function Position(line, col) { - this.line = line; - this.column = col; -}; - -Position.prototype.offset = function offset (n) { - return new Position(this.line, this.column + n) -}; - -var SourceLocation = function SourceLocation(p, start, end) { - this.start = start; - this.end = end; - if (p.sourceFile !== null) { this.source = p.sourceFile; } -}; - -// The `getLineInfo` function is mostly useful when the -// `locations` option is off (for performance reasons) and you -// want to find the line/column position for a given character -// offset. `input` should be the code string that the offset refers -// into. - -function getLineInfo(input, offset) { - for (var line = 1, cur = 0;;) { - lineBreakG.lastIndex = cur; - var match = lineBreakG.exec(input); - if (match && match.index < offset) { - ++line; - cur = match.index + match[0].length; - } else { - return new Position(line, offset - cur) - } - } -} - -// A second argument must be given to configure the parser process. -// These options are recognized (only `ecmaVersion` is required): - -var defaultOptions = { - // `ecmaVersion` indicates the ECMAScript version to parse. Must be - // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 - // (2019), 11 (2020), 12 (2021), or `"latest"` (the latest version - // the library supports). This influences support for strict mode, - // the set of reserved words, and support for new syntax features. - ecmaVersion: null, - // `sourceType` indicates the mode the code should be parsed in. - // Can be either `"script"` or `"module"`. This influences global - // strict mode and parsing of `import` and `export` declarations. - sourceType: "script", - // `onInsertedSemicolon` can be a callback that will be called - // when a semicolon is automatically inserted. It will be passed - // the position of the comma as an offset, and if `locations` is - // enabled, it is given the location as a `{line, column}` object - // as second argument. - onInsertedSemicolon: null, - // `onTrailingComma` is similar to `onInsertedSemicolon`, but for - // trailing commas. - onTrailingComma: null, - // By default, reserved words are only enforced if ecmaVersion >= 5. - // Set `allowReserved` to a boolean value to explicitly turn this on - // an off. When this option has the value "never", reserved words - // and keywords can also not be used as property names. - allowReserved: null, - // When enabled, a return at the top level is not considered an - // error. - allowReturnOutsideFunction: false, - // When enabled, import/export statements are not constrained to - // appearing at the top of the program, and an import.meta expression - // in a script isn't considered an error. - allowImportExportEverywhere: false, - // When enabled, await identifiers are allowed to appear at the top-level scope, - // but they are still not allowed in non-async functions. - allowAwaitOutsideFunction: false, - // When enabled, hashbang directive in the beginning of file - // is allowed and treated as a line comment. - allowHashBang: false, - // When `locations` is on, `loc` properties holding objects with - // `start` and `end` properties in `{line, column}` form (with - // line being 1-based and column 0-based) will be attached to the - // nodes. - locations: false, - // A function can be passed as `onToken` option, which will - // cause Acorn to call that function with object in the same - // format as tokens returned from `tokenizer().getToken()`. Note - // that you are not allowed to call the parser from the - // callback—that will corrupt its internal state. - onToken: null, - // A function can be passed as `onComment` option, which will - // cause Acorn to call that function with `(block, text, start, - // end)` parameters whenever a comment is skipped. `block` is a - // boolean indicating whether this is a block (`/* */`) comment, - // `text` is the content of the comment, and `start` and `end` are - // character offsets that denote the start and end of the comment. - // When the `locations` option is on, two more parameters are - // passed, the full `{line, column}` locations of the start and - // end of the comments. Note that you are not allowed to call the - // parser from the callback—that will corrupt its internal state. - onComment: null, - // Nodes have their start and end characters offsets recorded in - // `start` and `end` properties (directly on the node, rather than - // the `loc` object, which holds line/column data. To also add a - // [semi-standardized][range] `range` property holding a `[start, - // end]` array with the same numbers, set the `ranges` option to - // `true`. - // - // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 - ranges: false, - // It is possible to parse multiple files into a single AST by - // passing the tree produced by parsing the first file as - // `program` option in subsequent parses. This will add the - // toplevel forms of the parsed file to the `Program` (top) node - // of an existing parse tree. - program: null, - // When `locations` is on, you can pass this to record the source - // file in every node's `loc` object. - sourceFile: null, - // This value, if given, is stored in every node, whether - // `locations` is on or off. - directSourceFile: null, - // When enabled, parenthesized expressions are represented by - // (non-standard) ParenthesizedExpression nodes - preserveParens: false -}; - -// Interpret and default an options object - -var warnedAboutEcmaVersion = false; - -function getOptions(opts) { - var options = {}; - - for (var opt in defaultOptions) - { options[opt] = opts && has$1(opts, opt) ? opts[opt] : defaultOptions[opt]; } - - if (options.ecmaVersion === "latest") { - options.ecmaVersion = 1e8; - } else if (options.ecmaVersion == null) { - if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { - warnedAboutEcmaVersion = true; - console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); - } - options.ecmaVersion = 11; - } else if (options.ecmaVersion >= 2015) { - options.ecmaVersion -= 2009; - } - - if (options.allowReserved == null) - { options.allowReserved = options.ecmaVersion < 5; } - - if (isArray(options.onToken)) { - var tokens = options.onToken; - options.onToken = function (token) { return tokens.push(token); }; - } - if (isArray(options.onComment)) - { options.onComment = pushComment(options, options.onComment); } - - return options -} - -function pushComment(options, array) { - return function(block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? "Block" : "Line", - value: text, - start: start, - end: end - }; - if (options.locations) - { comment.loc = new SourceLocation(this, startLoc, endLoc); } - if (options.ranges) - { comment.range = [start, end]; } - array.push(comment); - } -} - -// Each scope gets a bitset that may contain these flags -var - SCOPE_TOP = 1, - SCOPE_FUNCTION = 2, - SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION, - SCOPE_ASYNC = 4, - SCOPE_GENERATOR = 8, - SCOPE_ARROW = 16, - SCOPE_SIMPLE_CATCH = 32, - SCOPE_SUPER = 64, - SCOPE_DIRECT_SUPER = 128; - -function functionFlags(async, generator) { - return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) -} - -// Used in checkLVal* and declareName to determine the type of a binding -var - BIND_NONE = 0, // Not a binding - BIND_VAR = 1, // Var-style binding - BIND_LEXICAL = 2, // Let- or const-style binding - BIND_FUNCTION = 3, // Function declaration - BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding - BIND_OUTSIDE = 5; // Special case for function names as bound inside the function - -var Parser = function Parser(options, input, startPos) { - this.options = options = getOptions(options); - this.sourceFile = options.sourceFile; - this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); - var reserved = ""; - if (options.allowReserved !== true) { - reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; - if (options.sourceType === "module") { reserved += " await"; } - } - this.reservedWords = wordsRegexp(reserved); - var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; - this.reservedWordsStrict = wordsRegexp(reservedStrict); - this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); - this.input = String(input); - - // Used to signal to callers of `readWord1` whether the word - // contained any escape sequences. This is needed because words with - // escape sequences must not be interpreted as keywords. - this.containsEsc = false; - - // Set up token state - - // The current position of the tokenizer in the input. - if (startPos) { - this.pos = startPos; - this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; - this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; - } else { - this.pos = this.lineStart = 0; - this.curLine = 1; - } - - // Properties of the current token: - // Its type - this.type = types.eof; - // For tokens that include more information than their type, the value - this.value = null; - // Its start and end offset - this.start = this.end = this.pos; - // And, if locations are used, the {line, column} object - // corresponding to those offsets - this.startLoc = this.endLoc = this.curPosition(); - - // Position information for the previous token - this.lastTokEndLoc = this.lastTokStartLoc = null; - this.lastTokStart = this.lastTokEnd = this.pos; - - // The context stack is used to superficially track syntactic - // context to predict whether a regular expression is allowed in a - // given position. - this.context = this.initialContext(); - this.exprAllowed = true; - - // Figure out if it's a module code. - this.inModule = options.sourceType === "module"; - this.strict = this.inModule || this.strictDirective(this.pos); - - // Used to signify the start of a potential arrow function - this.potentialArrowAt = -1; - - // Positions to delayed-check that yield/await does not exist in default parameters. - this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; - // Labels in scope. - this.labels = []; - // Thus-far undefined exports. - this.undefinedExports = Object.create(null); - - // If enabled, skip leading hashbang line. - if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") - { this.skipLineComment(2); } - - // Scope tracking for duplicate variable names (see scope.js) - this.scopeStack = []; - this.enterScope(SCOPE_TOP); - - // For RegExp validation - this.regexpState = null; -}; - -var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } }; - -Parser.prototype.parse = function parse () { - var node = this.options.program || this.startNode(); - this.nextToken(); - return this.parseTopLevel(node) -}; - -prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; -prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 }; -prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }; -prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 }; -prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; -prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; -prototypeAccessors.inNonArrowFunction.get = function () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }; - -Parser.extend = function extend () { - var plugins = [], len = arguments.length; - while ( len-- ) plugins[ len ] = arguments[ len ]; - - var cls = this; - for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } - return cls -}; - -Parser.parse = function parse (input, options) { - return new this(options, input).parse() -}; - -Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { - var parser = new this(options, input, pos); - parser.nextToken(); - return parser.parseExpression() -}; - -Parser.tokenizer = function tokenizer (input, options) { - return new this(options, input) -}; - -Object.defineProperties( Parser.prototype, prototypeAccessors ); - -var pp = Parser.prototype; - -// ## Parser utilities - -var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; -pp.strictDirective = function(start) { - for (;;) { - // Try to find string literal. - skipWhiteSpace.lastIndex = start; - start += skipWhiteSpace.exec(this.input)[0].length; - var match = literal.exec(this.input.slice(start)); - if (!match) { return false } - if ((match[1] || match[2]) === "use strict") { - skipWhiteSpace.lastIndex = start + match[0].length; - var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; - var next = this.input.charAt(end); - return next === ";" || next === "}" || - (lineBreak.test(spaceAfter[0]) && - !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) - } - start += match[0].length; - - // Skip semicolon, if any. - skipWhiteSpace.lastIndex = start; - start += skipWhiteSpace.exec(this.input)[0].length; - if (this.input[start] === ";") - { start++; } - } -}; - -// Predicate that tests whether the next token is of the given -// type, and if yes, consumes it as a side effect. - -pp.eat = function(type) { - if (this.type === type) { - this.next(); - return true - } else { - return false - } -}; - -// Tests whether parsed token is a contextual keyword. - -pp.isContextual = function(name) { - return this.type === types.name && this.value === name && !this.containsEsc -}; - -// Consumes contextual keyword if possible. - -pp.eatContextual = function(name) { - if (!this.isContextual(name)) { return false } - this.next(); - return true -}; - -// Asserts that following token is given contextual keyword. - -pp.expectContextual = function(name) { - if (!this.eatContextual(name)) { this.unexpected(); } -}; - -// Test whether a semicolon can be inserted at the current position. - -pp.canInsertSemicolon = function() { - return this.type === types.eof || - this.type === types.braceR || - lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) -}; - -pp.insertSemicolon = function() { - if (this.canInsertSemicolon()) { - if (this.options.onInsertedSemicolon) - { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } - return true - } -}; - -// Consume a semicolon, or, failing that, see if we are allowed to -// pretend that there is a semicolon at this position. - -pp.semicolon = function() { - if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } -}; - -pp.afterTrailingComma = function(tokType, notNext) { - if (this.type === tokType) { - if (this.options.onTrailingComma) - { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } - if (!notNext) - { this.next(); } - return true - } -}; - -// Expect a token of a given type. If found, consume it, otherwise, -// raise an unexpected token error. - -pp.expect = function(type) { - this.eat(type) || this.unexpected(); -}; - -// Raise an unexpected token error. - -pp.unexpected = function(pos) { - this.raise(pos != null ? pos : this.start, "Unexpected token"); -}; - -function DestructuringErrors() { - this.shorthandAssign = - this.trailingComma = - this.parenthesizedAssign = - this.parenthesizedBind = - this.doubleProto = - -1; -} - -pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { - if (!refDestructuringErrors) { return } - if (refDestructuringErrors.trailingComma > -1) - { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } - var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; - if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } -}; - -pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { - if (!refDestructuringErrors) { return false } - var shorthandAssign = refDestructuringErrors.shorthandAssign; - var doubleProto = refDestructuringErrors.doubleProto; - if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } - if (shorthandAssign >= 0) - { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } - if (doubleProto >= 0) - { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } -}; - -pp.checkYieldAwaitInDefaultParams = function() { - if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) - { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } - if (this.awaitPos) - { this.raise(this.awaitPos, "Await expression cannot be a default value"); } -}; - -pp.isSimpleAssignTarget = function(expr) { - if (expr.type === "ParenthesizedExpression") - { return this.isSimpleAssignTarget(expr.expression) } - return expr.type === "Identifier" || expr.type === "MemberExpression" -}; - -var pp$1 = Parser.prototype; - -// ### Statement parsing - -// Parse a program. Initializes the parser, reads any number of -// statements, and wraps them in a Program node. Optionally takes a -// `program` argument. If present, the statements will be appended -// to its body instead of creating a new node. - -pp$1.parseTopLevel = function(node) { - var exports = Object.create(null); - if (!node.body) { node.body = []; } - while (this.type !== types.eof) { - var stmt = this.parseStatement(null, true, exports); - node.body.push(stmt); - } - if (this.inModule) - { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) - { - var name = list[i]; - - this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); - } } - this.adaptDirectivePrologue(node.body); - this.next(); - node.sourceType = this.options.sourceType; - return this.finishNode(node, "Program") -}; - -var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; - -pp$1.isLet = function(context) { - if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); - // For ambiguous cases, determine if a LexicalDeclaration (or only a - // Statement) is allowed here. If context is not empty then only a Statement - // is allowed. However, `let [` is an explicit negative lookahead for - // ExpressionStatement, so special-case it first. - if (nextCh === 91) { return true } // '[' - if (context) { return false } - - if (nextCh === 123) { return true } // '{' - if (isIdentifierStart(nextCh, true)) { - var pos = next + 1; - while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; } - var ident = this.input.slice(next, pos); - if (!keywordRelationalOperator.test(ident)) { return true } - } - return false -}; - -// check 'async [no LineTerminator here] function' -// - 'async /*foo*/ function' is OK. -// - 'async /*\n*/ function' is invalid. -pp$1.isAsyncFunction = function() { - if (this.options.ecmaVersion < 8 || !this.isContextual("async")) - { return false } - - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length; - return !lineBreak.test(this.input.slice(this.pos, next)) && - this.input.slice(next, next + 8) === "function" && - (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) -}; - -// Parse a single statement. -// -// If expecting a statement and finding a slash operator, parse a -// regular expression literal. This is to handle cases like -// `if (foo) /blah/.exec(foo)`, where looking at the previous token -// does not help. - -pp$1.parseStatement = function(context, topLevel, exports) { - var starttype = this.type, node = this.startNode(), kind; - - if (this.isLet(context)) { - starttype = types._var; - kind = "let"; - } - - // Most types of statements are recognized by the keyword they - // start with. Many are trivial to parse, some require a bit of - // complexity. - - switch (starttype) { - case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) - case types._debugger: return this.parseDebuggerStatement(node) - case types._do: return this.parseDoStatement(node) - case types._for: return this.parseForStatement(node) - case types._function: - // Function as sole body of either an if statement or a labeled statement - // works, but not when it is part of a labeled statement that is the sole - // body of an if statement. - if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } - return this.parseFunctionStatement(node, false, !context) - case types._class: - if (context) { this.unexpected(); } - return this.parseClass(node, true) - case types._if: return this.parseIfStatement(node) - case types._return: return this.parseReturnStatement(node) - case types._switch: return this.parseSwitchStatement(node) - case types._throw: return this.parseThrowStatement(node) - case types._try: return this.parseTryStatement(node) - case types._const: case types._var: - kind = kind || this.value; - if (context && kind !== "var") { this.unexpected(); } - return this.parseVarStatement(node, kind) - case types._while: return this.parseWhileStatement(node) - case types._with: return this.parseWithStatement(node) - case types.braceL: return this.parseBlock(true, node) - case types.semi: return this.parseEmptyStatement(node) - case types._export: - case types._import: - if (this.options.ecmaVersion > 10 && starttype === types._import) { - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); - if (nextCh === 40 || nextCh === 46) // '(' or '.' - { return this.parseExpressionStatement(node, this.parseExpression()) } - } - - if (!this.options.allowImportExportEverywhere) { - if (!topLevel) - { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } - if (!this.inModule) - { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } - } - return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports) - - // If the statement does not start with a statement keyword or a - // brace, it's an ExpressionStatement or LabeledStatement. We - // simply start parsing an expression, and afterwards, if the - // next token is a colon and the expression was a simple - // Identifier node, we switch to interpreting it as a label. - default: - if (this.isAsyncFunction()) { - if (context) { this.unexpected(); } - this.next(); - return this.parseFunctionStatement(node, true, !context) - } - - var maybeName = this.value, expr = this.parseExpression(); - if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) - { return this.parseLabeledStatement(node, maybeName, expr, context) } - else { return this.parseExpressionStatement(node, expr) } - } -}; - -pp$1.parseBreakContinueStatement = function(node, keyword) { - var isBreak = keyword === "break"; - this.next(); - if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } - else if (this.type !== types.name) { this.unexpected(); } - else { - node.label = this.parseIdent(); - this.semicolon(); - } - - // Verify that there is an actual destination to break or - // continue to. - var i = 0; - for (; i < this.labels.length; ++i) { - var lab = this.labels[i]; - if (node.label == null || lab.name === node.label.name) { - if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } - if (node.label && isBreak) { break } - } - } - if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } - return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") -}; - -pp$1.parseDebuggerStatement = function(node) { - this.next(); - this.semicolon(); - return this.finishNode(node, "DebuggerStatement") -}; - -pp$1.parseDoStatement = function(node) { - this.next(); - this.labels.push(loopLabel); - node.body = this.parseStatement("do"); - this.labels.pop(); - this.expect(types._while); - node.test = this.parseParenExpression(); - if (this.options.ecmaVersion >= 6) - { this.eat(types.semi); } - else - { this.semicolon(); } - return this.finishNode(node, "DoWhileStatement") -}; - -// Disambiguating between a `for` and a `for`/`in` or `for`/`of` -// loop is non-trivial. Basically, we have to parse the init `var` -// statement or expression, disallowing the `in` operator (see -// the second parameter to `parseExpression`), and then check -// whether the next token is `in` or `of`. When there is no init -// part (semicolon immediately after the opening parenthesis), it -// is a regular `for` loop. - -pp$1.parseForStatement = function(node) { - this.next(); - var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1; - this.labels.push(loopLabel); - this.enterScope(0); - this.expect(types.parenL); - if (this.type === types.semi) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, null) - } - var isLet = this.isLet(); - if (this.type === types._var || this.type === types._const || isLet) { - var init$1 = this.startNode(), kind = isLet ? "let" : this.value; - this.next(); - this.parseVar(init$1, true, kind); - this.finishNode(init$1, "VariableDeclaration"); - if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { - if (this.options.ecmaVersion >= 9) { - if (this.type === types._in) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - } else { node.await = awaitAt > -1; } - } - return this.parseForIn(node, init$1) - } - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, init$1) - } - var refDestructuringErrors = new DestructuringErrors; - var init = this.parseExpression(true, refDestructuringErrors); - if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { - if (this.options.ecmaVersion >= 9) { - if (this.type === types._in) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - } else { node.await = awaitAt > -1; } - } - this.toAssignable(init, false, refDestructuringErrors); - this.checkLValPattern(init); - return this.parseForIn(node, init) - } else { - this.checkExpressionErrors(refDestructuringErrors, true); - } - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, init) -}; - -pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { - this.next(); - return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) -}; - -pp$1.parseIfStatement = function(node) { - this.next(); - node.test = this.parseParenExpression(); - // allow function declarations in branches, but only in non-strict mode - node.consequent = this.parseStatement("if"); - node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; - return this.finishNode(node, "IfStatement") -}; - -pp$1.parseReturnStatement = function(node) { - if (!this.inFunction && !this.options.allowReturnOutsideFunction) - { this.raise(this.start, "'return' outside of function"); } - this.next(); - - // In `return` (and `break`/`continue`), the keywords with - // optional arguments, we eagerly look for a semicolon or the - // possibility to insert one. - - if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } - else { node.argument = this.parseExpression(); this.semicolon(); } - return this.finishNode(node, "ReturnStatement") -}; - -pp$1.parseSwitchStatement = function(node) { - this.next(); - node.discriminant = this.parseParenExpression(); - node.cases = []; - this.expect(types.braceL); - this.labels.push(switchLabel); - this.enterScope(0); - - // Statements under must be grouped (by label) in SwitchCase - // nodes. `cur` is used to keep the node that we are currently - // adding statements to. - - var cur; - for (var sawDefault = false; this.type !== types.braceR;) { - if (this.type === types._case || this.type === types._default) { - var isCase = this.type === types._case; - if (cur) { this.finishNode(cur, "SwitchCase"); } - node.cases.push(cur = this.startNode()); - cur.consequent = []; - this.next(); - if (isCase) { - cur.test = this.parseExpression(); - } else { - if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } - sawDefault = true; - cur.test = null; - } - this.expect(types.colon); - } else { - if (!cur) { this.unexpected(); } - cur.consequent.push(this.parseStatement(null)); - } - } - this.exitScope(); - if (cur) { this.finishNode(cur, "SwitchCase"); } - this.next(); // Closing brace - this.labels.pop(); - return this.finishNode(node, "SwitchStatement") -}; - -pp$1.parseThrowStatement = function(node) { - this.next(); - if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) - { this.raise(this.lastTokEnd, "Illegal newline after throw"); } - node.argument = this.parseExpression(); - this.semicolon(); - return this.finishNode(node, "ThrowStatement") -}; - -// Reused empty array added for node fields that are always empty. - -var empty = []; - -pp$1.parseTryStatement = function(node) { - this.next(); - node.block = this.parseBlock(); - node.handler = null; - if (this.type === types._catch) { - var clause = this.startNode(); - this.next(); - if (this.eat(types.parenL)) { - clause.param = this.parseBindingAtom(); - var simple = clause.param.type === "Identifier"; - this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); - this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); - this.expect(types.parenR); - } else { - if (this.options.ecmaVersion < 10) { this.unexpected(); } - clause.param = null; - this.enterScope(0); - } - clause.body = this.parseBlock(false); - this.exitScope(); - node.handler = this.finishNode(clause, "CatchClause"); - } - node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; - if (!node.handler && !node.finalizer) - { this.raise(node.start, "Missing catch or finally clause"); } - return this.finishNode(node, "TryStatement") -}; - -pp$1.parseVarStatement = function(node, kind) { - this.next(); - this.parseVar(node, false, kind); - this.semicolon(); - return this.finishNode(node, "VariableDeclaration") -}; - -pp$1.parseWhileStatement = function(node) { - this.next(); - node.test = this.parseParenExpression(); - this.labels.push(loopLabel); - node.body = this.parseStatement("while"); - this.labels.pop(); - return this.finishNode(node, "WhileStatement") -}; - -pp$1.parseWithStatement = function(node) { - if (this.strict) { this.raise(this.start, "'with' in strict mode"); } - this.next(); - node.object = this.parseParenExpression(); - node.body = this.parseStatement("with"); - return this.finishNode(node, "WithStatement") -}; - -pp$1.parseEmptyStatement = function(node) { - this.next(); - return this.finishNode(node, "EmptyStatement") -}; - -pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { - for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) - { - var label = list[i$1]; - - if (label.name === maybeName) - { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); - } } - var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; - for (var i = this.labels.length - 1; i >= 0; i--) { - var label$1 = this.labels[i]; - if (label$1.statementStart === node.start) { - // Update information about previous labels on this node - label$1.statementStart = this.start; - label$1.kind = kind; - } else { break } - } - this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); - node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); - this.labels.pop(); - node.label = expr; - return this.finishNode(node, "LabeledStatement") -}; - -pp$1.parseExpressionStatement = function(node, expr) { - node.expression = expr; - this.semicolon(); - return this.finishNode(node, "ExpressionStatement") -}; - -// Parse a semicolon-enclosed block of statements, handling `"use -// strict"` declarations when `allowStrict` is true (used for -// function bodies). - -pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) { - if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; - if ( node === void 0 ) node = this.startNode(); - - node.body = []; - this.expect(types.braceL); - if (createNewLexicalScope) { this.enterScope(0); } - while (this.type !== types.braceR) { - var stmt = this.parseStatement(null); - node.body.push(stmt); - } - if (exitStrict) { this.strict = false; } - this.next(); - if (createNewLexicalScope) { this.exitScope(); } - return this.finishNode(node, "BlockStatement") -}; - -// Parse a regular `for` loop. The disambiguation code in -// `parseStatement` will already have parsed the init statement or -// expression. - -pp$1.parseFor = function(node, init) { - node.init = init; - this.expect(types.semi); - node.test = this.type === types.semi ? null : this.parseExpression(); - this.expect(types.semi); - node.update = this.type === types.parenR ? null : this.parseExpression(); - this.expect(types.parenR); - node.body = this.parseStatement("for"); - this.exitScope(); - this.labels.pop(); - return this.finishNode(node, "ForStatement") -}; - -// Parse a `for`/`in` and `for`/`of` loop, which are almost -// same from parser's perspective. - -pp$1.parseForIn = function(node, init) { - var isForIn = this.type === types._in; - this.next(); - - if ( - init.type === "VariableDeclaration" && - init.declarations[0].init != null && - ( - !isForIn || - this.options.ecmaVersion < 8 || - this.strict || - init.kind !== "var" || - init.declarations[0].id.type !== "Identifier" - ) - ) { - this.raise( - init.start, - ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") - ); - } - node.left = init; - node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); - this.expect(types.parenR); - node.body = this.parseStatement("for"); - this.exitScope(); - this.labels.pop(); - return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") -}; - -// Parse a list of variable declarations. - -pp$1.parseVar = function(node, isFor, kind) { - node.declarations = []; - node.kind = kind; - for (;;) { - var decl = this.startNode(); - this.parseVarId(decl, kind); - if (this.eat(types.eq)) { - decl.init = this.parseMaybeAssign(isFor); - } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { - this.unexpected(); - } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) { - this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); - } else { - decl.init = null; - } - node.declarations.push(this.finishNode(decl, "VariableDeclarator")); - if (!this.eat(types.comma)) { break } - } - return node -}; - -pp$1.parseVarId = function(decl, kind) { - decl.id = this.parseBindingAtom(); - this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); -}; - -var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; - -// Parse a function declaration or literal (depending on the -// `statement & FUNC_STATEMENT`). - -// Remove `allowExpressionBody` for 7.0.0, as it is only called with false -pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) { - this.initFunction(node); - if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { - if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT)) - { this.unexpected(); } - node.generator = this.eat(types.star); - } - if (this.options.ecmaVersion >= 8) - { node.async = !!isAsync; } - - if (statement & FUNC_STATEMENT) { - node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); - if (node.id && !(statement & FUNC_HANGING_STATEMENT)) - // If it is a regular function declaration in sloppy mode, then it is - // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding - // mode depends on properties of the current scope (see - // treatFunctionsAsVar). - { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } - } - - var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - this.enterScope(functionFlags(node.async, node.generator)); - - if (!(statement & FUNC_STATEMENT)) - { node.id = this.type === types.name ? this.parseIdent() : null; } - - this.parseFunctionParams(node); - this.parseFunctionBody(node, allowExpressionBody, false); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") -}; - -pp$1.parseFunctionParams = function(node) { - this.expect(types.parenL); - node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); - this.checkYieldAwaitInDefaultParams(); -}; - -// Parse a class declaration or literal (depending on the -// `isStatement` parameter). - -pp$1.parseClass = function(node, isStatement) { - this.next(); - - // ecma-262 14.6 Class Definitions - // A class definition is always strict mode code. - var oldStrict = this.strict; - this.strict = true; - - this.parseClassId(node, isStatement); - this.parseClassSuper(node); - var classBody = this.startNode(); - var hadConstructor = false; - classBody.body = []; - this.expect(types.braceL); - while (this.type !== types.braceR) { - var element = this.parseClassElement(node.superClass !== null); - if (element) { - classBody.body.push(element); - if (element.type === "MethodDefinition" && element.kind === "constructor") { - if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); } - hadConstructor = true; - } - } - } - this.strict = oldStrict; - this.next(); - node.body = this.finishNode(classBody, "ClassBody"); - return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") -}; - -pp$1.parseClassElement = function(constructorAllowsSuper) { - var this$1 = this; - - if (this.eat(types.semi)) { return null } - - var method = this.startNode(); - var tryContextual = function (k, noLineBreak) { - if ( noLineBreak === void 0 ) noLineBreak = false; - - var start = this$1.start, startLoc = this$1.startLoc; - if (!this$1.eatContextual(k)) { return false } - if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true } - if (method.key) { this$1.unexpected(); } - method.computed = false; - method.key = this$1.startNodeAt(start, startLoc); - method.key.name = k; - this$1.finishNode(method.key, "Identifier"); - return false - }; - - method.kind = "method"; - method.static = tryContextual("static"); - var isGenerator = this.eat(types.star); - var isAsync = false; - if (!isGenerator) { - if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) { - isAsync = true; - isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); - } else if (tryContextual("get")) { - method.kind = "get"; - } else if (tryContextual("set")) { - method.kind = "set"; - } - } - if (!method.key) { this.parsePropertyName(method); } - var key = method.key; - var allowsDirectSuper = false; - if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || - key.type === "Literal" && key.value === "constructor")) { - if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); } - if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } - if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } - method.kind = "constructor"; - allowsDirectSuper = constructorAllowsSuper; - } else if (method.static && key.type === "Identifier" && key.name === "prototype") { - this.raise(key.start, "Classes may not have a static property named prototype"); - } - this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper); - if (method.kind === "get" && method.value.params.length !== 0) - { this.raiseRecoverable(method.value.start, "getter should have no params"); } - if (method.kind === "set" && method.value.params.length !== 1) - { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); } - if (method.kind === "set" && method.value.params[0].type === "RestElement") - { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); } - return method -}; - -pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { - method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); - return this.finishNode(method, "MethodDefinition") -}; - -pp$1.parseClassId = function(node, isStatement) { - if (this.type === types.name) { - node.id = this.parseIdent(); - if (isStatement) - { this.checkLValSimple(node.id, BIND_LEXICAL, false); } - } else { - if (isStatement === true) - { this.unexpected(); } - node.id = null; - } -}; - -pp$1.parseClassSuper = function(node) { - node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; -}; - -// Parses module export declaration. - -pp$1.parseExport = function(node, exports) { - this.next(); - // export * from '...' - if (this.eat(types.star)) { - if (this.options.ecmaVersion >= 11) { - if (this.eatContextual("as")) { - node.exported = this.parseIdent(true); - this.checkExport(exports, node.exported.name, this.lastTokStart); - } else { - node.exported = null; - } - } - this.expectContextual("from"); - if (this.type !== types.string) { this.unexpected(); } - node.source = this.parseExprAtom(); - this.semicolon(); - return this.finishNode(node, "ExportAllDeclaration") - } - if (this.eat(types._default)) { // export default ... - this.checkExport(exports, "default", this.lastTokStart); - var isAsync; - if (this.type === types._function || (isAsync = this.isAsyncFunction())) { - var fNode = this.startNode(); - this.next(); - if (isAsync) { this.next(); } - node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); - } else if (this.type === types._class) { - var cNode = this.startNode(); - node.declaration = this.parseClass(cNode, "nullableID"); - } else { - node.declaration = this.parseMaybeAssign(); - this.semicolon(); - } - return this.finishNode(node, "ExportDefaultDeclaration") - } - // export var|const|let|function|class ... - if (this.shouldParseExportStatement()) { - node.declaration = this.parseStatement(null); - if (node.declaration.type === "VariableDeclaration") - { this.checkVariableExport(exports, node.declaration.declarations); } - else - { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } - node.specifiers = []; - node.source = null; - } else { // export { x, y as z } [from '...'] - node.declaration = null; - node.specifiers = this.parseExportSpecifiers(exports); - if (this.eatContextual("from")) { - if (this.type !== types.string) { this.unexpected(); } - node.source = this.parseExprAtom(); - } else { - for (var i = 0, list = node.specifiers; i < list.length; i += 1) { - // check for keywords used as local names - var spec = list[i]; - - this.checkUnreserved(spec.local); - // check if export is defined - this.checkLocalExport(spec.local); - } - - node.source = null; - } - this.semicolon(); - } - return this.finishNode(node, "ExportNamedDeclaration") -}; - -pp$1.checkExport = function(exports, name, pos) { - if (!exports) { return } - if (has$1(exports, name)) - { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } - exports[name] = true; -}; - -pp$1.checkPatternExport = function(exports, pat) { - var type = pat.type; - if (type === "Identifier") - { this.checkExport(exports, pat.name, pat.start); } - else if (type === "ObjectPattern") - { for (var i = 0, list = pat.properties; i < list.length; i += 1) - { - var prop = list[i]; - - this.checkPatternExport(exports, prop); - } } - else if (type === "ArrayPattern") - { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { - var elt = list$1[i$1]; - - if (elt) { this.checkPatternExport(exports, elt); } - } } - else if (type === "Property") - { this.checkPatternExport(exports, pat.value); } - else if (type === "AssignmentPattern") - { this.checkPatternExport(exports, pat.left); } - else if (type === "RestElement") - { this.checkPatternExport(exports, pat.argument); } - else if (type === "ParenthesizedExpression") - { this.checkPatternExport(exports, pat.expression); } -}; - -pp$1.checkVariableExport = function(exports, decls) { - if (!exports) { return } - for (var i = 0, list = decls; i < list.length; i += 1) - { - var decl = list[i]; - - this.checkPatternExport(exports, decl.id); - } -}; - -pp$1.shouldParseExportStatement = function() { - return this.type.keyword === "var" || - this.type.keyword === "const" || - this.type.keyword === "class" || - this.type.keyword === "function" || - this.isLet() || - this.isAsyncFunction() -}; - -// Parses a comma-separated list of module exports. - -pp$1.parseExportSpecifiers = function(exports) { - var nodes = [], first = true; - // export { x, y as z } [from '...'] - this.expect(types.braceL); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } - - var node = this.startNode(); - node.local = this.parseIdent(true); - node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local; - this.checkExport(exports, node.exported.name, node.exported.start); - nodes.push(this.finishNode(node, "ExportSpecifier")); - } - return nodes -}; - -// Parses import declaration. - -pp$1.parseImport = function(node) { - this.next(); - // import '...' - if (this.type === types.string) { - node.specifiers = empty; - node.source = this.parseExprAtom(); - } else { - node.specifiers = this.parseImportSpecifiers(); - this.expectContextual("from"); - node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); - } - this.semicolon(); - return this.finishNode(node, "ImportDeclaration") -}; - -// Parses a comma-separated list of module imports. - -pp$1.parseImportSpecifiers = function() { - var nodes = [], first = true; - if (this.type === types.name) { - // import defaultObj, { x, y as z } from '...' - var node = this.startNode(); - node.local = this.parseIdent(); - this.checkLValSimple(node.local, BIND_LEXICAL); - nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); - if (!this.eat(types.comma)) { return nodes } - } - if (this.type === types.star) { - var node$1 = this.startNode(); - this.next(); - this.expectContextual("as"); - node$1.local = this.parseIdent(); - this.checkLValSimple(node$1.local, BIND_LEXICAL); - nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); - return nodes - } - this.expect(types.braceL); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } - - var node$2 = this.startNode(); - node$2.imported = this.parseIdent(true); - if (this.eatContextual("as")) { - node$2.local = this.parseIdent(); - } else { - this.checkUnreserved(node$2.imported); - node$2.local = node$2.imported; - } - this.checkLValSimple(node$2.local, BIND_LEXICAL); - nodes.push(this.finishNode(node$2, "ImportSpecifier")); - } - return nodes -}; - -// Set `ExpressionStatement#directive` property for directive prologues. -pp$1.adaptDirectivePrologue = function(statements) { - for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { - statements[i].directive = statements[i].expression.raw.slice(1, -1); - } -}; -pp$1.isDirectiveCandidate = function(statement) { - return ( - statement.type === "ExpressionStatement" && - statement.expression.type === "Literal" && - typeof statement.expression.value === "string" && - // Reject parenthesized strings. - (this.input[statement.start] === "\"" || this.input[statement.start] === "'") - ) -}; - -var pp$2 = Parser.prototype; - -// Convert existing expression atom to assignable pattern -// if possible. - -pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { - if (this.options.ecmaVersion >= 6 && node) { - switch (node.type) { - case "Identifier": - if (this.inAsync && node.name === "await") - { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } - break - - case "ObjectPattern": - case "ArrayPattern": - case "AssignmentPattern": - case "RestElement": - break - - case "ObjectExpression": - node.type = "ObjectPattern"; - if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - for (var i = 0, list = node.properties; i < list.length; i += 1) { - var prop = list[i]; - - this.toAssignable(prop, isBinding); - // Early error: - // AssignmentRestProperty[Yield, Await] : - // `...` DestructuringAssignmentTarget[Yield, Await] - // - // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. - if ( - prop.type === "RestElement" && - (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") - ) { - this.raise(prop.argument.start, "Unexpected token"); - } - } - break - - case "Property": - // AssignmentProperty has type === "Property" - if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } - this.toAssignable(node.value, isBinding); - break - - case "ArrayExpression": - node.type = "ArrayPattern"; - if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - this.toAssignableList(node.elements, isBinding); - break - - case "SpreadElement": - node.type = "RestElement"; - this.toAssignable(node.argument, isBinding); - if (node.argument.type === "AssignmentPattern") - { this.raise(node.argument.start, "Rest elements cannot have a default value"); } - break - - case "AssignmentExpression": - if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } - node.type = "AssignmentPattern"; - delete node.operator; - this.toAssignable(node.left, isBinding); - break - - case "ParenthesizedExpression": - this.toAssignable(node.expression, isBinding, refDestructuringErrors); - break - - case "ChainExpression": - this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); - break - - case "MemberExpression": - if (!isBinding) { break } - - default: - this.raise(node.start, "Assigning to rvalue"); - } - } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - return node -}; - -// Convert list of expression atoms to binding list. - -pp$2.toAssignableList = function(exprList, isBinding) { - var end = exprList.length; - for (var i = 0; i < end; i++) { - var elt = exprList[i]; - if (elt) { this.toAssignable(elt, isBinding); } - } - if (end) { - var last = exprList[end - 1]; - if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") - { this.unexpected(last.argument.start); } - } - return exprList -}; - -// Parses spread element. - -pp$2.parseSpread = function(refDestructuringErrors) { - var node = this.startNode(); - this.next(); - node.argument = this.parseMaybeAssign(false, refDestructuringErrors); - return this.finishNode(node, "SpreadElement") -}; - -pp$2.parseRestBinding = function() { - var node = this.startNode(); - this.next(); - - // RestElement inside of a function parameter must be an identifier - if (this.options.ecmaVersion === 6 && this.type !== types.name) - { this.unexpected(); } - - node.argument = this.parseBindingAtom(); - - return this.finishNode(node, "RestElement") -}; - -// Parses lvalue (assignable) atom. - -pp$2.parseBindingAtom = function() { - if (this.options.ecmaVersion >= 6) { - switch (this.type) { - case types.bracketL: - var node = this.startNode(); - this.next(); - node.elements = this.parseBindingList(types.bracketR, true, true); - return this.finishNode(node, "ArrayPattern") - - case types.braceL: - return this.parseObj(true) - } - } - return this.parseIdent() -}; - -pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { - var elts = [], first = true; - while (!this.eat(close)) { - if (first) { first = false; } - else { this.expect(types.comma); } - if (allowEmpty && this.type === types.comma) { - elts.push(null); - } else if (allowTrailingComma && this.afterTrailingComma(close)) { - break - } else if (this.type === types.ellipsis) { - var rest = this.parseRestBinding(); - this.parseBindingListItem(rest); - elts.push(rest); - if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } - this.expect(close); - break - } else { - var elem = this.parseMaybeDefault(this.start, this.startLoc); - this.parseBindingListItem(elem); - elts.push(elem); - } - } - return elts -}; - -pp$2.parseBindingListItem = function(param) { - return param -}; - -// Parses assignment pattern around given atom if possible. - -pp$2.parseMaybeDefault = function(startPos, startLoc, left) { - left = left || this.parseBindingAtom(); - if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } - var node = this.startNodeAt(startPos, startLoc); - node.left = left; - node.right = this.parseMaybeAssign(); - return this.finishNode(node, "AssignmentPattern") -}; - -// The following three functions all verify that a node is an lvalue — -// something that can be bound, or assigned to. In order to do so, they perform -// a variety of checks: -// -// - Check that none of the bound/assigned-to identifiers are reserved words. -// - Record name declarations for bindings in the appropriate scope. -// - Check duplicate argument names, if checkClashes is set. -// -// If a complex binding pattern is encountered (e.g., object and array -// destructuring), the entire pattern is recursively checked. -// -// There are three versions of checkLVal*() appropriate for different -// circumstances: -// -// - checkLValSimple() shall be used if the syntactic construct supports -// nothing other than identifiers and member expressions. Parenthesized -// expressions are also correctly handled. This is generally appropriate for -// constructs for which the spec says -// -// > It is a Syntax Error if AssignmentTargetType of [the production] is not -// > simple. -// -// It is also appropriate for checking if an identifier is valid and not -// defined elsewhere, like import declarations or function/class identifiers. -// -// Examples where this is used include: -// a += …; -// import a from '…'; -// where a is the node to be checked. -// -// - checkLValPattern() shall be used if the syntactic construct supports -// anything checkLValSimple() supports, as well as object and array -// destructuring patterns. This is generally appropriate for constructs for -// which the spec says -// -// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor -// > an ArrayLiteral and AssignmentTargetType of [the production] is not -// > simple. -// -// Examples where this is used include: -// (a = …); -// const a = …; -// try { … } catch (a) { … } -// where a is the node to be checked. -// -// - checkLValInnerPattern() shall be used if the syntactic construct supports -// anything checkLValPattern() supports, as well as default assignment -// patterns, rest elements, and other constructs that may appear within an -// object or array destructuring pattern. -// -// As a special case, function parameters also use checkLValInnerPattern(), -// as they also support defaults and rest constructs. -// -// These functions deliberately support both assignment and binding constructs, -// as the logic for both is exceedingly similar. If the node is the target of -// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it -// should be set to the appropriate BIND_* constant, like BIND_VAR or -// BIND_LEXICAL. -// -// If the function is called with a non-BIND_NONE bindingType, then -// additionally a checkClashes object may be specified to allow checking for -// duplicate argument names. checkClashes is ignored if the provided construct -// is an assignment (i.e., bindingType is BIND_NONE). - -pp$2.checkLValSimple = function(expr, bindingType, checkClashes) { - if ( bindingType === void 0 ) bindingType = BIND_NONE; - - var isBind = bindingType !== BIND_NONE; - - switch (expr.type) { - case "Identifier": - if (this.strict && this.reservedWordsStrictBind.test(expr.name)) - { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } - if (isBind) { - if (bindingType === BIND_LEXICAL && expr.name === "let") - { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } - if (checkClashes) { - if (has$1(checkClashes, expr.name)) - { this.raiseRecoverable(expr.start, "Argument name clash"); } - checkClashes[expr.name] = true; - } - if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } - } - break - - case "ChainExpression": - this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); - break - - case "MemberExpression": - if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } - break - - case "ParenthesizedExpression": - if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } - return this.checkLValSimple(expr.expression, bindingType, checkClashes) - - default: - this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); - } -}; - -pp$2.checkLValPattern = function(expr, bindingType, checkClashes) { - if ( bindingType === void 0 ) bindingType = BIND_NONE; - - switch (expr.type) { - case "ObjectPattern": - for (var i = 0, list = expr.properties; i < list.length; i += 1) { - var prop = list[i]; - - this.checkLValInnerPattern(prop, bindingType, checkClashes); - } - break - - case "ArrayPattern": - for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { - var elem = list$1[i$1]; - - if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } - } - break - - default: - this.checkLValSimple(expr, bindingType, checkClashes); - } -}; - -pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) { - if ( bindingType === void 0 ) bindingType = BIND_NONE; - - switch (expr.type) { - case "Property": - // AssignmentProperty has type === "Property" - this.checkLValInnerPattern(expr.value, bindingType, checkClashes); - break - - case "AssignmentPattern": - this.checkLValPattern(expr.left, bindingType, checkClashes); - break - - case "RestElement": - this.checkLValPattern(expr.argument, bindingType, checkClashes); - break - - default: - this.checkLValPattern(expr, bindingType, checkClashes); - } -}; - -// A recursive descent parser operates by defining functions for all - -var pp$3 = Parser.prototype; - -// Check if property name clashes with already added. -// Object/class getters and setters are not allowed to clash — -// either with each other or with an init property — and in -// strict mode, init properties are also not allowed to be repeated. - -pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) { - if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") - { return } - if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) - { return } - var key = prop.key; - var name; - switch (key.type) { - case "Identifier": name = key.name; break - case "Literal": name = String(key.value); break - default: return - } - var kind = prop.kind; - if (this.options.ecmaVersion >= 6) { - if (name === "__proto__" && kind === "init") { - if (propHash.proto) { - if (refDestructuringErrors) { - if (refDestructuringErrors.doubleProto < 0) - { refDestructuringErrors.doubleProto = key.start; } - // Backwards-compat kludge. Can be removed in version 6.0 - } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } - } - propHash.proto = true; - } - return - } - name = "$" + name; - var other = propHash[name]; - if (other) { - var redefinition; - if (kind === "init") { - redefinition = this.strict && other.init || other.get || other.set; - } else { - redefinition = other.init || other[kind]; - } - if (redefinition) - { this.raiseRecoverable(key.start, "Redefinition of property"); } - } else { - other = propHash[name] = { - init: false, - get: false, - set: false - }; - } - other[kind] = true; -}; - -// ### Expression parsing - -// These nest, from the most general expression type at the top to -// 'atomic', nondivisible expression types at the bottom. Most of -// the functions will simply let the function(s) below them parse, -// and, *if* the syntactic construct they handle is present, wrap -// the AST node that the inner parser gave them in another node. - -// Parse a full expression. The optional arguments are used to -// forbid the `in` operator (in for loops initalization expressions) -// and provide reference for storing '=' operator inside shorthand -// property assignment in contexts where both object expression -// and object pattern might appear (so it's possible to raise -// delayed syntax error at correct position). - -pp$3.parseExpression = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseMaybeAssign(noIn, refDestructuringErrors); - if (this.type === types.comma) { - var node = this.startNodeAt(startPos, startLoc); - node.expressions = [expr]; - while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); } - return this.finishNode(node, "SequenceExpression") - } - return expr -}; - -// Parse an assignment expression. This includes applications of -// operators like `+=`. - -pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { - if (this.isContextual("yield")) { - if (this.inGenerator) { return this.parseYield(noIn) } - // The tokenizer will assume an expression is allowed after - // `yield`, but this isn't that kind of yield - else { this.exprAllowed = false; } - } - - var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1; - if (refDestructuringErrors) { - oldParenAssign = refDestructuringErrors.parenthesizedAssign; - oldTrailingComma = refDestructuringErrors.trailingComma; - refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; - } else { - refDestructuringErrors = new DestructuringErrors; - ownDestructuringErrors = true; - } - - var startPos = this.start, startLoc = this.startLoc; - if (this.type === types.parenL || this.type === types.name) - { this.potentialArrowAt = this.start; } - var left = this.parseMaybeConditional(noIn, refDestructuringErrors); - if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } - if (this.type.isAssign) { - var node = this.startNodeAt(startPos, startLoc); - node.operator = this.value; - if (this.type === types.eq) - { left = this.toAssignable(left, false, refDestructuringErrors); } - if (!ownDestructuringErrors) { - refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; - } - if (refDestructuringErrors.shorthandAssign >= left.start) - { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly - if (this.type === types.eq) - { this.checkLValPattern(left); } - else - { this.checkLValSimple(left); } - node.left = left; - this.next(); - node.right = this.parseMaybeAssign(noIn); - return this.finishNode(node, "AssignmentExpression") - } else { - if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } - } - if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } - if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } - return left -}; - -// Parse a ternary conditional (`?:`) operator. - -pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseExprOps(noIn, refDestructuringErrors); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - if (this.eat(types.question)) { - var node = this.startNodeAt(startPos, startLoc); - node.test = expr; - node.consequent = this.parseMaybeAssign(); - this.expect(types.colon); - node.alternate = this.parseMaybeAssign(noIn); - return this.finishNode(node, "ConditionalExpression") - } - return expr -}; - -// Start the precedence parser. - -pp$3.parseExprOps = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseMaybeUnary(refDestructuringErrors, false); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn) -}; - -// Parse binary operators with the operator precedence parsing -// algorithm. `left` is the left-hand side of the operator. -// `minPrec` provides context that allows the function to stop and -// defer further parser to one of its callers when it encounters an -// operator that has a lower precedence than the set it is parsing. - -pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { - var prec = this.type.binop; - if (prec != null && (!noIn || this.type !== types._in)) { - if (prec > minPrec) { - var logical = this.type === types.logicalOR || this.type === types.logicalAND; - var coalesce = this.type === types.coalesce; - if (coalesce) { - // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. - // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. - prec = types.logicalAND.binop; - } - var op = this.value; - this.next(); - var startPos = this.start, startLoc = this.startLoc; - var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn); - var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); - if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) { - this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); - } - return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) - } - } - return left -}; - -pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { - var node = this.startNodeAt(startPos, startLoc); - node.left = left; - node.operator = op; - node.right = right; - return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") -}; - -// Parse unary operators, both prefix and postfix. - -pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { - var startPos = this.start, startLoc = this.startLoc, expr; - if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) { - expr = this.parseAwait(); - sawUnary = true; - } else if (this.type.prefix) { - var node = this.startNode(), update = this.type === types.incDec; - node.operator = this.value; - node.prefix = true; - this.next(); - node.argument = this.parseMaybeUnary(null, true); - this.checkExpressionErrors(refDestructuringErrors, true); - if (update) { this.checkLValSimple(node.argument); } - else if (this.strict && node.operator === "delete" && - node.argument.type === "Identifier") - { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } - else { sawUnary = true; } - expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); - } else { - expr = this.parseExprSubscripts(refDestructuringErrors); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - while (this.type.postfix && !this.canInsertSemicolon()) { - var node$1 = this.startNodeAt(startPos, startLoc); - node$1.operator = this.value; - node$1.prefix = false; - node$1.argument = expr; - this.checkLValSimple(expr); - this.next(); - expr = this.finishNode(node$1, "UpdateExpression"); - } - } - - if (!sawUnary && this.eat(types.starstar)) - { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } - else - { return expr } -}; - -// Parse call, dot, and `[]`-subscript expressions. - -pp$3.parseExprSubscripts = function(refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseExprAtom(refDestructuringErrors); - if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") - { return expr } - var result = this.parseSubscripts(expr, startPos, startLoc); - if (refDestructuringErrors && result.type === "MemberExpression") { - if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } - if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } - if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } - } - return result -}; - -pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { - var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && - this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && - this.potentialArrowAt === base.start; - var optionalChained = false; - - while (true) { - var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained); - - if (element.optional) { optionalChained = true; } - if (element === base || element.type === "ArrowFunctionExpression") { - if (optionalChained) { - var chainNode = this.startNodeAt(startPos, startLoc); - chainNode.expression = element; - element = this.finishNode(chainNode, "ChainExpression"); - } - return element - } - - base = element; - } -}; - -pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) { - var optionalSupported = this.options.ecmaVersion >= 11; - var optional = optionalSupported && this.eat(types.questionDot); - if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } - - var computed = this.eat(types.bracketL); - if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) { - var node = this.startNodeAt(startPos, startLoc); - node.object = base; - node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never"); - node.computed = !!computed; - if (computed) { this.expect(types.bracketR); } - if (optionalSupported) { - node.optional = optional; - } - base = this.finishNode(node, "MemberExpression"); - } else if (!noCalls && this.eat(types.parenL)) { - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); - if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) { - this.checkPatternErrors(refDestructuringErrors, false); - this.checkYieldAwaitInDefaultParams(); - if (this.awaitIdentPos > 0) - { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true) - } - this.checkExpressionErrors(refDestructuringErrors, true); - this.yieldPos = oldYieldPos || this.yieldPos; - this.awaitPos = oldAwaitPos || this.awaitPos; - this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; - var node$1 = this.startNodeAt(startPos, startLoc); - node$1.callee = base; - node$1.arguments = exprList; - if (optionalSupported) { - node$1.optional = optional; - } - base = this.finishNode(node$1, "CallExpression"); - } else if (this.type === types.backQuote) { - if (optional || optionalChained) { - this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); - } - var node$2 = this.startNodeAt(startPos, startLoc); - node$2.tag = base; - node$2.quasi = this.parseTemplate({isTagged: true}); - base = this.finishNode(node$2, "TaggedTemplateExpression"); - } - return base -}; - -// Parse an atomic expression — either a single token that is an -// expression, an expression started by a keyword like `function` or -// `new`, or an expression wrapped in punctuation like `()`, `[]`, -// or `{}`. - -pp$3.parseExprAtom = function(refDestructuringErrors) { - // If a division operator appears in an expression position, the - // tokenizer got confused, and we force it to read a regexp instead. - if (this.type === types.slash) { this.readRegexp(); } - - var node, canBeArrow = this.potentialArrowAt === this.start; - switch (this.type) { - case types._super: - if (!this.allowSuper) - { this.raise(this.start, "'super' keyword outside a method"); } - node = this.startNode(); - this.next(); - if (this.type === types.parenL && !this.allowDirectSuper) - { this.raise(node.start, "super() call outside constructor of a subclass"); } - // The `super` keyword can appear at below: - // SuperProperty: - // super [ Expression ] - // super . IdentifierName - // SuperCall: - // super ( Arguments ) - if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) - { this.unexpected(); } - return this.finishNode(node, "Super") - - case types._this: - node = this.startNode(); - this.next(); - return this.finishNode(node, "ThisExpression") - - case types.name: - var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; - var id = this.parseIdent(false); - if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) - { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } - if (canBeArrow && !this.canInsertSemicolon()) { - if (this.eat(types.arrow)) - { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } - if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) { - id = this.parseIdent(false); - if (this.canInsertSemicolon() || !this.eat(types.arrow)) - { this.unexpected(); } - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) - } - } - return id - - case types.regexp: - var value = this.value; - node = this.parseLiteral(value.value); - node.regex = {pattern: value.pattern, flags: value.flags}; - return node - - case types.num: case types.string: - return this.parseLiteral(this.value) - - case types._null: case types._true: case types._false: - node = this.startNode(); - node.value = this.type === types._null ? null : this.type === types._true; - node.raw = this.type.keyword; - this.next(); - return this.finishNode(node, "Literal") - - case types.parenL: - var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow); - if (refDestructuringErrors) { - if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) - { refDestructuringErrors.parenthesizedAssign = start; } - if (refDestructuringErrors.parenthesizedBind < 0) - { refDestructuringErrors.parenthesizedBind = start; } - } - return expr - - case types.bracketL: - node = this.startNode(); - this.next(); - node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); - return this.finishNode(node, "ArrayExpression") - - case types.braceL: - return this.parseObj(false, refDestructuringErrors) - - case types._function: - node = this.startNode(); - this.next(); - return this.parseFunction(node, 0) - - case types._class: - return this.parseClass(this.startNode(), false) - - case types._new: - return this.parseNew() - - case types.backQuote: - return this.parseTemplate() - - case types._import: - if (this.options.ecmaVersion >= 11) { - return this.parseExprImport() - } else { - return this.unexpected() - } - - default: - this.unexpected(); - } -}; - -pp$3.parseExprImport = function() { - var node = this.startNode(); - - // Consume `import` as an identifier for `import.meta`. - // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. - if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } - var meta = this.parseIdent(true); - - switch (this.type) { - case types.parenL: - return this.parseDynamicImport(node) - case types.dot: - node.meta = meta; - return this.parseImportMeta(node) - default: - this.unexpected(); - } -}; - -pp$3.parseDynamicImport = function(node) { - this.next(); // skip `(` - - // Parse node.source. - node.source = this.parseMaybeAssign(); - - // Verify ending. - if (!this.eat(types.parenR)) { - var errorPos = this.start; - if (this.eat(types.comma) && this.eat(types.parenR)) { - this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); - } else { - this.unexpected(errorPos); - } - } - - return this.finishNode(node, "ImportExpression") -}; - -pp$3.parseImportMeta = function(node) { - this.next(); // skip `.` - - var containsEsc = this.containsEsc; - node.property = this.parseIdent(true); - - if (node.property.name !== "meta") - { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } - if (containsEsc) - { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } - if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) - { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } - - return this.finishNode(node, "MetaProperty") -}; - -pp$3.parseLiteral = function(value) { - var node = this.startNode(); - node.value = value; - node.raw = this.input.slice(this.start, this.end); - if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } - this.next(); - return this.finishNode(node, "Literal") -}; - -pp$3.parseParenExpression = function() { - this.expect(types.parenL); - var val = this.parseExpression(); - this.expect(types.parenR); - return val -}; - -pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { - var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; - if (this.options.ecmaVersion >= 6) { - this.next(); - - var innerStartPos = this.start, innerStartLoc = this.startLoc; - var exprList = [], first = true, lastIsComma = false; - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; - this.yieldPos = 0; - this.awaitPos = 0; - // Do not save awaitIdentPos to allow checking awaits nested in parameters - while (this.type !== types.parenR) { - first ? first = false : this.expect(types.comma); - if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) { - lastIsComma = true; - break - } else if (this.type === types.ellipsis) { - spreadStart = this.start; - exprList.push(this.parseParenItem(this.parseRestBinding())); - if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } - break - } else { - exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); - } - } - var innerEndPos = this.start, innerEndLoc = this.startLoc; - this.expect(types.parenR); - - if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { - this.checkPatternErrors(refDestructuringErrors, false); - this.checkYieldAwaitInDefaultParams(); - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - return this.parseParenArrowList(startPos, startLoc, exprList) - } - - if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } - if (spreadStart) { this.unexpected(spreadStart); } - this.checkExpressionErrors(refDestructuringErrors, true); - this.yieldPos = oldYieldPos || this.yieldPos; - this.awaitPos = oldAwaitPos || this.awaitPos; - - if (exprList.length > 1) { - val = this.startNodeAt(innerStartPos, innerStartLoc); - val.expressions = exprList; - this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); - } else { - val = exprList[0]; - } - } else { - val = this.parseParenExpression(); - } - - if (this.options.preserveParens) { - var par = this.startNodeAt(startPos, startLoc); - par.expression = val; - return this.finishNode(par, "ParenthesizedExpression") - } else { - return val - } -}; - -pp$3.parseParenItem = function(item) { - return item -}; - -pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) -}; - -// New's precedence is slightly tricky. It must allow its argument to -// be a `[]` or dot subscript expression, but not a call — at least, -// not without wrapping it in parentheses. Thus, it uses the noCalls -// argument to parseSubscripts to prevent it from consuming the -// argument list. - -var empty$1 = []; - -pp$3.parseNew = function() { - if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } - var node = this.startNode(); - var meta = this.parseIdent(true); - if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { - node.meta = meta; - var containsEsc = this.containsEsc; - node.property = this.parseIdent(true); - if (node.property.name !== "target") - { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } - if (containsEsc) - { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } - if (!this.inNonArrowFunction) - { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); } - return this.finishNode(node, "MetaProperty") - } - var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import; - node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); - if (isImport && node.callee.type === "ImportExpression") { - this.raise(startPos, "Cannot use new with import()"); - } - if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } - else { node.arguments = empty$1; } - return this.finishNode(node, "NewExpression") -}; - -// Parse template expression. - -pp$3.parseTemplateElement = function(ref) { - var isTagged = ref.isTagged; - - var elem = this.startNode(); - if (this.type === types.invalidTemplate) { - if (!isTagged) { - this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); - } - elem.value = { - raw: this.value, - cooked: null - }; - } else { - elem.value = { - raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), - cooked: this.value - }; - } - this.next(); - elem.tail = this.type === types.backQuote; - return this.finishNode(elem, "TemplateElement") -}; - -pp$3.parseTemplate = function(ref) { - if ( ref === void 0 ) ref = {}; - var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; - - var node = this.startNode(); - this.next(); - node.expressions = []; - var curElt = this.parseTemplateElement({isTagged: isTagged}); - node.quasis = [curElt]; - while (!curElt.tail) { - if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); } - this.expect(types.dollarBraceL); - node.expressions.push(this.parseExpression()); - this.expect(types.braceR); - node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); - } - this.next(); - return this.finishNode(node, "TemplateLiteral") -}; - -pp$3.isAsyncProp = function(prop) { - return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && - (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && - !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) -}; - -// Parse an object literal or binding pattern. - -pp$3.parseObj = function(isPattern, refDestructuringErrors) { - var node = this.startNode(), first = true, propHash = {}; - node.properties = []; - this.next(); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } - - var prop = this.parseProperty(isPattern, refDestructuringErrors); - if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } - node.properties.push(prop); - } - return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") -}; - -pp$3.parseProperty = function(isPattern, refDestructuringErrors) { - var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; - if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { - if (isPattern) { - prop.argument = this.parseIdent(false); - if (this.type === types.comma) { - this.raise(this.start, "Comma is not permitted after the rest element"); - } - return this.finishNode(prop, "RestElement") - } - // To disallow parenthesized identifier via `this.toAssignable()`. - if (this.type === types.parenL && refDestructuringErrors) { - if (refDestructuringErrors.parenthesizedAssign < 0) { - refDestructuringErrors.parenthesizedAssign = this.start; - } - if (refDestructuringErrors.parenthesizedBind < 0) { - refDestructuringErrors.parenthesizedBind = this.start; - } - } - // Parse argument. - prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); - // To disallow trailing comma via `this.toAssignable()`. - if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { - refDestructuringErrors.trailingComma = this.start; - } - // Finish - return this.finishNode(prop, "SpreadElement") - } - if (this.options.ecmaVersion >= 6) { - prop.method = false; - prop.shorthand = false; - if (isPattern || refDestructuringErrors) { - startPos = this.start; - startLoc = this.startLoc; - } - if (!isPattern) - { isGenerator = this.eat(types.star); } - } - var containsEsc = this.containsEsc; - this.parsePropertyName(prop); - if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { - isAsync = true; - isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); - this.parsePropertyName(prop, refDestructuringErrors); - } else { - isAsync = false; - } - this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); - return this.finishNode(prop, "Property") -}; - -pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { - if ((isGenerator || isAsync) && this.type === types.colon) - { this.unexpected(); } - - if (this.eat(types.colon)) { - prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); - prop.kind = "init"; - } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { - if (isPattern) { this.unexpected(); } - prop.kind = "init"; - prop.method = true; - prop.value = this.parseMethod(isGenerator, isAsync); - } else if (!isPattern && !containsEsc && - this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && - (prop.key.name === "get" || prop.key.name === "set") && - (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) { - if (isGenerator || isAsync) { this.unexpected(); } - prop.kind = prop.key.name; - this.parsePropertyName(prop); - prop.value = this.parseMethod(false); - var paramCount = prop.kind === "get" ? 0 : 1; - if (prop.value.params.length !== paramCount) { - var start = prop.value.start; - if (prop.kind === "get") - { this.raiseRecoverable(start, "getter should have no params"); } - else - { this.raiseRecoverable(start, "setter should have exactly one param"); } - } else { - if (prop.kind === "set" && prop.value.params[0].type === "RestElement") - { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } - } - } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { - if (isGenerator || isAsync) { this.unexpected(); } - this.checkUnreserved(prop.key); - if (prop.key.name === "await" && !this.awaitIdentPos) - { this.awaitIdentPos = startPos; } - prop.kind = "init"; - if (isPattern) { - prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); - } else if (this.type === types.eq && refDestructuringErrors) { - if (refDestructuringErrors.shorthandAssign < 0) - { refDestructuringErrors.shorthandAssign = this.start; } - prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); - } else { - prop.value = this.copyNode(prop.key); - } - prop.shorthand = true; - } else { this.unexpected(); } -}; - -pp$3.parsePropertyName = function(prop) { - if (this.options.ecmaVersion >= 6) { - if (this.eat(types.bracketL)) { - prop.computed = true; - prop.key = this.parseMaybeAssign(); - this.expect(types.bracketR); - return prop.key - } else { - prop.computed = false; - } - } - return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") -}; - -// Initialize empty function node. - -pp$3.initFunction = function(node) { - node.id = null; - if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } - if (this.options.ecmaVersion >= 8) { node.async = false; } -}; - -// Parse object or class method. - -pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { - var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - - this.initFunction(node); - if (this.options.ecmaVersion >= 6) - { node.generator = isGenerator; } - if (this.options.ecmaVersion >= 8) - { node.async = !!isAsync; } - - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); - - this.expect(types.parenL); - node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); - this.checkYieldAwaitInDefaultParams(); - this.parseFunctionBody(node, false, true); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, "FunctionExpression") -}; - -// Parse arrow function expression with given parameters. - -pp$3.parseArrowExpression = function(node, params, isAsync) { - var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - - this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); - this.initFunction(node); - if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } - - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - - node.params = this.toAssignableList(params, true); - this.parseFunctionBody(node, true, false); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, "ArrowFunctionExpression") -}; - -// Parse function body and check parameters. - -pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { - var isExpression = isArrowFunction && this.type !== types.braceL; - var oldStrict = this.strict, useStrict = false; - - if (isExpression) { - node.body = this.parseMaybeAssign(); - node.expression = true; - this.checkParams(node, false); - } else { - var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); - if (!oldStrict || nonSimple) { - useStrict = this.strictDirective(this.end); - // If this is a strict mode function, verify that argument names - // are not repeated, and it does not try to bind the words `eval` - // or `arguments`. - if (useStrict && nonSimple) - { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } - } - // Start a new scope with regard to labels and the `inFunction` - // flag (restore them to their old value afterwards). - var oldLabels = this.labels; - this.labels = []; - if (useStrict) { this.strict = true; } - - // Add the params to varDeclaredNames to ensure that an error is thrown - // if a let/const declaration in the function clashes with one of the params. - this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); - // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' - if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } - node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); - node.expression = false; - this.adaptDirectivePrologue(node.body.body); - this.labels = oldLabels; - } - this.exitScope(); -}; - -pp$3.isSimpleParamList = function(params) { - for (var i = 0, list = params; i < list.length; i += 1) - { - var param = list[i]; - - if (param.type !== "Identifier") { return false - } } - return true -}; - -// Checks function params for various disallowed patterns such as using "eval" -// or "arguments" and duplicate parameters. - -pp$3.checkParams = function(node, allowDuplicates) { - var nameHash = Object.create(null); - for (var i = 0, list = node.params; i < list.length; i += 1) - { - var param = list[i]; - - this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); - } -}; - -// Parses a comma-separated list of expressions, and returns them as -// an array. `close` is the token type that ends the list, and -// `allowEmpty` can be turned on to allow subsequent commas with -// nothing in between them to be parsed as `null` (which is needed -// for array literals). - -pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { - var elts = [], first = true; - while (!this.eat(close)) { - if (!first) { - this.expect(types.comma); - if (allowTrailingComma && this.afterTrailingComma(close)) { break } - } else { first = false; } - - var elt = (void 0); - if (allowEmpty && this.type === types.comma) - { elt = null; } - else if (this.type === types.ellipsis) { - elt = this.parseSpread(refDestructuringErrors); - if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0) - { refDestructuringErrors.trailingComma = this.start; } - } else { - elt = this.parseMaybeAssign(false, refDestructuringErrors); - } - elts.push(elt); - } - return elts -}; - -pp$3.checkUnreserved = function(ref) { - var start = ref.start; - var end = ref.end; - var name = ref.name; - - if (this.inGenerator && name === "yield") - { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } - if (this.inAsync && name === "await") - { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } - if (this.keywords.test(name)) - { this.raise(start, ("Unexpected keyword '" + name + "'")); } - if (this.options.ecmaVersion < 6 && - this.input.slice(start, end).indexOf("\\") !== -1) { return } - var re = this.strict ? this.reservedWordsStrict : this.reservedWords; - if (re.test(name)) { - if (!this.inAsync && name === "await") - { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } - this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); - } -}; - -// Parse the next token as an identifier. If `liberal` is true (used -// when parsing properties), it will also convert keywords into -// identifiers. - -pp$3.parseIdent = function(liberal, isBinding) { - var node = this.startNode(); - if (this.type === types.name) { - node.name = this.value; - } else if (this.type.keyword) { - node.name = this.type.keyword; - - // To fix https://github.com/acornjs/acorn/issues/575 - // `class` and `function` keywords push new context into this.context. - // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. - // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword - if ((node.name === "class" || node.name === "function") && - (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { - this.context.pop(); - } - } else { - this.unexpected(); - } - this.next(!!liberal); - this.finishNode(node, "Identifier"); - if (!liberal) { - this.checkUnreserved(node); - if (node.name === "await" && !this.awaitIdentPos) - { this.awaitIdentPos = node.start; } - } - return node -}; - -// Parses yield expression inside generator. - -pp$3.parseYield = function(noIn) { - if (!this.yieldPos) { this.yieldPos = this.start; } - - var node = this.startNode(); - this.next(); - if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { - node.delegate = false; - node.argument = null; - } else { - node.delegate = this.eat(types.star); - node.argument = this.parseMaybeAssign(noIn); - } - return this.finishNode(node, "YieldExpression") -}; - -pp$3.parseAwait = function() { - if (!this.awaitPos) { this.awaitPos = this.start; } - - var node = this.startNode(); - this.next(); - node.argument = this.parseMaybeUnary(null, true); - return this.finishNode(node, "AwaitExpression") -}; - -var pp$4 = Parser.prototype; - -// This function is used to raise exceptions on parse errors. It -// takes an offset integer (into the current `input`) to indicate -// the location of the error, attaches the position to the end -// of the error message, and then raises a `SyntaxError` with that -// message. - -pp$4.raise = function(pos, message) { - var loc = getLineInfo(this.input, pos); - message += " (" + loc.line + ":" + loc.column + ")"; - var err = new SyntaxError(message); - err.pos = pos; err.loc = loc; err.raisedAt = this.pos; - throw err -}; - -pp$4.raiseRecoverable = pp$4.raise; - -pp$4.curPosition = function() { - if (this.options.locations) { - return new Position(this.curLine, this.pos - this.lineStart) - } -}; - -var pp$5 = Parser.prototype; - -var Scope = function Scope(flags) { - this.flags = flags; - // A list of var-declared names in the current lexical scope - this.var = []; - // A list of lexically-declared names in the current lexical scope - this.lexical = []; - // A list of lexically-declared FunctionDeclaration names in the current lexical scope - this.functions = []; -}; - -// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. - -pp$5.enterScope = function(flags) { - this.scopeStack.push(new Scope(flags)); -}; - -pp$5.exitScope = function() { - this.scopeStack.pop(); -}; - -// The spec says: -// > At the top level of a function, or script, function declarations are -// > treated like var declarations rather than like lexical declarations. -pp$5.treatFunctionsAsVarInScope = function(scope) { - return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) -}; - -pp$5.declareName = function(name, bindingType, pos) { - var redeclared = false; - if (bindingType === BIND_LEXICAL) { - var scope = this.currentScope(); - redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; - scope.lexical.push(name); - if (this.inModule && (scope.flags & SCOPE_TOP)) - { delete this.undefinedExports[name]; } - } else if (bindingType === BIND_SIMPLE_CATCH) { - var scope$1 = this.currentScope(); - scope$1.lexical.push(name); - } else if (bindingType === BIND_FUNCTION) { - var scope$2 = this.currentScope(); - if (this.treatFunctionsAsVar) - { redeclared = scope$2.lexical.indexOf(name) > -1; } - else - { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } - scope$2.functions.push(name); - } else { - for (var i = this.scopeStack.length - 1; i >= 0; --i) { - var scope$3 = this.scopeStack[i]; - if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || - !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { - redeclared = true; - break - } - scope$3.var.push(name); - if (this.inModule && (scope$3.flags & SCOPE_TOP)) - { delete this.undefinedExports[name]; } - if (scope$3.flags & SCOPE_VAR) { break } - } - } - if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } -}; - -pp$5.checkLocalExport = function(id) { - // scope.functions must be empty as Module code is always strict. - if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && - this.scopeStack[0].var.indexOf(id.name) === -1) { - this.undefinedExports[id.name] = id; - } -}; - -pp$5.currentScope = function() { - return this.scopeStack[this.scopeStack.length - 1] -}; - -pp$5.currentVarScope = function() { - for (var i = this.scopeStack.length - 1;; i--) { - var scope = this.scopeStack[i]; - if (scope.flags & SCOPE_VAR) { return scope } - } -}; - -// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. -pp$5.currentThisScope = function() { - for (var i = this.scopeStack.length - 1;; i--) { - var scope = this.scopeStack[i]; - if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } - } -}; - -var Node = function Node(parser, pos, loc) { - this.type = ""; - this.start = pos; - this.end = 0; - if (parser.options.locations) - { this.loc = new SourceLocation(parser, loc); } - if (parser.options.directSourceFile) - { this.sourceFile = parser.options.directSourceFile; } - if (parser.options.ranges) - { this.range = [pos, 0]; } -}; - -// Start an AST node, attaching a start offset. - -var pp$6 = Parser.prototype; - -pp$6.startNode = function() { - return new Node(this, this.start, this.startLoc) -}; - -pp$6.startNodeAt = function(pos, loc) { - return new Node(this, pos, loc) -}; - -// Finish an AST node, adding `type` and `end` properties. - -function finishNodeAt(node, type, pos, loc) { - node.type = type; - node.end = pos; - if (this.options.locations) - { node.loc.end = loc; } - if (this.options.ranges) - { node.range[1] = pos; } - return node -} - -pp$6.finishNode = function(node, type) { - return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) -}; - -// Finish node at given position - -pp$6.finishNodeAt = function(node, type, pos, loc) { - return finishNodeAt.call(this, node, type, pos, loc) -}; - -pp$6.copyNode = function(node) { - var newNode = new Node(this, node.start, this.startLoc); - for (var prop in node) { newNode[prop] = node[prop]; } - return newNode -}; - -// The algorithm used to determine whether a regexp can appear at a - -var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { - this.token = token; - this.isExpr = !!isExpr; - this.preserveSpace = !!preserveSpace; - this.override = override; - this.generator = !!generator; -}; - -var types$1 = { - b_stat: new TokContext("{", false), - b_expr: new TokContext("{", true), - b_tmpl: new TokContext("${", false), - p_stat: new TokContext("(", false), - p_expr: new TokContext("(", true), - q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), - f_stat: new TokContext("function", false), - f_expr: new TokContext("function", true), - f_expr_gen: new TokContext("function", true, false, null, true), - f_gen: new TokContext("function", false, false, null, true) -}; - -var pp$7 = Parser.prototype; - -pp$7.initialContext = function() { - return [types$1.b_stat] -}; - -pp$7.braceIsBlock = function(prevType) { - var parent = this.curContext(); - if (parent === types$1.f_expr || parent === types$1.f_stat) - { return true } - if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) - { return !parent.isExpr } - - // The check for `tt.name && exprAllowed` detects whether we are - // after a `yield` or `of` construct. See the `updateContext` for - // `tt.name`. - if (prevType === types._return || prevType === types.name && this.exprAllowed) - { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } - if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) - { return true } - if (prevType === types.braceL) - { return parent === types$1.b_stat } - if (prevType === types._var || prevType === types._const || prevType === types.name) - { return false } - return !this.exprAllowed -}; - -pp$7.inGeneratorContext = function() { - for (var i = this.context.length - 1; i >= 1; i--) { - var context = this.context[i]; - if (context.token === "function") - { return context.generator } - } - return false -}; - -pp$7.updateContext = function(prevType) { - var update, type = this.type; - if (type.keyword && prevType === types.dot) - { this.exprAllowed = false; } - else if (update = type.updateContext) - { update.call(this, prevType); } - else - { this.exprAllowed = type.beforeExpr; } -}; - -// Token-specific context update code - -types.parenR.updateContext = types.braceR.updateContext = function() { - if (this.context.length === 1) { - this.exprAllowed = true; - return - } - var out = this.context.pop(); - if (out === types$1.b_stat && this.curContext().token === "function") { - out = this.context.pop(); - } - this.exprAllowed = !out.isExpr; -}; - -types.braceL.updateContext = function(prevType) { - this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); - this.exprAllowed = true; -}; - -types.dollarBraceL.updateContext = function() { - this.context.push(types$1.b_tmpl); - this.exprAllowed = true; -}; - -types.parenL.updateContext = function(prevType) { - var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; - this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); - this.exprAllowed = true; -}; - -types.incDec.updateContext = function() { - // tokExprAllowed stays unchanged -}; - -types._function.updateContext = types._class.updateContext = function(prevType) { - if (prevType.beforeExpr && prevType !== types._else && - !(prevType === types.semi && this.curContext() !== types$1.p_stat) && - !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && - !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) - { this.context.push(types$1.f_expr); } - else - { this.context.push(types$1.f_stat); } - this.exprAllowed = false; -}; - -types.backQuote.updateContext = function() { - if (this.curContext() === types$1.q_tmpl) - { this.context.pop(); } - else - { this.context.push(types$1.q_tmpl); } - this.exprAllowed = false; -}; - -types.star.updateContext = function(prevType) { - if (prevType === types._function) { - var index = this.context.length - 1; - if (this.context[index] === types$1.f_expr) - { this.context[index] = types$1.f_expr_gen; } - else - { this.context[index] = types$1.f_gen; } - } - this.exprAllowed = true; -}; - -types.name.updateContext = function(prevType) { - var allowed = false; - if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { - if (this.value === "of" && !this.exprAllowed || - this.value === "yield" && this.inGeneratorContext()) - { allowed = true; } - } - this.exprAllowed = allowed; -}; - -// This file contains Unicode properties extracted from the ECMAScript -// specification. The lists are extracted like so: -// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) - -// #table-binary-unicode-properties -var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; -var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; -var ecma11BinaryProperties = ecma10BinaryProperties; -var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; -var unicodeBinaryProperties = { - 9: ecma9BinaryProperties, - 10: ecma10BinaryProperties, - 11: ecma11BinaryProperties, - 12: ecma12BinaryProperties -}; - -// #table-unicode-general-category-values -var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; - -// #table-unicode-script-values -var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; -var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; -var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; -var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; -var unicodeScriptValues = { - 9: ecma9ScriptValues, - 10: ecma10ScriptValues, - 11: ecma11ScriptValues, - 12: ecma12ScriptValues -}; - -var data = {}; -function buildUnicodeData(ecmaVersion) { - var d = data[ecmaVersion] = { - binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), - nonBinary: { - General_Category: wordsRegexp(unicodeGeneralCategoryValues), - Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) - } - }; - d.nonBinary.Script_Extensions = d.nonBinary.Script; - - d.nonBinary.gc = d.nonBinary.General_Category; - d.nonBinary.sc = d.nonBinary.Script; - d.nonBinary.scx = d.nonBinary.Script_Extensions; -} -buildUnicodeData(9); -buildUnicodeData(10); -buildUnicodeData(11); -buildUnicodeData(12); - -var pp$8 = Parser.prototype; - -var RegExpValidationState = function RegExpValidationState(parser) { - this.parser = parser; - this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : ""); - this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion]; - this.source = ""; - this.flags = ""; - this.start = 0; - this.switchU = false; - this.switchN = false; - this.pos = 0; - this.lastIntValue = 0; - this.lastStringValue = ""; - this.lastAssertionIsQuantifiable = false; - this.numCapturingParens = 0; - this.maxBackReference = 0; - this.groupNames = []; - this.backReferenceNames = []; -}; - -RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { - var unicode = flags.indexOf("u") !== -1; - this.start = start | 0; - this.source = pattern + ""; - this.flags = flags; - this.switchU = unicode && this.parser.options.ecmaVersion >= 6; - this.switchN = unicode && this.parser.options.ecmaVersion >= 9; -}; - -RegExpValidationState.prototype.raise = function raise (message) { - this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); -}; - -// If u flag is given, this returns the code point at the index (it combines a surrogate pair). -// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). -RegExpValidationState.prototype.at = function at (i, forceU) { - if ( forceU === void 0 ) forceU = false; - - var s = this.source; - var l = s.length; - if (i >= l) { - return -1 - } - var c = s.charCodeAt(i); - if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { - return c - } - var next = s.charCodeAt(i + 1); - return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c -}; - -RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { - if ( forceU === void 0 ) forceU = false; - - var s = this.source; - var l = s.length; - if (i >= l) { - return l - } - var c = s.charCodeAt(i), next; - if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || - (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { - return i + 1 - } - return i + 2 -}; - -RegExpValidationState.prototype.current = function current (forceU) { - if ( forceU === void 0 ) forceU = false; - - return this.at(this.pos, forceU) -}; - -RegExpValidationState.prototype.lookahead = function lookahead (forceU) { - if ( forceU === void 0 ) forceU = false; - - return this.at(this.nextIndex(this.pos, forceU), forceU) -}; - -RegExpValidationState.prototype.advance = function advance (forceU) { - if ( forceU === void 0 ) forceU = false; - - this.pos = this.nextIndex(this.pos, forceU); -}; - -RegExpValidationState.prototype.eat = function eat (ch, forceU) { - if ( forceU === void 0 ) forceU = false; - - if (this.current(forceU) === ch) { - this.advance(forceU); - return true - } - return false -}; - -function codePointToString(ch) { - if (ch <= 0xFFFF) { return String.fromCharCode(ch) } - ch -= 0x10000; - return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) -} - -/** - * Validate the flags part of a given RegExpLiteral. - * - * @param {RegExpValidationState} state The state to validate RegExp. - * @returns {void} - */ -pp$8.validateRegExpFlags = function(state) { - var validFlags = state.validFlags; - var flags = state.flags; - - for (var i = 0; i < flags.length; i++) { - var flag = flags.charAt(i); - if (validFlags.indexOf(flag) === -1) { - this.raise(state.start, "Invalid regular expression flag"); - } - if (flags.indexOf(flag, i + 1) > -1) { - this.raise(state.start, "Duplicate regular expression flag"); - } - } -}; - -/** - * Validate the pattern part of a given RegExpLiteral. - * - * @param {RegExpValidationState} state The state to validate RegExp. - * @returns {void} - */ -pp$8.validateRegExpPattern = function(state) { - this.regexp_pattern(state); - - // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of - // parsing contains a |GroupName|, reparse with the goal symbol - // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* - // exception if _P_ did not conform to the grammar, if any elements of _P_ - // were not matched by the parse, or if any Early Error conditions exist. - if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { - state.switchN = true; - this.regexp_pattern(state); - } -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern -pp$8.regexp_pattern = function(state) { - state.pos = 0; - state.lastIntValue = 0; - state.lastStringValue = ""; - state.lastAssertionIsQuantifiable = false; - state.numCapturingParens = 0; - state.maxBackReference = 0; - state.groupNames.length = 0; - state.backReferenceNames.length = 0; - - this.regexp_disjunction(state); - - if (state.pos !== state.source.length) { - // Make the same messages as V8. - if (state.eat(0x29 /* ) */)) { - state.raise("Unmatched ')'"); - } - if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { - state.raise("Lone quantifier brackets"); - } - } - if (state.maxBackReference > state.numCapturingParens) { - state.raise("Invalid escape"); - } - for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { - var name = list[i]; - - if (state.groupNames.indexOf(name) === -1) { - state.raise("Invalid named capture referenced"); - } - } -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction -pp$8.regexp_disjunction = function(state) { - this.regexp_alternative(state); - while (state.eat(0x7C /* | */)) { - this.regexp_alternative(state); - } - - // Make the same message as V8. - if (this.regexp_eatQuantifier(state, true)) { - state.raise("Nothing to repeat"); - } - if (state.eat(0x7B /* { */)) { - state.raise("Lone quantifier brackets"); - } -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative -pp$8.regexp_alternative = function(state) { - while (state.pos < state.source.length && this.regexp_eatTerm(state)) - { } -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term -pp$8.regexp_eatTerm = function(state) { - if (this.regexp_eatAssertion(state)) { - // Handle `QuantifiableAssertion Quantifier` alternative. - // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion - // is a QuantifiableAssertion. - if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { - // Make the same message as V8. - if (state.switchU) { - state.raise("Invalid quantifier"); - } - } - return true - } - - if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { - this.regexp_eatQuantifier(state); - return true - } - - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion -pp$8.regexp_eatAssertion = function(state) { - var start = state.pos; - state.lastAssertionIsQuantifiable = false; - - // ^, $ - if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { - return true - } - - // \b \B - if (state.eat(0x5C /* \ */)) { - if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { - return true - } - state.pos = start; - } - - // Lookahead / Lookbehind - if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { - var lookbehind = false; - if (this.options.ecmaVersion >= 9) { - lookbehind = state.eat(0x3C /* < */); - } - if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { - this.regexp_disjunction(state); - if (!state.eat(0x29 /* ) */)) { - state.raise("Unterminated group"); - } - state.lastAssertionIsQuantifiable = !lookbehind; - return true - } - } - - state.pos = start; - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier -pp$8.regexp_eatQuantifier = function(state, noError) { - if ( noError === void 0 ) noError = false; - - if (this.regexp_eatQuantifierPrefix(state, noError)) { - state.eat(0x3F /* ? */); - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix -pp$8.regexp_eatQuantifierPrefix = function(state, noError) { - return ( - state.eat(0x2A /* * */) || - state.eat(0x2B /* + */) || - state.eat(0x3F /* ? */) || - this.regexp_eatBracedQuantifier(state, noError) - ) -}; -pp$8.regexp_eatBracedQuantifier = function(state, noError) { - var start = state.pos; - if (state.eat(0x7B /* { */)) { - var min = 0, max = -1; - if (this.regexp_eatDecimalDigits(state)) { - min = state.lastIntValue; - if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { - max = state.lastIntValue; - } - if (state.eat(0x7D /* } */)) { - // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term - if (max !== -1 && max < min && !noError) { - state.raise("numbers out of order in {} quantifier"); - } - return true - } - } - if (state.switchU && !noError) { - state.raise("Incomplete quantifier"); - } - state.pos = start; - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom -pp$8.regexp_eatAtom = function(state) { - return ( - this.regexp_eatPatternCharacters(state) || - state.eat(0x2E /* . */) || - this.regexp_eatReverseSolidusAtomEscape(state) || - this.regexp_eatCharacterClass(state) || - this.regexp_eatUncapturingGroup(state) || - this.regexp_eatCapturingGroup(state) - ) -}; -pp$8.regexp_eatReverseSolidusAtomEscape = function(state) { - var start = state.pos; - if (state.eat(0x5C /* \ */)) { - if (this.regexp_eatAtomEscape(state)) { - return true - } - state.pos = start; - } - return false -}; -pp$8.regexp_eatUncapturingGroup = function(state) { - var start = state.pos; - if (state.eat(0x28 /* ( */)) { - if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { - this.regexp_disjunction(state); - if (state.eat(0x29 /* ) */)) { - return true - } - state.raise("Unterminated group"); - } - state.pos = start; - } - return false -}; -pp$8.regexp_eatCapturingGroup = function(state) { - if (state.eat(0x28 /* ( */)) { - if (this.options.ecmaVersion >= 9) { - this.regexp_groupSpecifier(state); - } else if (state.current() === 0x3F /* ? */) { - state.raise("Invalid group"); - } - this.regexp_disjunction(state); - if (state.eat(0x29 /* ) */)) { - state.numCapturingParens += 1; - return true - } - state.raise("Unterminated group"); - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom -pp$8.regexp_eatExtendedAtom = function(state) { - return ( - state.eat(0x2E /* . */) || - this.regexp_eatReverseSolidusAtomEscape(state) || - this.regexp_eatCharacterClass(state) || - this.regexp_eatUncapturingGroup(state) || - this.regexp_eatCapturingGroup(state) || - this.regexp_eatInvalidBracedQuantifier(state) || - this.regexp_eatExtendedPatternCharacter(state) - ) -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier -pp$8.regexp_eatInvalidBracedQuantifier = function(state) { - if (this.regexp_eatBracedQuantifier(state, true)) { - state.raise("Nothing to repeat"); - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter -pp$8.regexp_eatSyntaxCharacter = function(state) { - var ch = state.current(); - if (isSyntaxCharacter(ch)) { - state.lastIntValue = ch; - state.advance(); - return true - } - return false -}; -function isSyntaxCharacter(ch) { - return ( - ch === 0x24 /* $ */ || - ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || - ch === 0x2E /* . */ || - ch === 0x3F /* ? */ || - ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || - ch >= 0x7B /* { */ && ch <= 0x7D /* } */ - ) -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter -// But eat eager. -pp$8.regexp_eatPatternCharacters = function(state) { - var start = state.pos; - var ch = 0; - while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { - state.advance(); - } - return state.pos !== start -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter -pp$8.regexp_eatExtendedPatternCharacter = function(state) { - var ch = state.current(); - if ( - ch !== -1 && - ch !== 0x24 /* $ */ && - !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && - ch !== 0x2E /* . */ && - ch !== 0x3F /* ? */ && - ch !== 0x5B /* [ */ && - ch !== 0x5E /* ^ */ && - ch !== 0x7C /* | */ - ) { - state.advance(); - return true - } - return false -}; - -// GroupSpecifier :: -// [empty] -// `?` GroupName -pp$8.regexp_groupSpecifier = function(state) { - if (state.eat(0x3F /* ? */)) { - if (this.regexp_eatGroupName(state)) { - if (state.groupNames.indexOf(state.lastStringValue) !== -1) { - state.raise("Duplicate capture group name"); - } - state.groupNames.push(state.lastStringValue); - return - } - state.raise("Invalid group"); - } -}; - -// GroupName :: -// `<` RegExpIdentifierName `>` -// Note: this updates `state.lastStringValue` property with the eaten name. -pp$8.regexp_eatGroupName = function(state) { - state.lastStringValue = ""; - if (state.eat(0x3C /* < */)) { - if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { - return true - } - state.raise("Invalid capture group name"); - } - return false -}; - -// RegExpIdentifierName :: -// RegExpIdentifierStart -// RegExpIdentifierName RegExpIdentifierPart -// Note: this updates `state.lastStringValue` property with the eaten name. -pp$8.regexp_eatRegExpIdentifierName = function(state) { - state.lastStringValue = ""; - if (this.regexp_eatRegExpIdentifierStart(state)) { - state.lastStringValue += codePointToString(state.lastIntValue); - while (this.regexp_eatRegExpIdentifierPart(state)) { - state.lastStringValue += codePointToString(state.lastIntValue); - } - return true - } - return false -}; - -// RegExpIdentifierStart :: -// UnicodeIDStart -// `$` -// `_` -// `\` RegExpUnicodeEscapeSequence[+U] -pp$8.regexp_eatRegExpIdentifierStart = function(state) { - var start = state.pos; - var forceU = this.options.ecmaVersion >= 11; - var ch = state.current(forceU); - state.advance(forceU); - - if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { - ch = state.lastIntValue; - } - if (isRegExpIdentifierStart(ch)) { - state.lastIntValue = ch; - return true - } - - state.pos = start; - return false -}; -function isRegExpIdentifierStart(ch) { - return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ -} - -// RegExpIdentifierPart :: -// UnicodeIDContinue -// `$` -// `_` -// `\` RegExpUnicodeEscapeSequence[+U] -// -// -pp$8.regexp_eatRegExpIdentifierPart = function(state) { - var start = state.pos; - var forceU = this.options.ecmaVersion >= 11; - var ch = state.current(forceU); - state.advance(forceU); - - if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { - ch = state.lastIntValue; - } - if (isRegExpIdentifierPart(ch)) { - state.lastIntValue = ch; - return true - } - - state.pos = start; - return false -}; -function isRegExpIdentifierPart(ch) { - return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape -pp$8.regexp_eatAtomEscape = function(state) { - if ( - this.regexp_eatBackReference(state) || - this.regexp_eatCharacterClassEscape(state) || - this.regexp_eatCharacterEscape(state) || - (state.switchN && this.regexp_eatKGroupName(state)) - ) { - return true - } - if (state.switchU) { - // Make the same message as V8. - if (state.current() === 0x63 /* c */) { - state.raise("Invalid unicode escape"); - } - state.raise("Invalid escape"); - } - return false -}; -pp$8.regexp_eatBackReference = function(state) { - var start = state.pos; - if (this.regexp_eatDecimalEscape(state)) { - var n = state.lastIntValue; - if (state.switchU) { - // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape - if (n > state.maxBackReference) { - state.maxBackReference = n; - } - return true - } - if (n <= state.numCapturingParens) { - return true - } - state.pos = start; - } - return false -}; -pp$8.regexp_eatKGroupName = function(state) { - if (state.eat(0x6B /* k */)) { - if (this.regexp_eatGroupName(state)) { - state.backReferenceNames.push(state.lastStringValue); - return true - } - state.raise("Invalid named reference"); - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape -pp$8.regexp_eatCharacterEscape = function(state) { - return ( - this.regexp_eatControlEscape(state) || - this.regexp_eatCControlLetter(state) || - this.regexp_eatZero(state) || - this.regexp_eatHexEscapeSequence(state) || - this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || - (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || - this.regexp_eatIdentityEscape(state) - ) -}; -pp$8.regexp_eatCControlLetter = function(state) { - var start = state.pos; - if (state.eat(0x63 /* c */)) { - if (this.regexp_eatControlLetter(state)) { - return true - } - state.pos = start; - } - return false -}; -pp$8.regexp_eatZero = function(state) { - if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { - state.lastIntValue = 0; - state.advance(); - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape -pp$8.regexp_eatControlEscape = function(state) { - var ch = state.current(); - if (ch === 0x74 /* t */) { - state.lastIntValue = 0x09; /* \t */ - state.advance(); - return true - } - if (ch === 0x6E /* n */) { - state.lastIntValue = 0x0A; /* \n */ - state.advance(); - return true - } - if (ch === 0x76 /* v */) { - state.lastIntValue = 0x0B; /* \v */ - state.advance(); - return true - } - if (ch === 0x66 /* f */) { - state.lastIntValue = 0x0C; /* \f */ - state.advance(); - return true - } - if (ch === 0x72 /* r */) { - state.lastIntValue = 0x0D; /* \r */ - state.advance(); - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter -pp$8.regexp_eatControlLetter = function(state) { - var ch = state.current(); - if (isControlLetter(ch)) { - state.lastIntValue = ch % 0x20; - state.advance(); - return true - } - return false -}; -function isControlLetter(ch) { - return ( - (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || - (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) - ) -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence -pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { - if ( forceU === void 0 ) forceU = false; - - var start = state.pos; - var switchU = forceU || state.switchU; - - if (state.eat(0x75 /* u */)) { - if (this.regexp_eatFixedHexDigits(state, 4)) { - var lead = state.lastIntValue; - if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { - var leadSurrogateEnd = state.pos; - if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { - var trail = state.lastIntValue; - if (trail >= 0xDC00 && trail <= 0xDFFF) { - state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; - return true - } - } - state.pos = leadSurrogateEnd; - state.lastIntValue = lead; - } - return true - } - if ( - switchU && - state.eat(0x7B /* { */) && - this.regexp_eatHexDigits(state) && - state.eat(0x7D /* } */) && - isValidUnicode(state.lastIntValue) - ) { - return true - } - if (switchU) { - state.raise("Invalid unicode escape"); - } - state.pos = start; - } - - return false -}; -function isValidUnicode(ch) { - return ch >= 0 && ch <= 0x10FFFF -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape -pp$8.regexp_eatIdentityEscape = function(state) { - if (state.switchU) { - if (this.regexp_eatSyntaxCharacter(state)) { - return true - } - if (state.eat(0x2F /* / */)) { - state.lastIntValue = 0x2F; /* / */ - return true - } - return false - } - - var ch = state.current(); - if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { - state.lastIntValue = ch; - state.advance(); - return true - } - - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape -pp$8.regexp_eatDecimalEscape = function(state) { - state.lastIntValue = 0; - var ch = state.current(); - if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { - do { - state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); - state.advance(); - } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape -pp$8.regexp_eatCharacterClassEscape = function(state) { - var ch = state.current(); - - if (isCharacterClassEscape(ch)) { - state.lastIntValue = -1; - state.advance(); - return true - } - - if ( - state.switchU && - this.options.ecmaVersion >= 9 && - (ch === 0x50 /* P */ || ch === 0x70 /* p */) - ) { - state.lastIntValue = -1; - state.advance(); - if ( - state.eat(0x7B /* { */) && - this.regexp_eatUnicodePropertyValueExpression(state) && - state.eat(0x7D /* } */) - ) { - return true - } - state.raise("Invalid property name"); - } - - return false -}; -function isCharacterClassEscape(ch) { - return ( - ch === 0x64 /* d */ || - ch === 0x44 /* D */ || - ch === 0x73 /* s */ || - ch === 0x53 /* S */ || - ch === 0x77 /* w */ || - ch === 0x57 /* W */ - ) -} - -// UnicodePropertyValueExpression :: -// UnicodePropertyName `=` UnicodePropertyValue -// LoneUnicodePropertyNameOrValue -pp$8.regexp_eatUnicodePropertyValueExpression = function(state) { - var start = state.pos; - - // UnicodePropertyName `=` UnicodePropertyValue - if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { - var name = state.lastStringValue; - if (this.regexp_eatUnicodePropertyValue(state)) { - var value = state.lastStringValue; - this.regexp_validateUnicodePropertyNameAndValue(state, name, value); - return true - } - } - state.pos = start; - - // LoneUnicodePropertyNameOrValue - if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { - var nameOrValue = state.lastStringValue; - this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); - return true - } - return false -}; -pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { - if (!has$1(state.unicodeProperties.nonBinary, name)) - { state.raise("Invalid property name"); } - if (!state.unicodeProperties.nonBinary[name].test(value)) - { state.raise("Invalid property value"); } -}; -pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { - if (!state.unicodeProperties.binary.test(nameOrValue)) - { state.raise("Invalid property name"); } -}; - -// UnicodePropertyName :: -// UnicodePropertyNameCharacters -pp$8.regexp_eatUnicodePropertyName = function(state) { - var ch = 0; - state.lastStringValue = ""; - while (isUnicodePropertyNameCharacter(ch = state.current())) { - state.lastStringValue += codePointToString(ch); - state.advance(); - } - return state.lastStringValue !== "" -}; -function isUnicodePropertyNameCharacter(ch) { - return isControlLetter(ch) || ch === 0x5F /* _ */ -} - -// UnicodePropertyValue :: -// UnicodePropertyValueCharacters -pp$8.regexp_eatUnicodePropertyValue = function(state) { - var ch = 0; - state.lastStringValue = ""; - while (isUnicodePropertyValueCharacter(ch = state.current())) { - state.lastStringValue += codePointToString(ch); - state.advance(); - } - return state.lastStringValue !== "" -}; -function isUnicodePropertyValueCharacter(ch) { - return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) -} - -// LoneUnicodePropertyNameOrValue :: -// UnicodePropertyValueCharacters -pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { - return this.regexp_eatUnicodePropertyValue(state) -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass -pp$8.regexp_eatCharacterClass = function(state) { - if (state.eat(0x5B /* [ */)) { - state.eat(0x5E /* ^ */); - this.regexp_classRanges(state); - if (state.eat(0x5D /* ] */)) { - return true - } - // Unreachable since it threw "unterminated regular expression" error before. - state.raise("Unterminated character class"); - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges -// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges -// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash -pp$8.regexp_classRanges = function(state) { - while (this.regexp_eatClassAtom(state)) { - var left = state.lastIntValue; - if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { - var right = state.lastIntValue; - if (state.switchU && (left === -1 || right === -1)) { - state.raise("Invalid character class"); - } - if (left !== -1 && right !== -1 && left > right) { - state.raise("Range out of order in character class"); - } - } - } -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom -// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash -pp$8.regexp_eatClassAtom = function(state) { - var start = state.pos; - - if (state.eat(0x5C /* \ */)) { - if (this.regexp_eatClassEscape(state)) { - return true - } - if (state.switchU) { - // Make the same message as V8. - var ch$1 = state.current(); - if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { - state.raise("Invalid class escape"); - } - state.raise("Invalid escape"); - } - state.pos = start; - } - - var ch = state.current(); - if (ch !== 0x5D /* ] */) { - state.lastIntValue = ch; - state.advance(); - return true - } - - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape -pp$8.regexp_eatClassEscape = function(state) { - var start = state.pos; - - if (state.eat(0x62 /* b */)) { - state.lastIntValue = 0x08; /* */ - return true - } - - if (state.switchU && state.eat(0x2D /* - */)) { - state.lastIntValue = 0x2D; /* - */ - return true - } - - if (!state.switchU && state.eat(0x63 /* c */)) { - if (this.regexp_eatClassControlLetter(state)) { - return true - } - state.pos = start; - } - - return ( - this.regexp_eatCharacterClassEscape(state) || - this.regexp_eatCharacterEscape(state) - ) -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter -pp$8.regexp_eatClassControlLetter = function(state) { - var ch = state.current(); - if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { - state.lastIntValue = ch % 0x20; - state.advance(); - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence -pp$8.regexp_eatHexEscapeSequence = function(state) { - var start = state.pos; - if (state.eat(0x78 /* x */)) { - if (this.regexp_eatFixedHexDigits(state, 2)) { - return true - } - if (state.switchU) { - state.raise("Invalid escape"); - } - state.pos = start; - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits -pp$8.regexp_eatDecimalDigits = function(state) { - var start = state.pos; - var ch = 0; - state.lastIntValue = 0; - while (isDecimalDigit(ch = state.current())) { - state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); - state.advance(); - } - return state.pos !== start -}; -function isDecimalDigit(ch) { - return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits -pp$8.regexp_eatHexDigits = function(state) { - var start = state.pos; - var ch = 0; - state.lastIntValue = 0; - while (isHexDigit(ch = state.current())) { - state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); - state.advance(); - } - return state.pos !== start -}; -function isHexDigit(ch) { - return ( - (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || - (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || - (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) - ) -} -function hexToInt(ch) { - if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { - return 10 + (ch - 0x41 /* A */) - } - if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { - return 10 + (ch - 0x61 /* a */) - } - return ch - 0x30 /* 0 */ -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence -// Allows only 0-377(octal) i.e. 0-255(decimal). -pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) { - if (this.regexp_eatOctalDigit(state)) { - var n1 = state.lastIntValue; - if (this.regexp_eatOctalDigit(state)) { - var n2 = state.lastIntValue; - if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { - state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; - } else { - state.lastIntValue = n1 * 8 + n2; - } - } else { - state.lastIntValue = n1; - } - return true - } - return false -}; - -// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit -pp$8.regexp_eatOctalDigit = function(state) { - var ch = state.current(); - if (isOctalDigit(ch)) { - state.lastIntValue = ch - 0x30; /* 0 */ - state.advance(); - return true - } - state.lastIntValue = 0; - return false -}; -function isOctalDigit(ch) { - return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ -} - -// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits -// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit -// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence -pp$8.regexp_eatFixedHexDigits = function(state, length) { - var start = state.pos; - state.lastIntValue = 0; - for (var i = 0; i < length; ++i) { - var ch = state.current(); - if (!isHexDigit(ch)) { - state.pos = start; - return false - } - state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); - state.advance(); - } - return true -}; - -// Object type used to represent tokens. Note that normally, tokens -// simply exist as properties on the parser object. This is only -// used for the onToken callback and the external tokenizer. - -var Token = function Token(p) { - this.type = p.type; - this.value = p.value; - this.start = p.start; - this.end = p.end; - if (p.options.locations) - { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } - if (p.options.ranges) - { this.range = [p.start, p.end]; } -}; - -// ## Tokenizer - -var pp$9 = Parser.prototype; - -// Move to the next token - -pp$9.next = function(ignoreEscapeSequenceInKeyword) { - if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) - { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } - if (this.options.onToken) - { this.options.onToken(new Token(this)); } - - this.lastTokEnd = this.end; - this.lastTokStart = this.start; - this.lastTokEndLoc = this.endLoc; - this.lastTokStartLoc = this.startLoc; - this.nextToken(); -}; - -pp$9.getToken = function() { - this.next(); - return new Token(this) -}; - -// If we're in an ES6 environment, make parsers iterable -if (typeof Symbol !== "undefined") - { pp$9[Symbol.iterator] = function() { - var this$1 = this; - - return { - next: function () { - var token = this$1.getToken(); - return { - done: token.type === types.eof, - value: token - } - } - } - }; } - -// Toggle strict mode. Re-reads the next number or string to please -// pedantic tests (`"use strict"; 010;` should fail). - -pp$9.curContext = function() { - return this.context[this.context.length - 1] -}; - -// Read a single token, updating the parser object's token-related -// properties. - -pp$9.nextToken = function() { - var curContext = this.curContext(); - if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } - - this.start = this.pos; - if (this.options.locations) { this.startLoc = this.curPosition(); } - if (this.pos >= this.input.length) { return this.finishToken(types.eof) } - - if (curContext.override) { return curContext.override(this) } - else { this.readToken(this.fullCharCodeAtPos()); } -}; - -pp$9.readToken = function(code) { - // Identifier or keyword. '\uXXXX' sequences are allowed in - // identifiers, so '\' also dispatches to that. - if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) - { return this.readWord() } - - return this.getTokenFromCode(code) -}; - -pp$9.fullCharCodeAtPos = function() { - var code = this.input.charCodeAt(this.pos); - if (code <= 0xd7ff || code >= 0xe000) { return code } - var next = this.input.charCodeAt(this.pos + 1); - return (code << 10) + next - 0x35fdc00 -}; - -pp$9.skipBlockComment = function() { - var startLoc = this.options.onComment && this.curPosition(); - var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); - if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } - this.pos = end + 2; - if (this.options.locations) { - lineBreakG.lastIndex = start; - var match; - while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { - ++this.curLine; - this.lineStart = match.index + match[0].length; - } - } - if (this.options.onComment) - { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, - startLoc, this.curPosition()); } -}; - -pp$9.skipLineComment = function(startSkip) { - var start = this.pos; - var startLoc = this.options.onComment && this.curPosition(); - var ch = this.input.charCodeAt(this.pos += startSkip); - while (this.pos < this.input.length && !isNewLine(ch)) { - ch = this.input.charCodeAt(++this.pos); - } - if (this.options.onComment) - { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, - startLoc, this.curPosition()); } -}; - -// Called at the start of the parse and after every token. Skips -// whitespace and comments, and. - -pp$9.skipSpace = function() { - loop: while (this.pos < this.input.length) { - var ch = this.input.charCodeAt(this.pos); - switch (ch) { - case 32: case 160: // ' ' - ++this.pos; - break - case 13: - if (this.input.charCodeAt(this.pos + 1) === 10) { - ++this.pos; - } - case 10: case 8232: case 8233: - ++this.pos; - if (this.options.locations) { - ++this.curLine; - this.lineStart = this.pos; - } - break - case 47: // '/' - switch (this.input.charCodeAt(this.pos + 1)) { - case 42: // '*' - this.skipBlockComment(); - break - case 47: - this.skipLineComment(2); - break - default: - break loop - } - break - default: - if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++this.pos; - } else { - break loop - } - } - } -}; - -// Called at the end of every token. Sets `end`, `val`, and -// maintains `context` and `exprAllowed`, and skips the space after -// the token, so that the next one's `start` will point at the -// right position. - -pp$9.finishToken = function(type, val) { - this.end = this.pos; - if (this.options.locations) { this.endLoc = this.curPosition(); } - var prevType = this.type; - this.type = type; - this.value = val; - - this.updateContext(prevType); -}; - -// ### Token reading - -// This is the function that is called to fetch the next token. It -// is somewhat obscure, because it works in character codes rather -// than characters, and because operator parsing has been inlined -// into it. -// -// All in the name of speed. -// -pp$9.readToken_dot = function() { - var next = this.input.charCodeAt(this.pos + 1); - if (next >= 48 && next <= 57) { return this.readNumber(true) } - var next2 = this.input.charCodeAt(this.pos + 2); - if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' - this.pos += 3; - return this.finishToken(types.ellipsis) - } else { - ++this.pos; - return this.finishToken(types.dot) - } -}; - -pp$9.readToken_slash = function() { // '/' - var next = this.input.charCodeAt(this.pos + 1); - if (this.exprAllowed) { ++this.pos; return this.readRegexp() } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.slash, 1) -}; - -pp$9.readToken_mult_modulo_exp = function(code) { // '%*' - var next = this.input.charCodeAt(this.pos + 1); - var size = 1; - var tokentype = code === 42 ? types.star : types.modulo; - - // exponentiation operator ** and **= - if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { - ++size; - tokentype = types.starstar; - next = this.input.charCodeAt(this.pos + 2); - } - - if (next === 61) { return this.finishOp(types.assign, size + 1) } - return this.finishOp(tokentype, size) -}; - -pp$9.readToken_pipe_amp = function(code) { // '|&' - var next = this.input.charCodeAt(this.pos + 1); - if (next === code) { - if (this.options.ecmaVersion >= 12) { - var next2 = this.input.charCodeAt(this.pos + 2); - if (next2 === 61) { return this.finishOp(types.assign, 3) } - } - return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) - } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) -}; - -pp$9.readToken_caret = function() { // '^' - var next = this.input.charCodeAt(this.pos + 1); - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.bitwiseXOR, 1) -}; - -pp$9.readToken_plus_min = function(code) { // '+-' - var next = this.input.charCodeAt(this.pos + 1); - if (next === code) { - if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && - (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { - // A `-->` line comment - this.skipLineComment(3); - this.skipSpace(); - return this.nextToken() - } - return this.finishOp(types.incDec, 2) - } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.plusMin, 1) -}; - -pp$9.readToken_lt_gt = function(code) { // '<>' - var next = this.input.charCodeAt(this.pos + 1); - var size = 1; - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; - if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } - return this.finishOp(types.bitShift, size) - } - if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && - this.input.charCodeAt(this.pos + 3) === 45) { - // `` line comment - this.skipLineComment(3); - this.skipSpace(); - return this.nextToken() - } - return this.finishOp(types.incDec, 2) - } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.plusMin, 1) - }; - - pp$9.readToken_lt_gt = function(code) { // '<>' - var next = this.input.charCodeAt(this.pos + 1); - var size = 1; - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; - if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } - return this.finishOp(types.bitShift, size) - } - if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && - this.input.charCodeAt(this.pos + 3) === 45) { - // `|close frame|-->|ws.close()|- - - - * | +----------+ +-----------+ +----------+ | - * +----------+ +-----------+ | - * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING - * +----------+ +-----------+ | - * | | | +---+ | - * +------------------------+-->|fin| - - - - - * | +---+ | +---+ - * - - - - -|fin|<---------------------+ - * +---+ - * - * @param {Number} [code] Status code explaining why the connection is closing - * @param {String} [data] A string explaining why the connection is closing - * @public - */ - close(code, data) { - if (this.readyState === WebSocket.CLOSED) return; - if (this.readyState === WebSocket.CONNECTING) { - const msg = 'WebSocket was closed before the connection was established'; - return abortHandshake$1(this, this._req, msg); - } - - if (this.readyState === WebSocket.CLOSING) { - if (this._closeFrameSent && this._closeFrameReceived) this._socket.end(); - return; - } - - this._readyState = WebSocket.CLOSING; - this._sender.close(code, data, !this._isServer, (err) => { - // - // This error is handled by the `'error'` listener on the socket. We only - // want to know if the close frame has been sent here. - // - if (err) return; - - this._closeFrameSent = true; - if (this._closeFrameReceived) this._socket.end(); - }); - - // - // Specify a timeout for the closing handshake to complete. - // - this._closeTimer = setTimeout( - this._socket.destroy.bind(this._socket), - closeTimeout - ); - } - - /** - * Send a ping. - * - * @param {*} [data] The data to send - * @param {Boolean} [mask] Indicates whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when the ping is sent - * @public - */ - ping(data, mask, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - - if (typeof data === 'function') { - cb = data; - data = mask = undefined; - } else if (typeof mask === 'function') { - cb = mask; - mask = undefined; - } - - if (typeof data === 'number') data = data.toString(); - - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - - if (mask === undefined) mask = !this._isServer; - this._sender.ping(data || EMPTY_BUFFER, mask, cb); - } - - /** - * Send a pong. - * - * @param {*} [data] The data to send - * @param {Boolean} [mask] Indicates whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when the pong is sent - * @public - */ - pong(data, mask, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - - if (typeof data === 'function') { - cb = data; - data = mask = undefined; - } else if (typeof mask === 'function') { - cb = mask; - mask = undefined; - } - - if (typeof data === 'number') data = data.toString(); - - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - - if (mask === undefined) mask = !this._isServer; - this._sender.pong(data || EMPTY_BUFFER, mask, cb); - } - - /** - * Send a data message. - * - * @param {*} data The message to send - * @param {Object} [options] Options object - * @param {Boolean} [options.compress] Specifies whether or not to compress - * `data` - * @param {Boolean} [options.binary] Specifies whether `data` is binary or - * text - * @param {Boolean} [options.fin=true] Specifies whether the fragment is the - * last one - * @param {Boolean} [options.mask] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when data is written out - * @public - */ - send(data, options, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - - if (typeof options === 'function') { - cb = options; - options = {}; - } - - if (typeof data === 'number') data = data.toString(); - - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - - const opts = { - binary: typeof data !== 'string', - mask: !this._isServer, - compress: true, - fin: true, - ...options - }; - - if (!this._extensions[permessageDeflate.extensionName]) { - opts.compress = false; - } - - this._sender.send(data || EMPTY_BUFFER, opts, cb); - } - - /** - * Forcibly close the connection. - * - * @public - */ - terminate() { - if (this.readyState === WebSocket.CLOSED) return; - if (this.readyState === WebSocket.CONNECTING) { - const msg = 'WebSocket was closed before the connection was established'; - return abortHandshake$1(this, this._req, msg); - } - - if (this._socket) { - this._readyState = WebSocket.CLOSING; - this._socket.destroy(); - } - } -} - -readyStates.forEach((readyState, i) => { - const descriptor = { enumerable: true, value: i }; - - Object.defineProperty(WebSocket.prototype, readyState, descriptor); - Object.defineProperty(WebSocket, readyState, descriptor); -}); - -[ - 'binaryType', - 'bufferedAmount', - 'extensions', - 'protocol', - 'readyState', - 'url' -].forEach((property) => { - Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); -}); - -// -// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. -// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface -// -['open', 'error', 'close', 'message'].forEach((method) => { - Object.defineProperty(WebSocket.prototype, `on${method}`, { - configurable: true, - enumerable: true, - /** - * Return the listener of the event. - * - * @return {(Function|undefined)} The event listener or `undefined` - * @public - */ - get() { - const listeners = this.listeners(method); - for (let i = 0; i < listeners.length; i++) { - if (listeners[i]._listener) return listeners[i]._listener; - } - - return undefined; - }, - /** - * Add a listener for the event. - * - * @param {Function} listener The listener to add - * @public - */ - set(listener) { - const listeners = this.listeners(method); - for (let i = 0; i < listeners.length; i++) { - // - // Remove only the listeners added via `addEventListener`. - // - if (listeners[i]._listener) this.removeListener(method, listeners[i]); - } - this.addEventListener(method, listener); - } - }); -}); - -WebSocket.prototype.addEventListener = addEventListener; -WebSocket.prototype.removeEventListener = removeEventListener; - -var websocket = WebSocket; - -/** - * Initialize a WebSocket client. - * - * @param {WebSocket} websocket The client to initialize - * @param {(String|url.URL)} address The URL to which to connect - * @param {String} [protocols] The subprotocols - * @param {Object} [options] Connection options - * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable - * permessage-deflate - * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the - * handshake request - * @param {Number} [options.protocolVersion=13] Value of the - * `Sec-WebSocket-Version` header - * @param {String} [options.origin] Value of the `Origin` or - * `Sec-WebSocket-Origin` header - * @param {Number} [options.maxPayload=104857600] The maximum allowed message - * size - * @param {Boolean} [options.followRedirects=false] Whether or not to follow - * redirects - * @param {Number} [options.maxRedirects=10] The maximum number of redirects - * allowed - * @private - */ -function initAsClient(websocket, address, protocols, options) { - const opts = { - protocolVersion: protocolVersions[1], - maxPayload: 100 * 1024 * 1024, - perMessageDeflate: true, - followRedirects: false, - maxRedirects: 10, - ...options, - createConnection: undefined, - socketPath: undefined, - hostname: undefined, - protocol: undefined, - timeout: undefined, - method: undefined, - host: undefined, - path: undefined, - port: undefined - }; - - if (!protocolVersions.includes(opts.protocolVersion)) { - throw new RangeError( - `Unsupported protocol version: ${opts.protocolVersion} ` + - `(supported versions: ${protocolVersions.join(', ')})` - ); - } - - let parsedUrl; - - if (address instanceof URL$2) { - parsedUrl = address; - websocket._url = address.href; - } else { - parsedUrl = new URL$2(address); - websocket._url = address; - } - - const isUnixSocket = parsedUrl.protocol === 'ws+unix:'; - - if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) { - throw new Error(`Invalid URL: ${websocket.url}`); - } - - const isSecure = - parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:'; - const defaultPort = isSecure ? 443 : 80; - const key = randomBytes(16).toString('base64'); - const get = isSecure ? https__default.get : http__default.get; - let perMessageDeflate; - - opts.createConnection = isSecure ? tlsConnect : netConnect; - opts.defaultPort = opts.defaultPort || defaultPort; - opts.port = parsedUrl.port || defaultPort; - opts.host = parsedUrl.hostname.startsWith('[') - ? parsedUrl.hostname.slice(1, -1) - : parsedUrl.hostname; - opts.headers = { - 'Sec-WebSocket-Version': opts.protocolVersion, - 'Sec-WebSocket-Key': key, - Connection: 'Upgrade', - Upgrade: 'websocket', - ...opts.headers - }; - opts.path = parsedUrl.pathname + parsedUrl.search; - opts.timeout = opts.handshakeTimeout; - - if (opts.perMessageDeflate) { - perMessageDeflate = new permessageDeflate( - opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, - false, - opts.maxPayload - ); - opts.headers['Sec-WebSocket-Extensions'] = format$1({ - [permessageDeflate.extensionName]: perMessageDeflate.offer() - }); - } - if (protocols) { - opts.headers['Sec-WebSocket-Protocol'] = protocols; - } - if (opts.origin) { - if (opts.protocolVersion < 13) { - opts.headers['Sec-WebSocket-Origin'] = opts.origin; - } else { - opts.headers.Origin = opts.origin; - } - } - if (parsedUrl.username || parsedUrl.password) { - opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; - } - - if (isUnixSocket) { - const parts = opts.path.split(':'); - - opts.socketPath = parts[0]; - opts.path = parts[1]; - } - - let req = (websocket._req = get(opts)); - - if (opts.timeout) { - req.on('timeout', () => { - abortHandshake$1(websocket, req, 'Opening handshake has timed out'); - }); - } - - req.on('error', (err) => { - if (req === null || req.aborted) return; - - req = websocket._req = null; - websocket._readyState = WebSocket.CLOSING; - websocket.emit('error', err); - websocket.emitClose(); - }); - - req.on('response', (res) => { - const location = res.headers.location; - const statusCode = res.statusCode; - - if ( - location && - opts.followRedirects && - statusCode >= 300 && - statusCode < 400 - ) { - if (++websocket._redirects > opts.maxRedirects) { - abortHandshake$1(websocket, req, 'Maximum redirects exceeded'); - return; - } - - req.abort(); - - const addr = new URL$2(location, address); - - initAsClient(websocket, addr, protocols, options); - } else if (!websocket.emit('unexpected-response', req, res)) { - abortHandshake$1( - websocket, - req, - `Unexpected server response: ${res.statusCode}` - ); - } - }); - - req.on('upgrade', (res, socket, head) => { - websocket.emit('upgrade', res); - - // - // The user may have closed the connection from a listener of the `upgrade` - // event. - // - if (websocket.readyState !== WebSocket.CONNECTING) return; - - req = websocket._req = null; - - const digest = createHash$1('sha1') - .update(key + GUID$1) - .digest('base64'); - - if (res.headers['sec-websocket-accept'] !== digest) { - abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); - return; - } - - const serverProt = res.headers['sec-websocket-protocol']; - const protList = (protocols || '').split(/, */); - let protError; - - if (!protocols && serverProt) { - protError = 'Server sent a subprotocol but none was requested'; - } else if (protocols && !serverProt) { - protError = 'Server sent no subprotocol'; - } else if (serverProt && !protList.includes(serverProt)) { - protError = 'Server sent an invalid subprotocol'; - } - - if (protError) { - abortHandshake$1(websocket, socket, protError); - return; - } - - if (serverProt) websocket._protocol = serverProt; - - if (perMessageDeflate) { - try { - const extensions = parse$4(res.headers['sec-websocket-extensions']); - - if (extensions[permessageDeflate.extensionName]) { - perMessageDeflate.accept(extensions[permessageDeflate.extensionName]); - websocket._extensions[ - permessageDeflate.extensionName - ] = perMessageDeflate; - } - } catch (err) { - abortHandshake$1( - websocket, - socket, - 'Invalid Sec-WebSocket-Extensions header' - ); - return; - } - } - - websocket.setSocket(socket, head, opts.maxPayload); - }); -} - -/** - * Create a `net.Socket` and initiate a connection. - * - * @param {Object} options Connection options - * @return {net.Socket} The newly created socket used to start the connection - * @private - */ -function netConnect(options) { - options.path = options.socketPath; - return require$$2__default.connect(options); -} - -/** - * Create a `tls.TLSSocket` and initiate a connection. - * - * @param {Object} options Connection options - * @return {tls.TLSSocket} The newly created socket used to start the connection - * @private - */ -function tlsConnect(options) { - options.path = undefined; - - if (!options.servername && options.servername !== '') { - options.servername = require$$2__default.isIP(options.host) ? '' : options.host; - } - - return tls__default.connect(options); -} - -/** - * Abort the handshake and emit an error. - * - * @param {WebSocket} websocket The WebSocket instance - * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the - * socket to destroy - * @param {String} message The error message - * @private - */ -function abortHandshake$1(websocket, stream, message) { - websocket._readyState = WebSocket.CLOSING; - - const err = new Error(message); - Error.captureStackTrace(err, abortHandshake$1); - - if (stream.setHeader) { - stream.abort(); - stream.once('abort', websocket.emitClose.bind(websocket)); - websocket.emit('error', err); - } else { - stream.destroy(err); - stream.once('error', websocket.emit.bind(websocket, 'error')); - stream.once('close', websocket.emitClose.bind(websocket)); - } -} - -/** - * Handle cases where the `ping()`, `pong()`, or `send()` methods are called - * when the `readyState` attribute is `CLOSING` or `CLOSED`. - * - * @param {WebSocket} websocket The WebSocket instance - * @param {*} [data] The data to send - * @param {Function} [cb] Callback - * @private - */ -function sendAfterClose(websocket, data, cb) { - if (data) { - const length = toBuffer(data).length; - - // - // The `_bufferedAmount` property is used only when the peer is a client and - // the opening handshake fails. Under these circumstances, in fact, the - // `setSocket()` method is not called, so the `_socket` and `_sender` - // properties are set to `null`. - // - if (websocket._socket) websocket._sender._bufferedBytes += length; - else websocket._bufferedAmount += length; - } - - if (cb) { - const err = new Error( - `WebSocket is not open: readyState ${websocket.readyState} ` + - `(${readyStates[websocket.readyState]})` - ); - cb(err); - } -} - -/** - * The listener of the `Receiver` `'conclude'` event. - * - * @param {Number} code The status code - * @param {String} reason The reason for closing - * @private - */ -function receiverOnConclude(code, reason) { - const websocket = this[kWebSocket$1]; - - websocket._socket.removeListener('data', socketOnData); - websocket._socket.resume(); - - websocket._closeFrameReceived = true; - websocket._closeMessage = reason; - websocket._closeCode = code; - - if (code === 1005) websocket.close(); - else websocket.close(code, reason); -} - -/** - * The listener of the `Receiver` `'drain'` event. - * - * @private - */ -function receiverOnDrain() { - this[kWebSocket$1]._socket.resume(); -} - -/** - * The listener of the `Receiver` `'error'` event. - * - * @param {(RangeError|Error)} err The emitted error - * @private - */ -function receiverOnError(err) { - const websocket = this[kWebSocket$1]; - - websocket._socket.removeListener('data', socketOnData); - - websocket._readyState = WebSocket.CLOSING; - websocket._closeCode = err[kStatusCode]; - websocket.emit('error', err); - websocket._socket.destroy(); -} - -/** - * The listener of the `Receiver` `'finish'` event. - * - * @private - */ -function receiverOnFinish() { - this[kWebSocket$1].emitClose(); -} - -/** - * The listener of the `Receiver` `'message'` event. - * - * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message - * @private - */ -function receiverOnMessage(data) { - this[kWebSocket$1].emit('message', data); -} - -/** - * The listener of the `Receiver` `'ping'` event. - * - * @param {Buffer} data The data included in the ping frame - * @private - */ -function receiverOnPing(data) { - const websocket = this[kWebSocket$1]; - - websocket.pong(data, !websocket._isServer, NOOP); - websocket.emit('ping', data); -} - -/** - * The listener of the `Receiver` `'pong'` event. - * - * @param {Buffer} data The data included in the pong frame - * @private - */ -function receiverOnPong(data) { - this[kWebSocket$1].emit('pong', data); -} - -/** - * The listener of the `net.Socket` `'close'` event. - * - * @private - */ -function socketOnClose() { - const websocket = this[kWebSocket$1]; - - this.removeListener('close', socketOnClose); - this.removeListener('end', socketOnEnd); - - websocket._readyState = WebSocket.CLOSING; - - // - // The close frame might not have been received or the `'end'` event emitted, - // for example, if the socket was destroyed due to an error. Ensure that the - // `receiver` stream is closed after writing any remaining buffered data to - // it. If the readable side of the socket is in flowing mode then there is no - // buffered data as everything has been already written and `readable.read()` - // will return `null`. If instead, the socket is paused, any possible buffered - // data will be read as a single chunk and emitted synchronously in a single - // `'data'` event. - // - websocket._socket.read(); - websocket._receiver.end(); - - this.removeListener('data', socketOnData); - this[kWebSocket$1] = undefined; - - clearTimeout(websocket._closeTimer); - - if ( - websocket._receiver._writableState.finished || - websocket._receiver._writableState.errorEmitted - ) { - websocket.emitClose(); - } else { - websocket._receiver.on('error', receiverOnFinish); - websocket._receiver.on('finish', receiverOnFinish); - } -} - -/** - * The listener of the `net.Socket` `'data'` event. - * - * @param {Buffer} chunk A chunk of data - * @private - */ -function socketOnData(chunk) { - if (!this[kWebSocket$1]._receiver.write(chunk)) { - this.pause(); - } -} - -/** - * The listener of the `net.Socket` `'end'` event. - * - * @private - */ -function socketOnEnd() { - const websocket = this[kWebSocket$1]; - - websocket._readyState = WebSocket.CLOSING; - websocket._receiver.end(); - this.end(); -} - -/** - * The listener of the `net.Socket` `'error'` event. - * - * @private - */ -function socketOnError$1() { - const websocket = this[kWebSocket$1]; - - this.removeListener('error', socketOnError$1); - this.on('error', NOOP); - - if (websocket) { - websocket._readyState = WebSocket.CLOSING; - this.destroy(); - } -} - -const { Duplex } = require$$0__default; - -/** - * Emits the `'close'` event on a stream. - * - * @param {stream.Duplex} The stream. - * @private - */ -function emitClose$1(stream) { - stream.emit('close'); -} - -/** - * The listener of the `'end'` event. - * - * @private - */ -function duplexOnEnd() { - if (!this.destroyed && this._writableState.finished) { - this.destroy(); - } -} - -/** - * The listener of the `'error'` event. - * - * @param {Error} err The error - * @private - */ -function duplexOnError(err) { - this.removeListener('error', duplexOnError); - this.destroy(); - if (this.listenerCount('error') === 0) { - // Do not suppress the throwing behavior. - this.emit('error', err); - } -} - -/** - * Wraps a `WebSocket` in a duplex stream. - * - * @param {WebSocket} ws The `WebSocket` to wrap - * @param {Object} [options] The options for the `Duplex` constructor - * @return {stream.Duplex} The duplex stream - * @public - */ -function createWebSocketStream(ws, options) { - let resumeOnReceiverDrain = true; - - function receiverOnDrain() { - if (resumeOnReceiverDrain) ws._socket.resume(); - } - - if (ws.readyState === ws.CONNECTING) { - ws.once('open', function open() { - ws._receiver.removeAllListeners('drain'); - ws._receiver.on('drain', receiverOnDrain); - }); - } else { - ws._receiver.removeAllListeners('drain'); - ws._receiver.on('drain', receiverOnDrain); - } - - const duplex = new Duplex({ - ...options, - autoDestroy: false, - emitClose: false, - objectMode: false, - writableObjectMode: false - }); - - ws.on('message', function message(msg) { - if (!duplex.push(msg)) { - resumeOnReceiverDrain = false; - ws._socket.pause(); - } - }); - - ws.once('error', function error(err) { - if (duplex.destroyed) return; - - duplex.destroy(err); - }); - - ws.once('close', function close() { - if (duplex.destroyed) return; - - duplex.push(null); - }); - - duplex._destroy = function (err, callback) { - if (ws.readyState === ws.CLOSED) { - callback(err); - process.nextTick(emitClose$1, duplex); - return; - } - - let called = false; - - ws.once('error', function error(err) { - called = true; - callback(err); - }); - - ws.once('close', function close() { - if (!called) callback(err); - process.nextTick(emitClose$1, duplex); - }); - ws.terminate(); - }; - - duplex._final = function (callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once('open', function open() { - duplex._final(callback); - }); - return; - } - - // If the value of the `_socket` property is `null` it means that `ws` is a - // client websocket and the handshake failed. In fact, when this happens, a - // socket is never assigned to the websocket. Wait for the `'error'` event - // that will be emitted by the websocket. - if (ws._socket === null) return; - - if (ws._socket._writableState.finished) { - callback(); - if (duplex._readableState.endEmitted) duplex.destroy(); - } else { - ws._socket.once('finish', function finish() { - // `duplex` is not destroyed here because the `'end'` event will be - // emitted on `duplex` after this `'finish'` event. The EOF signaling - // `null` chunk is, in fact, pushed when the websocket emits `'close'`. - callback(); - }); - ws.close(); - } - }; - - duplex._read = function () { - if (ws.readyState === ws.OPEN && !resumeOnReceiverDrain) { - resumeOnReceiverDrain = true; - if (!ws._receiver._writableState.needDrain) ws._socket.resume(); - } - }; - - duplex._write = function (chunk, encoding, callback) { - if (ws.readyState === ws.CONNECTING) { - ws.once('open', function open() { - duplex._write(chunk, encoding, callback); - }); - return; - } - - ws.send(chunk, callback); - }; - - duplex.on('end', duplexOnEnd); - duplex.on('error', duplexOnError); - return duplex; -} - -var stream$1 = createWebSocketStream; - -const { createHash } = require$$0__default$2; -const { createServer: createServer$1, STATUS_CODES } = http__default; - - - -const { format, parse: parse$3 } = extension; -const { GUID, kWebSocket } = constants; - -const keyRegex = /^[+/0-9A-Za-z]{22}==$/; - -/** - * Class representing a WebSocket server. - * - * @extends EventEmitter - */ -class WebSocketServer extends require$$0__default$1 { - /** - * Create a `WebSocketServer` instance. - * - * @param {Object} options Configuration options - * @param {Number} [options.backlog=511] The maximum length of the queue of - * pending connections - * @param {Boolean} [options.clientTracking=true] Specifies whether or not to - * track clients - * @param {Function} [options.handleProtocols] A hook to handle protocols - * @param {String} [options.host] The hostname where to bind the server - * @param {Number} [options.maxPayload=104857600] The maximum allowed message - * size - * @param {Boolean} [options.noServer=false] Enable no server mode - * @param {String} [options.path] Accept only connections matching this path - * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable - * permessage-deflate - * @param {Number} [options.port] The port where to bind the server - * @param {http.Server} [options.server] A pre-created HTTP/S server to use - * @param {Function} [options.verifyClient] A hook to reject connections - * @param {Function} [callback] A listener for the `listening` event - */ - constructor(options, callback) { - super(); - - options = { - maxPayload: 100 * 1024 * 1024, - perMessageDeflate: false, - handleProtocols: null, - clientTracking: true, - verifyClient: null, - noServer: false, - backlog: null, // use default (511 as implemented in net.js) - server: null, - host: null, - path: null, - port: null, - ...options - }; - - if (options.port == null && !options.server && !options.noServer) { - throw new TypeError( - 'One of the "port", "server", or "noServer" options must be specified' - ); - } - - if (options.port != null) { - this._server = createServer$1((req, res) => { - const body = STATUS_CODES[426]; - - res.writeHead(426, { - 'Content-Length': body.length, - 'Content-Type': 'text/plain' - }); - res.end(body); - }); - this._server.listen( - options.port, - options.host, - options.backlog, - callback - ); - } else if (options.server) { - this._server = options.server; - } - - if (this._server) { - const emitConnection = this.emit.bind(this, 'connection'); - - this._removeListeners = addListeners(this._server, { - listening: this.emit.bind(this, 'listening'), - error: this.emit.bind(this, 'error'), - upgrade: (req, socket, head) => { - this.handleUpgrade(req, socket, head, emitConnection); - } - }); - } - - if (options.perMessageDeflate === true) options.perMessageDeflate = {}; - if (options.clientTracking) this.clients = new Set(); - this.options = options; - } - - /** - * Returns the bound address, the address family name, and port of the server - * as reported by the operating system if listening on an IP socket. - * If the server is listening on a pipe or UNIX domain socket, the name is - * returned as a string. - * - * @return {(Object|String|null)} The address of the server - * @public - */ - address() { - if (this.options.noServer) { - throw new Error('The server is operating in "noServer" mode'); - } - - if (!this._server) return null; - return this._server.address(); - } - - /** - * Close the server. - * - * @param {Function} [cb] Callback - * @public - */ - close(cb) { - if (cb) this.once('close', cb); - - // - // Terminate all associated clients. - // - if (this.clients) { - for (const client of this.clients) client.terminate(); - } - - const server = this._server; - - if (server) { - this._removeListeners(); - this._removeListeners = this._server = null; - - // - // Close the http server if it was internally created. - // - if (this.options.port != null) { - server.close(() => this.emit('close')); - return; - } - } - - process.nextTick(emitClose, this); - } - - /** - * See if a given request should be handled by this server instance. - * - * @param {http.IncomingMessage} req Request object to inspect - * @return {Boolean} `true` if the request is valid, else `false` - * @public - */ - shouldHandle(req) { - if (this.options.path) { - const index = req.url.indexOf('?'); - const pathname = index !== -1 ? req.url.slice(0, index) : req.url; - - if (pathname !== this.options.path) return false; - } - - return true; - } - - /** - * Handle a HTTP Upgrade request. - * - * @param {http.IncomingMessage} req The request object - * @param {net.Socket} socket The network socket between the server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback - * @public - */ - handleUpgrade(req, socket, head, cb) { - socket.on('error', socketOnError); - - const key = - req.headers['sec-websocket-key'] !== undefined - ? req.headers['sec-websocket-key'].trim() - : false; - const version = +req.headers['sec-websocket-version']; - const extensions = {}; - - if ( - req.method !== 'GET' || - req.headers.upgrade.toLowerCase() !== 'websocket' || - !key || - !keyRegex.test(key) || - (version !== 8 && version !== 13) || - !this.shouldHandle(req) - ) { - return abortHandshake(socket, 400); - } - - if (this.options.perMessageDeflate) { - const perMessageDeflate = new permessageDeflate( - this.options.perMessageDeflate, - true, - this.options.maxPayload - ); - - try { - const offers = parse$3(req.headers['sec-websocket-extensions']); - - if (offers[permessageDeflate.extensionName]) { - perMessageDeflate.accept(offers[permessageDeflate.extensionName]); - extensions[permessageDeflate.extensionName] = perMessageDeflate; - } - } catch (err) { - return abortHandshake(socket, 400); - } - } - - // - // Optionally call external client verification handler. - // - if (this.options.verifyClient) { - const info = { - origin: - req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], - secure: !!(req.socket.authorized || req.socket.encrypted), - req - }; - - if (this.options.verifyClient.length === 2) { - this.options.verifyClient(info, (verified, code, message, headers) => { - if (!verified) { - return abortHandshake(socket, code || 401, message, headers); - } - - this.completeUpgrade(key, extensions, req, socket, head, cb); - }); - return; - } - - if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); - } - - this.completeUpgrade(key, extensions, req, socket, head, cb); - } - - /** - * Upgrade the connection to WebSocket. - * - * @param {String} key The value of the `Sec-WebSocket-Key` header - * @param {Object} extensions The accepted extensions - * @param {http.IncomingMessage} req The request object - * @param {net.Socket} socket The network socket between the server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback - * @throws {Error} If called more than once with the same socket - * @private - */ - completeUpgrade(key, extensions, req, socket, head, cb) { - // - // Destroy the socket if the client has already sent a FIN packet. - // - if (!socket.readable || !socket.writable) return socket.destroy(); - - if (socket[kWebSocket]) { - throw new Error( - 'server.handleUpgrade() was called more than once with the same ' + - 'socket, possibly due to a misconfiguration' - ); - } - - const digest = createHash('sha1') - .update(key + GUID) - .digest('base64'); - - const headers = [ - 'HTTP/1.1 101 Switching Protocols', - 'Upgrade: websocket', - 'Connection: Upgrade', - `Sec-WebSocket-Accept: ${digest}` - ]; - - const ws = new websocket(null); - let protocol = req.headers['sec-websocket-protocol']; - - if (protocol) { - protocol = protocol.trim().split(/ *, */); - - // - // Optionally call external protocol selection handler. - // - if (this.options.handleProtocols) { - protocol = this.options.handleProtocols(protocol, req); - } else { - protocol = protocol[0]; - } - - if (protocol) { - headers.push(`Sec-WebSocket-Protocol: ${protocol}`); - ws._protocol = protocol; - } - } - - if (extensions[permessageDeflate.extensionName]) { - const params = extensions[permessageDeflate.extensionName].params; - const value = format({ - [permessageDeflate.extensionName]: [params] - }); - headers.push(`Sec-WebSocket-Extensions: ${value}`); - ws._extensions = extensions; - } - - // - // Allow external modification/inspection of handshake headers. - // - this.emit('headers', headers, req); - - socket.write(headers.concat('\r\n').join('\r\n')); - socket.removeListener('error', socketOnError); - - ws.setSocket(socket, head, this.options.maxPayload); - - if (this.clients) { - this.clients.add(ws); - ws.on('close', () => this.clients.delete(ws)); - } - - cb(ws, req); - } -} - -var websocketServer = WebSocketServer; - -/** - * Add event listeners on an `EventEmitter` using a map of - * pairs. - * - * @param {EventEmitter} server The event emitter - * @param {Object.} map The listeners to add - * @return {Function} A function that will remove the added listeners when - * called - * @private - */ -function addListeners(server, map) { - for (const event of Object.keys(map)) server.on(event, map[event]); - - return function removeListeners() { - for (const event of Object.keys(map)) { - server.removeListener(event, map[event]); - } - }; -} - -/** - * Emit a `'close'` event on an `EventEmitter`. - * - * @param {EventEmitter} server The event emitter - * @private - */ -function emitClose(server) { - server.emit('close'); -} - -/** - * Handle premature socket errors. - * - * @private - */ -function socketOnError() { - this.destroy(); -} - -/** - * Close the connection when preconditions are not fulfilled. - * - * @param {net.Socket} socket The socket of the upgrade request - * @param {Number} code The HTTP response status code - * @param {String} [message] The HTTP response body - * @param {Object} [headers] Additional HTTP response headers - * @private - */ -function abortHandshake(socket, code, message, headers) { - if (socket.writable) { - message = message || STATUS_CODES[code]; - headers = { - Connection: 'close', - 'Content-Type': 'text/html', - 'Content-Length': Buffer.byteLength(message), - ...headers - }; - - socket.write( - `HTTP/1.1 ${code} ${STATUS_CODES[code]}\r\n` + - Object.keys(headers) - .map((h) => `${h}: ${headers[h]}`) - .join('\r\n') + - '\r\n\r\n' + - message - ); - } - - socket.removeListener('error', socketOnError); - socket.destroy(); -} - -websocket.createWebSocketStream = stream$1; -websocket.Server = websocketServer; -websocket.Receiver = receiver; -websocket.Sender = sender; - -var ws = websocket; - -const HMR_HEADER = 'vite-hmr'; -function createWebSocketServer(server, config) { - let wss; - const hmr = typeof config.server.hmr === 'object' && config.server.hmr; - const wsServer = (hmr && hmr.server) || server; - if (wsServer) { - wss = new ws.Server({ noServer: true }); - wsServer.on('upgrade', (req, socket, head) => { - if (req.headers['sec-websocket-protocol'] === HMR_HEADER) { - wss.handleUpgrade(req, socket, head, (ws) => { - wss.emit('connection', ws, req); - }); - } - }); - } - else { - // vite dev server in middleware mode - wss = new ws.Server({ - port: (hmr && hmr.port) || 24678 - }); - } - wss.on('connection', (socket) => { - socket.send(JSON.stringify({ type: 'connected' })); - if (bufferedError) { - socket.send(JSON.stringify(bufferedError)); - bufferedError = null; - } - }); - wss.on('error', (e) => { - if (e.code !== 'EADDRINUSE') { - config.logger.error(source.red(`WebSocket server error:\n${e.stack || e.message}`)); - } - }); - // On page reloads, if a file fails to compile and returns 500, the server - // sends the error payload before the client connection is established. - // If we have no open clients, buffer the error and send it to the next - // connected client. - let bufferedError = null; - return { - send(payload) { - if (payload.type === 'error' && !wss.clients.size) { - bufferedError = payload; - return; - } - const stringified = JSON.stringify(payload); - wss.clients.forEach((client) => { - if (client.readyState === ws.OPEN) { - client.send(stringified); - } - }); - }, - close() { - return new Promise((resolve, reject) => { - wss.close((err) => { - if (err) { - reject(err); - } - else { - resolve(); - } - }); - }); - } - }; -} - -// this middleware is only active when (config.base !== '/') -function baseMiddleware({ config }) { - const base = config.base; - return (req, res, next) => { - var _a; - const url$1 = req.url; - const parsed = url.parse(url$1); - const path = parsed.pathname || '/'; - if (path.startsWith(base)) { - // rewrite url to remove base.. this ensures that other middleware does - // not need to consider base being prepended or not - req.url = url$1.replace(base, '/'); - } - else if (path === '/' || path === '/index.html') { - // redirect root visit to based url - res.writeHead(302, { - Location: base - }); - res.end(); - return; - } - else if ((_a = req.headers.accept) === null || _a === void 0 ? void 0 : _a.includes('text/html')) { - // non-based page visit - res.statusCode = 404; - res.end(`The server is configured with a public base URL of ${base} - ` + - `did you mean to visit ${base}${url$1.slice(1)} instead?`); - return; - } - next(); - }; -} - -var eventemitter3 = createCommonjsModule(function (module) { - -var has = Object.prototype.hasOwnProperty - , prefix = '~'; - -/** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ -function Events() {} - -// -// We try to not inherit from `Object.prototype`. In some engines creating an -// instance in this way is faster than calling `Object.create(null)` directly. -// If `Object.create(null)` is not supported we prefix the event names with a -// character to make sure that the built-in object properties are not -// overridden or used as an attack vector. -// -if (Object.create) { - Events.prototype = Object.create(null); - - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; -} - -/** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ -function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; -} - -/** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ -function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); - } - - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; - - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; - - return emitter; -} - -/** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ -function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; -} - -/** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ -function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; -} - -/** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ -EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; - - if (this._eventsCount === 0) return names; - - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); - } - - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } - - return names; -}; - -/** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ -EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; - - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; - - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; - } - - return ee; -}; - -/** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ -EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; - - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; -}; - -/** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ -EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return false; - - var listeners = this._events[evt] - , len = arguments.length - , args - , i; - - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); - - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } - - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; - } - - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; - - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); - - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } - - listeners[i].fn.apply(listeners[i].context, args); - } - } - } - - return true; -}; - -/** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); -}; - -/** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); -}; - -/** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; - } - - var listeners = this._events[evt]; - - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); - } - } - - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); - } - - return this; -}; - -/** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } - - return this; -}; - -// -// Alias methods names because people roll like that. -// -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -// -// Expose the prefix. -// -EventEmitter.prefixed = prefix; - -// -// Allow `EventEmitter` to be imported as module namespace. -// -EventEmitter.EventEmitter = EventEmitter; - -// -// Expose the module. -// -{ - module.exports = EventEmitter; -} -}); - -/** - * Check if we're required to add a port number. - * - * @see https://url.spec.whatwg.org/#default-port - * @param {Number|String} port Port number we need to check - * @param {String} protocol Protocol we need to check against. - * @returns {Boolean} Is it a default port for the given protocol - * @api private - */ -var requiresPort = function required(port, protocol) { - protocol = protocol.split(':')[0]; - port = +port; - - if (!port) return false; - - switch (protocol) { - case 'http': - case 'ws': - return port !== 80; - - case 'https': - case 'wss': - return port !== 443; - - case 'ftp': - return port !== 21; - - case 'gopher': - return port !== 70; - - case 'file': - return false; - } - - return port !== 0; -}; - -var common_1 = createCommonjsModule(function (module, exports) { -var common = exports, - extend = util__default._extend; - -var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i, - isSSL = /^https|wss/; - -/** - * Simple Regex for testing if protocol is https - */ -common.isSSL = isSSL; -/** - * Copies the right headers from `options` and `req` to - * `outgoing` which is then used to fire the proxied - * request. - * - * Examples: - * - * common.setupOutgoing(outgoing, options, req) - * // => { host: ..., hostname: ...} - * - * @param {Object} Outgoing Base object to be filled with required properties - * @param {Object} Options Config object passed to the proxy - * @param {ClientRequest} Req Request Object - * @param {String} Forward String to select forward or target - *  - * @return {Object} Outgoing Object with all required properties set - * - * @api private - */ - -common.setupOutgoing = function(outgoing, options, req, forward) { - outgoing.port = options[forward || 'target'].port || - (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80); - - ['host', 'hostname', 'socketPath', 'pfx', 'key', - 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach( - function(e) { outgoing[e] = options[forward || 'target'][e]; } - ); - - outgoing.method = options.method || req.method; - outgoing.headers = extend({}, req.headers); - - if (options.headers){ - extend(outgoing.headers, options.headers); - } - - if (options.auth) { - outgoing.auth = options.auth; - } - - if (options.ca) { - outgoing.ca = options.ca; - } - - if (isSSL.test(options[forward || 'target'].protocol)) { - outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure; - } - - - outgoing.agent = options.agent || false; - outgoing.localAddress = options.localAddress; - - // - // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do - // as node core doesn't handle this COMPLETELY properly yet. - // - if (!outgoing.agent) { - outgoing.headers = outgoing.headers || {}; - if (typeof outgoing.headers.connection !== 'string' - || !upgradeHeader.test(outgoing.headers.connection) - ) { outgoing.headers.connection = 'close'; } - } - - - // the final path is target path + relative path requested by user: - var target = options[forward || 'target']; - var targetPath = target && options.prependPath !== false - ? (target.path || '') - : ''; - - // - // Remark: Can we somehow not use url.parse as a perf optimization? - // - var outgoingPath = !options.toProxy - ? (url__default.parse(req.url).path || '') - : req.url; - - // - // Remark: ignorePath will just straight up ignore whatever the request's - // path is. This can be labeled as FOOT-GUN material if you do not know what - // you are doing and are using conflicting options. - // - outgoingPath = !options.ignorePath ? outgoingPath : ''; - - outgoing.path = common.urlJoin(targetPath, outgoingPath); - - if (options.changeOrigin) { - outgoing.headers.host = - requiresPort(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host) - ? outgoing.host + ':' + outgoing.port - : outgoing.host; - } - return outgoing; -}; - -/** - * Set the proper configuration for sockets, - * set no delay and set keep alive, also set - * the timeout to 0. - * - * Examples: - * - * common.setupSocket(socket) - * // => Socket - * - * @param {Socket} Socket instance to setup - *  - * @return {Socket} Return the configured socket. - * - * @api private - */ - -common.setupSocket = function(socket) { - socket.setTimeout(0); - socket.setNoDelay(true); - - socket.setKeepAlive(true, 0); - - return socket; -}; - -/** - * Get the port number from the host. Or guess it based on the connection type. - * - * @param {Request} req Incoming HTTP request. - * - * @return {String} The port number. - * - * @api private - */ -common.getPort = function(req) { - var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : ''; - - return res ? - res[1] : - common.hasEncryptedConnection(req) ? '443' : '80'; -}; - -/** - * Check if the request has an encrypted connection. - * - * @param {Request} req Incoming HTTP request. - * - * @return {Boolean} Whether the connection is encrypted or not. - * - * @api private - */ -common.hasEncryptedConnection = function(req) { - return Boolean(req.connection.encrypted || req.connection.pair); -}; - -/** - * OS-agnostic join (doesn't break on URLs like path.join does on Windows)> - * - * @return {String} The generated path. - * - * @api private - */ - -common.urlJoin = function() { - // - // We do not want to mess with the query string. All we want to touch is the path. - // - var args = Array.prototype.slice.call(arguments), - lastIndex = args.length - 1, - last = args[lastIndex], - lastSegs = last.split('?'), - retSegs; - - args[lastIndex] = lastSegs.shift(); - - // - // Join all strings, but remove empty strings so we don't get extra slashes from - // joining e.g. ['', 'am'] - // - retSegs = [ - args.filter(Boolean).join('/') - .replace(/\/+/g, '/') - .replace('http:/', 'http://') - .replace('https:/', 'https://') - ]; - - // Only join the query string if it exists so we don't have trailing a '?' - // on every request - - // Handle case where there could be multiple ? in the URL. - retSegs.push.apply(retSegs, lastSegs); - - return retSegs.join('?') -}; - -/** - * Rewrites or removes the domain of a cookie header - * - * @param {String|Array} Header - * @param {Object} Config, mapping of domain to rewritten domain. - * '*' key to match any domain, null value to remove the domain. - * - * @api private - */ -common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) { - if (Array.isArray(header)) { - return header.map(function (headerElement) { - return rewriteCookieProperty(headerElement, config, property); - }); - } - return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) { - var newValue; - if (previousValue in config) { - newValue = config[previousValue]; - } else if ('*' in config) { - newValue = config['*']; - } else { - //no match, return previous value - return match; - } - if (newValue) { - //replace value - return prefix + newValue; - } else { - //remove value - return ''; - } - }); -}; - -/** - * Check the host and see if it potentially has a port in it (keep it simple) - * - * @returns {Boolean} Whether we have one or not - * - * @api private - */ -function hasPort(host) { - return !!~host.indexOf(':'); -}}); - -var redirectRegex = /^201|30(1|2|7|8)$/; - -/*! - * Array of passes. - * - * A `pass` is just a function that is executed on `req, res, options` - * so that you can easily add new checks while still keeping the base - * flexible. - */ - -var webOutgoing = { // <-- - - /** - * If is a HTTP 1.0 request, remove chunk headers - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {proxyResponse} Res Response object from the proxy request - * - * @api private - */ - removeChunked: function removeChunked(req, res, proxyRes) { - if (req.httpVersion === '1.0') { - delete proxyRes.headers['transfer-encoding']; - } - }, - - /** - * If is a HTTP 1.0 request, set the correct connection header - * or if connection header not present, then use `keep-alive` - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {proxyResponse} Res Response object from the proxy request - * - * @api private - */ - setConnection: function setConnection(req, res, proxyRes) { - if (req.httpVersion === '1.0') { - proxyRes.headers.connection = req.headers.connection || 'close'; - } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) { - proxyRes.headers.connection = req.headers.connection || 'keep-alive'; - } - }, - - setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) { - if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite) - && proxyRes.headers['location'] - && redirectRegex.test(proxyRes.statusCode)) { - var target = url__default.parse(options.target); - var u = url__default.parse(proxyRes.headers['location']); - - // make sure the redirected host matches the target host before rewriting - if (target.host != u.host) { - return; - } - - if (options.hostRewrite) { - u.host = options.hostRewrite; - } else if (options.autoRewrite) { - u.host = req.headers['host']; - } - if (options.protocolRewrite) { - u.protocol = options.protocolRewrite; - } - - proxyRes.headers['location'] = u.format(); - } - }, - /** - * Copy headers from proxyResponse to response - * set each header in response object. - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {proxyResponse} Res Response object from the proxy request - * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain - * - * @api private - */ - writeHeaders: function writeHeaders(req, res, proxyRes, options) { - var rewriteCookieDomainConfig = options.cookieDomainRewrite, - rewriteCookiePathConfig = options.cookiePathRewrite, - preserveHeaderKeyCase = options.preserveHeaderKeyCase, - rawHeaderKeyMap, - setHeader = function(key, header) { - if (header == undefined) return; - if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') { - header = common_1.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain'); - } - if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') { - header = common_1.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path'); - } - res.setHeader(String(key).trim(), header); - }; - - if (typeof rewriteCookieDomainConfig === 'string') { //also test for '' - rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig }; - } - - if (typeof rewriteCookiePathConfig === 'string') { //also test for '' - rewriteCookiePathConfig = { '*': rewriteCookiePathConfig }; - } - - // message.rawHeaders is added in: v0.11.6 - // https://nodejs.org/api/http.html#http_message_rawheaders - if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) { - rawHeaderKeyMap = {}; - for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) { - var key = proxyRes.rawHeaders[i]; - rawHeaderKeyMap[key.toLowerCase()] = key; - } - } - - Object.keys(proxyRes.headers).forEach(function(key) { - var header = proxyRes.headers[key]; - if (preserveHeaderKeyCase && rawHeaderKeyMap) { - key = rawHeaderKeyMap[key] || key; - } - setHeader(key, header); - }); - }, - - /** - * Set the statusCode from the proxyResponse - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {proxyResponse} Res Response object from the proxy request - * - * @api private - */ - writeStatusCode: function writeStatusCode(req, res, proxyRes) { - // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers]) - if(proxyRes.statusMessage) { - res.statusCode = proxyRes.statusCode; - res.statusMessage = proxyRes.statusMessage; - } else { - res.statusCode = proxyRes.statusCode; - } - } - -}; - -var debug$2; - -var debug_1 = function () { - if (!debug$2) { - try { - /* eslint global-require: off */ - debug$2 = src$3("follow-redirects"); - } - catch (error) { - debug$2 = function () { /* */ }; - } - } - debug$2.apply(null, arguments); -}; - -var URL$1 = url__default.URL; - - -var Writable = require$$0__default.Writable; - - - -// Create handlers that pass events from native requests -var eventHandlers = Object.create(null); -["abort", "aborted", "connect", "error", "socket", "timeout"].forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; -}); - -// Error types with codes -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded" -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); - -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; - - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); - } - - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - self._processResponse(response); - }; - - // Perform the first request - this._performRequest(); -} -RedirectableRequest.prototype = Object.create(Writable.prototype); - -RedirectableRequest.prototype.abort = function () { - // Abort the internal request - this._currentRequest.removeAllListeners(); - this._currentRequest.on("error", noop$1); - this._currentRequest.abort(); - - // Abort this request - this.emit("abort"); - this.removeAllListeners(); -}; - -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } - - // Validate input and shift parameters if necessary - if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } - - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } -}; - -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (typeof data === "function") { - callback = data; - data = encoding = null; - } - else if (typeof encoding === "function") { - callback = encoding; - encoding = null; - } - - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } -}; - -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; - -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); -}; - -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - var self = this; - if (callback) { - this.on("timeout", callback); - } - - // Sets up a timer to trigger a timeout event - function startTimer() { - if (self._timeout) { - clearTimeout(self._timeout); - } - self._timeout = setTimeout(function () { - self.emit("timeout"); - clearTimer(); - }, msecs); - } - - // Prevent a timeout from triggering - function clearTimer() { - clearTimeout(this._timeout); - if (callback) { - self.removeListener("timeout", callback); - } - if (!this.socket) { - self._currentRequest.removeListener("socket", startTimer); - } - } - - // Start the timer when the socket is opened - if (this.socket) { - startTimer(); - } - else { - this._currentRequest.once("socket", startTimer); - } - - this.once("response", clearTimer); - this.once("error", clearTimer); - - return this; -}; - -// Proxy all other public ClientRequest methods -[ - "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); - -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); - -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } - - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } - - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } -}; - - -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - this.emit("error", new TypeError("Unsupported protocol " + protocol)); - return; - } - - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.substr(0, protocol.length - 1); - this._options.agent = this._options.agents[scheme]; - } - - // Create the native request - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - this._currentUrl = url__default.format(this._options); - - // Set up event handlers - request._redirectable = this; - for (var event in eventHandlers) { - /* istanbul ignore else */ - if (event) { - request.on(event, eventHandlers[event]); - } - } - - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end. - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - /* istanbul ignore else */ - if (request === self._currentRequest) { - // Report any write errors - /* istanbul ignore if */ - if (error) { - self.emit("error", error); - } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - /* istanbul ignore else */ - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } - } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); - } - } - }()); - } -}; - -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); - } - - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. - var location = response.headers.location; - if (location && this._options.followRedirects !== false && - statusCode >= 300 && statusCode < 400) { - // Abort the current request - this._currentRequest.removeAllListeners(); - this._currentRequest.on("error", noop$1); - this._currentRequest.abort(); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); - - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - this.emit("error", new TooManyRedirectsError()); - return; - } - - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - - // Drop the Host header, as the redirect might lead to a different host - var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) || - url__default.parse(this._currentUrl).hostname; - - // Create the redirected request - var redirectUrl = url__default.resolve(this._currentUrl, location); - debug_1("redirecting to", redirectUrl); - this._isRedirect = true; - var redirectUrlParts = url__default.parse(redirectUrl); - Object.assign(this._options, redirectUrlParts); - - // Drop the Authorization header if redirecting to another host - if (redirectUrlParts.hostname !== previousHostName) { - removeMatchingHeaders(/^authorization$/i, this._options.headers); - } - - // Evaluate the beforeRedirect callback - if (typeof this._options.beforeRedirect === "function") { - var responseDetails = { headers: response.headers }; - try { - this._options.beforeRedirect.call(null, this._options, responseDetails); - } - catch (err) { - this.emit("error", err); - return; - } - this._sanitizeOptions(this._options); - } - - // Perform the redirected request - try { - this._performRequest(); - } - catch (cause) { - var error = new RedirectionError("Redirected request failed: " + cause.message); - error.cause = cause; - this.emit("error", error); - } - } - else { - // The response is not a redirect; return it as-is - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - - // Clean up - this._requestBodyBuffers = []; - } -}; - -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; - - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); - - // Executes a request, following redirects - function request(input, options, callback) { - // Parse parameters - if (typeof input === "string") { - var urlStr = input; - try { - input = urlToOptions(new URL$1(urlStr)); - } - catch (err) { - /* istanbul ignore next */ - input = url__default.parse(urlStr); - } - } - else if (URL$1 && (input instanceof URL$1)) { - input = urlToOptions(input); - } - else { - callback = options; - options = input; - input = { protocol: protocol }; - } - if (typeof options === "function") { - callback = options; - options = null; - } - - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; - - assert__default.equal(options.protocol, protocol, "protocol mismatch"); - debug_1("options", options); - return new RedirectableRequest(options, callback); - } - - // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } - - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, - }); - }); - return exports; -} - -/* istanbul ignore next */ -function noop$1() { /* empty */ } - -// from https://github.com/nodejs/node/blob/master/lib/internal/url.js -function urlToOptions(urlObject) { - var options = { - protocol: urlObject.protocol, - hostname: urlObject.hostname.startsWith("[") ? - /* istanbul ignore next */ - urlObject.hostname.slice(1, -1) : - urlObject.hostname, - hash: urlObject.hash, - search: urlObject.search, - pathname: urlObject.pathname, - path: urlObject.pathname + urlObject.search, - href: urlObject.href, - }; - if (urlObject.port !== "") { - options.port = Number(urlObject.port); - } - return options; -} - -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } - } - return lastValue; -} - -function createErrorType(code, defaultMessage) { - function CustomError(message) { - Error.captureStackTrace(this, this.constructor); - this.message = message || defaultMessage; - } - CustomError.prototype = new Error(); - CustomError.prototype.constructor = CustomError; - CustomError.prototype.name = "Error [" + code + "]"; - CustomError.prototype.code = code; - return CustomError; -} - -// Exports -var followRedirects = wrap({ http: http__default, https: https__default }); -var wrap_1 = wrap; -followRedirects.wrap = wrap_1; - -var web_o = webOutgoing; - -web_o = Object.keys(web_o).map(function(pass) { - return web_o[pass]; -}); - -var nativeAgents = { http: http__default, https: https__default }; - -/*! - * Array of passes. - * - * A `pass` is just a function that is executed on `req, res, options` - * so that you can easily add new checks while still keeping the base - * flexible. - */ - - -var webIncoming = { - - /** - * Sets `content-length` to '0' if request is of DELETE type. - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - - deleteLength: function deleteLength(req, res, options) { - if((req.method === 'DELETE' || req.method === 'OPTIONS') - && !req.headers['content-length']) { - req.headers['content-length'] = '0'; - delete req.headers['transfer-encoding']; - } - }, - - /** - * Sets timeout in request socket if it was specified in options. - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - - timeout: function timeout(req, res, options) { - if(options.timeout) { - req.socket.setTimeout(options.timeout); - } - }, - - /** - * Sets `x-forwarded-*` headers if specified in config. - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - - XHeaders: function XHeaders(req, res, options) { - if(!options.xfwd) return; - - var encrypted = req.isSpdy || common_1.hasEncryptedConnection(req); - var values = { - for : req.connection.remoteAddress || req.socket.remoteAddress, - port : common_1.getPort(req), - proto: encrypted ? 'https' : 'http' - }; - - ['for', 'port', 'proto'].forEach(function(header) { - req.headers['x-forwarded-' + header] = - (req.headers['x-forwarded-' + header] || '') + - (req.headers['x-forwarded-' + header] ? ',' : '') + - values[header]; - }); - - req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || ''; - }, - - /** - * Does the actual proxying. If `forward` is enabled fires up - * a ForwardStream, same happens for ProxyStream. The request - * just dies otherwise. - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - - stream: function stream(req, res, options, _, server, clb) { - - // And we begin! - server.emit('start', req, res, options.target || options.forward); - - var agents = options.followRedirects ? followRedirects : nativeAgents; - var http = agents.http; - var https = agents.https; - - if(options.forward) { - // If forward enable, so just pipe the request - var forwardReq = (options.forward.protocol === 'https:' ? https : http).request( - common_1.setupOutgoing(options.ssl || {}, options, req, 'forward') - ); - - // error handler (e.g. ECONNRESET, ECONNREFUSED) - // Handle errors on incoming request as well as it makes sense to - var forwardError = createErrorHandler(forwardReq, options.forward); - req.on('error', forwardError); - forwardReq.on('error', forwardError); - - (options.buffer || req).pipe(forwardReq); - if(!options.target) { return res.end(); } - } - - // Request initalization - var proxyReq = (options.target.protocol === 'https:' ? https : http).request( - common_1.setupOutgoing(options.ssl || {}, options, req) - ); - - // Enable developers to modify the proxyReq before headers are sent - proxyReq.on('socket', function(socket) { - if(server && !proxyReq.getHeader('expect')) { - server.emit('proxyReq', proxyReq, req, res, options); - } - }); - - // allow outgoing socket to timeout so that we could - // show an error page at the initial request - if(options.proxyTimeout) { - proxyReq.setTimeout(options.proxyTimeout, function() { - proxyReq.abort(); - }); - } - - // Ensure we abort proxy if request is aborted - req.on('aborted', function () { - proxyReq.abort(); - }); - - // handle errors in proxy and incoming request, just like for forward proxy - var proxyError = createErrorHandler(proxyReq, options.target); - req.on('error', proxyError); - proxyReq.on('error', proxyError); - - function createErrorHandler(proxyReq, url) { - return function proxyError(err) { - if (req.socket.destroyed && err.code === 'ECONNRESET') { - server.emit('econnreset', err, req, res, url); - return proxyReq.abort(); - } - - if (clb) { - clb(err, req, res, url); - } else { - server.emit('error', err, req, res, url); - } - } - } - - (options.buffer || req).pipe(proxyReq); - - proxyReq.on('response', function(proxyRes) { - if(server) { server.emit('proxyRes', proxyRes, req, res); } - - if(!res.headersSent && !options.selfHandleResponse) { - for(var i=0; i < web_o.length; i++) { - if(web_o[i](req, res, proxyRes, options)) { break; } - } - } - - if (!res.finished) { - // Allow us to listen when the proxy has completed - proxyRes.on('end', function () { - if (server) server.emit('end', req, res, proxyRes); - }); - // We pipe to the response unless its expected to be handled by the user - if (!options.selfHandleResponse) proxyRes.pipe(res); - } else { - if (server) server.emit('end', req, res, proxyRes); - } - }); - } - -}; - -/*! - * Array of passes. - * - * A `pass` is just a function that is executed on `req, socket, options` - * so that you can easily add new checks while still keeping the base - * flexible. - */ - -/* - * Websockets Passes - * - */ - - -var wsIncoming = { - /** - * WebSocket requests must have the `GET` method and - * the `upgrade:websocket` header - * - * @param {ClientRequest} Req Request object - * @param {Socket} Websocket - * - * @api private - */ - - checkMethodAndHeader : function checkMethodAndHeader(req, socket) { - if (req.method !== 'GET' || !req.headers.upgrade) { - socket.destroy(); - return true; - } - - if (req.headers.upgrade.toLowerCase() !== 'websocket') { - socket.destroy(); - return true; - } - }, - - /** - * Sets `x-forwarded-*` headers if specified in config. - * - * @param {ClientRequest} Req Request object - * @param {Socket} Websocket - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - - XHeaders : function XHeaders(req, socket, options) { - if(!options.xfwd) return; - - var values = { - for : req.connection.remoteAddress || req.socket.remoteAddress, - port : common_1.getPort(req), - proto: common_1.hasEncryptedConnection(req) ? 'wss' : 'ws' - }; - - ['for', 'port', 'proto'].forEach(function(header) { - req.headers['x-forwarded-' + header] = - (req.headers['x-forwarded-' + header] || '') + - (req.headers['x-forwarded-' + header] ? ',' : '') + - values[header]; - }); - }, - - /** - * Does the actual proxying. Make the request and upgrade it - * send the Switching Protocols request and pipe the sockets. - * - * @param {ClientRequest} Req Request object - * @param {Socket} Websocket - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - stream : function stream(req, socket, options, head, server, clb) { - - var createHttpHeader = function(line, headers) { - return Object.keys(headers).reduce(function (head, key) { - var value = headers[key]; - - if (!Array.isArray(value)) { - head.push(key + ': ' + value); - return head; - } - - for (var i = 0; i < value.length; i++) { - head.push(key + ': ' + value[i]); - } - return head; - }, [line]) - .join('\r\n') + '\r\n\r\n'; - }; - - common_1.setupSocket(socket); - - if (head && head.length) socket.unshift(head); - - - var proxyReq = (common_1.isSSL.test(options.target.protocol) ? https__default : http__default).request( - common_1.setupOutgoing(options.ssl || {}, options, req) - ); - - // Enable developers to modify the proxyReq before headers are sent - if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); } - - // Error Handler - proxyReq.on('error', onOutgoingError); - proxyReq.on('response', function (res) { - // if upgrade event isn't going to happen, close the socket - if (!res.upgrade) { - socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers)); - res.pipe(socket); - } - }); - - proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) { - proxySocket.on('error', onOutgoingError); - - // Allow us to listen when the websocket has completed - proxySocket.on('end', function () { - server.emit('close', proxyRes, proxySocket, proxyHead); - }); - - // The pipe below will end proxySocket if socket closes cleanly, but not - // if it errors (eg, vanishes from the net and starts returning - // EHOSTUNREACH). We need to do that explicitly. - socket.on('error', function () { - proxySocket.end(); - }); - - common_1.setupSocket(proxySocket); - - if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead); - - // - // Remark: Handle writing the headers to the socket when switching protocols - // Also handles when a header is an array - // - socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers)); - - proxySocket.pipe(socket).pipe(proxySocket); - - server.emit('open', proxySocket); - server.emit('proxySocket', proxySocket); //DEPRECATED. - }); - - return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT - - function onOutgoingError(err) { - if (clb) { - clb(err, req, socket); - } else { - server.emit('error', err, req, socket); - } - socket.end(); - } - } -}; - -var httpProxy_1 = createCommonjsModule(function (module) { -var httpProxy = module.exports, - extend = util__default._extend, - parse_url = url__default.parse; - -httpProxy.Server = ProxyServer; - -/** - * Returns a function that creates the loader for - * either `ws` or `web`'s passes. - * - * Examples: - * - * httpProxy.createRightProxy('ws') - * // => [Function] - * - * @param {String} Type Either 'ws' or 'web' - *  - * @return {Function} Loader Function that when called returns an iterator for the right passes - * - * @api private - */ - -function createRightProxy(type) { - - return function(options) { - return function(req, res /*, [head], [opts] */) { - var passes = (type === 'ws') ? this.wsPasses : this.webPasses, - args = [].slice.call(arguments), - cntr = args.length - 1, - head, cbl; - - /* optional args parse begin */ - if(typeof args[cntr] === 'function') { - cbl = args[cntr]; - - cntr--; - } - - var requestOptions = options; - if( - !(args[cntr] instanceof Buffer) && - args[cntr] !== res - ) { - //Copy global options - requestOptions = extend({}, options); - //Overwrite with request options - extend(requestOptions, args[cntr]); - - cntr--; - } - - if(args[cntr] instanceof Buffer) { - head = args[cntr]; - } - - /* optional args parse end */ - - ['target', 'forward'].forEach(function(e) { - if (typeof requestOptions[e] === 'string') - requestOptions[e] = parse_url(requestOptions[e]); - }); - - if (!requestOptions.target && !requestOptions.forward) { - return this.emit('error', new Error('Must provide a proper URL as target')); - } - - for(var i=0; i < passes.length; i++) { - /** - * Call of passes functions - * pass(req, res, options, head) - * - * In WebSockets case the `res` variable - * refer to the connection socket - * pass(req, socket, options, head) - */ - if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop - break; - } - } - }; - }; -} -httpProxy.createRightProxy = createRightProxy; - -function ProxyServer(options) { - eventemitter3.call(this); - - options = options || {}; - options.prependPath = options.prependPath === false ? false : true; - - this.web = this.proxyRequest = createRightProxy('web')(options); - this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options); - this.options = options; - - this.webPasses = Object.keys(webIncoming).map(function(pass) { - return webIncoming[pass]; - }); - - this.wsPasses = Object.keys(wsIncoming).map(function(pass) { - return wsIncoming[pass]; - }); - - this.on('error', this.onError, this); - -} - -util__default.inherits(ProxyServer, eventemitter3); - -ProxyServer.prototype.onError = function (err) { - // - // Remark: Replicate node core behavior using EE3 - // so we force people to handle their own errors - // - if(this.listeners('error').length === 1) { - throw err; - } -}; - -ProxyServer.prototype.listen = function(port, hostname) { - var self = this, - closure = function(req, res) { self.web(req, res); }; - - this._server = this.options.ssl ? - https__default.createServer(this.options.ssl, closure) : - http__default.createServer(closure); - - if(this.options.ws) { - this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); }); - } - - this._server.listen(port, hostname); - - return this; -}; - -ProxyServer.prototype.close = function(callback) { - var self = this; - if (this._server) { - this._server.close(done); - } - - // Wrap callback to nullify server after all open connections are closed. - function done() { - self._server = null; - if (callback) { - callback.apply(null, arguments); - } - }}; - -ProxyServer.prototype.before = function(type, passName, callback) { - if (type !== 'ws' && type !== 'web') { - throw new Error('type must be `web` or `ws`'); - } - var passes = (type === 'ws') ? this.wsPasses : this.webPasses, - i = false; - - passes.forEach(function(v, idx) { - if(v.name === passName) i = idx; - }); - - if(i === false) throw new Error('No such pass'); - - passes.splice(i, 0, callback); -}; -ProxyServer.prototype.after = function(type, passName, callback) { - if (type !== 'ws' && type !== 'web') { - throw new Error('type must be `web` or `ws`'); - } - var passes = (type === 'ws') ? this.wsPasses : this.webPasses, - i = false; - - passes.forEach(function(v, idx) { - if(v.name === passName) i = idx; - }); - - if(i === false) throw new Error('No such pass'); - - passes.splice(i++, 0, callback); -}; -}); - -// Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!) -var ProxyServer = httpProxy_1.Server; - - -/** - * Creates the proxy server. - * - * Examples: - * - * httpProxy.createProxyServer({ .. }, 8000) - * // => '{ web: [Function], ws: [Function] ... }' - * - * @param {Object} Options Config object passed to the proxy - * - * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests - * - * @api public - */ - - -function createProxyServer(options) { - /* - * `options` is needed and it must have the following layout: - * - * { - * target : - * forward: - * agent : - * ssl : - * ws : - * xfwd : - * secure : - * toProxy: - * prependPath: - * ignorePath: - * localAddress : - * changeOrigin: - * preserveHeaderKeyCase: - * auth : Basic authentication i.e. 'user:password' to compute an Authorization header. - * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null. - * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false. - * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null. - * } - * - * NOTE: `options.ws` and `options.ssl` are optional. - * `options.target and `options.forward` cannot be - * both missing - * } - */ - - return new ProxyServer(options); -} - - -ProxyServer.createProxyServer = createProxyServer; -ProxyServer.createServer = createProxyServer; -ProxyServer.createProxy = createProxyServer; - - - - -/** - * Export the proxy "Server" as the main export. - */ -var httpProxy$1 = ProxyServer; - -/*! - * Caron dimonio, con occhi di bragia - * loro accennando, tutte le raccoglie; - * batte col remo qualunque s’adagia - * - * Charon the demon, with the eyes of glede, - * Beckoning to them, collects them all together, - * Beats with his oar whoever lags behind - * - * Dante - The Divine Comedy (Canto III) - */ - -var httpProxy = httpProxy$1; - -const debug$1 = createDebugger('vite:proxy'); -function proxyMiddleware(httpServer, config) { - const options = config.server.proxy; - // lazy require only when proxy is used - const proxies = {}; - Object.keys(options).forEach((context) => { - let opts = options[context]; - if (typeof opts === 'string') { - opts = { target: opts, changeOrigin: true }; - } - const proxy = httpProxy.createProxyServer(opts); - proxy.on('error', (err) => { - config.logger.error(`${source.red(`http proxy error:`)}\n${err.stack}`, { - timestamp: true - }); - }); - if (opts.configure) { - opts.configure(proxy, opts); - } - // clone before saving because http-proxy mutates the options - proxies[context] = [proxy, { ...opts }]; - }); - if (httpServer) { - httpServer.on('upgrade', (req, socket, head) => { - var _a; - const url = req.url; - for (const context in proxies) { - if (url.startsWith(context)) { - const [proxy, opts] = proxies[context]; - if ((opts.ws || ((_a = opts.target) === null || _a === void 0 ? void 0 : _a.toString().startsWith('ws:'))) && - req.headers['sec-websocket-protocol'] !== HMR_HEADER) { - if (opts.rewrite) { - req.url = opts.rewrite(url); - } - proxy.ws(req, socket, head); - } - } - } - }); - } - return (req, res, next) => { - const url = req.url; - for (const context in proxies) { - if ((context.startsWith('^') && new RegExp(context).test(url)) || - url.startsWith(context)) { - const [proxy, opts] = proxies[context]; - const options = {}; - if (opts.bypass) { - const bypassResult = opts.bypass(req, res, opts); - if (typeof bypassResult === 'string') { - req.url = bypassResult; - debug$1(`bypass: ${req.url} -> ${bypassResult}`); - return next(); - } - else if (typeof bypassResult === 'object') { - Object.assign(options, bypassResult); - debug$1(`bypass: ${req.url} use modified options: %O`, options); - return next(); - } - else if (bypassResult === false) { - debug$1(`bypass: ${req.url} -> 404`); - return res.end(404); - } - } - debug$1(`${req.url} -> ${opts.target || opts.forward}`); - if (opts.rewrite) { - req.url = opts.rewrite(req.url); - } - proxy.web(req, res, options); - return; - } - } - next(); - }; -} - -/*! - * etag - * Copyright(c) 2014-2016 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module exports. - * @public - */ - -var etag_1 = etag; - -/** - * Module dependencies. - * @private - */ - - -var Stats = fs__default.Stats; - -/** - * Module variables. - * @private - */ - -var toString = Object.prototype.toString; - -/** - * Generate an entity tag. - * - * @param {Buffer|string} entity - * @return {string} - * @private - */ - -function entitytag (entity) { - if (entity.length === 0) { - // fast-path empty - return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' - } - - // compute hash of entity - var hash = require$$0__default$2 - .createHash('sha1') - .update(entity, 'utf8') - .digest('base64') - .substring(0, 27); - - // compute length of entity - var len = typeof entity === 'string' - ? Buffer.byteLength(entity, 'utf8') - : entity.length; - - return '"' + len.toString(16) + '-' + hash + '"' -} - -/** - * Create a simple ETag. - * - * @param {string|Buffer|Stats} entity - * @param {object} [options] - * @param {boolean} [options.weak] - * @return {String} - * @public - */ - -function etag (entity, options) { - if (entity == null) { - throw new TypeError('argument entity is required') - } - - // support fs.Stats object - var isStats = isstats(entity); - var weak = options && typeof options.weak === 'boolean' - ? options.weak - : isStats; - - // validate argument - if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { - throw new TypeError('argument entity must be string, Buffer, or fs.Stats') - } - - // generate entity tag - var tag = isStats - ? stattag(entity) - : entitytag(entity); - - return weak - ? 'W/' + tag - : tag -} - -/** - * Determine if object is a Stats object. - * - * @param {object} obj - * @return {boolean} - * @api private - */ - -function isstats (obj) { - // genuine fs.Stats - if (typeof Stats === 'function' && obj instanceof Stats) { - return true - } - - // quack quack - return obj && typeof obj === 'object' && - 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && - 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && - 'ino' in obj && typeof obj.ino === 'number' && - 'size' in obj && typeof obj.size === 'number' -} - -/** - * Generate a tag for a stat. - * - * @param {object} stat - * @return {string} - * @private - */ - -function stattag (stat) { - var mtime = stat.mtime.getTime().toString(16); - var size = stat.size.toString(16); - - return '"' + size + '-' + mtime + '"' -} - -const isDebug$2 = process.env.DEBUG; -const alias = { - js: 'application/javascript', - css: 'text/css', - html: 'text/html', - json: 'application/json' -}; -function send$1(req, res, content, type, etag = etag_1(content, { weak: true }), cacheControl = 'no-cache', map) { - if (req.headers['if-none-match'] === etag) { - res.statusCode = 304; - return res.end(); - } - res.setHeader('Content-Type', alias[type] || type); - res.setHeader('Cache-Control', cacheControl); - res.setHeader('Etag', etag); - // inject source map reference - if (map && map.mappings) { - if (isDebug$2) { - content += `\n/*${JSON.stringify(map, null, 2).replace(/\*\//g, '*\\/')}*/\n`; - } - content += genSourceMapString(map); - } - res.statusCode = 200; - return res.end(content); -} -function genSourceMapString(map) { - if (typeof map !== 'string') { - map = JSON.stringify(map); - } - return `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(map).toString('base64')}`; -} - -/* eslint-disable node/no-deprecated-api */ - -var safeBuffer = createCommonjsModule(function (module, exports) { -var Buffer = buffer__default.Buffer; - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key]; - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer__default; -} else { - // Copy properties from require('buffer') - copyProps(buffer__default, exports); - exports.Buffer = SafeBuffer; -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer); - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -}; - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size); - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding); - } else { - buf.fill(fill); - } - } else { - buf.fill(0); - } - return buf -}; - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -}; - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer__default.SlowBuffer(size) -}; -}); - -var convertSourceMap = createCommonjsModule(function (module, exports) { - - - - -Object.defineProperty(exports, 'commentRegex', { - get: function getCommentRegex () { - return /^\s*\/(?:\/|\*)[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/mg; - } -}); - -Object.defineProperty(exports, 'mapFileCommentRegex', { - get: function getMapFileCommentRegex () { - // Matches sourceMappingURL in either // or /* comment styles. - return /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"`]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/){1}[ \t]*$)/mg; - } -}); - - -function decodeBase64(base64) { - return safeBuffer.Buffer.from(base64, 'base64').toString(); -} - -function stripComment(sm) { - return sm.split(',').pop(); -} - -function readFromFileMap(sm, dir) { - // NOTE: this will only work on the server since it attempts to read the map file - - var r = exports.mapFileCommentRegex.exec(sm); - - // for some odd reason //# .. captures in 1 and /* .. */ in 2 - var filename = r[1] || r[2]; - var filepath = path__default.resolve(dir, filename); - - try { - return fs__default.readFileSync(filepath, 'utf8'); - } catch (e) { - throw new Error('An error occurred while trying to read the map file at ' + filepath + '\n' + e); - } -} - -function Converter (sm, opts) { - opts = opts || {}; - - if (opts.isFileComment) sm = readFromFileMap(sm, opts.commentFileDir); - if (opts.hasComment) sm = stripComment(sm); - if (opts.isEncoded) sm = decodeBase64(sm); - if (opts.isJSON || opts.isEncoded) sm = JSON.parse(sm); - - this.sourcemap = sm; -} - -Converter.prototype.toJSON = function (space) { - return JSON.stringify(this.sourcemap, null, space); -}; - -Converter.prototype.toBase64 = function () { - var json = this.toJSON(); - return safeBuffer.Buffer.from(json, 'utf8').toString('base64'); -}; - -Converter.prototype.toComment = function (options) { - var base64 = this.toBase64(); - var data = 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + base64; - return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; -}; - -// returns copy instead of original -Converter.prototype.toObject = function () { - return JSON.parse(this.toJSON()); -}; - -Converter.prototype.addProperty = function (key, value) { - if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead'); - return this.setProperty(key, value); -}; - -Converter.prototype.setProperty = function (key, value) { - this.sourcemap[key] = value; - return this; -}; - -Converter.prototype.getProperty = function (key) { - return this.sourcemap[key]; -}; - -exports.fromObject = function (obj) { - return new Converter(obj); -}; - -exports.fromJSON = function (json) { - return new Converter(json, { isJSON: true }); -}; - -exports.fromBase64 = function (base64) { - return new Converter(base64, { isEncoded: true }); -}; - -exports.fromComment = function (comment) { - comment = comment - .replace(/^\/\*/g, '//') - .replace(/\*\/$/g, ''); - - return new Converter(comment, { isEncoded: true, hasComment: true }); -}; - -exports.fromMapFileComment = function (comment, dir) { - return new Converter(comment, { commentFileDir: dir, isFileComment: true, isJSON: true }); -}; - -// Finds last sourcemap comment in file or returns null if none was found -exports.fromSource = function (content) { - var m = content.match(exports.commentRegex); - return m ? exports.fromComment(m.pop()) : null; -}; - -// Finds last sourcemap comment in file or returns null if none was found -exports.fromMapFileSource = function (content, dir) { - var m = content.match(exports.mapFileCommentRegex); - return m ? exports.fromMapFileComment(m.pop(), dir) : null; -}; - -exports.removeComments = function (src) { - return src.replace(exports.commentRegex, ''); -}; - -exports.removeMapFileComments = function (src) { - return src.replace(exports.mapFileCommentRegex, ''); -}; - -exports.generateMapFileComment = function (file, options) { - var data = 'sourceMappingURL=' + file; - return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data; -}; -}); - -/** - * - * @param {Node} param - * @returns {string[]} - */ -function extract_names(param) { - return extract_identifiers(param).map(node => node.name); -} - -/** - * - * @param {Node} param - * @param {Identifier[]} nodes - * @returns {Identifier[]} - */ -function extract_identifiers(param, nodes = []) { - switch (param.type) { - case 'Identifier': - nodes.push(param); - break; - - case 'MemberExpression': - let object = param; - while (object.type === 'MemberExpression') { - object = /** @type {any} */ (object.object); - } - nodes.push(/** @type {any} */ (object)); - break; - - case 'ObjectPattern': - /** - * - * @param {Property | RestElement} prop - */ - const handle_prop = (prop) => { - if (prop.type === 'RestElement') { - extract_identifiers(prop.argument, nodes); - } else { - extract_identifiers(prop.value, nodes); - } - }; - - param.properties.forEach(handle_prop); - break; - - case 'ArrayPattern': - /** - * - * @param {Node} element - */ - const handle_element = (element) => { - if (element) extract_identifiers(element, nodes); - }; - - param.elements.forEach(handle_element); - break; - - case 'RestElement': - extract_identifiers(param.argument, nodes); - break; - - case 'AssignmentPattern': - extract_identifiers(param.left, nodes); - break; - } - - return nodes; -} - -const ssrModuleExportsKey = `__vite_ssr_exports__`; -const ssrImportKey = `__vite_ssr_import__`; -const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`; -const ssrExportAllKey = `__vite_ssr_exportAll__`; -const ssrImportMetaKey = `__vite_ssr_import_meta__`; -async function ssrTransform(code, inMap, url) { - const s = new MagicString(code); - const ast = parser$1.parse(code, { - sourceType: 'module', - ecmaVersion: 2021, - locations: true - }); - let uid = 0; - const deps = new Set(); - const idToImportMap = new Map(); - const declaredConst = new Set(); - function defineImport(node, source) { - deps.add(source); - const importId = `__vite_ssr_import_${uid++}__`; - s.appendLeft(node.start, `const ${importId} = ${ssrImportKey}(${JSON.stringify(source)})\n`); - return importId; - } - function defineExport(name, local = name) { - s.append(`\nObject.defineProperty(${ssrModuleExportsKey}, "${name}", ` + - `{ enumerable: true, configurable: true, get(){ return ${local} }})`); - } - // 1. check all import statements and record id -> importName map - for (const node of ast.body) { - // import foo from 'foo' --> foo -> __import_foo__.default - // import { baz } from 'foo' --> baz -> __import_foo__.baz - // import * as ok from 'foo' --> ok -> __import_foo__ - if (node.type === 'ImportDeclaration') { - const importId = defineImport(node, node.source.value); - for (const spec of node.specifiers) { - if (spec.type === 'ImportSpecifier') { - idToImportMap.set(spec.local.name, `${importId}.${spec.imported.name}`); - } - else if (spec.type === 'ImportDefaultSpecifier') { - idToImportMap.set(spec.local.name, `${importId}.default`); - } - else { - // namespace specifier - idToImportMap.set(spec.local.name, importId); - } - } - s.remove(node.start, node.end); - } - } - // 2. check all export statements and define exports - for (const node of ast.body) { - // named exports - if (node.type === 'ExportNamedDeclaration') { - if (node.declaration) { - if (node.declaration.type === 'FunctionDeclaration' || - node.declaration.type === 'ClassDeclaration') { - // export function foo() {} - defineExport(node.declaration.id.name); - } - else { - // export const foo = 1, bar = 2 - for (const declaration of node.declaration.declarations) { - const names = extract_names(declaration.id); - for (const name of names) { - defineExport(name); - } - } - } - s.remove(node.start, node.declaration.start); - } - else if (node.source) { - // export { foo, bar } from './foo' - const importId = defineImport(node, node.source.value); - for (const spec of node.specifiers) { - defineExport(spec.exported.name, `${importId}.${spec.local.name}`); - } - s.remove(node.start, node.end); - } - else { - // export { foo, bar } - for (const spec of node.specifiers) { - const local = spec.local.name; - const binding = idToImportMap.get(local); - defineExport(spec.exported.name, binding || local); - } - s.remove(node.start, node.end); - } - } - // default export - if (node.type === 'ExportDefaultDeclaration') { - s.overwrite(node.start, node.start + 14, `${ssrModuleExportsKey}.default =`); - } - // export * from './foo' - if (node.type === 'ExportAllDeclaration') { - const importId = defineImport(node, node.source.value); - s.remove(node.start, node.end); - s.append(`\n${ssrExportAllKey}(${importId})`); - } - } - // 3. convert references to import bindings & import.meta references - walk(ast, { - onIdentifier(id, parent, parentStack) { - const binding = idToImportMap.get(id.name); - if (!binding) { - return; - } - if (isStaticProperty(parent) && parent.shorthand) { - // let binding used in a property shorthand - // { foo } -> { foo: __import_x__.foo } - // skip for destructuring patterns - if (!parent.inPattern || - isInDestructuringAssignment(parent, parentStack)) { - s.appendLeft(id.end, `: ${binding}`); - } - } - else if (parent.type === 'ClassDeclaration' && - id === parent.superClass) { - if (!declaredConst.has(id.name)) { - declaredConst.add(id.name); - // locate the top-most node containing the class declaration - const topNode = parentStack[1]; - s.prependRight(topNode.start, `const ${id.name} = ${binding};\n`); - } - } - else { - s.overwrite(id.start, id.end, binding); - } - }, - onImportMeta(node) { - s.overwrite(node.start, node.end, ssrImportMetaKey); - }, - onDynamicImport(node) { - s.overwrite(node.start, node.start + 6, ssrDynamicImportKey); - } - }); - let map = s.generateMap({ hires: true }); - if (inMap && inMap.mappings && inMap.sources.length > 0) { - map = combineSourcemaps(url, [ - { - ...map, - sources: inMap.sources, - sourcesContent: inMap.sourcesContent - }, - inMap - ]); - } - else { - map.sources = [url]; - map.sourcesContent = [code]; - } - return { - code: s.toString(), - map, - deps: [...deps] - }; -} -/** - * Same logic from \@vue/compiler-core & \@vue/compiler-sfc - * Except this is using acorn AST - */ -function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) { - const parentStack = []; - const scope = Object.create(null); - const scopeMap = new WeakMap(); - const setScope = (node, name) => { - let scopeIds = scopeMap.get(node); - if (scopeIds && scopeIds.has(name)) { - return; - } - if (name in scope) { - scope[name]++; - } - else { - scope[name] = 1; - } - if (!scopeIds) { - scopeIds = new Set(); - scopeMap.set(node, scopeIds); - } - scopeIds.add(name); - }; - walk$1(root, { - enter(node, parent) { - if (node.type === 'ImportDeclaration') { - return this.skip(); - } - parent && parentStack.push(parent); - if (node.type === 'MetaProperty' && node.meta.name === 'import') { - onImportMeta(node); - } - else if (node.type === 'ImportExpression') { - onDynamicImport(node); - } - if (node.type === 'Identifier') { - if (!scope[node.name] && isRefIdentifier(node, parent, parentStack)) { - onIdentifier(node, parent, parentStack); - } - } - else if (isFunction(node)) { - // walk function expressions and add its arguments to known identifiers - // so that we don't prefix them - node.params.forEach((p) => walk$1(p, { - enter(child, parent) { - if (child.type === 'Identifier' && - // do not record as scope variable if is a destructuring key - !isStaticPropertyKey(child, parent) && - // do not record if this is a default value - // assignment of a destructuring variable - !(parent && - parent.type === 'AssignmentPattern' && - parent.right === child)) { - setScope(node, child.name); - } - } - })); - } - else if (node.type === 'Property' && parent.type === 'ObjectPattern') { - node.inPattern = true; - } - else if (node.type === 'VariableDeclarator') { - const parentFunction = findParentFunction(parentStack); - if (parentFunction) { - if (node.id.type === 'ObjectPattern') { - node.id.properties.forEach((property) => { - if (property.type === 'RestElement') { - setScope(parentFunction, property.argument.name); - } - else { - setScope(parentFunction, property.value.name); - } - }); - } - else { - setScope(parentFunction, node.id.name); - } - } - } - }, - leave(node, parent) { - parent && parentStack.pop(); - const scopeIds = scopeMap.get(node); - if (scopeIds) { - scopeIds.forEach((id) => { - scope[id]--; - if (scope[id] === 0) { - delete scope[id]; - } - }); - } - } - }); -} -function isRefIdentifier(id, parent, parentStack) { - // declaration id - if ((parent.type === 'VariableDeclarator' || - parent.type === 'ClassDeclaration') && - parent.id === id) { - return false; - } - if (isFunction(parent)) { - // function declaration/expression id - if (parent.id === id) { - return false; - } - // params list - if (parent.params.includes(id)) { - return false; - } - } - // class method name - if (parent.type === 'MethodDefinition') { - return false; - } - // property key - // this also covers object destructuring pattern - if (isStaticPropertyKey(id, parent) || parent.inPattern) { - return false; - } - // non-assignment array destructuring pattern - if (parent.type === 'ArrayPattern' && - !isInDestructuringAssignment(parent, parentStack)) { - return false; - } - // member expression property - if (parent.type === 'MemberExpression' && - parent.property === id && - !parent.computed) { - return false; - } - if (parent.type === 'ExportSpecifier') { - return false; - } - // is a special keyword but parsed as identifier - if (id.name === 'arguments') { - return false; - } - return true; -} -const isStaticProperty = (node) => node && node.type === 'Property' && !node.computed; -const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node; -function isFunction(node) { - return /Function(?:Expression|Declaration)$|Method$/.test(node.type); -} -function findParentFunction(parentStack) { - for (const node of parentStack) { - if (isFunction(node)) { - return node; - } - } -} -function isInDestructuringAssignment(parent, parentStack) { - if (parent && - (parent.type === 'Property' || parent.type === 'ArrayPattern')) { - let i = parentStack.length; - while (i--) { - const p = parentStack[i]; - if (p.type === 'AssignmentExpression') { - return true; - } - else if (p.type !== 'Property' && !p.type.endsWith('Pattern')) { - break; - } - } - } - return false; -} - -async function injectSourcesContent(map, file) { - const sourceRoot = await fs$2.promises.realpath(path__default.resolve(path__default.dirname(file), map.sourceRoot || '')); - map.sourcesContent = []; - await Promise.all(map.sources.map(async (sourcePath, i) => { - map.sourcesContent[i] = await fs$2.promises.readFile(path__default.resolve(sourceRoot, decodeURI(sourcePath)), 'utf-8'); - })); -} - -const debugLoad = createDebugger('vite:load'); -const debugTransform = createDebugger('vite:transform'); -const debugCache$1 = createDebugger('vite:cache'); -const isDebug$1 = !!process.env.DEBUG; -async function transformRequest(url, { config, pluginContainer, moduleGraph, watcher }, options = {}) { - var _a, _b; - url = removeTimestampQuery(url); - const { root, logger } = config; - const prettyUrl = isDebug$1 ? prettifyUrl(url, root) : ''; - const ssr = !!options.ssr; - // check if we have a fresh cache - const module = await moduleGraph.getModuleByUrl(url); - const cached = module && (ssr ? module.ssrTransformResult : module.transformResult); - if (cached) { - isDebug$1 && debugCache$1(`[memory] ${prettyUrl}`); - return cached; - } - // resolve - const id = ((_a = (await pluginContainer.resolveId(url))) === null || _a === void 0 ? void 0 : _a.id) || url; - const file = cleanUrl(id); - let code = null; - let map = null; - // load - const loadStart = isDebug$1 ? Date.now() : 0; - const loadResult = await pluginContainer.load(id, ssr); - if (loadResult == null) { - // if this is an html request and there is no load result, skip ahead to - // SPA fallback. - if (options.html && !id.endsWith('.html')) { - return null; - } - // try fallback loading it from fs as string - // if the file is a binary, there should be a plugin that already loaded it - // as string - try { - code = await fs$2.promises.readFile(file, 'utf-8'); - isDebug$1 && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`); - } - catch (e) { - if (e.code !== 'ENOENT') { - throw e; - } - } - if (code) { - try { - map = (_b = (convertSourceMap.fromSource(code) || - convertSourceMap.fromMapFileSource(code, path__default.dirname(file)))) === null || _b === void 0 ? void 0 : _b.toObject(); - } - catch (e) { - logger.warn(`Failed to load source map for ${url}.`, { - timestamp: true - }); - } - } - } - else { - isDebug$1 && debugLoad(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`); - if (typeof loadResult === 'object') { - code = loadResult.code; - map = loadResult.map; - } - else { - code = loadResult; - } - } - if (code == null) { - if (checkPublicFile(url, config)) { - throw new Error(`Failed to load url ${url} (resolved id: ${id}). ` + - `This file is in /public and will be copied as-is during build without ` + - `going through the plugin transforms, and therefore should not be ` + - `imported from source code. It can only be referenced via HTML tags.`); - } - else { - return null; - } - } - // ensure module in graph after successful load - const mod = await moduleGraph.ensureEntryFromUrl(url); - ensureWatchedFile(watcher, mod.file, root); - // transform - const transformStart = isDebug$1 ? Date.now() : 0; - const transformResult = await pluginContainer.transform(code, id, map, ssr); - if (transformResult == null || - (typeof transformResult === 'object' && transformResult.code == null)) { - // no transform applied, keep code as-is - isDebug$1 && - debugTransform(timeFrom(transformStart) + source.dim(` [skipped] ${prettyUrl}`)); - } - else { - isDebug$1 && debugTransform(`${timeFrom(transformStart)} ${prettyUrl}`); - code = transformResult.code; - map = transformResult.map; - } - if (map && mod.file) { - map = (typeof map === 'string' ? JSON.parse(map) : map); - if (map.mappings && !map.sourcesContent) { - await injectSourcesContent(map, mod.file); - } - } - if (ssr) { - return (mod.ssrTransformResult = await ssrTransform(code, map, url)); - } - else { - return (mod.transformResult = { - code, - map, - etag: etag_1(code, { weak: true }) - }); - } -} - -/** - * Time (ms) Vite has to full-reload the page before returning - * an empty response. - */ -const NEW_DEPENDENCY_BUILD_TIMEOUT = 1000; -const debugCache = createDebugger('vite:cache'); -const isDebug = !!process.env.DEBUG; -const knownIgnoreList = new Set(['/', '/favicon.ico']); -function transformMiddleware(server) { - const { config: { root, logger }, moduleGraph } = server; - return async (req, res, next) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j; - if (req.method !== 'GET' || knownIgnoreList.has(req.url)) { - return next(); - } - if (server._pendingReload && - // always allow vite client requests so that it can trigger page reload - !((_a = req.url) === null || _a === void 0 ? void 0 : _a.startsWith(CLIENT_PUBLIC_PATH)) && - !((_b = req.url) === null || _b === void 0 ? void 0 : _b.includes('vite/dist/client'))) { - // missing dep pending reload, hold request until reload happens - server._pendingReload.then(() => - // If the refresh has not happened after timeout, Vite considers - // something unexpected has happened. In this case, Vite - // returns an empty response that will error. - setTimeout(() => { - // status code request timeout - res.statusCode = 408; - res.end(`

[vite] Something unexpected happened while optimizing "${req.url}"

` + - `

The current page should have reloaded by now

`); - }, NEW_DEPENDENCY_BUILD_TIMEOUT)); - return; - } - let url; - try { - url = removeTimestampQuery(req.url).replace(NULL_BYTE_PLACEHOLDER, '\0'); - } - catch (err) { - // if it starts with %PUBLIC%, someone's migrating from something - // like create-react-app - let errorMessage; - if ((_c = req.url) === null || _c === void 0 ? void 0 : _c.startsWith('/%PUBLIC')) { - errorMessage = `index.html shouldn't include environment variables like %PUBLIC_URL%, see https://vitejs.dev/guide/#index-html-and-project-root for more information`; - } - else { - errorMessage = `Vite encountered a suspiciously malformed request ${req.url}`; - } - next(new Error(errorMessage)); - return; - } - const withoutQuery = cleanUrl(url); - try { - const isSourceMap = withoutQuery.endsWith('.map'); - // since we generate source map references, handle those requests here - if (isSourceMap) { - const originalUrl = url.replace(/\.map($|\?)/, '$1'); - const map = (_e = (_d = (await moduleGraph.getModuleByUrl(originalUrl))) === null || _d === void 0 ? void 0 : _d.transformResult) === null || _e === void 0 ? void 0 : _e.map; - if (map) { - return send$1(req, res, JSON.stringify(map), 'json'); - } - else { - return next(); - } - } - // warn explicit /public/ paths - if (url.startsWith('/public/')) { - logger.warn(source.yellow(`files in the public directory are served at the root path.\n` + - `Instead of ${source.cyan(url)}, use ${source.cyan(url.replace(/^\/public\//, '/'))}.`)); - } - if (isJSRequest(url) || - isImportRequest(url) || - isCSSRequest(url) || - isHTMLProxy(url)) { - // strip ?import - url = removeImportQuery(url); - // Strip valid id prefix. This is prepended to resolved Ids that are - // not valid browser import specifiers by the importAnalysis plugin. - url = unwrapId$1(url); - // for CSS, we need to differentiate between normal CSS requests and - // imports - if (isCSSRequest(url) && ((_f = req.headers.accept) === null || _f === void 0 ? void 0 : _f.includes('text/css'))) { - url = injectQuery(url, 'direct'); - } - // check if we can return 304 early - const ifNoneMatch = req.headers['if-none-match']; - if (ifNoneMatch && - ((_h = (_g = (await moduleGraph.getModuleByUrl(url))) === null || _g === void 0 ? void 0 : _g.transformResult) === null || _h === void 0 ? void 0 : _h.etag) === - ifNoneMatch) { - isDebug && debugCache(`[304] ${prettifyUrl(url, root)}`); - res.statusCode = 304; - return res.end(); - } - // resolve, load and transform using the plugin container - const result = await transformRequest(url, server, { - html: (_j = req.headers.accept) === null || _j === void 0 ? void 0 : _j.includes('text/html') - }); - if (result) { - const type = isDirectCSSRequest(url) ? 'css' : 'js'; - const isDep = DEP_VERSION_RE.test(url) || - url.includes(`node_modules/${DEP_CACHE_DIR}`); - return send$1(req, res, result.code, type, result.etag, - // allow browser to cache npm deps! - isDep ? 'max-age=31536000,immutable' : 'no-cache', result.map); - } - } - } - catch (e) { - return next(e); - } - next(); - }; -} - -function createDevHtmlTransformFn(server) { - const [preHooks, postHooks] = resolveHtmlTransforms(server.config.plugins); - return (url, html) => { - return applyHtmlTransforms(html, url, getHtmlFilename(url, server), [...preHooks, devHtmlHook, ...postHooks], server); - }; -} -function getHtmlFilename(url, server) { - if (url.startsWith(FS_PREFIX)) { - return fsPathFromId(url); - } - else { - return path__default.join(server.config.root, url.slice(1)); - } -} -const startsWithSingleSlashRE = /^\/(?!\/)/; -const devHtmlHook = async (html, { path: htmlPath, server }) => { - const config = server === null || server === void 0 ? void 0 : server.config; - const base = config.base || '/'; - const s = new MagicString(html); - let scriptModuleIndex = -1; - await traverseHtml(html, htmlPath, (node) => { - var _a; - if (node.type !== 1 /* ELEMENT */) { - return; - } - // script tags - if (node.tag === 'script') { - const { src, isModule } = getScriptInfo(node); - if (isModule) { - scriptModuleIndex++; - } - if (src) { - const url = ((_a = src.value) === null || _a === void 0 ? void 0 : _a.content) || ''; - if (startsWithSingleSlashRE.test(url)) { - // prefix with base - s.overwrite(src.value.loc.start.offset, src.value.loc.end.offset, `"${config.base + url.slice(1)}"`); - } - } - else if (isModule) { - // inline js module. convert to src="proxy" - s.overwrite(node.loc.start.offset, node.loc.end.offset, ``); - } - } - // elements with [href/src] attrs - const assetAttrs = assetAttrsConfig[node.tag]; - if (assetAttrs) { - for (const p of node.props) { - if (p.type === 6 /* ATTRIBUTE */ && - p.value && - assetAttrs.includes(p.name)) { - const url = p.value.content || ''; - if (startsWithSingleSlashRE.test(url)) { - s.overwrite(p.value.loc.start.offset, p.value.loc.end.offset, `"${config.base + url.slice(1)}"`); - } - } - } - } - }); - html = s.toString(); - return { - html, - tags: [ - { - tag: 'script', - attrs: { - type: 'module', - src: path__default.posix.join(base, CLIENT_PUBLIC_PATH) - }, - injectTo: 'head-prepend' - } - ] - }; -}; -function indexHtmlMiddleware(server) { - return async (req, res, next) => { - const url = req.url && cleanUrl(req.url); - // spa-fallback always redirects to /index.html - if ((url === null || url === void 0 ? void 0 : url.endsWith('.html')) && req.headers['sec-fetch-dest'] !== 'script') { - const filename = getHtmlFilename(url, server); - if (fs__default.existsSync(filename)) { - try { - let html = fs__default.readFileSync(filename, 'utf-8'); - html = await server.transformIndexHtml(url, html); - return send$1(req, res, html, 'html'); - } - catch (e) { - return next(e); - } - } - } - next(); - }; -} - -var lib = createCommonjsModule(function (module, exports) { - - - -module.exports = function historyApiFallback(options) { - options = options || {}; - var logger = getLogger(options); - - return function(req, res, next) { - var headers = req.headers; - if (req.method !== 'GET') { - logger( - 'Not rewriting', - req.method, - req.url, - 'because the method is not GET.' - ); - return next(); - } else if (!headers || typeof headers.accept !== 'string') { - logger( - 'Not rewriting', - req.method, - req.url, - 'because the client did not send an HTTP accept header.' - ); - return next(); - } else if (headers.accept.indexOf('application/json') === 0) { - logger( - 'Not rewriting', - req.method, - req.url, - 'because the client prefers JSON.' - ); - return next(); - } else if (!acceptsHtml(headers.accept, options)) { - logger( - 'Not rewriting', - req.method, - req.url, - 'because the client does not accept HTML.' - ); - return next(); - } - - var parsedUrl = url__default.parse(req.url); - var rewriteTarget; - options.rewrites = options.rewrites || []; - for (var i = 0; i < options.rewrites.length; i++) { - var rewrite = options.rewrites[i]; - var match = parsedUrl.pathname.match(rewrite.from); - if (match !== null) { - rewriteTarget = evaluateRewriteRule(parsedUrl, match, rewrite.to, req); - - if(rewriteTarget.charAt(0) !== '/') { - logger( - 'We recommend using an absolute path for the rewrite target.', - 'Received a non-absolute rewrite target', - rewriteTarget, - 'for URL', - req.url - ); - } - - logger('Rewriting', req.method, req.url, 'to', rewriteTarget); - req.url = rewriteTarget; - return next(); - } - } - - var pathname = parsedUrl.pathname; - if (pathname.lastIndexOf('.') > pathname.lastIndexOf('/') && - options.disableDotRule !== true) { - logger( - 'Not rewriting', - req.method, - req.url, - 'because the path includes a dot (.) character.' - ); - return next(); - } - - rewriteTarget = options.index || '/index.html'; - logger('Rewriting', req.method, req.url, 'to', rewriteTarget); - req.url = rewriteTarget; - next(); - }; -}; - -function evaluateRewriteRule(parsedUrl, match, rule, req) { - if (typeof rule === 'string') { - return rule; - } else if (typeof rule !== 'function') { - throw new Error('Rewrite rule can only be of type string or function.'); - } - - return rule({ - parsedUrl: parsedUrl, - match: match, - request: req - }); -} - -function acceptsHtml(header, options) { - options.htmlAcceptHeaders = options.htmlAcceptHeaders || ['text/html', '*/*']; - for (var i = 0; i < options.htmlAcceptHeaders.length; i++) { - if (header.indexOf(options.htmlAcceptHeaders[i]) !== -1) { - return true; - } - } - return false; -} - -function getLogger(options) { - if (options && options.logger) { - return options.logger; - } else if (options && options.verbose) { - return console.log.bind(console); - } - return function(){}; -} -}); - -function decodeURIMiddleware() { - return (req, _, next) => { - // #2195 - req.url = decodeURI(req.url); - // `sirv` middleware uses the req._parsedUrl values to find the file, - // so decode it all together. - // @ts-ignore - const parsedUrl = req._parsedUrl; - for (const key of Object.keys(parsedUrl)) { - const val = parsedUrl[key]; - if (val) - parsedUrl[key] = decodeURI(val); - } - next(); - }; -} - -function list(dir, callback, pre='') { - dir = path$1.resolve('.', dir); - let arr = fs$2.readdirSync(dir); - let i=0, abs, stats; - for (; i < arr.length; i++) { - abs = path$1.join(dir, arr[i]); - stats = fs$2.statSync(abs); - stats.isDirectory() - ? list(abs, callback, path$1.join(pre, arr[i])) - : callback(path$1.join(pre, arr[i]), abs, stats); - } -} - -function parse$2(str) { - let i=0, j=0, k, v; - let out={}, arr=str.split('&'); - for (; i < arr.length; i++) { - j = arr[i].indexOf('='); - v = !!~j && arr[i].substring(j+1) || ''; - k = !!~j ? arr[i].substring(0, j) : arr[i]; - out[k] = out[k] !== void 0 ? [].concat(out[k], v) : v; - } - return out; -} - -function parser (req, toDecode) { - let url = req.url; - if (url == null) return; - - let obj = req._parsedUrl; - if (obj && obj._raw === url) return obj; - - obj = { - path: url, - pathname: url, - search: null, - query: null, - href: url, - _raw: url - }; - - if (url.length > 1) { - if (toDecode && !req._decoded && !!~url.indexOf('%', 1)) { - let nxt = url; - try { nxt = decodeURIComponent(url); } catch (e) {/* bad */} - url = req.url = obj.href = obj.path = obj.pathname = obj._raw = nxt; - req._decoded = true; - } - - let idx = url.indexOf('?', 1); - - if (idx !== -1) { - obj.search = url.substring(idx); - obj.query = obj.search.substring(1); - obj.pathname = url.substring(0, idx); - if (toDecode && obj.query.length > 0) { - obj.query = parse$2(obj.query); - } - } - } - - return (req._parsedUrl = obj); -} - -/** - * @param typeMap [Object] Map of MIME type -> Array[extensions] - * @param ... - */ -function Mime() { - this._types = Object.create(null); - this._extensions = Object.create(null); - - for (let i = 0; i < arguments.length; i++) { - this.define(arguments[i]); - } - - this.define = this.define.bind(this); - this.getType = this.getType.bind(this); - this.getExtension = this.getExtension.bind(this); -} - -/** - * Define mimetype -> extension mappings. Each key is a mime-type that maps - * to an array of extensions associated with the type. The first extension is - * used as the default extension for the type. - * - * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); - * - * If a type declares an extension that has already been defined, an error will - * be thrown. To suppress this error and force the extension to be associated - * with the new type, pass `force`=true. Alternatively, you may prefix the - * extension with "*" to map the type to extension, without mapping the - * extension to the type. - * - * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']}); - * - * - * @param map (Object) type definitions - * @param force (Boolean) if true, force overriding of existing definitions - */ -Mime.prototype.define = function(typeMap, force) { - for (let type in typeMap) { - let extensions = typeMap[type].map(function(t) { - return t.toLowerCase(); - }); - type = type.toLowerCase(); - - for (let i = 0; i < extensions.length; i++) { - const ext = extensions[i]; - - // '*' prefix = not the preferred type for this extension. So fixup the - // extension, and skip it. - if (ext[0] === '*') { - continue; - } - - if (!force && (ext in this._types)) { - throw new Error( - 'Attempt to change mapping for "' + ext + - '" extension from "' + this._types[ext] + '" to "' + type + - '". Pass `force=true` to allow this, otherwise remove "' + ext + - '" from the list of extensions for "' + type + '".' - ); - } - - this._types[ext] = type; - } - - // Use first extension as default - if (force || !this._extensions[type]) { - const ext = extensions[0]; - this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1); - } - } -}; - -/** - * Lookup a mime type based on extension - */ -Mime.prototype.getType = function(path) { - path = String(path); - let last = path.replace(/^.*[/\\]/, '').toLowerCase(); - let ext = last.replace(/^.*\./, '').toLowerCase(); - - let hasPath = last.length < path.length; - let hasDot = ext.length < last.length - 1; - - return (hasDot || !hasPath) && this._types[ext] || null; -}; - -/** - * Return file extension associated with a mime type - */ -Mime.prototype.getExtension = function(type) { - type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; - return type && this._extensions[type.toLowerCase()] || null; -}; - -var Mime_1 = Mime; - -var standard = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma","es"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/mrb-consumer+xml":["*xdf"],"application/mrb-publish+xml":["*xdf"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["*xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-error+xml":["xer"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}; - -var lite = new Mime_1(standard); - -const noop = () => {}; - -function isMatch(uri, arr) { - for (let i=0; i < arr.length; i++) { - if (arr[i].test(uri)) return true; - } -} - -function toAssume(uri, extns) { - let i=0, x, len=uri.length - 1; - if (uri.charCodeAt(len) === 47) { - uri = uri.substring(0, len); - } - - let arr=[], tmp=`${uri}/index`; - for (; i < extns.length; i++) { - x = extns[i] ? `.${extns[i]}` : ''; - if (uri) arr.push(uri + x); - arr.push(tmp + x); - } - - return arr; -} - -function viaCache(cache, uri, extns) { - let i=0, data, arr=toAssume(uri, extns); - for (; i < arr.length; i++) { - if (data = cache[arr[i]]) return data; - } -} - -function viaLocal(dir, isEtag, uri, extns) { - let i=0, arr=toAssume(uri, extns); - let abs, stats, name, headers; - for (; i < arr.length; i++) { - abs = path$1.normalize(path$1.join(dir, name=arr[i])); - if (abs.startsWith(dir) && fs__namespace.existsSync(abs)) { - stats = fs__namespace.statSync(abs); - if (stats.isDirectory()) continue; - headers = toHeaders(name, stats, isEtag); - headers['Cache-Control'] = isEtag ? 'no-cache' : 'no-store'; - return { abs, stats, headers }; - } - } -} - -function is404(req, res) { - return (res.statusCode=404,res.end()); -} - -function send(req, res, file, stats, headers) { - let code=200, tmp, opts={}; - headers = { ...headers }; - - for (let key in headers) { - tmp = res.getHeader(key); - if (tmp) headers[key] = tmp; - } - - if (tmp = res.getHeader('content-type')) { - headers['Content-Type'] = tmp; - } - - if (req.headers.range) { - code = 206; - let [x, y] = req.headers.range.replace('bytes=', '').split('-'); - let end = opts.end = parseInt(y, 10) || stats.size - 1; - let start = opts.start = parseInt(x, 10) || 0; - - if (start >= stats.size || end >= stats.size) { - res.setHeader('Content-Range', `bytes */${stats.size}`); - res.statusCode = 416; - return res.end(); - } - - headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`; - headers['Content-Length'] = (end - start + 1); - headers['Accept-Ranges'] = 'bytes'; - } - - res.writeHead(code, headers); - fs__namespace.createReadStream(file, opts).pipe(res); -} - -function isEncoding(name, type, headers) { - headers['Content-Encoding'] = type; - headers['Content-Type'] = lite.getType(name.replace(/\.([^.]*)$/, '')) || ''; -} - -function toHeaders(name, stats, isEtag) { - let headers = { - 'Content-Length': stats.size, - 'Content-Type': lite.getType(name) || '', - 'Last-Modified': stats.mtime.toUTCString(), - }; - if (isEtag) headers['ETag'] = `W/"${stats.size}-${stats.mtime.getTime()}"`; - if (/\.br$/.test(name)) isEncoding(name, 'br', headers); - if (/\.gz$/.test(name)) isEncoding(name, 'gzip', headers); - return headers; -} - -function sirv (dir, opts={}) { - dir = path$1.resolve(dir || '.'); - - let isNotFound = opts.onNoMatch || is404; - let setHeaders = opts.setHeaders || noop; - - let extensions = opts.extensions || ['html', 'htm']; - let gzips = opts.gzip && extensions.map(x => `${x}.gz`).concat('gz'); - let brots = opts.brotli && extensions.map(x => `${x}.br`).concat('br'); - - const FILES = {}; - - let fallback = '/'; - let isEtag = !!opts.etag; - let isSPA = !!opts.single; - if (typeof opts.single === 'string') { - let idx = opts.single.lastIndexOf('.'); - fallback += !!~idx ? opts.single.substring(0, idx) : opts.single; - } - - let ignores = []; - if (opts.ignores !== false) { - ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/); // any extn - if (opts.dotfiles) ignores.push(/\/\.\w/); - else ignores.push(/\/\.well-known/); - [].concat(opts.ignores || []).forEach(x => { - ignores.push(new RegExp(x, 'i')); - }); - } - - let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`; - if (cc && opts.immutable) cc += ',immutable'; - else if (cc && opts.maxAge === 0) cc += ',must-revalidate'; - - if (!opts.dev) { - list(dir, (name, abs, stats) => { - if (/\.well-known[\\+\/]/.test(name)) ; // keep - else if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return; - - let headers = toHeaders(name, stats, isEtag); - if (cc) headers['Cache-Control'] = cc; - - FILES['/' + name.normalize().replace(/\\+/g, '/')] = { abs, stats, headers }; - }); - } - - let lookup = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES); - - return function (req, res, next) { - let extns = ['']; - let val = req.headers['accept-encoding'] || ''; - if (gzips && val.includes('gzip')) extns.unshift(...gzips); - if (brots && /(br|brotli)/i.test(val)) extns.unshift(...brots); - extns.push(...extensions); // [...br, ...gz, orig, ...exts] - - let pathname = req.path || parser(req, true).pathname; - let data = lookup(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup(fallback, extns); - if (!data) return next ? next() : isNotFound(req, res); - - if (isEtag && req.headers['if-none-match'] === data.headers['ETag']) { - res.writeHead(304); - return res.end(); - } - - if (gzips || brots) { - res.setHeader('Vary', 'Accept-Encoding'); - } - - setHeaders(res, pathname, data.stats); - send(req, res, data.abs, data.stats, data.headers); - }; -} - -const sirvOptions = { dev: true, etag: true, extensions: [] }; -function servePublicMiddleware(dir) { - const serve = sirv(dir, sirvOptions); - return (req, res, next) => { - // skip import request - if (isImportRequest(req.url)) { - return next(); - } - serve(req, res, next); - }; -} -function serveStaticMiddleware(dir, config) { - const serve = sirv(dir, sirvOptions); - return (req, res, next) => { - let url = req.url; - // only serve the file if it's not an html request - // so that html requests can fallthrough to our html middleware for - // special processing - if (path__default.extname(cleanUrl(url)) === '.html') { - return next(); - } - // apply aliases to static requests as well - let redirected; - for (const { find, replacement } of config.resolve.alias) { - const matches = typeof find === 'string' ? url.startsWith(find) : find.test(url); - if (matches) { - redirected = url.replace(find, replacement); - break; - } - } - if (redirected) { - // dir is pre-normalized to posix style - if (redirected.startsWith(dir)) { - redirected = redirected.slice(dir.length); - } - req.url = redirected; - } - serve(req, res, next); - }; -} -function serveRawFsMiddleware() { - const isWin = os__default.platform() === 'win32'; - const serveFromRoot = sirv('/', sirvOptions); - return (req, res, next) => { - let url = req.url; - // In some cases (e.g. linked monorepos) files outside of root will - // reference assets that are also out of served root. In such cases - // the paths are rewritten to `/@fs/` prefixed paths and must be served by - // searching based from fs root. - if (url.startsWith(FS_PREFIX)) { - url = url.slice(FS_PREFIX.length); - if (isWin) - url = url.replace(/^[A-Z]:/i, ''); - req.url = url; - serveFromRoot(req, res, next); - } - else { - next(); - } - }; -} - -const logTime = createDebugger('vite:time'); -function timeMiddleware(root) { - return (req, res, next) => { - const start = Date.now(); - const end = res.end; - res.end = (...args) => { - logTime(`${timeFrom(start)} ${prettifyUrl(req.url, root)}`); - // @ts-ignore - return end.call(res, ...args); - }; - next(); - }; -} - -class ModuleNode { - constructor(url) { - /** - * Resolved file system path + query - */ - this.id = null; - this.file = null; - this.importers = new Set(); - this.importedModules = new Set(); - this.acceptedHmrDeps = new Set(); - this.isSelfAccepting = false; - this.transformResult = null; - this.ssrTransformResult = null; - this.ssrModule = null; - this.lastHMRTimestamp = 0; - this.url = url; - this.type = isDirectCSSRequest(url) ? 'css' : 'js'; - } -} -function invalidateSSRModule(mod, seen) { - if (seen.has(mod)) { - return; - } - seen.add(mod); - mod.ssrModule = null; - mod.importers.forEach((importer) => invalidateSSRModule(importer, seen)); -} -class ModuleGraph { - constructor(container) { - this.urlToModuleMap = new Map(); - this.idToModuleMap = new Map(); - // a single file may corresponds to multiple modules with different queries - this.fileToModulesMap = new Map(); - this.container = container; - } - async getModuleByUrl(rawUrl) { - const [url] = await this.resolveUrl(rawUrl); - return this.urlToModuleMap.get(url); - } - getModuleById(id) { - return this.idToModuleMap.get(removeTimestampQuery(id)); - } - getModulesByFile(file) { - return this.fileToModulesMap.get(file); - } - onFileChange(file) { - const mods = this.getModulesByFile(file); - if (mods) { - const seen = new Set(); - mods.forEach((mod) => { - this.invalidateModule(mod, seen); - }); - } - } - invalidateModule(mod, seen = new Set()) { - mod.transformResult = null; - mod.ssrTransformResult = null; - invalidateSSRModule(mod, seen); - } - invalidateAll() { - const seen = new Set(); - this.idToModuleMap.forEach((mod) => { - this.invalidateModule(mod, seen); - }); - } - /** - * Update the module graph based on a module's updated imports information - * If there are dependencies that no longer have any importers, they are - * returned as a Set. - */ - async updateModuleInfo(mod, importedModules, acceptedModules, isSelfAccepting) { - mod.isSelfAccepting = isSelfAccepting; - const prevImports = mod.importedModules; - const nextImports = (mod.importedModules = new Set()); - let noLongerImported; - // update import graph - for (const imported of importedModules) { - const dep = typeof imported === 'string' - ? await this.ensureEntryFromUrl(imported) - : imported; - dep.importers.add(mod); - nextImports.add(dep); - } - // remove the importer from deps that were imported but no longer are. - prevImports.forEach((dep) => { - if (!nextImports.has(dep)) { - dep.importers.delete(mod); - if (!dep.importers.size) { - (noLongerImported || (noLongerImported = new Set())).add(dep); - } - } - }); - // update accepted hmr deps - const deps = (mod.acceptedHmrDeps = new Set()); - for (const accepted of acceptedModules) { - const dep = typeof accepted === 'string' - ? await this.ensureEntryFromUrl(accepted) - : accepted; - deps.add(dep); - } - return noLongerImported; - } - async ensureEntryFromUrl(rawUrl) { - const [url, resolvedId] = await this.resolveUrl(rawUrl); - let mod = this.urlToModuleMap.get(url); - if (!mod) { - mod = new ModuleNode(url); - this.urlToModuleMap.set(url, mod); - mod.id = resolvedId; - this.idToModuleMap.set(resolvedId, mod); - const file = (mod.file = cleanUrl(resolvedId)); - let fileMappedModules = this.fileToModulesMap.get(file); - if (!fileMappedModules) { - fileMappedModules = new Set(); - this.fileToModulesMap.set(file, fileMappedModules); - } - fileMappedModules.add(mod); - } - return mod; - } - // some deps, like a css file referenced via @import, don't have its own - // url because they are inlined into the main css import. But they still - // need to be represented in the module graph so that they can trigger - // hmr in the importing css file. - createFileOnlyEntry(file) { - file = normalizePath$2(file); - const url = `${FS_PREFIX}${file}`; - let fileMappedModules = this.fileToModulesMap.get(file); - if (!fileMappedModules) { - fileMappedModules = new Set(); - this.fileToModulesMap.set(file, fileMappedModules); - } - for (const m of fileMappedModules) { - if (m.url === url) { - return m; - } - } - const mod = new ModuleNode(url); - mod.file = file; - fileMappedModules.add(mod); - return mod; - } - // for incoming urls, it is important to: - // 1. remove the HMR timestamp query (?t=xxxx) - // 2. resolve its extension so that urls with or without extension all map to - // the same module - async resolveUrl(url$1) { - var _a; - url$1 = removeImportQuery(removeTimestampQuery(url$1)); - const resolvedId = ((_a = (await this.container.resolveId(url$1))) === null || _a === void 0 ? void 0 : _a.id) || url$1; - const ext = path$1.extname(cleanUrl(resolvedId)); - const { pathname, search, hash } = url.parse(url$1); - if (ext && !pathname.endsWith(ext)) { - url$1 = pathname + ext + (search || '') + (hash || ''); - } - return [url$1, resolvedId]; - } -} - -let isDocker; - -function hasDockerEnv() { - try { - fs__default.statSync('/.dockerenv'); - return true; - } catch (_) { - return false; - } -} - -function hasDockerCGroup() { - try { - return fs__default.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); - } catch (_) { - return false; - } -} - -var isDocker_1 = () => { - if (isDocker === undefined) { - isDocker = hasDockerEnv() || hasDockerCGroup(); - } - - return isDocker; -}; - -var isWsl_1 = createCommonjsModule(function (module) { - - - - -const isWsl = () => { - if (process.platform !== 'linux') { - return false; - } - - if (os__default.release().toLowerCase().includes('microsoft')) { - if (isDocker_1()) { - return false; - } - - return true; - } - - try { - return fs__default.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? - !isDocker_1() : false; - } catch (_) { - return false; - } -}; - -if (process.env.__IS_WSL_TEST__) { - module.exports = isWsl; -} else { - module.exports = isWsl(); -} -}); - -const {promisify: promisify$1} = util__default; - - - - - - -const pAccess = promisify$1(fs__default.access); -const pReadFile = promisify$1(fs__default.readFile); - -// Path to included `xdg-open`. -const localXdgOpenPath = path__default.join(__dirname, 'xdg-open'); - -/** -Get the mount point for fixed drives in WSL. - -@inner -@returns {string} The mount point. -*/ -const getWslDrivesMountPoint = (() => { - // Default value for "root" param - // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config - const defaultMountPoint = '/mnt/'; - - let mountPoint; - - return async function () { - if (mountPoint) { - // Return memoized mount point value - return mountPoint; - } - - const configFilePath = '/etc/wsl.conf'; - - let isConfigFileExists = false; - try { - await pAccess(configFilePath, fs__default.constants.F_OK); - isConfigFileExists = true; - } catch (_) {} - - if (!isConfigFileExists) { - return defaultMountPoint; - } - - const configContent = await pReadFile(configFilePath, {encoding: 'utf8'}); - const configMountPoint = /root\s*=\s*(.*)/g.exec(configContent); - - if (!configMountPoint) { - return defaultMountPoint; - } - - mountPoint = configMountPoint[1].trim(); - mountPoint = mountPoint.endsWith('/') ? mountPoint : mountPoint + '/'; - - return mountPoint; - }; -})(); - -var open = async (target, options) => { - if (typeof target !== 'string') { - throw new TypeError('Expected a `target`'); - } - - options = { - wait: false, - background: false, - allowNonzeroExitCode: false, - ...options - }; - - let command; - let {app} = options; - let appArguments = []; - const cliArguments = []; - const childProcessOptions = {}; - - if (Array.isArray(app)) { - appArguments = app.slice(1); - app = app[0]; - } - - if (process.platform === 'darwin') { - command = 'open'; - - if (options.wait) { - cliArguments.push('--wait-apps'); - } - - if (options.background) { - cliArguments.push('--background'); - } - - if (app) { - cliArguments.push('-a', app); - } - } else if (process.platform === 'win32' || (isWsl_1 && !isDocker_1())) { - const mountPoint = await getWslDrivesMountPoint(); - - command = isWsl_1 ? - `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : - `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; - - cliArguments.push( - '-NoProfile', - '-NonInteractive', - '–ExecutionPolicy', - 'Bypass', - '-EncodedCommand' - ); - - if (!isWsl_1) { - childProcessOptions.windowsVerbatimArguments = true; - } - - const encodedArguments = ['Start']; - - if (options.wait) { - encodedArguments.push('-Wait'); - } - - if (app) { - // Double quote with double quotes to ensure the inner quotes are passed through. - // Inner quotes are delimited for PowerShell interpretation with backticks. - encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList'); - appArguments.unshift(target); - } else { - encodedArguments.push(`"${target}"`); - } - - if (appArguments.length > 0) { - appArguments = appArguments.map(arg => `"\`"${arg}\`""`); - encodedArguments.push(appArguments.join(',')); - } - - // Using Base64-encoded command, accepted by PowerShell, to allow special characters. - target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64'); - } else { - if (app) { - command = app; - } else { - // When bundled by Webpack, there's no actual package file path and no local `xdg-open`. - const isBundled = !__dirname || __dirname === '/'; - - // Check if local `xdg-open` exists and is executable. - let exeLocalXdgOpen = false; - try { - await pAccess(localXdgOpenPath, fs__default.constants.X_OK); - exeLocalXdgOpen = true; - } catch (_) {} - - const useSystemXdgOpen = process.versions.electron || - process.platform === 'android' || isBundled || !exeLocalXdgOpen; - command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath; - } - - if (appArguments.length > 0) { - cliArguments.push(...appArguments); - } - - if (!options.wait) { - // `xdg-open` will block the process unless stdio is ignored - // and it's detached from the parent even if it's unref'd. - childProcessOptions.stdio = 'ignore'; - childProcessOptions.detached = true; - } - } - - cliArguments.push(target); - - if (process.platform === 'darwin' && appArguments.length > 0) { - cliArguments.push('--args', ...appArguments); - } - - const subprocess = childProcess__default.spawn(command, cliArguments, childProcessOptions); - - if (options.wait) { - return new Promise((resolve, reject) => { - subprocess.once('error', reject); - - subprocess.once('close', exitCode => { - if (options.allowNonzeroExitCode && exitCode > 0) { - reject(new Error(`Exited with code ${exitCode}`)); - return; - } - - resolve(subprocess); - }); - }); - } - - subprocess.unref(); - - return subprocess; -}; - -var windows$1 = isexe$2; -isexe$2.sync = sync$4; - - - -function checkPathExt (path, options) { - var pathext = options.pathExt !== undefined ? - options.pathExt : process.env.PATHEXT; - - if (!pathext) { - return true - } - - pathext = pathext.split(';'); - if (pathext.indexOf('') !== -1) { - return true - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase(); - if (p && path.substr(-p.length).toLowerCase() === p) { - return true - } - } - return false -} - -function checkStat$1 (stat, path, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false - } - return checkPathExt(path, options) -} - -function isexe$2 (path, options, cb) { - fs__default.stat(path, function (er, stat) { - cb(er, er ? false : checkStat$1(stat, path, options)); - }); -} - -function sync$4 (path, options) { - return checkStat$1(fs__default.statSync(path), path, options) -} - -var mode = isexe$1; -isexe$1.sync = sync$3; - - - -function isexe$1 (path, options, cb) { - fs__default.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)); - }); -} - -function sync$3 (path, options) { - return checkStat(fs__default.statSync(path), options) -} - -function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) -} - -function checkMode (stat, options) { - var mod = stat.mode; - var uid = stat.uid; - var gid = stat.gid; - - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid(); - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid(); - - var u = parseInt('100', 8); - var g = parseInt('010', 8); - var o = parseInt('001', 8); - var ug = u | g; - - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0; - - return ret -} - -var core$1; -if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) { - core$1 = windows$1; -} else { - core$1 = mode; -} - -var isexe_1 = isexe; -isexe.sync = sync$2; - -function isexe (path, options, cb) { - if (typeof options === 'function') { - cb = options; - options = {}; - } - - if (!cb) { - if (typeof Promise !== 'function') { - throw new TypeError('callback not provided') - } - - return new Promise(function (resolve, reject) { - isexe(path, options || {}, function (er, is) { - if (er) { - reject(er); - } else { - resolve(is); - } - }); - }) - } - - core$1(path, options || {}, function (er, is) { - // ignore EACCES because that just means we aren't allowed to run it - if (er) { - if (er.code === 'EACCES' || options && options.ignoreErrors) { - er = null; - is = false; - } - } - cb(er, is); - }); -} - -function sync$2 (path, options) { - // my kingdom for a filtered catch - try { - return core$1.sync(path, options || {}) - } catch (er) { - if (options && options.ignoreErrors || er.code === 'EACCES') { - return false - } else { - throw er - } - } -} - -const isWindows = process.platform === 'win32' || - process.env.OSTYPE === 'cygwin' || - process.env.OSTYPE === 'msys'; - - -const COLON = isWindows ? ';' : ':'; - - -const getNotFoundError = (cmd) => - Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); - -const getPathInfo = (cmd, opt) => { - const colon = opt.colon || COLON; - - // If it has a slash, then we don't bother searching the pathenv. - // just check the file itself, and that's it. - const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] - : ( - [ - // windows always checks the cwd first - ...(isWindows ? [process.cwd()] : []), - ...(opt.path || process.env.PATH || - /* istanbul ignore next: very unusual */ '').split(colon), - ] - ); - const pathExtExe = isWindows - ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' - : ''; - const pathExt = isWindows ? pathExtExe.split(colon) : ['']; - - if (isWindows) { - if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') - pathExt.unshift(''); - } - - return { - pathEnv, - pathExt, - pathExtExe, - } -}; - -const which = (cmd, opt, cb) => { - if (typeof opt === 'function') { - cb = opt; - opt = {}; - } - if (!opt) - opt = {}; - - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); - const found = []; - - const step = i => new Promise((resolve, reject) => { - if (i === pathEnv.length) - return opt.all && found.length ? resolve(found) - : reject(getNotFoundError(cmd)) - - const ppRaw = pathEnv[i]; - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; - - const pCmd = path__default.join(pathPart, cmd); - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd; - - resolve(subStep(p, i, 0)); - }); - - const subStep = (p, i, ii) => new Promise((resolve, reject) => { - if (ii === pathExt.length) - return resolve(step(i + 1)) - const ext = pathExt[ii]; - isexe_1(p + ext, { pathExt: pathExtExe }, (er, is) => { - if (!er && is) { - if (opt.all) - found.push(p + ext); - else - return resolve(p + ext) - } - return resolve(subStep(p, i, ii + 1)) - }); - }); - - return cb ? step(0).then(res => cb(null, res), cb) : step(0) -}; - -const whichSync = (cmd, opt) => { - opt = opt || {}; - - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); - const found = []; - - for (let i = 0; i < pathEnv.length; i ++) { - const ppRaw = pathEnv[i]; - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; - - const pCmd = path__default.join(pathPart, cmd); - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd; - - for (let j = 0; j < pathExt.length; j ++) { - const cur = p + pathExt[j]; - try { - const is = isexe_1.sync(cur, { pathExt: pathExtExe }); - if (is) { - if (opt.all) - found.push(cur); - else - return cur - } - } catch (ex) {} - } - } - - if (opt.all && found.length) - return found - - if (opt.nothrow) - return null - - throw getNotFoundError(cmd) -}; - -var which_1 = which; -which.sync = whichSync; - -const pathKey$1 = (options = {}) => { - const environment = options.env || process.env; - const platform = options.platform || process.platform; - - if (platform !== 'win32') { - return 'PATH'; - } - - return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; -}; - -var pathKey_1$1 = pathKey$1; -// TODO: Remove this for the next major release -var _default$3 = pathKey$1; -pathKey_1$1.default = _default$3; - -function resolveCommandAttempt(parsed, withoutPathExt) { - const env = parsed.options.env || process.env; - const cwd = process.cwd(); - const hasCustomCwd = parsed.options.cwd != null; - // Worker threads do not have process.chdir() - const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; - - // If a custom `cwd` was specified, we need to change the process cwd - // because `which` will do stat calls but does not support a custom cwd - if (shouldSwitchCwd) { - try { - process.chdir(parsed.options.cwd); - } catch (err) { - /* Empty */ - } - } - - let resolved; - - try { - resolved = which_1.sync(parsed.command, { - path: env[pathKey_1$1({ env })], - pathExt: withoutPathExt ? path__default.delimiter : undefined, - }); - } catch (e) { - /* Empty */ - } finally { - if (shouldSwitchCwd) { - process.chdir(cwd); - } - } - - // If we successfully resolved, ensure that an absolute path is returned - // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it - if (resolved) { - resolved = path__default.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); - } - - return resolved; -} - -function resolveCommand(parsed) { - return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); -} - -var resolveCommand_1 = resolveCommand; - -// See http://www.robvanderwoude.com/escapechars.php -const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; - -function escapeCommand(arg) { - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); - - return arg; -} - -function escapeArgument(arg, doubleEscapeMetaChars) { - // Convert to string - arg = `${arg}`; - - // Algorithm below is based on https://qntm.org/cmd - - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(\\*)"/g, '$1$1\\"'); - - // Sequence of backslashes followed by the end of the string - // (which will become a double quote later): - // double up all the backslashes - arg = arg.replace(/(\\*)$/, '$1$1'); - - // All other backslashes occur literally - - // Quote the whole thing: - arg = `"${arg}"`; - - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); - - // Double escape meta chars if necessary - if (doubleEscapeMetaChars) { - arg = arg.replace(metaCharsRegExp, '^$1'); - } - - return arg; -} - -var command$2 = escapeCommand; -var argument = escapeArgument; - -var _escape = { - command: command$2, - argument: argument -}; - -var shebangRegex = /^#!(.*)/; - -var shebangCommand = (string = '') => { - const match = string.match(shebangRegex); - - if (!match) { - return null; - } - - const [path, argument] = match[0].replace(/#! ?/, '').split(' '); - const binary = path.split('/').pop(); - - if (binary === 'env') { - return argument; - } - - return argument ? `${binary} ${argument}` : binary; -}; - -function readShebang(command) { - // Read the first 150 bytes from the file - const size = 150; - const buffer = Buffer.alloc(size); - - let fd; - - try { - fd = fs__default.openSync(command, 'r'); - fs__default.readSync(fd, buffer, 0, size, 0); - fs__default.closeSync(fd); - } catch (e) { /* Empty */ } - - // Attempt to extract shebang (null is returned if not a shebang) - return shebangCommand(buffer.toString()); -} - -var readShebang_1 = readShebang; - -const isWin$2 = process.platform === 'win32'; -const isExecutableRegExp = /\.(?:com|exe)$/i; -const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; - -function detectShebang(parsed) { - parsed.file = resolveCommand_1(parsed); - - const shebang = parsed.file && readShebang_1(parsed.file); - - if (shebang) { - parsed.args.unshift(parsed.file); - parsed.command = shebang; - - return resolveCommand_1(parsed); - } - - return parsed.file; -} - -function parseNonShell(parsed) { - if (!isWin$2) { - return parsed; - } - - // Detect & add support for shebangs - const commandFile = detectShebang(parsed); - - // We don't need a shell if the command filename is an executable - const needsShell = !isExecutableRegExp.test(commandFile); - - // If a shell is required, use cmd.exe and take care of escaping everything correctly - // Note that `forceShell` is an hidden option used only in tests - if (parsed.options.forceShell || needsShell) { - // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` - // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument - // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, - // we need to double escape them - const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); - - // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) - // This is necessary otherwise it will always fail with ENOENT in those cases - parsed.command = path__default.normalize(parsed.command); - - // Escape command & arguments - parsed.command = _escape.command(parsed.command); - parsed.args = parsed.args.map((arg) => _escape.argument(arg, needsDoubleEscapeMetaChars)); - - const shellCommand = [parsed.command].concat(parsed.args).join(' '); - - parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; - parsed.command = process.env.comspec || 'cmd.exe'; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped - } - - return parsed; -} - -function parse$1(command, args, options) { - // Normalize arguments, similar to nodejs - if (args && !Array.isArray(args)) { - options = args; - args = null; - } - - args = args ? args.slice(0) : []; // Clone array to avoid changing the original - options = Object.assign({}, options); // Clone object to avoid changing the original - - // Build our parsed object - const parsed = { - command, - args, - options, - file: undefined, - original: { - command, - args, - }, - }; - - // Delegate further parsing to shell or non-shell - return options.shell ? parsed : parseNonShell(parsed); -} - -var parse_1$1 = parse$1; - -const isWin$1 = process.platform === 'win32'; - -function notFoundError(original, syscall) { - return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { - code: 'ENOENT', - errno: 'ENOENT', - syscall: `${syscall} ${original.command}`, - path: original.command, - spawnargs: original.args, - }); -} - -function hookChildProcess(cp, parsed) { - if (!isWin$1) { - return; - } - - const originalEmit = cp.emit; - - cp.emit = function (name, arg1) { - // If emitting "exit" event and exit code is 1, we need to check if - // the command exists and emit an "error" instead - // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 - if (name === 'exit') { - const err = verifyENOENT(arg1, parsed); - - if (err) { - return originalEmit.call(cp, 'error', err); - } - } - - return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params - }; -} - -function verifyENOENT(status, parsed) { - if (isWin$1 && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawn'); - } - - return null; -} - -function verifyENOENTSync(status, parsed) { - if (isWin$1 && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawnSync'); - } - - return null; -} - -var enoent = { - hookChildProcess, - verifyENOENT, - verifyENOENTSync, - notFoundError, -}; - -function spawn(command, args, options) { - // Parse the arguments - const parsed = parse_1$1(command, args, options); - - // Spawn the child process - const spawned = childProcess__default.spawn(parsed.command, parsed.args, parsed.options); - - // Hook into child process "exit" event to emit an error if the command - // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - enoent.hookChildProcess(spawned, parsed); - - return spawned; -} - -function spawnSync(command, args, options) { - // Parse the arguments - const parsed = parse_1$1(command, args, options); - - // Spawn the child process - const result = childProcess__default.spawnSync(parsed.command, parsed.args, parsed.options); - - // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); - - return result; -} - -var crossSpawn = spawn; -var spawn_1 = spawn; -var sync$1 = spawnSync; - -var _parse = parse_1$1; -var _enoent = enoent; -crossSpawn.spawn = spawn_1; -crossSpawn.sync = sync$1; -crossSpawn._parse = _parse; -crossSpawn._enoent = _enoent; - -var stripFinalNewline = input => { - const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt(); - const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt(); - - if (input[input.length - 1] === LF) { - input = input.slice(0, input.length - 1); - } - - if (input[input.length - 1] === CR) { - input = input.slice(0, input.length - 1); - } - - return input; -}; - -const pathKey = (options = {}) => { - const environment = options.env || process.env; - const platform = options.platform || process.platform; - - if (platform !== 'win32') { - return 'PATH'; - } - - return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; -}; - -var pathKey_1 = pathKey; -// TODO: Remove this for the next major release -var _default$2 = pathKey; -pathKey_1.default = _default$2; - -var npmRunPath_1 = createCommonjsModule(function (module) { - - - -const npmRunPath = options => { - options = { - cwd: process.cwd(), - path: process.env[pathKey_1()], - execPath: process.execPath, - ...options - }; - - let previous; - let cwdPath = path__default.resolve(options.cwd); - const result = []; - - while (previous !== cwdPath) { - result.push(path__default.join(cwdPath, 'node_modules/.bin')); - previous = cwdPath; - cwdPath = path__default.resolve(cwdPath, '..'); - } - - // Ensure the running `node` binary is used - const execPathDir = path__default.resolve(options.cwd, options.execPath, '..'); - result.push(execPathDir); - - return result.concat(options.path).join(path__default.delimiter); -}; - -module.exports = npmRunPath; -// TODO: Remove this for the next major release -module.exports.default = npmRunPath; - -module.exports.env = options => { - options = { - env: process.env, - ...options - }; - - const env = {...options.env}; - const path = pathKey_1({env}); - - options.path = env[path]; - env[path] = module.exports(options); - - return env; -}; -}); - -const mimicFn = (to, from) => { - for (const prop of Reflect.ownKeys(from)) { - Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); - } - - return to; -}; - -var mimicFn_1 = mimicFn; -// TODO: Remove this for the next major release -var _default$1 = mimicFn; -mimicFn_1.default = _default$1; - -const calledFunctions = new WeakMap(); - -const onetime = (function_, options = {}) => { - if (typeof function_ !== 'function') { - throw new TypeError('Expected a function'); - } - - let returnValue; - let callCount = 0; - const functionName = function_.displayName || function_.name || ''; - - const onetime = function (...arguments_) { - calledFunctions.set(onetime, ++callCount); - - if (callCount === 1) { - returnValue = function_.apply(this, arguments_); - function_ = null; - } else if (options.throw === true) { - throw new Error(`Function \`${functionName}\` can only be called once`); - } - - return returnValue; - }; - - mimicFn_1(onetime, function_); - calledFunctions.set(onetime, callCount); - - return onetime; -}; - -var onetime_1 = onetime; -// TODO: Remove this for the next major release -var _default = onetime; - -var callCount = function_ => { - if (!calledFunctions.has(function_)) { - throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); - } - - return calledFunctions.get(function_); -}; -onetime_1.default = _default; -onetime_1.callCount = callCount; - -var core = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports,"__esModule",{value:true});exports.SIGNALS=void 0; - -const SIGNALS=[ -{ -name:"SIGHUP", -number:1, -action:"terminate", -description:"Terminal closed", -standard:"posix"}, - -{ -name:"SIGINT", -number:2, -action:"terminate", -description:"User interruption with CTRL-C", -standard:"ansi"}, - -{ -name:"SIGQUIT", -number:3, -action:"core", -description:"User interruption with CTRL-\\", -standard:"posix"}, - -{ -name:"SIGILL", -number:4, -action:"core", -description:"Invalid machine instruction", -standard:"ansi"}, - -{ -name:"SIGTRAP", -number:5, -action:"core", -description:"Debugger breakpoint", -standard:"posix"}, - -{ -name:"SIGABRT", -number:6, -action:"core", -description:"Aborted", -standard:"ansi"}, - -{ -name:"SIGIOT", -number:6, -action:"core", -description:"Aborted", -standard:"bsd"}, - -{ -name:"SIGBUS", -number:7, -action:"core", -description: -"Bus error due to misaligned, non-existing address or paging error", -standard:"bsd"}, - -{ -name:"SIGEMT", -number:7, -action:"terminate", -description:"Command should be emulated but is not implemented", -standard:"other"}, - -{ -name:"SIGFPE", -number:8, -action:"core", -description:"Floating point arithmetic error", -standard:"ansi"}, - -{ -name:"SIGKILL", -number:9, -action:"terminate", -description:"Forced termination", -standard:"posix", -forced:true}, - -{ -name:"SIGUSR1", -number:10, -action:"terminate", -description:"Application-specific signal", -standard:"posix"}, - -{ -name:"SIGSEGV", -number:11, -action:"core", -description:"Segmentation fault", -standard:"ansi"}, - -{ -name:"SIGUSR2", -number:12, -action:"terminate", -description:"Application-specific signal", -standard:"posix"}, - -{ -name:"SIGPIPE", -number:13, -action:"terminate", -description:"Broken pipe or socket", -standard:"posix"}, - -{ -name:"SIGALRM", -number:14, -action:"terminate", -description:"Timeout or timer", -standard:"posix"}, - -{ -name:"SIGTERM", -number:15, -action:"terminate", -description:"Termination", -standard:"ansi"}, - -{ -name:"SIGSTKFLT", -number:16, -action:"terminate", -description:"Stack is empty or overflowed", -standard:"other"}, - -{ -name:"SIGCHLD", -number:17, -action:"ignore", -description:"Child process terminated, paused or unpaused", -standard:"posix"}, - -{ -name:"SIGCLD", -number:17, -action:"ignore", -description:"Child process terminated, paused or unpaused", -standard:"other"}, - -{ -name:"SIGCONT", -number:18, -action:"unpause", -description:"Unpaused", -standard:"posix", -forced:true}, - -{ -name:"SIGSTOP", -number:19, -action:"pause", -description:"Paused", -standard:"posix", -forced:true}, - -{ -name:"SIGTSTP", -number:20, -action:"pause", -description:"Paused using CTRL-Z or \"suspend\"", -standard:"posix"}, - -{ -name:"SIGTTIN", -number:21, -action:"pause", -description:"Background process cannot read terminal input", -standard:"posix"}, - -{ -name:"SIGBREAK", -number:21, -action:"terminate", -description:"User interruption with CTRL-BREAK", -standard:"other"}, - -{ -name:"SIGTTOU", -number:22, -action:"pause", -description:"Background process cannot write to terminal output", -standard:"posix"}, - -{ -name:"SIGURG", -number:23, -action:"ignore", -description:"Socket received out-of-band data", -standard:"bsd"}, - -{ -name:"SIGXCPU", -number:24, -action:"core", -description:"Process timed out", -standard:"bsd"}, - -{ -name:"SIGXFSZ", -number:25, -action:"core", -description:"File too big", -standard:"bsd"}, - -{ -name:"SIGVTALRM", -number:26, -action:"terminate", -description:"Timeout or timer", -standard:"bsd"}, - -{ -name:"SIGPROF", -number:27, -action:"terminate", -description:"Timeout or timer", -standard:"bsd"}, - -{ -name:"SIGWINCH", -number:28, -action:"ignore", -description:"Terminal window size changed", -standard:"bsd"}, - -{ -name:"SIGIO", -number:29, -action:"terminate", -description:"I/O is available", -standard:"other"}, - -{ -name:"SIGPOLL", -number:29, -action:"terminate", -description:"Watched event", -standard:"other"}, - -{ -name:"SIGINFO", -number:29, -action:"ignore", -description:"Request for process information", -standard:"other"}, - -{ -name:"SIGPWR", -number:30, -action:"terminate", -description:"Device running out of power", -standard:"systemv"}, - -{ -name:"SIGSYS", -number:31, -action:"core", -description:"Invalid system call", -standard:"other"}, - -{ -name:"SIGUNUSED", -number:31, -action:"terminate", -description:"Invalid system call", -standard:"other"}];exports.SIGNALS=SIGNALS; -//# sourceMappingURL=core.js.map -}); - -var realtime = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports,"__esModule",{value:true});exports.SIGRTMAX=exports.getRealtimeSignals=void 0; -const getRealtimeSignals=function(){ -const length=SIGRTMAX-SIGRTMIN+1; -return Array.from({length},getRealtimeSignal); -};exports.getRealtimeSignals=getRealtimeSignals; - -const getRealtimeSignal=function(value,index){ -return { -name:`SIGRT${index+1}`, -number:SIGRTMIN+index, -action:"terminate", -description:"Application-specific signal (realtime)", -standard:"posix"}; - -}; - -const SIGRTMIN=34; -const SIGRTMAX=64;exports.SIGRTMAX=SIGRTMAX; -//# sourceMappingURL=realtime.js.map -}); - -var signals$2 = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports,"__esModule",{value:true});exports.getSignals=void 0; - - - - - - -const getSignals=function(){ -const realtimeSignals=(0, realtime.getRealtimeSignals)(); -const signals=[...core.SIGNALS,...realtimeSignals].map(normalizeSignal); -return signals; -};exports.getSignals=getSignals; - - - - - - - -const normalizeSignal=function({ -name, -number:defaultNumber, -description, -action, -forced=false, -standard}) -{ -const{ -signals:{[name]:constantSignal}}= -os__default.constants; -const supported=constantSignal!==undefined; -const number=supported?constantSignal:defaultNumber; -return {name,number,description,supported,action,forced,standard}; -}; -//# sourceMappingURL=signals.js.map -}); - -var main = createCommonjsModule(function (module, exports) { -Object.defineProperty(exports,"__esModule",{value:true});exports.signalsByNumber=exports.signalsByName=void 0; - - - - - - -const getSignalsByName=function(){ -const signals=(0, signals$2.getSignals)(); -return signals.reduce(getSignalByName,{}); -}; - -const getSignalByName=function( -signalByNameMemo, -{name,number,description,supported,action,forced,standard}) -{ -return { -...signalByNameMemo, -[name]:{name,number,description,supported,action,forced,standard}}; - -}; - -const signalsByName=getSignalsByName();exports.signalsByName=signalsByName; - - - - -const getSignalsByNumber=function(){ -const signals=(0, signals$2.getSignals)(); -const length=realtime.SIGRTMAX+1; -const signalsA=Array.from({length},(value,number)=> -getSignalByNumber(number,signals)); - -return Object.assign({},...signalsA); -}; - -const getSignalByNumber=function(number,signals){ -const signal=findSignalByNumber(number,signals); - -if(signal===undefined){ -return {}; -} - -const{name,description,supported,action,forced,standard}=signal; -return { -[number]:{ -name, -number, -description, -supported, -action, -forced, -standard}}; - - -}; - - - -const findSignalByNumber=function(number,signals){ -const signal=signals.find(({name})=>os__default.constants.signals[name]===number); - -if(signal!==undefined){ -return signal; -} - -return signals.find(signalA=>signalA.number===number); -}; - -const signalsByNumber=getSignalsByNumber();exports.signalsByNumber=signalsByNumber; -//# sourceMappingURL=main.js.map -}); - -const {signalsByName} = main; - -const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { - if (timedOut) { - return `timed out after ${timeout} milliseconds`; - } - - if (isCanceled) { - return 'was canceled'; - } - - if (errorCode !== undefined) { - return `failed with ${errorCode}`; - } - - if (signal !== undefined) { - return `was killed with ${signal} (${signalDescription})`; - } - - if (exitCode !== undefined) { - return `failed with exit code ${exitCode}`; - } - - return 'failed'; -}; - -const makeError = ({ - stdout, - stderr, - all, - error, - signal, - exitCode, - command, - timedOut, - isCanceled, - killed, - parsed: {options: {timeout}} -}) => { - // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. - // We normalize them to `undefined` - exitCode = exitCode === null ? undefined : exitCode; - signal = signal === null ? undefined : signal; - const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; - - const errorCode = error && error.code; - - const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); - const execaMessage = `Command ${prefix}: ${command}`; - const isError = Object.prototype.toString.call(error) === '[object Error]'; - const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; - const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); - - if (isError) { - error.originalMessage = error.message; - error.message = message; - } else { - error = new Error(message); - } - - error.shortMessage = shortMessage; - error.command = command; - error.exitCode = exitCode; - error.signal = signal; - error.signalDescription = signalDescription; - error.stdout = stdout; - error.stderr = stderr; - - if (all !== undefined) { - error.all = all; - } - - if ('bufferedData' in error) { - delete error.bufferedData; - } - - error.failed = true; - error.timedOut = Boolean(timedOut); - error.isCanceled = isCanceled; - error.killed = killed && !timedOut; - - return error; -}; - -var error = makeError; - -const aliases = ['stdin', 'stdout', 'stderr']; - -const hasAlias = options => aliases.some(alias => options[alias] !== undefined); - -const normalizeStdio = options => { - if (!options) { - return; - } - - const {stdio} = options; - - if (stdio === undefined) { - return aliases.map(alias => options[alias]); - } - - if (hasAlias(options)) { - throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); - } - - if (typeof stdio === 'string') { - return stdio; - } - - if (!Array.isArray(stdio)) { - throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); - } - - const length = Math.max(stdio.length, aliases.length); - return Array.from({length}, (value, index) => stdio[index]); -}; - -var stdio = normalizeStdio; - -// `ipc` is pushed unless it is already present -var node$1 = options => { - const stdio = normalizeStdio(options); - - if (stdio === 'ipc') { - return 'ipc'; - } - - if (stdio === undefined || typeof stdio === 'string') { - return [stdio, stdio, stdio, 'ipc']; - } - - if (stdio.includes('ipc')) { - return stdio; - } - - return [...stdio, 'ipc']; -}; -stdio.node = node$1; - -var signals$1 = createCommonjsModule(function (module) { -// This is not the set of all possible signals. -// -// It IS, however, the set of all signals that trigger -// an exit on either Linux or BSD systems. Linux is a -// superset of the signal names supported on BSD, and -// the unknown signals just fail to register, so we can -// catch that easily enough. -// -// Don't bother with SIGKILL. It's uncatchable, which -// means that we can't fire any callbacks anyway. -// -// If a user does happen to register a handler on a non- -// fatal signal like SIGWINCH or something, and then -// exit, it'll end up firing `process.emit('exit')`, so -// the handler will be fired anyway. -// -// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised -// artificially, inherently leave the process in a -// state from which it is not safe to try and enter JS -// listeners. -module.exports = [ - 'SIGABRT', - 'SIGALRM', - 'SIGHUP', - 'SIGINT', - 'SIGTERM' -]; - -if (process.platform !== 'win32') { - module.exports.push( - 'SIGVTALRM', - 'SIGXCPU', - 'SIGXFSZ', - 'SIGUSR2', - 'SIGTRAP', - 'SIGSYS', - 'SIGQUIT', - 'SIGIOT' - // should detect profiler and enable/disable accordingly. - // see #21 - // 'SIGPROF' - ); -} - -if (process.platform === 'linux') { - module.exports.push( - 'SIGIO', - 'SIGPOLL', - 'SIGPWR', - 'SIGSTKFLT', - 'SIGUNUSED' - ); -} -}); - -// Note: since nyc uses this module to output coverage, any lines -// that are in the direct sync flow of nyc's outputCoverage are -// ignored, since we can never get coverage for them. - -var signals = signals$1; -var isWin = /^win/i.test(process.platform); - -var EE = require$$0__default$1; -/* istanbul ignore if */ -if (typeof EE !== 'function') { - EE = EE.EventEmitter; -} - -var emitter; -if (process.__signal_exit_emitter__) { - emitter = process.__signal_exit_emitter__; -} else { - emitter = process.__signal_exit_emitter__ = new EE(); - emitter.count = 0; - emitter.emitted = {}; -} - -// Because this emitter is a global, we have to check to see if a -// previous version of this library failed to enable infinite listeners. -// I know what you're about to say. But literally everything about -// signal-exit is a compromise with evil. Get used to it. -if (!emitter.infinite) { - emitter.setMaxListeners(Infinity); - emitter.infinite = true; -} - -var signalExit = function (cb, opts) { - assert__default.equal(typeof cb, 'function', 'a callback must be provided for exit handler'); - - if (loaded === false) { - load(); - } - - var ev = 'exit'; - if (opts && opts.alwaysLast) { - ev = 'afterexit'; - } - - var remove = function () { - emitter.removeListener(ev, cb); - if (emitter.listeners('exit').length === 0 && - emitter.listeners('afterexit').length === 0) { - unload(); - } - }; - emitter.on(ev, cb); - - return remove -}; - -var unload_1 = unload; -function unload () { - if (!loaded) { - return - } - loaded = false; - - signals.forEach(function (sig) { - try { - process.removeListener(sig, sigListeners[sig]); - } catch (er) {} - }); - process.emit = originalProcessEmit; - process.reallyExit = originalProcessReallyExit; - emitter.count -= 1; -} - -function emit (event, code, signal) { - if (emitter.emitted[event]) { - return - } - emitter.emitted[event] = true; - emitter.emit(event, code, signal); -} - -// { : , ... } -var sigListeners = {}; -signals.forEach(function (sig) { - sigListeners[sig] = function listener () { - // If there are no other listeners, an exit is coming! - // Simplest way: remove us and then re-send the signal. - // We know that this will kill the process, so we can - // safely emit now. - var listeners = process.listeners(sig); - if (listeners.length === emitter.count) { - unload(); - emit('exit', null, sig); - /* istanbul ignore next */ - emit('afterexit', null, sig); - /* istanbul ignore next */ - if (isWin && sig === 'SIGHUP') { - // "SIGHUP" throws an `ENOSYS` error on Windows, - // so use a supported signal instead - sig = 'SIGINT'; - } - process.kill(process.pid, sig); - } - }; -}); - -var signals_1 = function () { - return signals -}; - -var load_1 = load; - -var loaded = false; - -function load () { - if (loaded) { - return - } - loaded = true; - - // This is the number of onSignalExit's that are in play. - // It's important so that we can count the correct number of - // listeners on signals, and don't wait for the other one to - // handle it instead of us. - emitter.count += 1; - - signals = signals.filter(function (sig) { - try { - process.on(sig, sigListeners[sig]); - return true - } catch (er) { - return false - } - }); - - process.emit = processEmit; - process.reallyExit = processReallyExit; -} - -var originalProcessReallyExit = process.reallyExit; -function processReallyExit (code) { - process.exitCode = code || 0; - emit('exit', process.exitCode, null); - /* istanbul ignore next */ - emit('afterexit', process.exitCode, null); - /* istanbul ignore next */ - originalProcessReallyExit.call(process, process.exitCode); -} - -var originalProcessEmit = process.emit; -function processEmit (ev, arg) { - if (ev === 'exit') { - if (arg !== undefined) { - process.exitCode = arg; - } - var ret = originalProcessEmit.apply(this, arguments); - emit('exit', process.exitCode, null); - /* istanbul ignore next */ - emit('afterexit', process.exitCode, null); - return ret - } else { - return originalProcessEmit.apply(this, arguments) - } -} -signalExit.unload = unload_1; -signalExit.signals = signals_1; -signalExit.load = load_1; - -const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; - -// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior -const spawnedKill$1 = (kill, signal = 'SIGTERM', options = {}) => { - const killResult = kill(signal); - setKillTimeout(kill, signal, options, killResult); - return killResult; -}; - -const setKillTimeout = (kill, signal, options, killResult) => { - if (!shouldForceKill(signal, options, killResult)) { - return; - } - - const timeout = getForceKillAfterTimeout(options); - const t = setTimeout(() => { - kill('SIGKILL'); - }, timeout); - - // Guarded because there's no `.unref()` when `execa` is used in the renderer - // process in Electron. This cannot be tested since we don't run tests in - // Electron. - // istanbul ignore else - if (t.unref) { - t.unref(); - } -}; - -const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => { - return isSigterm(signal) && forceKillAfterTimeout !== false && killResult; -}; - -const isSigterm = signal => { - return signal === os__default.constants.signals.SIGTERM || - (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); -}; - -const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { - if (forceKillAfterTimeout === true) { - return DEFAULT_FORCE_KILL_TIMEOUT; - } - - if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { - throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); - } - - return forceKillAfterTimeout; -}; - -// `childProcess.cancel()` -const spawnedCancel$1 = (spawned, context) => { - const killResult = spawned.kill(); - - if (killResult) { - context.isCanceled = true; - } -}; - -const timeoutKill = (spawned, signal, reject) => { - spawned.kill(signal); - reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); -}; - -// `timeout` option handling -const setupTimeout$1 = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { - if (timeout === 0 || timeout === undefined) { - return spawnedPromise; - } - - if (!Number.isFinite(timeout) || timeout < 0) { - throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); - } - - let timeoutId; - const timeoutPromise = new Promise((resolve, reject) => { - timeoutId = setTimeout(() => { - timeoutKill(spawned, killSignal, reject); - }, timeout); - }); - - const safeSpawnedPromise = spawnedPromise.finally(() => { - clearTimeout(timeoutId); - }); - - return Promise.race([timeoutPromise, safeSpawnedPromise]); -}; - -// `cleanup` option handling -const setExitHandler$1 = async (spawned, {cleanup, detached}, timedPromise) => { - if (!cleanup || detached) { - return timedPromise; - } - - const removeExitHandler = signalExit(() => { - spawned.kill(); - }); - - return timedPromise.finally(() => { - removeExitHandler(); - }); -}; - -var kill = { - spawnedKill: spawnedKill$1, - spawnedCancel: spawnedCancel$1, - setupTimeout: setupTimeout$1, - setExitHandler: setExitHandler$1 -}; - -const isStream = stream => - stream !== null && - typeof stream === 'object' && - typeof stream.pipe === 'function'; - -isStream.writable = stream => - isStream(stream) && - stream.writable !== false && - typeof stream._write === 'function' && - typeof stream._writableState === 'object'; - -isStream.readable = stream => - isStream(stream) && - stream.readable !== false && - typeof stream._read === 'function' && - typeof stream._readableState === 'object'; - -isStream.duplex = stream => - isStream.writable(stream) && - isStream.readable(stream); - -isStream.transform = stream => - isStream.duplex(stream) && - typeof stream._transform === 'function' && - typeof stream._transformState === 'object'; - -var isStream_1 = isStream; - -const {PassThrough: PassThroughStream} = require$$0__default; - -var bufferStream = options => { - options = {...options}; - - const {array} = options; - let {encoding} = options; - const isBuffer = encoding === 'buffer'; - let objectMode = false; - - if (array) { - objectMode = !(encoding || isBuffer); - } else { - encoding = encoding || 'utf8'; - } - - if (isBuffer) { - encoding = null; - } - - const stream = new PassThroughStream({objectMode}); - - if (encoding) { - stream.setEncoding(encoding); - } - - let length = 0; - const chunks = []; - - stream.on('data', chunk => { - chunks.push(chunk); - - if (objectMode) { - length = chunks.length; - } else { - length += chunk.length; - } - }); - - stream.getBufferedValue = () => { - if (array) { - return chunks; - } - - return isBuffer ? Buffer.concat(chunks, length) : chunks.join(''); - }; - - stream.getBufferedLength = () => length; - - return stream; -}; - -const {constants: BufferConstants} = buffer__default; - -const {promisify} = util__default; - - -const streamPipelinePromisified = promisify(require$$0__default.pipeline); - -class MaxBufferError extends Error { - constructor() { - super('maxBuffer exceeded'); - this.name = 'MaxBufferError'; - } -} - -async function getStream(inputStream, options) { - if (!inputStream) { - throw new Error('Expected a stream'); - } - - options = { - maxBuffer: Infinity, - ...options - }; - - const {maxBuffer} = options; - const stream = bufferStream(options); - - await new Promise((resolve, reject) => { - const rejectPromise = error => { - // Don't retrieve an oversized buffer. - if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) { - error.bufferedData = stream.getBufferedValue(); - } - - reject(error); - }; - - (async () => { - try { - await streamPipelinePromisified(inputStream, stream); - resolve(); - } catch (error) { - rejectPromise(error); - } - })(); - - stream.on('data', () => { - if (stream.getBufferedLength() > maxBuffer) { - rejectPromise(new MaxBufferError()); - } - }); - }); - - return stream.getBufferedValue(); -} - -var getStream_1 = getStream; -var buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'}); -var array = (stream, options) => getStream(stream, {...options, array: true}); -var MaxBufferError_1 = MaxBufferError; -getStream_1.buffer = buffer; -getStream_1.array = array; -getStream_1.MaxBufferError = MaxBufferError_1; - -const { PassThrough } = require$$0__default; - -var mergeStream = function (/*streams...*/) { - var sources = []; - var output = new PassThrough({objectMode: true}); - - output.setMaxListeners(0); - - output.add = add; - output.isEmpty = isEmpty; - - output.on('unpipe', remove); - - Array.prototype.slice.call(arguments).forEach(add); - - return output - - function add (source) { - if (Array.isArray(source)) { - source.forEach(add); - return this - } - - sources.push(source); - source.once('end', remove.bind(null, source)); - source.once('error', output.emit.bind(output, 'error')); - source.pipe(output, {end: false}); - return this - } - - function isEmpty () { - return sources.length == 0; - } - - function remove (source) { - sources = sources.filter(function (it) { return it !== source }); - if (!sources.length && output.readable) { output.end(); } - } -}; - -// `input` option -const handleInput$1 = (spawned, input) => { - // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852 - // TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0 - if (input === undefined || spawned.stdin === undefined) { - return; - } - - if (isStream_1(input)) { - input.pipe(spawned.stdin); - } else { - spawned.stdin.end(input); - } -}; - -// `all` interleaves `stdout` and `stderr` -const makeAllStream$1 = (spawned, {all}) => { - if (!all || (!spawned.stdout && !spawned.stderr)) { - return; - } - - const mixed = mergeStream(); - - if (spawned.stdout) { - mixed.add(spawned.stdout); - } - - if (spawned.stderr) { - mixed.add(spawned.stderr); - } - - return mixed; -}; - -// On failure, `result.stdout|stderr|all` should contain the currently buffered stream -const getBufferedData = async (stream, streamPromise) => { - if (!stream) { - return; - } - - stream.destroy(); - - try { - return await streamPromise; - } catch (error) { - return error.bufferedData; - } -}; - -const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { - if (!stream || !buffer) { - return; - } - - if (encoding) { - return getStream_1(stream, {encoding, maxBuffer}); - } - - return getStream_1.buffer(stream, {maxBuffer}); -}; - -// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) -const getSpawnedResult$1 = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { - const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); - const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); - const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); - - try { - return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); - } catch (error) { - return Promise.all([ - {error, signal: error.signal, timedOut: error.timedOut}, - getBufferedData(stdout, stdoutPromise), - getBufferedData(stderr, stderrPromise), - getBufferedData(all, allPromise) - ]); - } -}; - -const validateInputSync$1 = ({input}) => { - if (isStream_1(input)) { - throw new TypeError('The `input` option cannot be a stream in sync mode'); - } -}; - -var stream = { - handleInput: handleInput$1, - makeAllStream: makeAllStream$1, - getSpawnedResult: getSpawnedResult$1, - validateInputSync: validateInputSync$1 -}; - -const nativePromisePrototype = (async () => {})().constructor.prototype; -const descriptors = ['then', 'catch', 'finally'].map(property => [ - property, - Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property) -]); - -// The return value is a mixin of `childProcess` and `Promise` -const mergePromise$1 = (spawned, promise) => { - for (const [property, descriptor] of descriptors) { - // Starting the main `promise` is deferred to avoid consuming streams - const value = typeof promise === 'function' ? - (...args) => Reflect.apply(descriptor.value, promise(), args) : - descriptor.value.bind(promise); - - Reflect.defineProperty(spawned, property, {...descriptor, value}); - } - - return spawned; -}; - -// Use promises instead of `child_process` events -const getSpawnedPromise$1 = spawned => { - return new Promise((resolve, reject) => { - spawned.on('exit', (exitCode, signal) => { - resolve({exitCode, signal}); - }); - - spawned.on('error', error => { - reject(error); - }); - - if (spawned.stdin) { - spawned.stdin.on('error', error => { - reject(error); - }); - } - }); -}; - -var promise = { - mergePromise: mergePromise$1, - getSpawnedPromise: getSpawnedPromise$1 -}; - -const SPACES_REGEXP = / +/g; - -const joinCommand$1 = (file, args = []) => { - if (!Array.isArray(args)) { - return file; - } - - return [file, ...args].join(' '); -}; - -// Handle `execa.command()` -const parseCommand$1 = command => { - const tokens = []; - for (const token of command.trim().split(SPACES_REGEXP)) { - // Allow spaces to be escaped by a backslash if not meant as a delimiter - const previousToken = tokens[tokens.length - 1]; - if (previousToken && previousToken.endsWith('\\')) { - // Merge previous token with current one - tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; - } else { - tokens.push(token); - } - } - - return tokens; -}; - -var command$1 = { - joinCommand: joinCommand$1, - parseCommand: parseCommand$1 -}; - -const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler} = kill; -const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = stream; -const {mergePromise, getSpawnedPromise} = promise; -const {joinCommand, parseCommand} = command$1; - -const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; - -const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { - const env = extendEnv ? {...process.env, ...envOption} : envOption; - - if (preferLocal) { - return npmRunPath_1.env({env, cwd: localDir, execPath}); - } - - return env; -}; - -const handleArguments = (file, args, options = {}) => { - const parsed = crossSpawn._parse(file, args, options); - file = parsed.command; - args = parsed.args; - options = parsed.options; - - options = { - maxBuffer: DEFAULT_MAX_BUFFER, - buffer: true, - stripFinalNewline: true, - extendEnv: true, - preferLocal: false, - localDir: options.cwd || process.cwd(), - execPath: process.execPath, - encoding: 'utf8', - reject: true, - cleanup: true, - all: false, - windowsHide: true, - ...options - }; - - options.env = getEnv(options); - - options.stdio = stdio(options); - - if (process.platform === 'win32' && path__default.basename(file, '.exe') === 'cmd') { - // #116 - args.unshift('/q'); - } - - return {file, args, options, parsed}; -}; - -const handleOutput = (options, value, error) => { - if (typeof value !== 'string' && !Buffer.isBuffer(value)) { - // When `execa.sync()` errors, we normalize it to '' to mimic `execa()` - return error === undefined ? undefined : ''; - } - - if (options.stripFinalNewline) { - return stripFinalNewline(value); - } - - return value; -}; - -const execa = (file, args, options) => { - const parsed = handleArguments(file, args, options); - const command = joinCommand(file, args); - - let spawned; - try { - spawned = childProcess__default.spawn(parsed.file, parsed.args, parsed.options); - } catch (error$1) { - // Ensure the returned error is always both a promise and a child process - const dummySpawned = new childProcess__default.ChildProcess(); - const errorPromise = Promise.reject(error({ - error: error$1, - stdout: '', - stderr: '', - all: '', - command, - parsed, - timedOut: false, - isCanceled: false, - killed: false - })); - return mergePromise(dummySpawned, errorPromise); - } - - const spawnedPromise = getSpawnedPromise(spawned); - const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); - const processDone = setExitHandler(spawned, parsed.options, timedPromise); - - const context = {isCanceled: false}; - - spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); - spawned.cancel = spawnedCancel.bind(null, spawned, context); - - const handlePromise = async () => { - const [{error: error$1, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); - const stdout = handleOutput(parsed.options, stdoutResult); - const stderr = handleOutput(parsed.options, stderrResult); - const all = handleOutput(parsed.options, allResult); - - if (error$1 || exitCode !== 0 || signal !== null) { - const returnedError = error({ - error: error$1, - exitCode, - signal, - stdout, - stderr, - all, - command, - parsed, - timedOut, - isCanceled: context.isCanceled, - killed: spawned.killed - }); - - if (!parsed.options.reject) { - return returnedError; - } - - throw returnedError; - } - - return { - command, - exitCode: 0, - stdout, - stderr, - all, - failed: false, - timedOut: false, - isCanceled: false, - killed: false - }; - }; - - const handlePromiseOnce = onetime_1(handlePromise); - - handleInput(spawned, parsed.options.input); - - spawned.all = makeAllStream(spawned, parsed.options); - - return mergePromise(spawned, handlePromiseOnce); -}; - -var execa_1 = execa; - -var sync = (file, args, options) => { - const parsed = handleArguments(file, args, options); - const command = joinCommand(file, args); - - validateInputSync(parsed.options); - - let result; - try { - result = childProcess__default.spawnSync(parsed.file, parsed.args, parsed.options); - } catch (error$1) { - throw error({ - error: error$1, - stdout: '', - stderr: '', - all: '', - command, - parsed, - timedOut: false, - isCanceled: false, - killed: false - }); - } - - const stdout = handleOutput(parsed.options, result.stdout, result.error); - const stderr = handleOutput(parsed.options, result.stderr, result.error); - - if (result.error || result.status !== 0 || result.signal !== null) { - const error$1 = error({ - stdout, - stderr, - error: result.error, - signal: result.signal, - exitCode: result.status, - command, - parsed, - timedOut: result.error && result.error.code === 'ETIMEDOUT', - isCanceled: false, - killed: result.signal !== null - }); - - if (!parsed.options.reject) { - return error$1; - } - - throw error$1; - } - - return { - command, - exitCode: 0, - stdout, - stderr, - failed: false, - timedOut: false, - isCanceled: false, - killed: false - }; -}; - -var command = (command, options) => { - const [file, ...args] = parseCommand(command); - return execa(file, args, options); -}; - -var commandSync = (command, options) => { - const [file, ...args] = parseCommand(command); - return execa.sync(file, args, options); -}; - -var node = (scriptPath, args, options = {}) => { - if (args && !Array.isArray(args) && typeof args === 'object') { - options = args; - args = []; - } - - const stdio$1 = stdio.node(options); - const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect')); - - const { - nodePath = process.execPath, - nodeOptions = defaultExecArgv - } = options; - - return execa( - nodePath, - [ - ...nodeOptions, - scriptPath, - ...(Array.isArray(args) ? args : []) - ], - { - ...options, - stdin: undefined, - stdout: undefined, - stderr: undefined, - stdio: stdio$1, - shell: false - } - ); -}; -execa_1.sync = sync; -execa_1.command = command; -execa_1.commandSync = commandSync; -execa_1.node = node; - -/** - * The following is modified based on source found in - * https://github.com/facebook/create-react-app - * - * MIT Licensed - * Copyright (c) 2015-present, Facebook, Inc. - * https://github.com/facebook/create-react-app/blob/master/LICENSE - * - */ -// https://github.com/sindresorhus/open#app -const OSX_CHROME = 'google chrome'; -/** - * Reads the BROWSER environment variable and decides what to do with it. - * Returns true if it opened a browser or ran a node.js script, otherwise false. - */ -function openBrowser(url, opt, logger) { - // The browser executable to open. - // See https://github.com/sindresorhus/open#app for documentation. - const browser = typeof opt === 'string' ? opt : process.env.BROWSER || ''; - if (browser.toLowerCase().endsWith('.js')) { - return executeNodeScript(browser, url, logger); - } - else if (browser.toLowerCase() !== 'none') { - return startBrowserProcess(browser, url); - } - return false; -} -function executeNodeScript(scriptPath, url, logger) { - const extraArgs = process.argv.slice(2); - const child = execa_1('node', [scriptPath, ...extraArgs, url], { - stdio: 'inherit' - }); - child.on('close', (code) => { - if (code !== 0) { - logger.error(source.red('\nThe script specified as BROWSER environment variable failed.\n')); - logger.error(source.cyan(scriptPath) + ' exited with code ' + code + '.'); - return; - } - }); - return true; -} -function startBrowserProcess(browser, url) { - // If we're on OS X, the user hasn't specifically - // requested a different browser, we can try opening - // Chrome with AppleScript. This lets us reuse an - // existing tab when possible instead of creating a new one. - const shouldTryOpenChromeWithAppleScript = process.platform === 'darwin' && (browser === '' || browser === OSX_CHROME); - if (shouldTryOpenChromeWithAppleScript) { - try { - // Try our best to reuse existing tab - // on OS X Google Chrome with AppleScript - childProcess.execSync('ps cax | grep "Google Chrome"'); - childProcess.execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', { - cwd: path__default.dirname(require.resolve('vite/bin/openChrome.applescript')), - stdio: 'ignore' - }); - return true; - } - catch (err) { - // Ignore errors - } - } - // Another special case: on OS X, check if BROWSER has been set to "open". - // In this case, instead of passing the string `open` to `open` function (which won't work), - // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser): - // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768 - if (process.platform === 'darwin' && browser === 'open') { - browser = undefined; - } - // Fallback to open - // (It will always open new tab) - try { - var options = { app: browser, url: true }; - open(url, options).catch(() => { }); // Prevent `unhandledRejection` error. - return true; - } - catch (err) { - return false; - } -} - -var colorName = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; - -/* MIT license */ - -var conversions = createCommonjsModule(function (module) { -// NOTE: conversions should only return primitive values (i.e. arrays, or -// values that give correct `typeof` results). -// do not use box values types (i.e. Number(), String(), etc.) - -var reverseKeywords = {}; -for (var key in colorName) { - if (colorName.hasOwnProperty(key)) { - reverseKeywords[colorName[key]] = key; - } -} - -var convert = module.exports = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} -}; - -// hide .channels and .labels properties -for (var model in convert) { - if (convert.hasOwnProperty(model)) { - if (!('channels' in convert[model])) { - throw new Error('missing channels property: ' + model); - } - - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } - - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } - - var channels = convert[model].channels; - var labels = convert[model].labels; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], 'channels', {value: channels}); - Object.defineProperty(convert[model], 'labels', {value: labels}); - } -} - -convert.rgb.hsl = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var min = Math.min(r, g, b); - var max = Math.max(r, g, b); - var delta = max - min; - var h; - var s; - var l; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - - if (h < 0) { - h += 360; - } - - l = (min + max) / 2; - - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - - return [h, s * 100, l * 100]; -}; - -convert.rgb.hsv = function (rgb) { - var rdif; - var gdif; - var bdif; - var h; - var s; - - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var v = Math.max(r, g, b); - var diff = v - Math.min(r, g, b); - var diffc = function (c) { - return (v - c) / 6 / diff + 1 / 2; - }; - - if (diff === 0) { - h = s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); - - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = (1 / 3) + rdif - bdif; - } else if (b === v) { - h = (2 / 3) + gdif - rdif; - } - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } - - return [ - h * 360, - s * 100, - v * 100 - ]; -}; - -convert.rgb.hwb = function (rgb) { - var r = rgb[0]; - var g = rgb[1]; - var b = rgb[2]; - var h = convert.rgb.hsl(rgb)[0]; - var w = 1 / 255 * Math.min(r, Math.min(g, b)); - - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - - return [h, w * 100, b * 100]; -}; - -convert.rgb.cmyk = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var c; - var m; - var y; - var k; - - k = Math.min(1 - r, 1 - g, 1 - b); - c = (1 - r - k) / (1 - k) || 0; - m = (1 - g - k) / (1 - k) || 0; - y = (1 - b - k) / (1 - k) || 0; - - return [c * 100, m * 100, y * 100, k * 100]; -}; - -/** - * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - * */ -function comparativeDistance(x, y) { - return ( - Math.pow(x[0] - y[0], 2) + - Math.pow(x[1] - y[1], 2) + - Math.pow(x[2] - y[2], 2) - ); -} - -convert.rgb.keyword = function (rgb) { - var reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } - - var currentClosestDistance = Infinity; - var currentClosestKeyword; - - for (var keyword in colorName) { - if (colorName.hasOwnProperty(keyword)) { - var value = colorName[keyword]; - - // Compute comparative distance - var distance = comparativeDistance(rgb, value); - - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - } - - return currentClosestKeyword; -}; - -convert.keyword.rgb = function (keyword) { - return colorName[keyword]; -}; - -convert.rgb.xyz = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - - // assume sRGB - r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); - g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); - b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); - - var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); - - return [x * 100, y * 100, z * 100]; -}; - -convert.rgb.lab = function (rgb) { - var xyz = convert.rgb.xyz(rgb); - var x = xyz[0]; - var y = xyz[1]; - var z = xyz[2]; - var l; - var a; - var b; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); - - l = (116 * y) - 16; - a = 500 * (x - y); - b = 200 * (y - z); - - return [l, a, b]; -}; - -convert.hsl.rgb = function (hsl) { - var h = hsl[0] / 360; - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var t1; - var t2; - var t3; - var rgb; - var val; - - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } - - t1 = 2 * l - t2; - - rgb = [0, 0, 0]; - for (var i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } - if (t3 > 1) { - t3--; - } - - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } - - rgb[i] = val * 255; - } - - return rgb; -}; - -convert.hsl.hsv = function (hsl) { - var h = hsl[0]; - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var smin = s; - var lmin = Math.max(l, 0.01); - var sv; - var v; - - l *= 2; - s *= (l <= 1) ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - v = (l + s) / 2; - sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); - - return [h, sv * 100, v * 100]; -}; - -convert.hsv.rgb = function (hsv) { - var h = hsv[0] / 60; - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var hi = Math.floor(h) % 6; - - var f = h - Math.floor(h); - var p = 255 * v * (1 - s); - var q = 255 * v * (1 - (s * f)); - var t = 255 * v * (1 - (s * (1 - f))); - v *= 255; - - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } -}; - -convert.hsv.hsl = function (hsv) { - var h = hsv[0]; - var s = hsv[1] / 100; - var v = hsv[2] / 100; - var vmin = Math.max(v, 0.01); - var lmin; - var sl; - var l; - - l = (2 - s) * v; - lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= (lmin <= 1) ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; - - return [h, sl * 100, l * 100]; -}; - -// http://dev.w3.org/csswg/css-color/#hwb-to-rgb -convert.hwb.rgb = function (hwb) { - var h = hwb[0] / 360; - var wh = hwb[1] / 100; - var bl = hwb[2] / 100; - var ratio = wh + bl; - var i; - var v; - var f; - var n; - - // wh + bl cant be > 1 - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } - - i = Math.floor(6 * h); - v = 1 - bl; - f = 6 * h - i; - - if ((i & 0x01) !== 0) { - f = 1 - f; - } - - n = wh + f * (v - wh); // linear interpolation - - var r; - var g; - var b; - switch (i) { - default: - case 6: - case 0: r = v; g = n; b = wh; break; - case 1: r = n; g = v; b = wh; break; - case 2: r = wh; g = v; b = n; break; - case 3: r = wh; g = n; b = v; break; - case 4: r = n; g = wh; b = v; break; - case 5: r = v; g = wh; b = n; break; - } - - return [r * 255, g * 255, b * 255]; -}; - -convert.cmyk.rgb = function (cmyk) { - var c = cmyk[0] / 100; - var m = cmyk[1] / 100; - var y = cmyk[2] / 100; - var k = cmyk[3] / 100; - var r; - var g; - var b; - - r = 1 - Math.min(1, c * (1 - k) + k); - g = 1 - Math.min(1, m * (1 - k) + k); - b = 1 - Math.min(1, y * (1 - k) + k); - - return [r * 255, g * 255, b * 255]; -}; - -convert.xyz.rgb = function (xyz) { - var x = xyz[0] / 100; - var y = xyz[1] / 100; - var z = xyz[2] / 100; - var r; - var g; - var b; - - r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); - g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); - b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); - - // assume sRGB - r = r > 0.0031308 - ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) - : r * 12.92; - - g = g > 0.0031308 - ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) - : g * 12.92; - - b = b > 0.0031308 - ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) - : b * 12.92; - - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); - - return [r * 255, g * 255, b * 255]; -}; - -convert.xyz.lab = function (xyz) { - var x = xyz[0]; - var y = xyz[1]; - var z = xyz[2]; - var l; - var a; - var b; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); - - l = (116 * y) - 16; - a = 500 * (x - y); - b = 200 * (y - z); - - return [l, a, b]; -}; - -convert.lab.xyz = function (lab) { - var l = lab[0]; - var a = lab[1]; - var b = lab[2]; - var x; - var y; - var z; - - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; - - var y2 = Math.pow(y, 3); - var x2 = Math.pow(x, 3); - var z2 = Math.pow(z, 3); - y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; - z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; - - x *= 95.047; - y *= 100; - z *= 108.883; - - return [x, y, z]; -}; - -convert.lab.lch = function (lab) { - var l = lab[0]; - var a = lab[1]; - var b = lab[2]; - var hr; - var h; - var c; - - hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; - - if (h < 0) { - h += 360; - } - - c = Math.sqrt(a * a + b * b); - - return [l, c, h]; -}; - -convert.lch.lab = function (lch) { - var l = lch[0]; - var c = lch[1]; - var h = lch[2]; - var a; - var b; - var hr; - - hr = h / 360 * 2 * Math.PI; - a = c * Math.cos(hr); - b = c * Math.sin(hr); - - return [l, a, b]; -}; - -convert.rgb.ansi16 = function (args) { - var r = args[0]; - var g = args[1]; - var b = args[2]; - var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization - - value = Math.round(value / 50); - - if (value === 0) { - return 30; - } - - var ansi = 30 - + ((Math.round(b / 255) << 2) - | (Math.round(g / 255) << 1) - | Math.round(r / 255)); - - if (value === 2) { - ansi += 60; - } - - return ansi; -}; - -convert.hsv.ansi16 = function (args) { - // optimization here; we already know the value and don't need to get - // it converted for us. - return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); -}; - -convert.rgb.ansi256 = function (args) { - var r = args[0]; - var g = args[1]; - var b = args[2]; - - // we use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (r === g && g === b) { - if (r < 8) { - return 16; - } - - if (r > 248) { - return 231; - } - - return Math.round(((r - 8) / 247) * 24) + 232; - } - - var ansi = 16 - + (36 * Math.round(r / 255 * 5)) - + (6 * Math.round(g / 255 * 5)) - + Math.round(b / 255 * 5); - - return ansi; -}; - -convert.ansi16.rgb = function (args) { - var color = args % 10; - - // handle greyscale - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } - - color = color / 10.5 * 255; - - return [color, color, color]; - } - - var mult = (~~(args > 50) + 1) * 0.5; - var r = ((color & 1) * mult) * 255; - var g = (((color >> 1) & 1) * mult) * 255; - var b = (((color >> 2) & 1) * mult) * 255; - - return [r, g, b]; -}; - -convert.ansi256.rgb = function (args) { - // handle greyscale - if (args >= 232) { - var c = (args - 232) * 10 + 8; - return [c, c, c]; - } - - args -= 16; - - var rem; - var r = Math.floor(args / 36) / 5 * 255; - var g = Math.floor((rem = args % 36) / 6) / 5 * 255; - var b = (rem % 6) / 5 * 255; - - return [r, g, b]; -}; - -convert.rgb.hex = function (args) { - var integer = ((Math.round(args[0]) & 0xFF) << 16) - + ((Math.round(args[1]) & 0xFF) << 8) - + (Math.round(args[2]) & 0xFF); - - var string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; - -convert.hex.rgb = function (args) { - var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match) { - return [0, 0, 0]; - } - - var colorString = match[0]; - - if (match[0].length === 3) { - colorString = colorString.split('').map(function (char) { - return char + char; - }).join(''); - } - - var integer = parseInt(colorString, 16); - var r = (integer >> 16) & 0xFF; - var g = (integer >> 8) & 0xFF; - var b = integer & 0xFF; - - return [r, g, b]; -}; - -convert.rgb.hcg = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var max = Math.max(Math.max(r, g), b); - var min = Math.min(Math.min(r, g), b); - var chroma = (max - min); - var grayscale; - var hue; - - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } - - if (chroma <= 0) { - hue = 0; - } else - if (max === r) { - hue = ((g - b) / chroma) % 6; - } else - if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma + 4; - } - - hue /= 6; - hue %= 1; - - return [hue * 360, chroma * 100, grayscale * 100]; -}; - -convert.hsl.hcg = function (hsl) { - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var c = 1; - var f = 0; - - if (l < 0.5) { - c = 2.0 * s * l; - } else { - c = 2.0 * s * (1.0 - l); - } - - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); - } - - return [hsl[0], c * 100, f * 100]; -}; - -convert.hsv.hcg = function (hsv) { - var s = hsv[1] / 100; - var v = hsv[2] / 100; - - var c = s * v; - var f = 0; - - if (c < 1.0) { - f = (v - c) / (1 - c); - } - - return [hsv[0], c * 100, f * 100]; -}; - -convert.hcg.rgb = function (hcg) { - var h = hcg[0] / 360; - var c = hcg[1] / 100; - var g = hcg[2] / 100; - - if (c === 0.0) { - return [g * 255, g * 255, g * 255]; - } - - var pure = [0, 0, 0]; - var hi = (h % 1) * 6; - var v = hi % 1; - var w = 1 - v; - var mg = 0; - - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; pure[1] = v; pure[2] = 0; break; - case 1: - pure[0] = w; pure[1] = 1; pure[2] = 0; break; - case 2: - pure[0] = 0; pure[1] = 1; pure[2] = v; break; - case 3: - pure[0] = 0; pure[1] = w; pure[2] = 1; break; - case 4: - pure[0] = v; pure[1] = 0; pure[2] = 1; break; - default: - pure[0] = 1; pure[1] = 0; pure[2] = w; - } - - mg = (1.0 - c) * g; - - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; -}; - -convert.hcg.hsv = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - - var v = c + g * (1.0 - c); - var f = 0; - - if (v > 0.0) { - f = c / v; - } - - return [hcg[0], f * 100, v * 100]; -}; - -convert.hcg.hsl = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - - var l = g * (1.0 - c) + 0.5 * c; - var s = 0; - - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else - if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } - - return [hcg[0], s * 100, l * 100]; -}; - -convert.hcg.hwb = function (hcg) { - var c = hcg[1] / 100; - var g = hcg[2] / 100; - var v = c + g * (1.0 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; -}; - -convert.hwb.hcg = function (hwb) { - var w = hwb[1] / 100; - var b = hwb[2] / 100; - var v = 1 - b; - var c = v - w; - var g = 0; - - if (c < 1) { - g = (v - c) / (1 - c); - } - - return [hwb[0], c * 100, g * 100]; -}; - -convert.apple.rgb = function (apple) { - return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; -}; - -convert.rgb.apple = function (rgb) { - return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; -}; - -convert.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; -}; - -convert.gray.hsl = convert.gray.hsv = function (args) { - return [0, 0, args[0]]; -}; - -convert.gray.hwb = function (gray) { - return [0, 100, gray[0]]; -}; - -convert.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; -}; - -convert.gray.lab = function (gray) { - return [gray[0], 0, 0]; -}; - -convert.gray.hex = function (gray) { - var val = Math.round(gray[0] / 100 * 255) & 0xFF; - var integer = (val << 16) + (val << 8) + val; - - var string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; - -convert.rgb.gray = function (rgb) { - var val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; -}; -}); - -/* - this function routes a model to all other models. - - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). - - conversions that are not possible simply are not included. -*/ - -function buildGraph() { - var graph = {}; - // https://jsperf.com/object-keys-vs-for-in-with-closure/3 - var models = Object.keys(conversions); - - for (var len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } - - return graph; -} - -// https://en.wikipedia.org/wiki/Breadth-first_search -function deriveBFS(fromModel) { - var graph = buildGraph(); - var queue = [fromModel]; // unshift -> queue -> pop - - graph[fromModel].distance = 0; - - while (queue.length) { - var current = queue.pop(); - var adjacents = Object.keys(conversions[current]); - - for (var len = adjacents.length, i = 0; i < len; i++) { - var adjacent = adjacents[i]; - var node = graph[adjacent]; - - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } - - return graph; -} - -function link(from, to) { - return function (args) { - return to(from(args)); - }; -} - -function wrapConversion(toModel, graph) { - var path = [graph[toModel].parent, toModel]; - var fn = conversions[graph[toModel].parent][toModel]; - - var cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } - - fn.conversion = path; - return fn; -} - -var route = function (fromModel) { - var graph = deriveBFS(fromModel); - var conversion = {}; - - var models = Object.keys(graph); - for (var len = models.length, i = 0; i < len; i++) { - var toModel = models[i]; - var node = graph[toModel]; - - if (node.parent === null) { - // no possible conversion, or this node is the source model. - continue; - } - - conversion[toModel] = wrapConversion(toModel, graph); - } - - return conversion; -}; - -var convert = {}; - -var models = Object.keys(conversions); - -function wrapRaw(fn) { - var wrappedFn = function (args) { - if (args === undefined || args === null) { - return args; - } - - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); - } - - return fn(args); - }; - - // preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -function wrapRounded(fn) { - var wrappedFn = function (args) { - if (args === undefined || args === null) { - return args; - } - - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); - } - - var result = fn(args); - - // we're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - if (typeof result === 'object') { - for (var len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } - - return result; - }; - - // preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -models.forEach(function (fromModel) { - convert[fromModel] = {}; - - Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); - Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - - var routes = route(fromModel); - var routeModels = Object.keys(routes); - - routeModels.forEach(function (toModel) { - var fn = routes[toModel]; - - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); -}); - -var colorConvert = convert; - -var ansiStyles = createCommonjsModule(function (module) { - - -const wrapAnsi16 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${code + offset}m`; -}; - -const wrapAnsi256 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};5;${code}m`; -}; - -const wrapAnsi16m = (fn, offset) => function () { - const rgb = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - - // Bright color - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Fix humans - styles.color.grey = styles.color.gray; - - for (const groupName of Object.keys(styles)) { - const group = styles[groupName]; - - for (const styleName of Object.keys(group)) { - const style = group[styleName]; - - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - } - - const ansi2ansi = n => n; - const rgb2rgb = (r, g, b) => [r, g, b]; - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - styles.color.ansi = { - ansi: wrapAnsi16(ansi2ansi, 0) - }; - styles.color.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 0) - }; - styles.color.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 0) - }; - - styles.bgColor.ansi = { - ansi: wrapAnsi16(ansi2ansi, 10) - }; - styles.bgColor.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 10) - }; - styles.bgColor.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 10) - }; - - for (let key of Object.keys(colorConvert)) { - if (typeof colorConvert[key] !== 'object') { - continue; - } - - const suite = colorConvert[key]; - - if (key === 'ansi16') { - key = 'ansi'; - } - - if ('ansi16' in suite) { - styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); - styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); - } - - if ('ansi256' in suite) { - styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); - styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); - } - - if ('rgb' in suite) { - styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); - styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); - } - } - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); -}); - -var hasFlag = (flag, argv) => { - argv = argv || process.argv; - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const pos = argv.indexOf(prefix + flag); - const terminatorPos = argv.indexOf('--'); - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); -}; - -const env = process.env; - -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; -} - -function translateLevel(level) { - if (level === 0) { - return false; - } - - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} - -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } - - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } - - if (hasFlag('color=256')) { - return 2; - } - - if (stream && !stream.isTTY && forceColor !== true) { - return 0; - } - - const min = forceColor ? 1 : 0; - - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. Windows 10 build 14931 is the first release - // that supports 16m/TrueColor. - const osRelease = os__default.release().split('.'); - if ( - Number(process.versions.node.split('.')[0]) >= 8 && - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - - return 1; - } - - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } - - return min; - } - - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - - if (env.COLORTERM === 'truecolor') { - return 3; - } - - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } - - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - - if ('COLORTERM' in env) { - return 1; - } - - if (env.TERM === 'dumb') { - return min; - } - - return min; -} - -function getSupportLevel(stream) { - const level = supportsColor(stream); - return translateLevel(level); -} - -var supportsColor_1 = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr) -}; - -const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; - -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); - -function unescape$1(c) { - if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } - - return ESCAPES.get(c) || c; -} - -function parseArguments(name, args) { - const results = []; - const chunks = args.trim().split(/\s*,\s*/g); - let matches; - - for (const chunk of chunks) { - if (!isNaN(chunk)) { - results.push(Number(chunk)); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape$1(escape) : chr)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } - - return results; -} - -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; - - const results = []; - let matches; - - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; - - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } - - return results; -} - -function buildStyle(chalk, styles) { - const enabled = {}; - - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } - - let current = chalk; - for (const styleName of Object.keys(enabled)) { - if (Array.isArray(enabled[styleName])) { - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } - - if (enabled[styleName].length > 0) { - current = current[styleName].apply(current, enabled[styleName]); - } else { - current = current[styleName]; - } - } - } - - return current; -} - -var templates = (chalk, tmp) => { - const styles = []; - const chunks = []; - let chunk = []; - - // eslint-disable-next-line max-params - tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { - if (escapeChar) { - chunk.push(unescape$1(escapeChar)); - } else if (style) { - const str = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } - - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(chr); - } - }); - - chunks.push(chunk.join('')); - - if (styles.length > 0) { - const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMsg); - } - - return chunks.join(''); -}; - -var chalk = createCommonjsModule(function (module) { - - -const stdoutColor = supportsColor_1.stdout; - - - -const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; - -// `color-convert` models to exclude from the Chalk API due to conflicts and such -const skipModels = new Set(['gray']); - -const styles = Object.create(null); - -function applyOptions(obj, options) { - options = options || {}; - - // Detect level if not set manually - const scLevel = stdoutColor ? stdoutColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; -} - -function Chalk(options) { - // We check for this.template here since calling `chalk.constructor()` - // by itself will have a `this` of a previously constructed chalk object - if (!this || !(this instanceof Chalk) || this.template) { - const chalk = {}; - applyOptions(chalk, options); - - chalk.template = function () { - const args = [].slice.call(arguments); - return chalkTag.apply(null, [chalk.template].concat(args)); - }; - - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); - - chalk.template.constructor = Chalk; - - return chalk.template; - } - - applyOptions(this, options); -} - -// Use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001B[94m'; -} - -for (const key of Object.keys(ansiStyles)) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - - styles[key] = { - get() { - const codes = ansiStyles[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); - } - }; -} - -styles.visible = { - get() { - return build.call(this, this._styles || [], true, 'visible'); - } -}; - -ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); -for (const model of Object.keys(ansiStyles.color.ansi)) { - if (skipModels.has(model)) { - continue; - } - - styles[model] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.color.close, - closeRe: ansiStyles.color.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} - -ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); -for (const model of Object.keys(ansiStyles.bgColor.ansi)) { - if (skipModels.has(model)) { - continue; - } - - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.bgColor.close, - closeRe: ansiStyles.bgColor.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} - -const proto = Object.defineProperties(() => {}, styles); - -function build(_styles, _empty, key) { - const builder = function () { - return applyStyle.apply(builder, arguments); - }; - - builder._styles = _styles; - builder._empty = _empty; - - const self = this; - - Object.defineProperty(builder, 'level', { - enumerable: true, - get() { - return self.level; - }, - set(level) { - self.level = level; - } - }); - - Object.defineProperty(builder, 'enabled', { - enumerable: true, - get() { - return self.enabled; - }, - set(enabled) { - self.enabled = enabled; - } - }); - - // See below for fix regarding invisible grey/dim combination on Windows - builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; - - // `__proto__` is used because we must return a function, but there is - // no way to create a function with a different prototype - builder.__proto__ = proto; // eslint-disable-line no-proto - - return builder; -} - -function applyStyle() { - // Support varags, but simply cast to string in case there's only one arg - const args = arguments; - const argsLen = args.length; - let str = String(arguments[0]); - - if (argsLen === 0) { - return ''; - } - - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (let a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } - - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; - } - - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - const originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && this.hasGrey) { - ansiStyles.dim.open = ''; - } - - for (const code of this._styles.slice().reverse()) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; - - // Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS - // https://github.com/chalk/chalk/pull/92 - str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); - } - - // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue - ansiStyles.dim.open = originalDim; - - return str; -} - -function chalkTag(chalk, strings) { - if (!Array.isArray(strings)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return [].slice.call(arguments, 1).join(' '); - } - - const args = [].slice.call(arguments, 2); - const parts = [strings.raw[0]]; - - for (let i = 1; i < strings.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(strings.raw[i])); - } - - return templates(chalk, parts.join('')); -} - -Object.defineProperties(Chalk.prototype, styles); - -module.exports = Chalk(); // eslint-disable-line new-cap -module.exports.supportsColor = stdoutColor; -module.exports.default = module.exports; // For TypeScript -}); - -var quote = function (xs) { - return xs.map(function (s) { - if (s && typeof s === 'object') { - return s.op.replace(/(.)/g, '\\$1'); - } - else if (/["\s]/.test(s) && !/'/.test(s)) { - return "'" + s.replace(/(['\\])/g, '\\$1') + "'"; - } - else if (/["'\s]/.test(s)) { - return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"'; - } - else { - return String(s).replace(/([A-z]:)?([#!"$&'()*,:;<=>?@\[\\\]^`{|}])/g, '$1\\$2'); - } - }).join(' '); -}; - -// '<(' is process substitution operator and -// can be parsed the same as control operator -var CONTROL = '(?:' + [ - '\\|\\|', '\\&\\&', ';;', '\\|\\&', '\\<\\(', '>>', '>\\&', '[&;()|<>]' -].join('|') + ')'; -var META = '|&;()<> \\t'; -var BAREWORD = '(\\\\[\'"' + META + ']|[^\\s\'"' + META + '])+'; -var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"'; -var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\''; - -var TOKEN = ''; -for (var i = 0; i < 4; i++) { - TOKEN += (Math.pow(16,8)*Math.random()).toString(16); -} - -var parse_1 = function (s, env, opts) { - var mapped = parse(s, env, opts); - if (typeof env !== 'function') return mapped; - return mapped.reduce(function (acc, s) { - if (typeof s === 'object') return acc.concat(s); - var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g')); - if (xs.length === 1) return acc.concat(xs[0]); - return acc.concat(xs.filter(Boolean).map(function (x) { - if (RegExp('^' + TOKEN).test(x)) { - return JSON.parse(x.split(TOKEN)[1]); - } - else return x; - })); - }, []); -}; - -function parse (s, env, opts) { - var chunker = new RegExp([ - '(' + CONTROL + ')', // control chars - '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')*' - ].join('|'), 'g'); - var match = s.match(chunker).filter(Boolean); - var commented = false; - - if (!match) return []; - if (!env) env = {}; - if (!opts) opts = {}; - return match.map(function (s, j) { - if (commented) { - return; - } - if (RegExp('^' + CONTROL + '$').test(s)) { - return { op: s }; - } - - // Hand-written scanner/parser for Bash quoting rules: - // - // 1. inside single quotes, all characters are printed literally. - // 2. inside double quotes, all characters are printed literally - // except variables prefixed by '$' and backslashes followed by - // either a double quote or another backslash. - // 3. outside of any quotes, backslashes are treated as escape - // characters and not printed (unless they are themselves escaped) - // 4. quote context can switch mid-token if there is no whitespace - // between the two quote contexts (e.g. all'one'"token" parses as - // "allonetoken") - var SQ = "'"; - var DQ = '"'; - var DS = '$'; - var BS = opts.escape || '\\'; - var quote = false; - var esc = false; - var out = ''; - var isGlob = false; - - for (var i = 0, len = s.length; i < len; i++) { - var c = s.charAt(i); - isGlob = isGlob || (!quote && (c === '*' || c === '?')); - if (esc) { - out += c; - esc = false; - } - else if (quote) { - if (c === quote) { - quote = false; - } - else if (quote == SQ) { - out += c; - } - else { // Double quote - if (c === BS) { - i += 1; - c = s.charAt(i); - if (c === DQ || c === BS || c === DS) { - out += c; - } else { - out += BS + c; - } - } - else if (c === DS) { - out += parseEnvVar(); - } - else { - out += c; - } - } - } - else if (c === DQ || c === SQ) { - quote = c; - } - else if (RegExp('^' + CONTROL + '$').test(c)) { - return { op: s }; - } - else if (RegExp('^#$').test(c)) { - commented = true; - if (out.length){ - return [out, { comment: s.slice(i+1) + match.slice(j+1).join(' ') }]; - } - return [{ comment: s.slice(i+1) + match.slice(j+1).join(' ') }]; - } - else if (c === BS) { - esc = true; - } - else if (c === DS) { - out += parseEnvVar(); - } - else out += c; - } - - if (isGlob) return {op: 'glob', pattern: out}; - - return out; - - function parseEnvVar() { - i += 1; - var varend, varname; - //debugger - if (s.charAt(i) === '{') { - i += 1; - if (s.charAt(i) === '}') { - throw new Error("Bad substitution: " + s.substr(i - 2, 3)); - } - varend = s.indexOf('}', i); - if (varend < 0) { - throw new Error("Bad substitution: " + s.substr(i)); - } - varname = s.substr(i, varend - i); - i = varend; - } - else if (/[*@#?$!_\-]/.test(s.charAt(i))) { - varname = s.charAt(i); - i += 1; - } - else { - varend = s.substr(i).match(/[^\w\d_]/); - if (!varend) { - varname = s.substr(i); - i = s.length; - } else { - varname = s.substr(i, varend.index); - i += varend.index - 1; - } - } - return getVar(null, '', varname); - } - }) - // finalize parsed aruments - .reduce(function(prev, arg){ - if (arg === undefined){ - return prev; - } - return prev.concat(arg); - },[]); - - function getVar (_, pre, key) { - var r = typeof env === 'function' ? env(key) : env[key]; - if (r === undefined && key != '') - r = ''; - else if (r === undefined) - r = '$'; - - if (typeof r === 'object') { - return pre + TOKEN + JSON.stringify(r) + TOKEN; - } - else return pre + r; - } -} - -var shellQuote = { - quote: quote, - parse: parse_1 -}; - -var osx = { - '/Applications/Atom.app/Contents/MacOS/Atom': 'atom', - '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta': - '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta', - '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets', - '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text': - '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl', - '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2': - '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl', - '/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text': - '/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl', - '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code', - '/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron': - 'code-insiders', - '/Applications/AppCode.app/Contents/MacOS/appcode': - '/Applications/AppCode.app/Contents/MacOS/appcode', - '/Applications/CLion.app/Contents/MacOS/clion': - '/Applications/CLion.app/Contents/MacOS/clion', - '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea': - '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea', - '/Applications/PhpStorm.app/Contents/MacOS/phpstorm': - '/Applications/PhpStorm.app/Contents/MacOS/phpstorm', - '/Applications/PyCharm.app/Contents/MacOS/pycharm': - '/Applications/PyCharm.app/Contents/MacOS/pycharm', - '/Applications/PyCharm CE.app/Contents/MacOS/pycharm': - '/Applications/PyCharm CE.app/Contents/MacOS/pycharm', - '/Applications/RubyMine.app/Contents/MacOS/rubymine': - '/Applications/RubyMine.app/Contents/MacOS/rubymine', - '/Applications/WebStorm.app/Contents/MacOS/webstorm': - '/Applications/WebStorm.app/Contents/MacOS/webstorm' -}; - -var linux = { - atom: 'atom', - Brackets: 'brackets', - code: 'code', - emacs: 'emacs', - 'idea.sh': 'idea', - 'phpstorm.sh': 'phpstorm', - 'pycharm.sh': 'pycharm', - 'rubymine.sh': 'rubymine', - sublime_text: 'subl', - vim: 'vim', - 'webstorm.sh': 'webstorm' -}; - -var windows = [ - 'Brackets.exe', - 'Code.exe', - 'atom.exe', - 'sublime_text.exe', - 'notepad++.exe', - 'clion.exe', - 'clion64.exe', - 'idea.exe', - 'idea64.exe', - 'phpstorm.exe', - 'phpstorm64.exe', - 'pycharm.exe', - 'pycharm64.exe', - 'rubymine.exe', - 'rubymine64.exe', - 'webstorm.exe', - 'webstorm64.exe' -]; - -// Map from full process name to binary that starts the process -// We can't just re-use full process name, because it will spawn a new instance -// of the app every time - - - - -var guess = function guessEditor (specifiedEditor) { - if (specifiedEditor) { - return shellQuote.parse(specifiedEditor) - } - // We can find out which editor is currently running by: - // `ps x` on macOS and Linux - // `Get-Process` on Windows - try { - if (process.platform === 'darwin') { - const output = childProcess__default.execSync('ps x').toString(); - const processNames = Object.keys(osx); - for (let i = 0; i < processNames.length; i++) { - const processName = processNames[i]; - if (output.indexOf(processName) !== -1) { - return [osx[processName]] - } - } - } else if (process.platform === 'win32') { - const output = childProcess__default - .execSync('powershell -Command "Get-Process | Select-Object Path"', { - stdio: ['pipe', 'pipe', 'ignore'] - }) - .toString(); - const runningProcesses = output.split('\r\n'); - for (let i = 0; i < runningProcesses.length; i++) { - // `Get-Process` sometimes returns empty lines - if (!runningProcesses[i]) { - continue - } - - const fullProcessPath = runningProcesses[i].trim(); - const shortProcessName = path__default.basename(fullProcessPath); - - if (windows.indexOf(shortProcessName) !== -1) { - return [fullProcessPath] - } - } - } else if (process.platform === 'linux') { - // --no-heading No header line - // x List all processes owned by you - // -o comm Need only names column - const output = childProcess__default - .execSync('ps x --no-heading -o comm --sort=comm') - .toString(); - const processNames = Object.keys(linux); - for (let i = 0; i < processNames.length; i++) { - const processName = processNames[i]; - if (output.indexOf(processName) !== -1) { - return [linux[processName]] - } - } - } - } catch (error) { - // Ignore... - } - - // Last resort, use old skool env vars - if (process.env.VISUAL) { - return [process.env.VISUAL] - } else if (process.env.EDITOR) { - return [process.env.EDITOR] - } - - return [null] -}; - -// normalize file/line numbers into command line args for specific editors -var getArgs = function getArgumentsForPosition ( - editor, - fileName, - lineNumber, - columnNumber = 1 -) { - const editorBasename = path__default.basename(editor).replace(/\.(exe|cmd|bat)$/i, ''); - switch (editorBasename) { - case 'atom': - case 'Atom': - case 'Atom Beta': - case 'subl': - case 'sublime': - case 'sublime_text': - case 'wstorm': - case 'charm': - return [`${fileName}:${lineNumber}:${columnNumber}`] - case 'notepad++': - return ['-n' + lineNumber, fileName] - case 'vim': - case 'mvim': - return [`+call cursor(${lineNumber}, ${columnNumber})`, fileName] - case 'joe': - return ['+' + `${lineNumber}`, fileName] - case 'emacs': - case 'emacsclient': - return [`+${lineNumber}:${columnNumber}`, fileName] - case 'rmate': - case 'mate': - case 'mine': - return ['--line', lineNumber, fileName] - case 'code': - case 'code-insiders': - case 'Code': - return ['-r', '-g', `${fileName}:${lineNumber}:${columnNumber}`] - case 'appcode': - case 'clion': - case 'clion64': - case 'idea': - case 'idea64': - case 'phpstorm': - case 'phpstorm64': - case 'pycharm': - case 'pycharm64': - case 'rubymine': - case 'rubymine64': - case 'webstorm': - case 'webstorm64': - return ['--line', lineNumber, fileName] - } - - // For all others, drop the lineNumber until we have - // a mapping above, since providing the lineNumber incorrectly - // can result in errors or confusing behavior. - return [fileName] -}; - -/** - * Copyright (c) 2015-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file at - * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE - * - * Modified by Yuxi Evan You - */ - -function wrapErrorCallback (cb) { - return (fileName, errorMessage) => { - console.log(); - console.log( - chalk.red('Could not open ' + path__default.basename(fileName) + ' in the editor.') - ); - if (errorMessage) { - if (errorMessage[errorMessage.length - 1] !== '.') { - errorMessage += '.'; - } - console.log( - chalk.red('The editor process exited with an error: ' + errorMessage) - ); - } - console.log(); - if (cb) cb(fileName, errorMessage); - } -} - -function isTerminalEditor (editor) { - switch (editor) { - case 'vim': - case 'emacs': - case 'nano': - return true - } - return false -} - -const positionRE = /:(\d+)(:(\d+))?$/; -function parseFile (file) { - const fileName = file.replace(positionRE, ''); - const match = file.match(positionRE); - const lineNumber = match && match[1]; - const columnNumber = match && match[3]; - return { - fileName, - lineNumber, - columnNumber - } -} - -let _childProcess = null; - -function launchEditor (file, specifiedEditor, onErrorCallback) { - const parsed = parseFile(file); - let { fileName } = parsed; - const { lineNumber, columnNumber } = parsed; - - if (!fs__default.existsSync(fileName)) { - return - } - - if (typeof specifiedEditor === 'function') { - onErrorCallback = specifiedEditor; - specifiedEditor = undefined; - } - - onErrorCallback = wrapErrorCallback(onErrorCallback); - - const [editor, ...args] = guess(specifiedEditor); - if (!editor) { - onErrorCallback(fileName, null); - return - } - - if ( - process.platform === 'linux' && - fileName.startsWith('/mnt/') && - /Microsoft/i.test(os__default.release()) - ) { - // Assume WSL / "Bash on Ubuntu on Windows" is being used, and - // that the file exists on the Windows file system. - // `os.release()` is "4.4.0-43-Microsoft" in the current release - // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364 - // When a Windows editor is specified, interop functionality can - // handle the path translation, but only if a relative path is used. - fileName = path__default.relative('', fileName); - } - - if (lineNumber) { - const extraArgs = getArgs(editor, fileName, lineNumber, columnNumber); - args.push.apply(args, extraArgs); - } else { - args.push(fileName); - } - - if (_childProcess && isTerminalEditor(editor)) { - // There's an existing editor process already and it's attached - // to the terminal, so go kill it. Otherwise two separate editor - // instances attach to the stdin/stdout which gets confusing. - _childProcess.kill('SIGKILL'); - } - - if (process.platform === 'win32') { - // On Windows, launch the editor in a shell because spawn can only - // launch .exe files. - _childProcess = childProcess__default.spawn( - 'cmd.exe', - ['/C', editor].concat(args), - { stdio: 'inherit' } - ); - } else { - _childProcess = childProcess__default.spawn(editor, args, { stdio: 'inherit' }); - } - _childProcess.on('exit', function (errorCode) { - _childProcess = null; - - if (errorCode) { - onErrorCallback(fileName, '(code ' + errorCode + ')'); - } - }); - - _childProcess.on('error', function (error) { - onErrorCallback(fileName, error.message); - }); -} - -var launchEditor_1 = launchEditor; - -var launchEditorMiddleware = (specifiedEditor, srcRoot, onErrorCallback) => { - if (typeof specifiedEditor === 'function') { - onErrorCallback = specifiedEditor; - specifiedEditor = undefined; - } - - if (typeof srcRoot === 'function') { - onErrorCallback = srcRoot; - srcRoot = undefined; - } - - srcRoot = srcRoot || process.cwd(); - - return function launchEditorMiddleware (req, res, next) { - const { file } = url__default.parse(req.url, true).query || {}; - if (!file) { - res.statusCode = 500; - res.end(`launch-editor-middleware: required query param "file" is missing.`); - } else { - launchEditor_1(path__default.resolve(srcRoot, file), specifiedEditor, onErrorCallback); - res.end(); - } - } -}; - -const externalTypes = [ - 'css', - // supported pre-processor types - 'less', - 'sass', - 'scss', - 'styl', - 'stylus', - 'postcss', - // known SFC types - 'vue', - 'svelte', - // JSX/TSX may be configured to be compiled differently from how esbuild - // handles it by default, so exclude them as well - 'jsx', - 'tsx', - ...KNOWN_ASSET_TYPES -]; -function esbuildDepPlugin(qualified, exportsData, config) { - // default resolver which prefers ESM - const _resolve = config.createResolver({ asSrc: false }); - // cjs resolver that prefers Node - const _resolveRequire = config.createResolver({ - asSrc: false, - isRequire: true - }); - const resolve = (id, importer, kind, resolveDir) => { - let _importer; - // explicit resolveDir - this is passed only during yarn pnp resolve for - // entries - if (resolveDir) { - _importer = normalizePath$2(path__default.join(resolveDir, '*')); - } - else { - // map importer ids to file paths for correct resolution - _importer = importer in qualified ? qualified[importer] : importer; - } - const resolver = kind.startsWith('require') ? _resolveRequire : _resolve; - return resolver(id, _importer); - }; - return { - name: 'vite:dep-pre-bundle', - setup(build) { - // externalize assets and commonly known non-js file types - build.onResolve({ - filter: new RegExp(`\\.(` + externalTypes.join('|') + `)(\\?.*)?$`) - }, async ({ path: id, importer, kind }) => { - const resolved = await resolve(id, importer, kind); - if (resolved) { - return { - path: resolved, - external: true - }; - } - }); - function resolveEntry(id, isEntry) { - const flatId = flattenId(id); - if (flatId in qualified) { - return isEntry - ? { - path: flatId, - namespace: 'dep' - } - : { - path: path__default.resolve(qualified[flatId]) - }; - } - } - build.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => { - const isEntry = !importer; - // ensure esbuild uses our resolved entries - let entry; - // if this is an entry, return entry namespace resolve result - if ((entry = resolveEntry(id, isEntry))) - return entry; - // check if this is aliased to an entry - also return entry namespace - const aliased = await _resolve(id, undefined, true); - if (aliased && (entry = resolveEntry(aliased, isEntry))) { - return entry; - } - // use vite's own resolver - const resolved = await resolve(id, importer, kind); - if (resolved) { - if (resolved.startsWith(browserExternalId)) { - return { - path: id, - namespace: 'browser-external' - }; - } - if (isExternalUrl(resolved)) { - return { - path: resolved, - external: true - }; - } - return { - path: path__default.resolve(resolved) - }; - } - }); - // For entry files, we'll read it ourselves and construct a proxy module - // to retain the entry's raw id instead of file path so that esbuild - // outputs desired output file structure. - // It is necessary to do the re-exporting to separate the virtual proxy - // module from the actual module since the actual module may get - // referenced via relative imports - if we don't separate the proxy and - // the actual module, esbuild will create duplicated copies of the same - // module! - const root = path__default.resolve(config.root); - build.onLoad({ filter: /.*/, namespace: 'dep' }, ({ path: id }) => { - const entryFile = qualified[id]; - let relativePath = normalizePath$2(path__default.relative(root, entryFile)); - if (!relativePath.startsWith('.')) { - relativePath = `./${relativePath}`; - } - let contents = ''; - const data = exportsData[id]; - const [imports, exports] = data; - if (!imports.length && !exports.length) { - // cjs - contents += `export default require("${relativePath}");`; - } - else { - if (exports.includes('default')) { - contents += `import d from "${relativePath}";export default d;`; - } - if (data.hasReExports || - exports.length > 1 || - exports[0] !== 'default') { - contents += `\nexport * from "${relativePath}"`; - } - } - let ext = path__default.extname(entryFile).slice(1); - if (ext === 'mjs') - ext = 'js'; - return { - loader: ext, - contents, - resolveDir: root - }; - }); - build.onLoad({ filter: /.*/, namespace: 'browser-external' }, ({ path: id }) => { - return { - contents: `export default new Proxy({}, { - get() { - throw new Error('Module "${id}" has been externalized for ` + - `browser compatibility and cannot be accessed in client code.') - } -})` - }; - }); - // yarn 2 pnp compat - if (isRunningWithYarnPnp) { - build.onResolve({ filter: /.*/ }, async ({ path, importer, kind, resolveDir }) => ({ - // pass along resolveDir for entries - path: await resolve(path, importer, kind, resolveDir) - })); - build.onLoad({ filter: /.*/ }, async (args) => ({ - contents: await require('fs').promises.readFile(args.path), - loader: 'default' - })); - } - } - }; -} - -const debug = createDebugger('vite:deps'); -async function optimizeDeps(config, force = config.server.force, asCommand = false, newDeps // missing imports encountered after server has started -) { - var _a, _b, _c; - config = { - ...config, - command: 'build' - }; - const { root, logger, optimizeCacheDir: cacheDir } = config; - const log = asCommand ? logger.info : debug; - if (!cacheDir) { - log(`No package.json. Skipping.`); - return null; - } - const dataPath = path__default.join(cacheDir, '_metadata.json'); - const mainHash = getDepHash(root, config); - const data = { - hash: mainHash, - browserHash: mainHash, - optimized: {} - }; - if (!force) { - let prevData; - try { - prevData = JSON.parse(fs__default.readFileSync(dataPath, 'utf-8')); - } - catch (e) { } - // hash is consistent, no need to re-bundle - if (prevData && prevData.hash === data.hash) { - log('Hash is consistent. Skipping. Use --force to override.'); - return prevData; - } - } - if (fs__default.existsSync(cacheDir)) { - emptyDir(cacheDir); - } - else { - fs__default.mkdirSync(cacheDir, { recursive: true }); - } - let deps, missing; - if (!newDeps) { - ({ deps, missing } = await scanImports(config)); - } - else { - deps = newDeps; - missing = {}; - } - // update browser hash - data.browserHash = require$$0$3.createHash('sha256') - .update(data.hash + JSON.stringify(deps)) - .digest('hex') - .substr(0, 8); - const missingIds = Object.keys(missing); - if (missingIds.length) { - throw new Error(`The following dependencies are imported but could not be resolved:\n\n ${missingIds - .map((id) => `${source.cyan(id)} ${source.white.dim(`(imported by ${missing[id]})`)}`) - .join(`\n `)}\n\nAre they installed?`); - } - const include = (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include; - if (include) { - const resolve = config.createResolver({ asSrc: false }); - for (const id of include) { - if (!deps[id]) { - const entry = await resolve(id); - if (entry) { - deps[id] = entry; - } - else { - throw new Error(`Failed to resolve force included dependency: ${source.cyan(id)}`); - } - } - } - } - const qualifiedIds = Object.keys(deps); - if (!qualifiedIds.length) { - writeFile(dataPath, JSON.stringify(data, null, 2)); - log(`No dependencies to bundle. Skipping.\n\n\n`); - return data; - } - const total = qualifiedIds.length; - const maxListed = 5; - const listed = Math.min(total, maxListed); - const extra = Math.max(0, total - maxListed); - const depsString = source.yellow(qualifiedIds.slice(0, listed).join(`\n `) + - (extra > 0 ? `\n (...and ${extra} more)` : ``)); - if (!asCommand) { - if (!newDeps) { - // This is auto run on server start - let the user know that we are - // pre-optimizing deps - logger.info(source.greenBright(`Pre-bundling dependencies:\n ${depsString}`)); - logger.info(`(this will be run only when your dependencies or config have changed)`); - } - } - else { - logger.info(source.greenBright(`Optimizing dependencies:\n ${depsString}`)); - } - // esbuild generates nested directory output with lowest common ancestor base - // this is unpredictable and makes it difficult to analyze entry / output - // mapping. So what we do here is: - // 1. flatten all ids to eliminate slash - // 2. in the plugin, read the entry ourselves as virtual files to retain the - // path. - const flatIdDeps = {}; - const idToExports = {}; - const flatIdToExports = {}; - await init; - for (const id in deps) { - const flatId = flattenId(id); - flatIdDeps[flatId] = deps[id]; - const entryContent = fs__default.readFileSync(deps[id], 'utf-8'); - const exportsData = parse$e(entryContent); - for (const { ss, se } of exportsData[0]) { - const exp = entryContent.slice(ss, se); - if (/export\s+\*\s+from/.test(exp)) { - exportsData.hasReExports = true; - } - } - idToExports[id] = exportsData; - flatIdToExports[flatId] = exportsData; - } - const define = { - 'process.env.NODE_ENV': JSON.stringify(config.mode) - }; - for (const key in config.define) { - define[key] = JSON.stringify(config.define[key]); - } - const start = Date.now(); - const result = await esbuild.build({ - entryPoints: Object.keys(flatIdDeps), - bundle: true, - keepNames: (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.keepNames, - format: 'esm', - external: (_c = config.optimizeDeps) === null || _c === void 0 ? void 0 : _c.exclude, - logLevel: 'error', - splitting: true, - sourcemap: true, - outdir: cacheDir, - treeShaking: 'ignore-annotations', - metafile: true, - define, - plugins: [esbuildDepPlugin(flatIdDeps, flatIdToExports, config)] - }); - const meta = result.metafile; - for (const id in deps) { - const entry = deps[id]; - data.optimized[id] = { - file: normalizePath$2(path__default.resolve(cacheDir, flattenId(id) + '.js')), - src: entry, - needsInterop: needsInterop(id, idToExports[id], meta.outputs) - }; - } - writeFile(dataPath, JSON.stringify(data, null, 2)); - debug(`deps bundled in ${Date.now() - start}ms`); - return data; -} -// https://github.com/vitejs/vite/issues/1724#issuecomment-767619642 -// a list of modules that pretends to be ESM but still uses `require`. -// this causes esbuild to wrap them as CJS even when its entry appears to be ESM. -const KNOWN_INTEROP_IDS = new Set(['moment']); -function needsInterop(id, exportsData, outputs) { - if (KNOWN_INTEROP_IDS.has(id)) { - return true; - } - const [imports, exports] = exportsData; - // entry has no ESM syntax - likely CJS or UMD - if (!exports.length && !imports.length) { - return true; - } - // if a peer dependency used require() on a ESM dependency, esbuild turns the - // ESM dependency's entry chunk into a single default export... detect - // such cases by checking exports mismatch, and force interop. - const flatId = flattenId(id) + '.js'; - let generatedExports; - for (const output in outputs) { - if (normalizePath$2(output).endsWith('.vite/' + flatId)) { - generatedExports = outputs[output].exports; - break; - } - } - if (!generatedExports || - (isSingleDefaultExport(generatedExports) && !isSingleDefaultExport(exports))) { - return true; - } - return false; -} -function isSingleDefaultExport(exports) { - return exports.length === 1 && exports[0] === 'default'; -} -const lockfileFormats = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']; -function getDepHash(root, config) { - var _a, _b; - let content = lookupFile(root, lockfileFormats) || ''; - // also take config into account - // only a subset of config options that can affect dep optimization - content += JSON.stringify({ - mode: config.mode, - root: config.root, - resolve: config.resolve, - assetsInclude: config.assetsInclude, - plugins: config.plugins.map((p) => p.name), - optimizeDeps: { - include: (_a = config.optimizeDeps) === null || _a === void 0 ? void 0 : _a.include, - exclude: (_b = config.optimizeDeps) === null || _b === void 0 ? void 0 : _b.exclude - } - }, (_, value) => { - if (typeof value === 'function' || value instanceof RegExp) { - return value.toString(); - } - return value; - }); - return require$$0$3.createHash('sha256').update(content).digest('hex').substr(0, 8); -} - -var index$1 = { - __proto__: null, - optimizeDeps: optimizeDeps -}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - -/** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ -var encode$1 = function (number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); -}; - -/** - * Decode a single base 64 character code digit to an integer. Returns -1 on - * failure. - */ -var decode$1 = function (charCode) { - var bigA = 65; // 'A' - var bigZ = 90; // 'Z' - - var littleA = 97; // 'a' - var littleZ = 122; // 'z' - - var zero = 48; // '0' - var nine = 57; // '9' - - var plus = 43; // '+' - var slash = 47; // '/' - - var littleOffset = 26; - var numberOffset = 52; - - // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ - if (bigA <= charCode && charCode <= bigZ) { - return (charCode - bigA); - } - - // 26 - 51: abcdefghijklmnopqrstuvwxyz - if (littleA <= charCode && charCode <= littleZ) { - return (charCode - littleA + littleOffset); - } - - // 52 - 61: 0123456789 - if (zero <= charCode && charCode <= nine) { - return (charCode - zero + numberOffset); - } - - // 62: + - if (charCode == plus) { - return 62; - } - - // 63: / - if (charCode == slash) { - return 63; - } - - // Invalid base64 digit. - return -1; -}; - -var base64 = { - encode: encode$1, - decode: decode$1 -}; - -/* -*- 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. - */ - - - -// A single base 64 digit can contain 6 bits of data. For the base 64 variable -// length quantities we use in the source map spec, the first bit is the sign, -// the next four bits are the actual value, and the 6th bit is the -// continuation bit. The continuation bit tells us whether there are more -// digits in this value following this digit. -// -// Continuation -// | Sign -// | | -// V V -// 101011 - -var VLQ_BASE_SHIFT = 5; - -// binary: 100000 -var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - -// binary: 011111 -var VLQ_BASE_MASK = VLQ_BASE - 1; - -// binary: 100000 -var VLQ_CONTINUATION_BIT = VLQ_BASE; - -/** - * Converts from a two-complement value to a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ -function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; -} - -/** - * Converts to a two-complement value from a value where the sign bit is - * placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ -function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; -} - -/** - * Returns the base 64 VLQ encoded value. - */ -var encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned(aValue); - - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - - return encoded; -}; - -/** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string via the out parameter. - */ -var decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - - do { - if (aIndex >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - - digit = base64.decode(aStr.charCodeAt(aIndex++)); - if (digit === -1) { - throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); - } - - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); - - aOutParam.value = fromVLQSigned(result); - aOutParam.rest = aIndex; -}; - -var base64Vlq = { - encode: encode, - decode: decode -}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -var util = createCommonjsModule(function (module, exports) { -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -/** - * This is a helper function for getting values from parameter/options - * objects. - * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. - */ -function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } -} -exports.getArg = getArg; - -var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; -var dataUrlRegexp = /^data:.+\,.+$/; - -function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[2], - host: match[3], - port: match[4], - path: match[5] - }; -} -exports.urlParse = urlParse; - -function urlGenerate(aParsedUrl) { - var url = ''; - if (aParsedUrl.scheme) { - url += aParsedUrl.scheme + ':'; - } - url += '//'; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + '@'; - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port; - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; -} -exports.urlGenerate = urlGenerate; - -/** - * Normalizes a path, or the path portion of a URL: - * - * - Replaces consecutive slashes with one slash. - * - Removes unnecessary '.' parts. - * - Removes unnecessary '/..' parts. - * - * Based on code in the Node.js 'path' core module. - * - * @param aPath The path or url to normalize. - */ -function normalize(aPath) { - var path = aPath; - var url = urlParse(aPath); - if (url) { - if (!url.path) { - return aPath; - } - path = url.path; - } - var isAbsolute = exports.isAbsolute(path); - - var parts = path.split(/\/+/); - for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { - part = parts[i]; - if (part === '.') { - parts.splice(i, 1); - } else if (part === '..') { - up++; - } else if (up > 0) { - if (part === '') { - // The first part is blank if the path is absolute. Trying to go - // above the root is a no-op. Therefore we can remove all '..' parts - // directly after the root. - parts.splice(i + 1, up); - up = 0; - } else { - parts.splice(i, 2); - up--; - } - } - } - path = parts.join('/'); - - if (path === '') { - path = isAbsolute ? '/' : '.'; - } - - if (url) { - url.path = path; - return urlGenerate(url); - } - return path; -} -exports.normalize = normalize; - -/** - * Joins two paths/URLs. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be joined with the root. - * - * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a - * scheme-relative URL: Then the scheme of aRoot, if any, is prepended - * first. - * - Otherwise aPath is a path. If aRoot is a URL, then its path portion - * is updated with the result and aRoot is returned. Otherwise the result - * is returned. - * - If aPath is absolute, the result is aPath. - * - Otherwise the two paths are joined with a slash. - * - Joining for example 'http://' and 'www.example.com' is also supported. - */ -function join(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - if (aPath === "") { - aPath = "."; - } - var aPathUrl = urlParse(aPath); - var aRootUrl = urlParse(aRoot); - if (aRootUrl) { - aRoot = aRootUrl.path || '/'; - } - - // `join(foo, '//www.example.org')` - if (aPathUrl && !aPathUrl.scheme) { - if (aRootUrl) { - aPathUrl.scheme = aRootUrl.scheme; - } - return urlGenerate(aPathUrl); - } - - if (aPathUrl || aPath.match(dataUrlRegexp)) { - return aPath; - } - - // `join('http://', 'www.example.com')` - if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { - aRootUrl.host = aPath; - return urlGenerate(aRootUrl); - } - - var joined = aPath.charAt(0) === '/' - ? aPath - : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); - - if (aRootUrl) { - aRootUrl.path = joined; - return urlGenerate(aRootUrl); - } - return joined; -} -exports.join = join; - -exports.isAbsolute = function (aPath) { - return aPath.charAt(0) === '/' || urlRegexp.test(aPath); -}; - -/** - * Make a path relative to a URL or another path. - * - * @param aRoot The root path or URL. - * @param aPath The path or URL to be made relative to aRoot. - */ -function relative(aRoot, aPath) { - if (aRoot === "") { - aRoot = "."; - } - - aRoot = aRoot.replace(/\/$/, ''); - - // It is possible for the path to be above the root. In this case, simply - // checking whether the root is a prefix of the path won't work. Instead, we - // need to remove components from the root one by one, until either we find - // a prefix that fits, or we run out of components to remove. - var level = 0; - while (aPath.indexOf(aRoot + '/') !== 0) { - var index = aRoot.lastIndexOf("/"); - if (index < 0) { - return aPath; - } - - // If the only part of the root that is left is the scheme (i.e. http://, - // file:///, etc.), one or more slashes (/), or simply nothing at all, we - // have exhausted all components, so the path is not relative to the root. - aRoot = aRoot.slice(0, index); - if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { - return aPath; - } - - ++level; - } - - // Make sure we add a "../" for each component we removed from the root. - return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); -} -exports.relative = relative; - -var supportsNullProto = (function () { - var obj = Object.create(null); - return !('__proto__' in obj); -}()); - -function identity (s) { - return s; -} - -/** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ -function toSetString(aStr) { - if (isProtoString(aStr)) { - return '$' + aStr; - } - - return aStr; -} -exports.toSetString = supportsNullProto ? identity : toSetString; - -function fromSetString(aStr) { - if (isProtoString(aStr)) { - return aStr.slice(1); - } - - return aStr; -} -exports.fromSetString = supportsNullProto ? identity : fromSetString; - -function isProtoString(s) { - if (!s) { - return false; - } - - var length = s.length; - - if (length < 9 /* "__proto__".length */) { - return false; - } - - if (s.charCodeAt(length - 1) !== 95 /* '_' */ || - s.charCodeAt(length - 2) !== 95 /* '_' */ || - s.charCodeAt(length - 3) !== 111 /* 'o' */ || - s.charCodeAt(length - 4) !== 116 /* 't' */ || - s.charCodeAt(length - 5) !== 111 /* 'o' */ || - s.charCodeAt(length - 6) !== 114 /* 'r' */ || - s.charCodeAt(length - 7) !== 112 /* 'p' */ || - s.charCodeAt(length - 8) !== 95 /* '_' */ || - s.charCodeAt(length - 9) !== 95 /* '_' */) { - return false; - } - - for (var i = length - 10; i >= 0; i--) { - if (s.charCodeAt(i) !== 36 /* '$' */) { - return false; - } - } - - return true; -} - -/** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ -function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0 || onlyCompareOriginal) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); -} -exports.compareByOriginalPositions = compareByOriginalPositions; - -/** - * Comparator between two mappings with deflated source and name indices where - * the generated positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ -function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0 || onlyCompareGenerated) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); -} -exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; - -function strcmp(aStr1, aStr2) { - if (aStr1 === aStr2) { - return 0; - } - - if (aStr1 === null) { - return 1; // aStr2 !== null - } - - if (aStr2 === null) { - return -1; // aStr1 !== null - } - - if (aStr1 > aStr2) { - return 1; - } - - return -1; -} - -/** - * Comparator between two mappings with inflated source and name strings where - * the generated positions are compared. - */ -function compareByGeneratedPositionsInflated(mappingA, mappingB) { - var cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp !== 0) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp !== 0) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp !== 0) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); -} -exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; - -/** - * Strip any JSON XSSI avoidance prefix from the string (as documented - * in the source maps specification), and then parse the string as - * JSON. - */ -function parseSourceMapInput(str) { - return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); -} -exports.parseSourceMapInput = parseSourceMapInput; - -/** - * Compute the URL of a source given the the source root, the source's - * URL, and the source map's URL. - */ -function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { - sourceURL = sourceURL || ''; - - if (sourceRoot) { - // This follows what Chrome does. - if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { - sourceRoot += '/'; - } - // The spec says: - // Line 4: An optional source root, useful for relocating source - // files on a server or removing repeated values in the - // “sources” entry. This value is prepended to the individual - // entries in the “source” field. - sourceURL = sourceRoot + sourceURL; - } - - // Historically, SourceMapConsumer did not take the sourceMapURL as - // a parameter. This mode is still somewhat supported, which is why - // this code block is conditional. However, it's preferable to pass - // the source map URL to SourceMapConsumer, so that this function - // can implement the source URL resolution algorithm as outlined in - // the spec. This block is basically the equivalent of: - // new URL(sourceURL, sourceMapURL).toString() - // ... except it avoids using URL, which wasn't available in the - // older releases of node still supported by this library. - // - // The spec says: - // If the sources are not absolute URLs after prepending of the - // “sourceRoot”, the sources are resolved relative to the - // SourceMap (like resolving script src in a html document). - if (sourceMapURL) { - var parsed = urlParse(sourceMapURL); - if (!parsed) { - throw new Error("sourceMapURL could not be parsed"); - } - if (parsed.path) { - // Strip the last path component, but keep the "/". - var index = parsed.path.lastIndexOf('/'); - if (index >= 0) { - parsed.path = parsed.path.substring(0, index + 1); - } - } - sourceURL = join(urlGenerate(parsed), sourceURL); - } - - return normalize(sourceURL); -} -exports.computeSourceURL = computeSourceURL; -}); - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - -var has = Object.prototype.hasOwnProperty; -var hasNativeMap = typeof Map !== "undefined"; - -/** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ -function ArraySet$2() { - this._array = []; - this._set = hasNativeMap ? new Map() : Object.create(null); -} - -/** - * Static method for creating ArraySet instances from an existing array. - */ -ArraySet$2.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet$2(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; -}; - -/** - * Return how many unique items are in this ArraySet. If duplicates have been - * added, than those do not count towards the size. - * - * @returns Number - */ -ArraySet$2.prototype.size = function ArraySet_size() { - return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; -}; - -/** - * Add the given string to this set. - * - * @param String aStr - */ -ArraySet$2.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var sStr = hasNativeMap ? aStr : util.toSetString(aStr); - var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); - } - if (!isDuplicate) { - if (hasNativeMap) { - this._set.set(aStr, idx); - } else { - this._set[sStr] = idx; - } - } -}; - -/** - * Is the given string a member of this set? - * - * @param String aStr - */ -ArraySet$2.prototype.has = function ArraySet_has(aStr) { - if (hasNativeMap) { - return this._set.has(aStr); - } else { - var sStr = util.toSetString(aStr); - return has.call(this._set, sStr); - } -}; - -/** - * What is the index of the given string in the array? - * - * @param String aStr - */ -ArraySet$2.prototype.indexOf = function ArraySet_indexOf(aStr) { - if (hasNativeMap) { - var idx = this._set.get(aStr); - if (idx >= 0) { - return idx; - } - } else { - var sStr = util.toSetString(aStr); - if (has.call(this._set, sStr)) { - return this._set[sStr]; - } - } - - throw new Error('"' + aStr + '" is not in the set.'); -}; - -/** - * What is the element at the given index? - * - * @param Number aIdx - */ -ArraySet$2.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); -}; - -/** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ -ArraySet$2.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); -}; - -var ArraySet_1 = ArraySet$2; - -var arraySet = { - ArraySet: ArraySet_1 -}; - -/* -*- 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 - */ - - - -/** - * Determine whether mappingB is after mappingA with respect to generated - * position. - */ -function generatedPositionAfter(mappingA, mappingB) { - // Optimized for most common case - var lineA = mappingA.generatedLine; - var lineB = mappingB.generatedLine; - var columnA = mappingA.generatedColumn; - var columnB = mappingB.generatedColumn; - return lineB > lineA || lineB == lineA && columnB >= columnA || - util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; -} - -/** - * A data structure to provide a sorted view of accumulated mappings in a - * performance conscious manner. It trades a neglibable overhead in general - * case for a large speedup in case of mappings being added in order. - */ -function MappingList$1() { - this._array = []; - this._sorted = true; - // Serves as infimum - this._last = {generatedLine: -1, generatedColumn: 0}; -} - -/** - * Iterate through internal items. This method takes the same arguments that - * `Array.prototype.forEach` takes. - * - * NOTE: The order of the mappings is NOT guaranteed. - */ -MappingList$1.prototype.unsortedForEach = - function MappingList_forEach(aCallback, aThisArg) { - this._array.forEach(aCallback, aThisArg); - }; - -/** - * Add the given source mapping. - * - * @param Object aMapping - */ -MappingList$1.prototype.add = function MappingList_add(aMapping) { - if (generatedPositionAfter(this._last, aMapping)) { - this._last = aMapping; - this._array.push(aMapping); - } else { - this._sorted = false; - this._array.push(aMapping); - } -}; - -/** - * Returns the flat, sorted array of mappings. The mappings are sorted by - * generated position. - * - * WARNING: This method returns internal data without copying, for - * performance. The return value must NOT be mutated, and should be treated as - * an immutable borrow. If you want to take ownership, you must make your own - * copy. - */ -MappingList$1.prototype.toArray = function MappingList_toArray() { - if (!this._sorted) { - this._array.sort(util.compareByGeneratedPositionsInflated); - this._sorted = true; - } - return this._array; -}; - -var MappingList_1 = MappingList$1; - -var mappingList = { - MappingList: MappingList_1 -}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - - -var ArraySet$1 = arraySet.ArraySet; -var MappingList = mappingList.MappingList; - -/** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. You may pass an object with the following - * properties: - * - * - file: The filename of the generated source. - * - sourceRoot: A root for all relative URLs in this source map. - */ -function SourceMapGenerator$2(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$1(); - this._names = new ArraySet$1(); - this._mappings = new MappingList(); - this._sourcesContents = null; -} - -SourceMapGenerator$2.prototype._version = 3; - -/** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ -SourceMapGenerator$2.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator$2({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - - if (mapping.source != null) { - newMapping.source = mapping.source; - if (sourceRoot != null) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name != null) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var sourceRelative = sourceFile; - if (sourceRoot !== null) { - sourceRelative = util.relative(sourceRoot, sourceFile); - } - - if (!generator._sources.has(sourceRelative)) { - generator._sources.add(sourceRelative); - } - - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; - -/** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ -SourceMapGenerator$2.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, 'generated'); - var original = util.getArg(aArgs, 'original', null); - var source = util.getArg(aArgs, 'source', null); - var name = util.getArg(aArgs, 'name', null); - - if (!this._skipValidation) { - this._validateMapping(generated, original, source, name); - } - - if (source != null) { - source = String(source); - if (!this._sources.has(source)) { - this._sources.add(source); - } - } - - if (name != null) { - name = String(name); - if (!this._names.has(name)) { - this._names.add(name); - } - } - - this._mappings.add({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - -/** - * Set the source content for a source file. - */ -SourceMapGenerator$2.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot != null) { - source = util.relative(this._sourceRoot, source); - } - - if (aSourceContent != null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = Object.create(null); - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else if (this._sourcesContents) { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - -/** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - * @param aSourceMapPath Optional. The dirname of the path to the source map - * to be applied. If relative, it is relative to the SourceMapConsumer. - * This parameter is needed when the two source maps aren't in the same - * directory, and the source map to be applied contains relative source - * paths. If so, those relative source paths need to be rewritten - * relative to the SourceMapGenerator. - */ -SourceMapGenerator$2.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { - var sourceFile = aSourceFile; - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (aSourceFile == null) { - if (aSourceMapConsumer.file == null) { - throw new Error( - 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + - 'or the source map\'s "file" property. Both were omitted.' - ); - } - sourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "sourceFile" relative if an absolute Url is passed. - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet$1(); - var newNames = new ArraySet$1(); - - // Find mappings for the "sourceFile" - this._mappings.unsortedForEach(function (mapping) { - if (mapping.source === sourceFile && mapping.originalLine != null) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source != null) { - // Copy mapping - mapping.source = original.source; - if (aSourceMapPath != null) { - mapping.source = util.join(aSourceMapPath, mapping.source); - } - if (sourceRoot != null) { - mapping.source = util.relative(sourceRoot, mapping.source); - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name != null) { - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source != null && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name != null && !newNames.has(name)) { - newNames.add(name); - } - - }, this); - this._sources = newSources; - this._names = newNames; - - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aSourceMapPath != null) { - sourceFile = util.join(aSourceMapPath, sourceFile); - } - if (sourceRoot != null) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; - -/** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ -SourceMapGenerator$2.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - // When aOriginal is truthy but has empty values for .line and .column, - // it is most likely a programmer error. In this case we throw a very - // specific error message to try to guide them the right way. - // For example: https://github.com/Polymer/polymer-bundler/pull/519 - if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { - throw new Error( - 'original.line and original.column are not numbers -- you probably meant to omit ' + - 'the original mapping entirely and only map the generated position. If so, pass ' + - 'null for the original mapping instead of an object with empty or null values.' - ); - } - - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - original: aOriginal, - name: aName - })); - } - }; - -/** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ -SourceMapGenerator$2.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var next; - var mapping; - var nameIdx; - var sourceIdx; - - var mappings = this._mappings.toArray(); - for (var i = 0, len = mappings.length; i < len; i++) { - mapping = mappings[i]; - next = ''; - - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - next += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { - continue; - } - next += ','; - } - } - - next += base64Vlq.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - - if (mapping.source != null) { - sourceIdx = this._sources.indexOf(mapping.source); - next += base64Vlq.encode(sourceIdx - previousSource); - previousSource = sourceIdx; - - // lines are stored 0-based in SourceMap spec version 3 - next += base64Vlq.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - - next += base64Vlq.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - - if (mapping.name != null) { - nameIdx = this._names.indexOf(mapping.name); - next += base64Vlq.encode(nameIdx - previousName); - previousName = nameIdx; - } - } - - result += next; - } - - return result; - }; - -SourceMapGenerator$2.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot != null) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) - ? this._sourcesContents[key] - : null; - }, this); - }; - -/** - * Externalize the source map. - */ -SourceMapGenerator$2.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._file != null) { - map.file = this._file; - } - if (this._sourceRoot != null) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - - return map; - }; - -/** - * Render the source map being generated to a string. - */ -SourceMapGenerator$2.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this.toJSON()); - }; - -var SourceMapGenerator_1 = SourceMapGenerator$2; - -var sourceMapGenerator = { - SourceMapGenerator: SourceMapGenerator_1 -}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -var binarySearch = createCommonjsModule(function (module, exports) { -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -exports.GREATEST_LOWER_BOUND = 1; -exports.LEAST_UPPER_BOUND = 2; - -/** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - */ -function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the index of - // the next-closest element. - // - // 3. We did not find the exact element, and there is no next-closest - // element than the one we are searching for, so we return -1. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return mid; - } - else if (cmp > 0) { - // Our needle is greater than aHaystack[mid]. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); - } - - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return aHigh < aHaystack.length ? aHigh : -1; - } else { - return mid; - } - } - else { - // Our needle is less than aHaystack[mid]. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); - } - - // we are in termination case (3) or (2) and return the appropriate thing. - if (aBias == exports.LEAST_UPPER_BOUND) { - return mid; - } else { - return aLow < 0 ? -1 : aLow; - } - } -} - -/** - * This is an implementation of binary search which will always try and return - * the index of the closest element if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or - * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. - */ -exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { - if (aHaystack.length === 0) { - return -1; - } - - var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, - aCompare, aBias || exports.GREATEST_LOWER_BOUND); - if (index < 0) { - return -1; - } - - // We have found either the exact element, or the next-closest element than - // the one we are searching for. However, there may be more than one such - // element. Make sure we always return the smallest of these. - while (index - 1 >= 0) { - if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { - break; - } - --index; - } - - return index; -}; -}); - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -// It turns out that some (most?) JavaScript engines don't self-host -// `Array.prototype.sort`. This makes sense because C++ will likely remain -// faster than JS when doing raw CPU-intensive sorting. However, when using a -// custom comparator function, calling back and forth between the VM's C++ and -// JIT'd JS is rather slow *and* loses JIT type information, resulting in -// worse generated code for the comparator function than would be optimal. In -// fact, when sorting with a comparator, these costs outweigh the benefits of -// sorting in C++. By using our own JS-implemented Quick Sort (below), we get -// a ~3500ms mean speed-up in `bench/bench.html`. - -/** - * Swap the elements indexed by `x` and `y` in the array `ary`. - * - * @param {Array} ary - * The array. - * @param {Number} x - * The index of the first item. - * @param {Number} y - * The index of the second item. - */ -function swap(ary, x, y) { - var temp = ary[x]; - ary[x] = ary[y]; - ary[y] = temp; -} - -/** - * Returns a random integer within the range `low .. high` inclusive. - * - * @param {Number} low - * The lower bound on the range. - * @param {Number} high - * The upper bound on the range. - */ -function randomIntInRange(low, high) { - return Math.round(low + (Math.random() * (high - low))); -} - -/** - * The Quick Sort algorithm. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - * @param {Number} p - * Start index of the array - * @param {Number} r - * End index of the array - */ -function doQuickSort(ary, comparator, p, r) { - // If our lower bound is less than our upper bound, we (1) partition the - // array into two pieces and (2) recurse on each half. If it is not, this is - // the empty array and our base case. - - if (p < r) { - // (1) Partitioning. - // - // The partitioning chooses a pivot between `p` and `r` and moves all - // elements that are less than or equal to the pivot to the before it, and - // all the elements that are greater than it after it. The effect is that - // once partition is done, the pivot is in the exact place it will be when - // the array is put in sorted order, and it will not need to be moved - // again. This runs in O(n) time. - - // Always choose a random pivot so that an input array which is reverse - // sorted does not cause O(n^2) running time. - var pivotIndex = randomIntInRange(p, r); - var i = p - 1; - - swap(ary, pivotIndex, r); - var pivot = ary[r]; - - // Immediately after `j` is incremented in this loop, the following hold - // true: - // - // * Every element in `ary[p .. i]` is less than or equal to the pivot. - // - // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. - for (var j = p; j < r; j++) { - if (comparator(ary[j], pivot) <= 0) { - i += 1; - swap(ary, i, j); - } - } - - swap(ary, i + 1, j); - var q = i + 1; - - // (2) Recurse on each half. - - doQuickSort(ary, comparator, p, q - 1); - doQuickSort(ary, comparator, q + 1, r); - } -} - -/** - * Sort the given array in-place with the given comparator function. - * - * @param {Array} ary - * An array to sort. - * @param {function} comparator - * Function to use to compare two items. - */ -var quickSort_1 = function (ary, comparator) { - doQuickSort(ary, comparator, 0, ary.length - 1); -}; - -var quickSort$1 = { - quickSort: quickSort_1 -}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - - - -var ArraySet = arraySet.ArraySet; - -var quickSort = quickSort$1.quickSort; - -function SourceMapConsumer$1(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - - return sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) - : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); -} - -SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); -}; - -/** - * The version of the source mapping spec that we are consuming. - */ -SourceMapConsumer$1.prototype._version = 3; - -// `__generatedMappings` and `__originalMappings` are arrays that hold the -// parsed mapping coordinates from the source map's "mappings" attribute. They -// are lazily instantiated, accessed via the `_generatedMappings` and -// `_originalMappings` getters respectively, and we only parse the mappings -// and create these arrays once queried for a source location. We jump through -// these hoops because there can be many thousands of mappings, and parsing -// them is expensive, so we only want to do it if we must. -// -// Each object in the arrays is of the form: -// -// { -// generatedLine: The line number in the generated code, -// generatedColumn: The column number in the generated code, -// source: The path to the original source file that generated this -// chunk of code, -// originalLine: The line number in the original source that -// corresponds to this chunk of generated code, -// originalColumn: The column number in the original source that -// corresponds to this chunk of generated code, -// name: The name of the original symbol which generated this chunk of -// code. -// } -// -// All properties except for `generatedLine` and `generatedColumn` can be -// `null`. -// -// `_generatedMappings` is ordered by the generated positions. -// -// `_originalMappings` is ordered by the original positions. - -SourceMapConsumer$1.prototype.__generatedMappings = null; -Object.defineProperty(SourceMapConsumer$1.prototype, '_generatedMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__generatedMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } -}); - -SourceMapConsumer$1.prototype.__originalMappings = null; -Object.defineProperty(SourceMapConsumer$1.prototype, '_originalMappings', { - configurable: true, - enumerable: true, - get: function () { - if (!this.__originalMappings) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } -}); - -SourceMapConsumer$1.prototype._charIsMappingSeparator = - function SourceMapConsumer_charIsMappingSeparator(aStr, index) { - var c = aStr.charAt(index); - return c === ";" || c === ","; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -SourceMapConsumer$1.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - }; - -SourceMapConsumer$1.GENERATED_ORDER = 1; -SourceMapConsumer$1.ORIGINAL_ORDER = 2; - -SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1; -SourceMapConsumer$1.LEAST_UPPER_BOUND = 2; - -/** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ -SourceMapConsumer$1.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer$1.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer$1.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source === null ? null : this._sources.at(mapping.source); - source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - }; - -/** - * Returns all generated line and column information for the original source, - * line, and column provided. If no column is provided, returns all mappings - * corresponding to a either the line we are searching for or the next - * closest line that has any mappings. Otherwise, returns all mappings - * corresponding to the given line and either the column we are searching for - * or the next closest column that has any offsets. - * - * The only argument is an object with the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number is 1-based. - * - column: Optional. the column number in the original source. - * The column number is 0-based. - * - * and an array of objects is returned, each with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ -SourceMapConsumer$1.prototype.allGeneratedPositionsFor = - function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { - var line = util.getArg(aArgs, 'line'); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: line, - originalColumn: util.getArg(aArgs, 'column', 0) - }; - - needle.source = this._findSourceIndex(needle.source); - if (needle.source < 0) { - return []; - } - - var mappings = []; - - var index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - var originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } else { - var originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - mappings.push({ - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - }; - -var SourceMapConsumer_1 = SourceMapConsumer$1; - -/** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The first parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: Optional. The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ -function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - - var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util.getArg(sourceMap, 'names', []); - var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); - var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - if (sourceRoot) { - sourceRoot = util.normalize(sourceRoot); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function (source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names.map(String), true); - this._sources = ArraySet.fromArray(sources, true); - - this._absoluteSources = this._sources.toArray().map(function (s) { - return util.computeSourceURL(sourceRoot, s, aSourceMapURL); - }); - - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this._sourceMapURL = aSourceMapURL; - this.file = file; -} - -BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); -BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1; - -/** - * Utility function to find the index of a source. Returns -1 if not - * found. - */ -BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util.relative(this.sourceRoot, relativeSource); - } - - if (this._sources.has(relativeSource)) { - return this._sources.indexOf(relativeSource); - } - - // Maybe aSource is an absolute URL as returned by |sources|. In - // this case we can't simply undo the transform. - var i; - for (i = 0; i < this._absoluteSources.length; ++i) { - if (this._absoluteSources[i] == aSource) { - return i; - } - } - - return -1; -}; - -/** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @param String aSourceMapURL - * The URL at which the source map can be found (optional) - * @returns BasicSourceMapConsumer - */ -BasicSourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { - var smc = Object.create(BasicSourceMapConsumer.prototype); - - var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - smc._sourceMapURL = aSourceMapURL; - smc._absoluteSources = smc._sources.toArray().map(function (s) { - return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); - }); - - // Because we are modifying the entries (by converting string sources and - // names to indices into the sources and names ArraySets), we have to make - // a copy of the entry or else bad things happen. Shared mutable state - // strikes again! See github issue #191. - - var generatedMappings = aSourceMap._mappings.toArray().slice(); - var destGeneratedMappings = smc.__generatedMappings = []; - var destOriginalMappings = smc.__originalMappings = []; - - for (var i = 0, length = generatedMappings.length; i < length; i++) { - var srcMapping = generatedMappings[i]; - var destMapping = new Mapping; - destMapping.generatedLine = srcMapping.generatedLine; - destMapping.generatedColumn = srcMapping.generatedColumn; - - if (srcMapping.source) { - destMapping.source = sources.indexOf(srcMapping.source); - destMapping.originalLine = srcMapping.originalLine; - destMapping.originalColumn = srcMapping.originalColumn; - - if (srcMapping.name) { - destMapping.name = names.indexOf(srcMapping.name); - } - - destOriginalMappings.push(destMapping); - } - - destGeneratedMappings.push(destMapping); - } - - quickSort(smc.__originalMappings, util.compareByOriginalPositions); - - return smc; - }; - -/** - * The version of the source mapping spec that we are consuming. - */ -BasicSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { - get: function () { - return this._absoluteSources.slice(); - } -}); - -/** - * Provide the JIT with a nice shape / hidden class. - */ -function Mapping() { - this.generatedLine = 0; - this.generatedColumn = 0; - this.source = null; - this.originalLine = null; - this.originalColumn = null; - this.name = null; -} - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -BasicSourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var length = aStr.length; - var index = 0; - var cachedSegments = {}; - var temp = {}; - var originalMappings = []; - var generatedMappings = []; - var mapping, str, segment, end, value; - - while (index < length) { - if (aStr.charAt(index) === ';') { - generatedLine++; - index++; - previousGeneratedColumn = 0; - } - else if (aStr.charAt(index) === ',') { - index++; - } - else { - mapping = new Mapping(); - mapping.generatedLine = generatedLine; - - // Because each offset is encoded relative to the previous one, - // many segments often have the same encoding. We can exploit this - // fact by caching the parsed variable length fields of each segment, - // allowing us to avoid a second parse if we encounter the same - // segment again. - for (end = index; end < length; end++) { - if (this._charIsMappingSeparator(aStr, end)) { - break; - } - } - str = aStr.slice(index, end); - - segment = cachedSegments[str]; - if (segment) { - index += str.length; - } else { - segment = []; - while (index < end) { - base64Vlq.decode(aStr, index, temp); - value = temp.value; - index = temp.rest; - segment.push(value); - } - - if (segment.length === 2) { - throw new Error('Found a source, but no line and column'); - } - - if (segment.length === 3) { - throw new Error('Found a source and line, but no column'); - } - - cachedSegments[str] = segment; - } - - // Generated column. - mapping.generatedColumn = previousGeneratedColumn + segment[0]; - previousGeneratedColumn = mapping.generatedColumn; - - if (segment.length > 1) { - // Original source. - mapping.source = previousSource + segment[1]; - previousSource += segment[1]; - - // Original line. - mapping.originalLine = previousOriginalLine + segment[2]; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - - // Original column. - mapping.originalColumn = previousOriginalColumn + segment[3]; - previousOriginalColumn = mapping.originalColumn; - - if (segment.length > 4) { - // Original name. - mapping.name = previousName + segment[4]; - previousName += segment[4]; - } - } - - generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - originalMappings.push(mapping); - } - } - } - - quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = generatedMappings; - - quickSort(originalMappings, util.compareByOriginalPositions); - this.__originalMappings = originalMappings; - }; - -/** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ -BasicSourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - }; - -/** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ -BasicSourceMapConsumer.prototype.computeColumnSpans = - function SourceMapConsumer_computeColumnSpans() { - for (var index = 0; index < this._generatedMappings.length; ++index) { - var mapping = this._generatedMappings[index]; - - // Mappings do not contain a field for the last generated columnt. We - // can come up with an optimistic estimate, however, by assuming that - // mappings are contiguous (i.e. given two consecutive mappings, the - // first mapping ends where the second one starts). - if (index + 1 < this._generatedMappings.length) { - var nextMapping = this._generatedMappings[index + 1]; - - if (mapping.generatedLine === nextMapping.generatedLine) { - mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; - continue; - } - } - - // The last mapping for each line spans the entire line. - mapping.lastGeneratedColumn = Infinity; - } - }; - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ -BasicSourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositionsDeflated, - util.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._generatedMappings[index]; - - if (mapping.generatedLine === needle.generatedLine) { - var source = util.getArg(mapping, 'source', null); - if (source !== null) { - source = this._sources.at(source); - source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); - } - var name = util.getArg(mapping, 'name', null); - if (name !== null) { - name = this._names.at(name); - } - return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: name - }; - } - } - - return { - source: null, - line: null, - column: null, - name: null - }; - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -BasicSourceMapConsumer.prototype.hasContentsOfAllSources = - function BasicSourceMapConsumer_hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function (sc) { return sc == null; }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -BasicSourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - var index = this._findSourceIndex(aSource); - if (index >= 0) { - return this.sourcesContent[index]; - } - - var relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util.relative(this.sourceRoot, relativeSource); - } - - var url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + relativeSource)) { - return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + relativeSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ -BasicSourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var source = util.getArg(aArgs, 'source'); - source = this._findSourceIndex(source); - if (source < 0) { - return { - line: null, - column: null, - lastColumn: null - }; - } - - var needle = { - source: source, - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; - - var index = this._findMapping( - needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - util.getArg(aArgs, 'bias', SourceMapConsumer$1.GREATEST_LOWER_BOUND) - ); - - if (index >= 0) { - var mapping = this._originalMappings[index]; - - if (mapping.source === needle.source) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null), - lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - }; - -var BasicSourceMapConsumer_1 = BasicSourceMapConsumer; - -/** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The first parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ -function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - - var version = util.getArg(sourceMap, 'version'); - var sections = util.getArg(sourceMap, 'sections'); - - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - this._sources = new ArraySet(); - this._names = new ArraySet(); - - var lastOffset = { - line: -1, - column: 0 - }; - this._sections = sections.map(function (s) { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error('Support for url field in sections not implemented.'); - } - var offset = util.getArg(s, 'offset'); - var offsetLine = util.getArg(offset, 'line'); - var offsetColumn = util.getArg(offset, 'column'); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error('Section offsets must be ordered and non-overlapping.'); - } - lastOffset = offset; - - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer: new SourceMapConsumer$1(util.getArg(s, 'map'), aSourceMapURL) - } - }); -} - -IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype); -IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1; - -/** - * The version of the source mapping spec that we are consuming. - */ -IndexedSourceMapConsumer.prototype._version = 3; - -/** - * The list of original sources. - */ -Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { - get: function () { - var sources = []; - for (var i = 0; i < this._sections.length; i++) { - for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; - } -}); - -/** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ -IndexedSourceMapConsumer.prototype.originalPositionFor = - function IndexedSourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - var sectionIndex = binarySearch.search(needle, this._sections, - function(needle, section) { - var cmp = needle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (needle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - var section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - }; - -/** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ -IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = - function IndexedSourceMapConsumer_hasContentsOfAllSources() { - return this._sections.every(function (s) { - return s.consumer.hasContentsOfAllSources(); - }); - }; - -/** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ -IndexedSourceMapConsumer.prototype.sourceContentFor = - function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - var content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - else { - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - }; - -/** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ -IndexedSourceMapConsumer.prototype.generatedPositionFor = - function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { - continue; - } - var generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - var ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - - return { - line: null, - column: null - }; - }; - -/** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ -IndexedSourceMapConsumer.prototype._parseMappings = - function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { - this.__generatedMappings = []; - this.__originalMappings = []; - for (var i = 0; i < this._sections.length; i++) { - var section = this._sections[i]; - var sectionMappings = section.consumer._generatedMappings; - for (var j = 0; j < sectionMappings.length; j++) { - var mapping = sectionMappings[j]; - - var source = section.consumer._sources.at(mapping.source); - source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); - this._sources.add(source); - source = this._sources.indexOf(source); - - var name = null; - if (mapping.name) { - name = section.consumer._names.at(mapping.name); - this._names.add(name); - name = this._names.indexOf(name); - } - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - var adjustedMapping = { - source: source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: name - }; - - this.__generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === 'number') { - this.__originalMappings.push(adjustedMapping); - } - } - } - - quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); - quickSort(this.__originalMappings, util.compareByOriginalPositions); - }; - -var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer; - -var sourceMapConsumer = { - SourceMapConsumer: SourceMapConsumer_1, - BasicSourceMapConsumer: BasicSourceMapConsumer_1, - IndexedSourceMapConsumer: IndexedSourceMapConsumer_1 -}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator; - - -// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other -// operating systems these days (capturing the result). -var REGEX_NEWLINE = /(\r?\n)/; - -// Newline character code for charCodeAt() comparisons -var NEWLINE_CODE = 10; - -// Private symbol for identifying `SourceNode`s when multiple versions of -// the source-map library are loaded. This MUST NOT CHANGE across -// versions! -var isSourceNode = "$$$isSourceNode$$$"; - -/** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ -function SourceNode$1(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine == null ? null : aLine; - this.column = aColumn == null ? null : aColumn; - this.source = aSource == null ? null : aSource; - this.name = aName == null ? null : aName; - this[isSourceNode] = true; - if (aChunks != null) this.add(aChunks); -} - -/** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - * @param aRelativePath Optional. The path that relative sources in the - * SourceMapConsumer should be relative to. - */ -SourceNode$1.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode$1(); - - // All even indices of this array are one line of the generated code, - // while all odd indices are the newlines between two adjacent lines - // (since `REGEX_NEWLINE` captures its match). - // Processed fragments are accessed by calling `shiftNextLine`. - var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); - var remainingLinesIndex = 0; - var shiftNextLine = function() { - var lineContents = getNextLine(); - // The last line of a file might not have a newline. - var newLine = getNextLine() || ""; - return lineContents + newLine; - - function getNextLine() { - return remainingLinesIndex < remainingLines.length ? - remainingLines[remainingLinesIndex++] : undefined; - } - }; - - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping !== null) { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - // Associate first line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - lastGeneratedLine++; - lastGeneratedColumn = 0; - // The remaining code is added without mapping - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[remainingLinesIndex] || ''; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - // No more remaining code, continue - lastMapping = mapping; - return; - } - } - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(shiftNextLine()); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[remainingLinesIndex] || ''; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - if (remainingLinesIndex < remainingLines.length) { - if (lastMapping) { - // Associate the remaining code in the current line with "lastMapping" - addMappingWithCode(lastMapping, shiftNextLine()); - } - // and add the remaining lines without any mapping - node.add(remainingLines.splice(remainingLinesIndex).join("")); - } - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content != null) { - if (aRelativePath != null) { - sourceFile = util.join(aRelativePath, sourceFile); - } - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - var source = aRelativePath - ? util.join(aRelativePath, mapping.source) - : mapping.source; - node.add(new SourceNode$1(mapping.originalLine, - mapping.originalColumn, - source, - code, - mapping.name)); - } - } - }; - -/** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode$1.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ -SourceNode$1.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk[isSourceNode] || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; -}; - -/** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ -SourceNode$1.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk[isSourceNode]) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); - } - } - } -}; - -/** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ -SourceNode$1.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len-1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; -}; - -/** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ -SourceNode$1.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild[isSourceNode]) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; -}; - -/** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ -SourceNode$1.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; - -/** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ -SourceNode$1.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i][isSourceNode]) { - this.children[i].walkSourceContents(aFn); - } - } - - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; - -/** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ -SourceNode$1.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; -}; - -/** - * Returns the string representation of this source node along with a source - * map. - */ -SourceNode$1.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator$1(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - for (var idx = 0, length = chunk.length; idx < length; idx++) { - if (chunk.charCodeAt(idx) === NEWLINE_CODE) { - generated.line++; - generated.column = 0; - // Mappings end at eol - if (idx + 1 === length) { - lastOriginalSource = null; - sourceMappingActive = false; - } else if (sourceMappingActive) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - } else { - generated.column++; - } - } - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - - return { code: generated.code, map: map }; -}; - -var SourceNode_1 = SourceNode$1; - -var sourceNode = { - SourceNode: SourceNode_1 -}; - -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var SourceMapGenerator = sourceMapGenerator.SourceMapGenerator; -var SourceMapConsumer = sourceMapConsumer.SourceMapConsumer; -var SourceNode = sourceNode.SourceNode; - -var sourceMap = { - SourceMapGenerator: SourceMapGenerator, - SourceMapConsumer: SourceMapConsumer, - SourceNode: SourceNode -}; - -let offset; -try { - new Function('throw new Error(1)')(); -} -catch (e) { - // in Node 12, stack traces account for the function wrapper. - // in Node 13 and later, the function wrapper adds two lines, - // which must be subtracted to generate a valid mapping - const match = /:(\d+):\d+\)$/.exec(e.stack.split('\n')[1]); - offset = match ? +match[1] - 1 : 0; -} -function ssrRewriteStacktrace(stack, moduleGraph) { - return stack - .split('\n') - .map((line) => { - return line.replace(/^ {4}at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?)\)?/, (input, varName, url, line, column) => { - var _a; - if (!url) - return input; - const mod = moduleGraph.urlToModuleMap.get(url); - const rawSourceMap = (_a = mod === null || mod === void 0 ? void 0 : mod.ssrTransformResult) === null || _a === void 0 ? void 0 : _a.map; - if (!rawSourceMap) { - return input; - } - const consumer = new SourceMapConsumer(rawSourceMap); - const pos = consumer.originalPositionFor({ - line: Number(line) - offset, - column: Number(column), - bias: SourceMapConsumer.LEAST_UPPER_BOUND - }); - if (!pos.source) { - return input; - } - const source = `${pos.source}:${pos.line || 0}:${pos.column || 0}`; - if (!varName || varName === 'eval') { - return ` at ${source}`; - } - else { - return ` at ${varName} (${source})`; - } - }); - }) - .join('\n'); -} - -const pendingModules = new Map(); -async function ssrLoadModule(url, server, context = { global }, urlStack = []) { - url = unwrapId$1(url); - if (urlStack.includes(url)) { - server.config.logger.warn(`Circular dependency: ${urlStack.join(' -> ')} -> ${url}`); - return {}; - } - // when we instantiate multiple dependency modules in parallel, they may - // point to shared modules. We need to avoid duplicate instantiation attempts - // by register every module as pending synchronously so that all subsequent - // request to that module are simply waiting on the same promise. - const pending = pendingModules.get(url); - if (pending) { - return pending; - } - const modulePromise = instantiateModule(url, server, context, urlStack); - pendingModules.set(url, modulePromise); - modulePromise.catch(() => { }).then(() => pendingModules.delete(url)); - return modulePromise; -} -async function instantiateModule(url, server, context = { global }, urlStack = []) { - const { moduleGraph } = server; - const mod = await moduleGraph.ensureEntryFromUrl(url); - if (mod.ssrModule) { - return mod.ssrModule; - } - const result = mod.ssrTransformResult || - (await transformRequest(url, server, { ssr: true })); - if (!result) { - // TODO more info? is this even necessary? - throw new Error(`failed to load module for ssr: ${url}`); - } - const ssrModule = { - [Symbol.toStringTag]: 'Module' - }; - Object.defineProperty(ssrModule, '__esModule', { value: true }); - const isExternal = (dep) => dep[0] !== '.' && dep[0] !== '/'; - await Promise.all(result.deps.map((dep) => { - if (!isExternal(dep)) { - return ssrLoadModule(dep, server, context, urlStack.concat(url)); - } - })); - const ssrImportMeta = { url }; - const ssrImport = (dep) => { - var _a; - if (isExternal(dep)) { - return nodeRequire(dep, mod.file, server.config.root); - } - else { - return (_a = moduleGraph.urlToModuleMap.get(unwrapId$1(dep))) === null || _a === void 0 ? void 0 : _a.ssrModule; - } - }; - const ssrDynamicImport = (dep) => { - if (isExternal(dep)) { - return Promise.resolve(nodeRequire(dep, mod.file, server.config.root)); - } - else { - return ssrLoadModule(dep, server, context, urlStack.concat(url)); - } - }; - function ssrExportAll(sourceModule) { - for (const key in sourceModule) { - if (key !== 'default') { - Object.defineProperty(ssrModule, key, { - enumerable: true, - configurable: true, - get() { - return sourceModule[key]; - } - }); - } - } - } - try { - new Function(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, result.code + `\n//# sourceURL=${mod.url}`)(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll); - } - catch (e) { - e.stack = ssrRewriteStacktrace(e.stack, moduleGraph); - server.config.logger.error(`Error when evaluating SSR module ${url}:\n${e.stack}`, { - timestamp: true, - clear: server.config.clearScreen - }); - throw e; - } - mod.ssrModule = Object.freeze(ssrModule); - return ssrModule; -} -function nodeRequire(id, importer, root) { - const mod = require(resolve(id, importer, root)); - const defaultExport = mod.__esModule ? mod.default : mod; - // rollup-style default import interop for cjs - return new Proxy(mod, { - get(mod, prop) { - if (prop === 'default') - return defaultExport; - return mod[prop]; - } - }); -} -const resolveCache = new Map(); -function resolve(id, importer, root) { - const key = id + importer + root; - const cached = resolveCache.get(key); - if (cached) { - return cached; - } - const resolveDir = importer && fs__default.existsSync(cleanUrl(importer)) - ? path__default.dirname(importer) - : root; - const resolved = resolveFrom$2(id, resolveDir, true); - resolveCache.set(key, resolved); - return resolved; -} - -/** - * The amount to wait for requests to register newly found dependencies before triggering - * a re-bundle + page reload - */ -const debounceMs = 100; -function createMissingImporterRegisterFn(server) { - const { logger } = server.config; - let knownOptimized = server._optimizeDepsMetadata.optimized; - let currentMissing = {}; - let handle; - let pendingResolve = null; - async function rerun() { - const newDeps = currentMissing; - currentMissing = {}; - logger.info(source.yellow(`new dependencies found: ${Object.keys(newDeps).join(', ')}, updating...`), { - timestamp: true - }); - for (const id in knownOptimized) { - newDeps[id] = knownOptimized[id].src; - } - try { - // Nullify previous metadata so that the resolver won't - // resolve to optimized files during the optimizer re-run - server._isRunningOptimizer = true; - server._optimizeDepsMetadata = null; - const newData = (server._optimizeDepsMetadata = await optimizeDeps(server.config, true, false, newDeps)); - knownOptimized = newData.optimized; - // update ssr externals - server._ssrExternals = resolveSSRExternal(server.config, Object.keys(knownOptimized)); - logger.info(source.greenBright(`✨ dependencies updated, reloading page...`), { timestamp: true }); - } - catch (e) { - logger.error(source.red(`error while updating dependencies:\n${e.stack}`), { timestamp: true }); - } - finally { - server._isRunningOptimizer = false; - pendingResolve && pendingResolve(); - server._pendingReload = pendingResolve = null; - } - // Cached transform results have stale imports (resolved to - // old locations) so they need to be invalidated before the page is - // reloaded. - server.moduleGraph.invalidateAll(); - server.ws.send({ - type: 'full-reload', - path: '*' - }); - } - return function registerMissingImport(id, resolved) { - if (!knownOptimized[id]) { - currentMissing[id] = resolved; - if (handle) - clearTimeout(handle); - handle = setTimeout(rerun, debounceMs); - server._pendingReload = new Promise((r) => { - pendingResolve = r; - }); - } - }; -} - -async function createServer(inlineConfig = {}) { - const config = await resolveConfig(inlineConfig, 'serve', 'development'); - const root = config.root; - const serverConfig = config.server || {}; - const middlewareMode = !!serverConfig.middlewareMode; - const middlewares = connect(); - const httpServer = middlewareMode - ? null - : await resolveHttpServer(serverConfig, middlewares); - const ws = createWebSocketServer(httpServer, config); - const { ignored = [], ...watchOptions } = serverConfig.watch || {}; - const watcher = chokidar.watch(path__default.resolve(root), { - ignored: ['**/node_modules/**', '**/.git/**', ...ignored], - ignoreInitial: true, - ignorePermissionErrors: true, - disableGlobbing: true, - ...watchOptions - }); - const plugins = config.plugins; - const container = await createPluginContainer(config, watcher); - const moduleGraph = new ModuleGraph(container); - const closeHttpServer = createServerCloseFn(httpServer); - let exitProcess; - const server = { - config: config, - middlewares, - get app() { - config.logger.warn(`ViteDevServer.app is deprecated. Use ViteDevServer.middlewares instead.`); - return middlewares; - }, - httpServer, - watcher, - pluginContainer: container, - ws, - moduleGraph, - transformWithEsbuild, - transformRequest(url, options) { - return transformRequest(url, server, options); - }, - transformIndexHtml: null, - ssrLoadModule(url) { - if (!server._ssrExternals) { - server._ssrExternals = resolveSSRExternal(config, server._optimizeDepsMetadata - ? Object.keys(server._optimizeDepsMetadata.optimized) - : []); - } - return ssrLoadModule(url, server); - }, - ssrFixStacktrace(e) { - if (e.stack) { - e.stack = ssrRewriteStacktrace(e.stack, moduleGraph); - } - }, - listen(port, isRestart) { - return startServer(server, port, isRestart); - }, - async close() { - process.off('SIGTERM', exitProcess); - if (!process.stdin.isTTY) { - process.stdin.off('end', exitProcess); - } - await Promise.all([ - watcher.close(), - ws.close(), - container.close(), - closeHttpServer() - ]); - }, - _optimizeDepsMetadata: null, - _ssrExternals: null, - _globImporters: {}, - _isRunningOptimizer: false, - _registerMissingImport: null, - _pendingReload: null - }; - server.transformIndexHtml = createDevHtmlTransformFn(server); - exitProcess = async () => { - try { - await server.close(); - } - finally { - process.exit(0); - } - }; - process.once('SIGTERM', exitProcess); - if (!process.stdin.isTTY) { - process.stdin.on('end', exitProcess); - } - watcher.on('change', async (file) => { - file = normalizePath$2(file); - // invalidate module graph cache on file change - moduleGraph.onFileChange(file); - if (serverConfig.hmr !== false) { - try { - await handleHMRUpdate(file, server); - } - catch (err) { - ws.send({ - type: 'error', - err: prepareError(err) - }); - } - } - }); - watcher.on('add', (file) => { - handleFileAddUnlink(normalizePath$2(file), server); - }); - watcher.on('unlink', (file) => { - handleFileAddUnlink(normalizePath$2(file), server, true); - }); - // apply server configuration hooks from plugins - const postHooks = []; - for (const plugin of plugins) { - if (plugin.configureServer) { - postHooks.push(await plugin.configureServer(server)); - } - } - // Internal middlewares ------------------------------------------------------ - // request timer - if (process.env.DEBUG) { - middlewares.use(timeMiddleware(root)); - } - // cors (enabled by default) - const { cors } = serverConfig; - if (cors !== false) { - middlewares.use(lib$1(typeof cors === 'boolean' ? {} : cors)); - } - // proxy - const { proxy } = serverConfig; - if (proxy) { - middlewares.use(proxyMiddleware(httpServer, config)); - } - // base - if (config.base !== '/') { - middlewares.use(baseMiddleware(server)); - } - // open in editor support - middlewares.use('/__open-in-editor', launchEditorMiddleware()); - // hmr reconnect ping - middlewares.use('/__vite_ping', (_, res) => res.end('pong')); - //decode request url - middlewares.use(decodeURIMiddleware()); - // serve static files under /public - // this applies before the transform middleware so that these files are served - // as-is without transforms. - middlewares.use(servePublicMiddleware(config.publicDir)); - // main transform middleware - middlewares.use(transformMiddleware(server)); - // serve static files - middlewares.use(serveRawFsMiddleware()); - middlewares.use(serveStaticMiddleware(root, config)); - // spa fallback - if (!middlewareMode) { - middlewares.use(lib({ - logger: createDebugger('vite:spa-fallback'), - // support /dir/ without explicit index.html - rewrites: [ - { - from: /\/$/, - to({ parsedUrl }) { - const rewritten = parsedUrl.pathname + 'index.html'; - if (fs__default.existsSync(path__default.join(root, rewritten))) { - return rewritten; - } - else { - return `/index.html`; - } - } - } - ] - })); - } - // run post config hooks - // This is applied before the html middleware so that user middleware can - // serve custom content instead of index.html. - postHooks.forEach((fn) => fn && fn()); - if (!middlewareMode) { - // transform index.html - middlewares.use(indexHtmlMiddleware(server)); - // handle 404s - middlewares.use((_, res) => { - res.statusCode = 404; - res.end(); - }); - } - // error handler - middlewares.use(errorMiddleware(server, middlewareMode)); - const runOptimize = async () => { - if (config.optimizeCacheDir) { - server._isRunningOptimizer = true; - try { - server._optimizeDepsMetadata = await optimizeDeps(config); - } - finally { - server._isRunningOptimizer = false; - } - server._registerMissingImport = createMissingImporterRegisterFn(server); - } - }; - if (!middlewareMode && httpServer) { - // overwrite listen to run optimizer before server start - const listen = httpServer.listen.bind(httpServer); - httpServer.listen = (async (port, ...args) => { - try { - await container.buildStart({}); - await runOptimize(); - } - catch (e) { - httpServer.emit('error', e); - return; - } - return listen(port, ...args); - }); - httpServer.once('listening', () => { - // update actual port since this may be different from initial value - serverConfig.port = httpServer.address().port; - }); - } - else { - await runOptimize(); - } - return server; -} -async function startServer(server, inlinePort, isRestart = false) { - const httpServer = server.httpServer; - if (!httpServer) { - throw new Error('Cannot call server.listen in middleware mode.'); - } - const options = server.config.server || {}; - let port = inlinePort || options.port || 3000; - let hostname = options.host || 'localhost'; - if (hostname === '0.0.0.0') - hostname = 'localhost'; - const protocol = options.https ? 'https' : 'http'; - const info = server.config.logger.info; - const base = server.config.base; - return new Promise((resolve, reject) => { - const onError = (e) => { - if (e.code === 'EADDRINUSE') { - if (options.strictPort) { - httpServer.removeListener('error', onError); - reject(new Error(`Port ${port} is already in use`)); - } - else { - info(`Port ${port} is in use, trying another one...`); - httpServer.listen(++port); - } - } - else { - httpServer.removeListener('error', onError); - reject(e); - } - }; - httpServer.on('error', onError); - httpServer.listen(port, options.host, () => { - httpServer.removeListener('error', onError); - info(source.cyan(`\n vite v${require('vite/package.json').version}`) + - source.green(` dev server running at:\n`), { - clear: !server.config.logger.hasWarned - }); - const interfaces = os__default.networkInterfaces(); - Object.keys(interfaces).forEach((key) => (interfaces[key] || []) - .filter((details) => details.family === 'IPv4') - .map((detail) => { - return { - type: detail.address.includes('127.0.0.1') - ? 'Local: ' - : 'Network: ', - host: detail.address.replace('127.0.0.1', hostname) - }; - }) - .forEach(({ type, host }) => { - const url = `${protocol}://${host}:${source.bold(port)}${base}`; - info(` > ${type} ${source.cyan(url)}`); - })); - // @ts-ignore - if (global.__vite_start_time) { - info(source.cyan( - // @ts-ignore - `\n ready in ${Date.now() - global.__vite_start_time}ms.\n`)); - } - // @ts-ignore - const profileSession = global.__vite_profile_session; - if (profileSession) { - profileSession.post('Profiler.stop', (err, { profile }) => { - // Write profile to disk, upload, etc. - if (!err) { - const outPath = path__default.resolve('./vite-profile.cpuprofile'); - fs__default.writeFileSync(outPath, JSON.stringify(profile)); - info(source.yellow(` CPU profile written to ${source.white.dim(outPath)}\n`)); - } - else { - throw err; - } - }); - } - if (options.open && !isRestart) { - const path = typeof options.open === 'string' ? options.open : base; - openBrowser(`${protocol}://${hostname}:${port}${path}`, true, server.config.logger); - } - resolve(server); - }); - }); -} -function createServerCloseFn(server) { - if (!server) { - return () => { }; - } - let hasListened = false; - const openSockets = new Set(); - server.on('connection', (socket) => { - openSockets.add(socket); - socket.on('close', () => { - openSockets.delete(socket); - }); - }); - server.once('listening', () => { - hasListened = true; - }); - return () => new Promise((resolve, reject) => { - openSockets.forEach((s) => s.destroy()); - if (hasListened) { - server.close((err) => { - if (err) { - reject(err); - } - else { - resolve(); - } - }); - } - else { - resolve(); - } - }); -} - -var index = { - __proto__: null, - createServer: createServer -}; - -exports.build = build; -exports.build$1 = build$1; -exports.commonjsGlobal = commonjsGlobal; -exports.connect = connect; -exports.createCommonjsModule = createCommonjsModule; -exports.createLogger = createLogger; -exports.createServer = createServer; -exports.defineConfig = defineConfig; -exports.getAugmentedNamespace = getAugmentedNamespace; -exports.getDefaultExportFromCjs = getDefaultExportFromCjs; -exports.index = index$1; -exports.index$1 = index; -exports.lib = lib$1; -exports.loadConfigFromFile = loadConfigFromFile; -exports.loadEnv = loadEnv; -exports.mergeConfig = mergeConfig; -exports.normalizePath = normalizePath$2; -exports.openBrowser = openBrowser; -exports.optimizeDeps = optimizeDeps; -exports.proxyMiddleware = proxyMiddleware; -exports.resolveConfig = resolveConfig; -exports.resolveHttpServer = resolveHttpServer; -exports.resolvePackageData = resolvePackageData; -exports.resolvePackageEntry = resolvePackageEntry; -exports.safeBuffer = safeBuffer; -exports.send = send$1; -exports.sirv = sirv; -exports.sortUserPlugins = sortUserPlugins; -exports.source = source; -exports.sourceMap = sourceMap; -exports.vary_1 = vary_1; diff --git a/node_modules/vite/dist/node/chunks/dep-685e7ba2.js b/node_modules/vite/dist/node/chunks/dep-685e7ba2.js deleted file mode 100644 index 2a4f4fb..0000000 --- a/node_modules/vite/dist/node/chunks/dep-685e7ba2.js +++ /dev/null @@ -1,526 +0,0 @@ -'use strict'; - -var openParentheses = "(".charCodeAt(0); -var closeParentheses = ")".charCodeAt(0); -var singleQuote = "'".charCodeAt(0); -var doubleQuote = '"'.charCodeAt(0); -var backslash = "\\".charCodeAt(0); -var slash = "/".charCodeAt(0); -var comma = ",".charCodeAt(0); -var colon = ":".charCodeAt(0); -var star = "*".charCodeAt(0); -var uLower = "u".charCodeAt(0); -var uUpper = "U".charCodeAt(0); -var plus$1 = "+".charCodeAt(0); -var isUnicodeRange = /^[a-f0-9?-]+$/i; - -var parse = function(input) { - var tokens = []; - var value = input; - - var next, - quote, - prev, - token, - escape, - escapePos, - whitespacePos, - parenthesesOpenPos; - var pos = 0; - var code = value.charCodeAt(pos); - var max = value.length; - var stack = [{ nodes: tokens }]; - var balanced = 0; - var parent; - - var name = ""; - var before = ""; - var after = ""; - - while (pos < max) { - // Whitespaces - if (code <= 32) { - next = pos; - do { - next += 1; - code = value.charCodeAt(next); - } while (code <= 32); - token = value.slice(pos, next); - - prev = tokens[tokens.length - 1]; - if (code === closeParentheses && balanced) { - after = token; - } else if (prev && prev.type === "div") { - prev.after = token; - } else if ( - code === comma || - code === colon || - (code === slash && - value.charCodeAt(next + 1) !== star && - (!parent || - (parent && parent.type === "function" && parent.value !== "calc"))) - ) { - before = token; - } else { - tokens.push({ - type: "space", - sourceIndex: pos, - value: token - }); - } - - pos = next; - - // Quotes - } else if (code === singleQuote || code === doubleQuote) { - next = pos; - quote = code === singleQuote ? "'" : '"'; - token = { - type: "string", - sourceIndex: pos, - quote: quote - }; - do { - escape = false; - next = value.indexOf(quote, next + 1); - if (~next) { - escapePos = next; - while (value.charCodeAt(escapePos - 1) === backslash) { - escapePos -= 1; - escape = !escape; - } - } else { - value += quote; - next = value.length - 1; - token.unclosed = true; - } - } while (escape); - token.value = value.slice(pos + 1, next); - - tokens.push(token); - pos = next + 1; - code = value.charCodeAt(pos); - - // Comments - } else if (code === slash && value.charCodeAt(pos + 1) === star) { - token = { - type: "comment", - sourceIndex: pos - }; - - next = value.indexOf("*/", pos); - if (next === -1) { - token.unclosed = true; - next = value.length; - } - - token.value = value.slice(pos + 2, next); - tokens.push(token); - - pos = next + 2; - code = value.charCodeAt(pos); - - // Operation within calc - } else if ( - (code === slash || code === star) && - parent && - parent.type === "function" && - parent.value === "calc" - ) { - token = value[pos]; - tokens.push({ - type: "word", - sourceIndex: pos - before.length, - value: token - }); - pos += 1; - code = value.charCodeAt(pos); - - // Dividers - } else if (code === slash || code === comma || code === colon) { - token = value[pos]; - - tokens.push({ - type: "div", - sourceIndex: pos - before.length, - value: token, - before: before, - after: "" - }); - before = ""; - - pos += 1; - code = value.charCodeAt(pos); - - // Open parentheses - } else if (openParentheses === code) { - // Whitespaces after open parentheses - next = pos; - do { - next += 1; - code = value.charCodeAt(next); - } while (code <= 32); - parenthesesOpenPos = pos; - token = { - type: "function", - sourceIndex: pos - name.length, - value: name, - before: value.slice(parenthesesOpenPos + 1, next) - }; - pos = next; - - if (name === "url" && code !== singleQuote && code !== doubleQuote) { - next -= 1; - do { - escape = false; - next = value.indexOf(")", next + 1); - if (~next) { - escapePos = next; - while (value.charCodeAt(escapePos - 1) === backslash) { - escapePos -= 1; - escape = !escape; - } - } else { - value += ")"; - next = value.length - 1; - token.unclosed = true; - } - } while (escape); - // Whitespaces before closed - whitespacePos = next; - do { - whitespacePos -= 1; - code = value.charCodeAt(whitespacePos); - } while (code <= 32); - if (parenthesesOpenPos < whitespacePos) { - if (pos !== whitespacePos + 1) { - token.nodes = [ - { - type: "word", - sourceIndex: pos, - value: value.slice(pos, whitespacePos + 1) - } - ]; - } else { - token.nodes = []; - } - if (token.unclosed && whitespacePos + 1 !== next) { - token.after = ""; - token.nodes.push({ - type: "space", - sourceIndex: whitespacePos + 1, - value: value.slice(whitespacePos + 1, next) - }); - } else { - token.after = value.slice(whitespacePos + 1, next); - } - } else { - token.after = ""; - token.nodes = []; - } - pos = next + 1; - code = value.charCodeAt(pos); - tokens.push(token); - } else { - balanced += 1; - token.after = ""; - tokens.push(token); - stack.push(token); - tokens = token.nodes = []; - parent = token; - } - name = ""; - - // Close parentheses - } else if (closeParentheses === code && balanced) { - pos += 1; - code = value.charCodeAt(pos); - - parent.after = after; - after = ""; - balanced -= 1; - stack.pop(); - parent = stack[balanced]; - tokens = parent.nodes; - - // Words - } else { - next = pos; - do { - if (code === backslash) { - next += 1; - } - next += 1; - code = value.charCodeAt(next); - } while ( - next < max && - !( - code <= 32 || - code === singleQuote || - code === doubleQuote || - code === comma || - code === colon || - code === slash || - code === openParentheses || - (code === star && - parent && - parent.type === "function" && - parent.value === "calc") || - (code === slash && - parent.type === "function" && - parent.value === "calc") || - (code === closeParentheses && balanced) - ) - ); - token = value.slice(pos, next); - - if (openParentheses === code) { - name = token; - } else if ( - (uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) && - plus$1 === token.charCodeAt(1) && - isUnicodeRange.test(token.slice(2)) - ) { - tokens.push({ - type: "unicode-range", - sourceIndex: pos, - value: token - }); - } else { - tokens.push({ - type: "word", - sourceIndex: pos, - value: token - }); - } - - pos = next; - } - } - - for (pos = stack.length - 1; pos; pos -= 1) { - stack[pos].unclosed = true; - } - - return stack[0].nodes; -}; - -var walk = function walk(nodes, cb, bubble) { - var i, max, node, result; - - for (i = 0, max = nodes.length; i < max; i += 1) { - node = nodes[i]; - if (!bubble) { - result = cb(node, i, nodes); - } - - if ( - result !== false && - node.type === "function" && - Array.isArray(node.nodes) - ) { - walk(node.nodes, cb, bubble); - } - - if (bubble) { - cb(node, i, nodes); - } - } -}; - -function stringifyNode(node, custom) { - var type = node.type; - var value = node.value; - var buf; - var customResult; - - if (custom && (customResult = custom(node)) !== undefined) { - return customResult; - } else if (type === "word" || type === "space") { - return value; - } else if (type === "string") { - buf = node.quote || ""; - return buf + value + (node.unclosed ? "" : buf); - } else if (type === "comment") { - return "/*" + value + (node.unclosed ? "" : "*/"); - } else if (type === "div") { - return (node.before || "") + value + (node.after || ""); - } else if (Array.isArray(node.nodes)) { - buf = stringify(node.nodes, custom); - if (type !== "function") { - return buf; - } - return ( - value + - "(" + - (node.before || "") + - buf + - (node.after || "") + - (node.unclosed ? "" : ")") - ); - } - return value; -} - -function stringify(nodes, custom) { - var result, i; - - if (Array.isArray(nodes)) { - result = ""; - for (i = nodes.length - 1; ~i; i -= 1) { - result = stringifyNode(nodes[i], custom) + result; - } - return result; - } - return stringifyNode(nodes, custom); -} - -var stringify_1 = stringify; - -var minus = "-".charCodeAt(0); -var plus = "+".charCodeAt(0); -var dot = ".".charCodeAt(0); -var exp = "e".charCodeAt(0); -var EXP = "E".charCodeAt(0); - -// Check if three code points would start a number -// https://www.w3.org/TR/css-syntax-3/#starts-with-a-number -function likeNumber(value) { - var code = value.charCodeAt(0); - var nextCode; - - if (code === plus || code === minus) { - nextCode = value.charCodeAt(1); - - if (nextCode >= 48 && nextCode <= 57) { - return true; - } - - var nextNextCode = value.charCodeAt(2); - - if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) { - return true; - } - - return false; - } - - if (code === dot) { - nextCode = value.charCodeAt(1); - - if (nextCode >= 48 && nextCode <= 57) { - return true; - } - - return false; - } - - if (code >= 48 && code <= 57) { - return true; - } - - return false; -} - -// Consume a number -// https://www.w3.org/TR/css-syntax-3/#consume-number -var unit = function(value) { - var pos = 0; - var length = value.length; - var code; - var nextCode; - var nextNextCode; - - if (length === 0 || !likeNumber(value)) { - return false; - } - - code = value.charCodeAt(pos); - - if (code === plus || code === minus) { - pos++; - } - - while (pos < length) { - code = value.charCodeAt(pos); - - if (code < 48 || code > 57) { - break; - } - - pos += 1; - } - - code = value.charCodeAt(pos); - nextCode = value.charCodeAt(pos + 1); - - if (code === dot && nextCode >= 48 && nextCode <= 57) { - pos += 2; - - while (pos < length) { - code = value.charCodeAt(pos); - - if (code < 48 || code > 57) { - break; - } - - pos += 1; - } - } - - code = value.charCodeAt(pos); - nextCode = value.charCodeAt(pos + 1); - nextNextCode = value.charCodeAt(pos + 2); - - if ( - (code === exp || code === EXP) && - ((nextCode >= 48 && nextCode <= 57) || - ((nextCode === plus || nextCode === minus) && - nextNextCode >= 48 && - nextNextCode <= 57)) - ) { - pos += nextCode === plus || nextCode === minus ? 3 : 2; - - while (pos < length) { - code = value.charCodeAt(pos); - - if (code < 48 || code > 57) { - break; - } - - pos += 1; - } - } - - return { - number: value.slice(0, pos), - unit: value.slice(pos) - }; -}; - -function ValueParser(value) { - if (this instanceof ValueParser) { - this.nodes = parse(value); - return this; - } - return new ValueParser(value); -} - -ValueParser.prototype.toString = function() { - return Array.isArray(this.nodes) ? stringify_1(this.nodes) : ""; -}; - -ValueParser.prototype.walk = function(cb, bubble) { - walk(this.nodes, cb, bubble); - return this; -}; - -ValueParser.unit = unit; - -ValueParser.walk = walk; - -ValueParser.stringify = stringify_1; - -var lib = ValueParser; - -exports.lib = lib; diff --git a/node_modules/vite/dist/node/chunks/dep-7af56b09.js b/node_modules/vite/dist/node/chunks/dep-7af56b09.js deleted file mode 100644 index 4564ffe..0000000 --- a/node_modules/vite/dist/node/chunks/dep-7af56b09.js +++ /dev/null @@ -1,10820 +0,0 @@ -'use strict'; - -var build = require('./dep-66eb515d.js'); -var os = require('os'); -var http = require('http'); -var https = require('https'); -var url = require('url'); -var path = require('path'); -var fs = require('fs'); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; } - -var os__default = /*#__PURE__*/_interopDefaultLegacy(os); -var http__default = /*#__PURE__*/_interopDefaultLegacy(http); -var https__default = /*#__PURE__*/_interopDefaultLegacy(https); -var url__default = /*#__PURE__*/_interopDefaultLegacy(url); -var path__default = /*#__PURE__*/_interopDefaultLegacy(path); -var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); - -function level0Optimize(tokens) { - // noop as level 0 means no optimizations! - return tokens; -} - -var optimize$3 = level0Optimize; - -var COLORS = { - aliceblue: '#f0f8ff', - antiquewhite: '#faebd7', - aqua: '#0ff', - aquamarine: '#7fffd4', - azure: '#f0ffff', - beige: '#f5f5dc', - bisque: '#ffe4c4', - black: '#000', - blanchedalmond: '#ffebcd', - blue: '#00f', - blueviolet: '#8a2be2', - brown: '#a52a2a', - burlywood: '#deb887', - cadetblue: '#5f9ea0', - chartreuse: '#7fff00', - chocolate: '#d2691e', - coral: '#ff7f50', - cornflowerblue: '#6495ed', - cornsilk: '#fff8dc', - crimson: '#dc143c', - cyan: '#0ff', - darkblue: '#00008b', - darkcyan: '#008b8b', - darkgoldenrod: '#b8860b', - darkgray: '#a9a9a9', - darkgreen: '#006400', - darkgrey: '#a9a9a9', - darkkhaki: '#bdb76b', - darkmagenta: '#8b008b', - darkolivegreen: '#556b2f', - darkorange: '#ff8c00', - darkorchid: '#9932cc', - darkred: '#8b0000', - darksalmon: '#e9967a', - darkseagreen: '#8fbc8f', - darkslateblue: '#483d8b', - darkslategray: '#2f4f4f', - darkslategrey: '#2f4f4f', - darkturquoise: '#00ced1', - darkviolet: '#9400d3', - deeppink: '#ff1493', - deepskyblue: '#00bfff', - dimgray: '#696969', - dimgrey: '#696969', - dodgerblue: '#1e90ff', - firebrick: '#b22222', - floralwhite: '#fffaf0', - forestgreen: '#228b22', - fuchsia: '#f0f', - gainsboro: '#dcdcdc', - ghostwhite: '#f8f8ff', - gold: '#ffd700', - goldenrod: '#daa520', - gray: '#808080', - green: '#008000', - greenyellow: '#adff2f', - grey: '#808080', - honeydew: '#f0fff0', - hotpink: '#ff69b4', - indianred: '#cd5c5c', - indigo: '#4b0082', - ivory: '#fffff0', - khaki: '#f0e68c', - lavender: '#e6e6fa', - lavenderblush: '#fff0f5', - lawngreen: '#7cfc00', - lemonchiffon: '#fffacd', - lightblue: '#add8e6', - lightcoral: '#f08080', - lightcyan: '#e0ffff', - lightgoldenrodyellow: '#fafad2', - lightgray: '#d3d3d3', - lightgreen: '#90ee90', - lightgrey: '#d3d3d3', - lightpink: '#ffb6c1', - lightsalmon: '#ffa07a', - lightseagreen: '#20b2aa', - lightskyblue: '#87cefa', - lightslategray: '#778899', - lightslategrey: '#778899', - lightsteelblue: '#b0c4de', - lightyellow: '#ffffe0', - lime: '#0f0', - limegreen: '#32cd32', - linen: '#faf0e6', - magenta: '#ff00ff', - maroon: '#800000', - mediumaquamarine: '#66cdaa', - mediumblue: '#0000cd', - mediumorchid: '#ba55d3', - mediumpurple: '#9370db', - mediumseagreen: '#3cb371', - mediumslateblue: '#7b68ee', - mediumspringgreen: '#00fa9a', - mediumturquoise: '#48d1cc', - mediumvioletred: '#c71585', - midnightblue: '#191970', - mintcream: '#f5fffa', - mistyrose: '#ffe4e1', - moccasin: '#ffe4b5', - navajowhite: '#ffdead', - navy: '#000080', - oldlace: '#fdf5e6', - olive: '#808000', - olivedrab: '#6b8e23', - orange: '#ffa500', - orangered: '#ff4500', - orchid: '#da70d6', - palegoldenrod: '#eee8aa', - palegreen: '#98fb98', - paleturquoise: '#afeeee', - palevioletred: '#db7093', - papayawhip: '#ffefd5', - peachpuff: '#ffdab9', - peru: '#cd853f', - pink: '#ffc0cb', - plum: '#dda0dd', - powderblue: '#b0e0e6', - purple: '#800080', - rebeccapurple: '#663399', - red: '#f00', - rosybrown: '#bc8f8f', - royalblue: '#4169e1', - saddlebrown: '#8b4513', - salmon: '#fa8072', - sandybrown: '#f4a460', - seagreen: '#2e8b57', - seashell: '#fff5ee', - sienna: '#a0522d', - silver: '#c0c0c0', - skyblue: '#87ceeb', - slateblue: '#6a5acd', - slategray: '#708090', - slategrey: '#708090', - snow: '#fffafa', - springgreen: '#00ff7f', - steelblue: '#4682b4', - tan: '#d2b48c', - teal: '#008080', - thistle: '#d8bfd8', - tomato: '#ff6347', - turquoise: '#40e0d0', - violet: '#ee82ee', - wheat: '#f5deb3', - white: '#fff', - whitesmoke: '#f5f5f5', - yellow: '#ff0', - yellowgreen: '#9acd32' -}; - -var toHex = {}; -var toName = {}; - -for (var name in COLORS) { - var hex = COLORS[name]; - - if (name.length < hex.length) { - toName[hex] = name; - } else { - toHex[name] = hex; - } -} - -var toHexPattern = new RegExp('(^| |,|\\))(' + Object.keys(toHex).join('|') + ')( |,|\\)|$)', 'ig'); -var toNamePattern = new RegExp('(' + Object.keys(toName).join('|') + ')([^a-f0-9]|$)', 'ig'); - -function hexConverter(match, prefix, colorValue, suffix) { - return prefix + toHex[colorValue.toLowerCase()] + suffix; -} - -function nameConverter(match, colorValue, suffix) { - return toName[colorValue.toLowerCase()] + suffix; -} - -function shortenHex(value) { - var hasHex = value.indexOf('#') > -1; - var shortened = value.replace(toHexPattern, hexConverter); - - if (shortened != value) { - shortened = shortened.replace(toHexPattern, hexConverter); - } - - return hasHex ? - shortened.replace(toNamePattern, nameConverter) : - shortened; -} - -var shortenHex_1 = shortenHex; - -// HSL to RGB converter. Both methods adapted from: -// http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript - -function hslToRgb(h, s, l) { - var r, g, b; - - // normalize hue orientation b/w 0 and 360 degrees - h = h % 360; - if (h < 0) - h += 360; - h = ~~h / 360; - - if (s < 0) - s = 0; - else if (s > 100) - s = 100; - s = ~~s / 100; - - if (l < 0) - l = 0; - else if (l > 100) - l = 100; - l = ~~l / 100; - - if (s === 0) { - r = g = b = l; // achromatic - } else { - var q = l < 0.5 ? - l * (1 + s) : - l + s - l * s; - var p = 2 * l - q; - r = hueToRgb(p, q, h + 1/3); - g = hueToRgb(p, q, h); - b = hueToRgb(p, q, h - 1/3); - } - - return [~~(r * 255), ~~(g * 255), ~~(b * 255)]; -} - -function hueToRgb(p, q, t) { - if (t < 0) t += 1; - if (t > 1) t -= 1; - if (t < 1/6) return p + (q - p) * 6 * t; - if (t < 1/2) return q; - if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; - return p; -} - -function shortenHsl(hue, saturation, lightness) { - var asRgb = hslToRgb(hue, saturation, lightness); - var redAsHex = asRgb[0].toString(16); - var greenAsHex = asRgb[1].toString(16); - var blueAsHex = asRgb[2].toString(16); - - return '#' + - ((redAsHex.length == 1 ? '0' : '') + redAsHex) + - ((greenAsHex.length == 1 ? '0' : '') + greenAsHex) + - ((blueAsHex.length == 1 ? '0' : '') + blueAsHex); -} - -var shortenHsl_1 = shortenHsl; - -function shortenRgb(red, green, blue) { - var normalizedRed = Math.max(0, Math.min(parseInt(red), 255)); - var normalizedGreen = Math.max(0, Math.min(parseInt(green), 255)); - var normalizedBlue = Math.max(0, Math.min(parseInt(blue), 255)); - - // Credit: Asen http://jsbin.com/UPUmaGOc/2/edit?js,console - return '#' + ('00000' + (normalizedRed << 16 | normalizedGreen << 8 | normalizedBlue).toString(16)).slice(-6); -} - -var shortenRgb_1 = shortenRgb; - -// adapted from http://nedbatchelder.com/blog/200712.html#e20071211T054956 - -var NUMBER_PATTERN = /([0-9]+)/; - -function naturalCompare(value1, value2) { - var keys1 = ('' + value1).split(NUMBER_PATTERN).map(tryParseInt); - var keys2 = ('' + value2).split(NUMBER_PATTERN).map(tryParseInt); - var key1; - var key2; - var compareFirst = Math.min(keys1.length, keys2.length); - var i, l; - - for (i = 0, l = compareFirst; i < l; i++) { - key1 = keys1[i]; - key2 = keys2[i]; - - if (key1 != key2) { - return key1 > key2 ? 1 : -1; - } - } - - return keys1.length > keys2.length ? 1 : (keys1.length == keys2.length ? 0 : -1); -} - -function tryParseInt(value) { - return ('' + parseInt(value)) == value ? - parseInt(value) : - value; -} - -var naturalCompare_1 = naturalCompare; - -function naturalSorter$1(scope1, scope2) { - return naturalCompare_1(scope1[1], scope2[1]); -} - -function standardSorter(scope1, scope2) { - return scope1[1] > scope2[1] ? 1 : -1; -} - -function sortSelectors(selectors, method) { - switch (method) { - case 'natural': - return selectors.sort(naturalSorter$1); - case 'standard': - return selectors.sort(standardSorter); - case 'none': - case false: - return selectors; - } -} - -var sortSelectors_1 = sortSelectors; - -function override$1(source1, source2) { - var target = {}; - var key1; - var key2; - var item; - - for (key1 in source1) { - item = source1[key1]; - - if (Array.isArray(item)) { - target[key1] = item.slice(0); - } else if (typeof item == 'object' && item !== null) { - target[key1] = override$1(item, {}); - } else { - target[key1] = item; - } - } - - for (key2 in source2) { - item = source2[key2]; - - if (key2 in target && Array.isArray(item)) { - target[key2] = item.slice(0); - } else if (key2 in target && typeof item == 'object' && item !== null) { - target[key2] = override$1(target[key2], item); - } else { - target[key2] = item; - } - } - - return target; -} - -var override_1 = override$1; - -var systemLineBreak = os__default.EOL; - - - -var Breaks$1 = { - AfterAtRule: 'afterAtRule', - AfterBlockBegins: 'afterBlockBegins', - AfterBlockEnds: 'afterBlockEnds', - AfterComment: 'afterComment', - AfterProperty: 'afterProperty', - AfterRuleBegins: 'afterRuleBegins', - AfterRuleEnds: 'afterRuleEnds', - BeforeBlockEnds: 'beforeBlockEnds', - BetweenSelectors: 'betweenSelectors' -}; - -var BreakWith = { - CarriageReturnLineFeed: '\r\n', - LineFeed: '\n', - System: systemLineBreak -}; - -var IndentWith = { - Space: ' ', - Tab: '\t' -}; - -var Spaces$2 = { - AroundSelectorRelation: 'aroundSelectorRelation', - BeforeBlockBegins: 'beforeBlockBegins', - BeforeValue: 'beforeValue' -}; - -var DEFAULTS$2 = { - breaks: breaks(false), - breakWith: BreakWith.System, - indentBy: 0, - indentWith: IndentWith.Space, - spaces: spaces(false), - wrapAt: false, - semicolonAfterLastProperty: false -}; - -var BEAUTIFY_ALIAS = 'beautify'; -var KEEP_BREAKS_ALIAS = 'keep-breaks'; - -var OPTION_SEPARATOR$1 = ';'; -var OPTION_NAME_VALUE_SEPARATOR = ':'; -var HASH_VALUES_OPTION_SEPARATOR = ','; -var HASH_VALUES_NAME_VALUE_SEPARATOR = '='; - -var FALSE_KEYWORD_1$1 = 'false'; -var FALSE_KEYWORD_2$1 = 'off'; -var TRUE_KEYWORD_1$1 = 'true'; -var TRUE_KEYWORD_2$1 = 'on'; - -function breaks(value) { - var breakOptions = {}; - - breakOptions[Breaks$1.AfterAtRule] = value; - breakOptions[Breaks$1.AfterBlockBegins] = value; - breakOptions[Breaks$1.AfterBlockEnds] = value; - breakOptions[Breaks$1.AfterComment] = value; - breakOptions[Breaks$1.AfterProperty] = value; - breakOptions[Breaks$1.AfterRuleBegins] = value; - breakOptions[Breaks$1.AfterRuleEnds] = value; - breakOptions[Breaks$1.BeforeBlockEnds] = value; - breakOptions[Breaks$1.BetweenSelectors] = value; - - return breakOptions; -} - -function spaces(value) { - var spaceOptions = {}; - - spaceOptions[Spaces$2.AroundSelectorRelation] = value; - spaceOptions[Spaces$2.BeforeBlockBegins] = value; - spaceOptions[Spaces$2.BeforeValue] = value; - - return spaceOptions; -} - -function formatFrom(source) { - if (source === undefined || source === false) { - return false; - } - - if (typeof source == 'object' && 'breakWith' in source) { - source = override_1(source, { breakWith: mapBreakWith(source.breakWith) }); - } - - if (typeof source == 'object' && 'indentBy' in source) { - source = override_1(source, { indentBy: parseInt(source.indentBy) }); - } - - if (typeof source == 'object' && 'indentWith' in source) { - source = override_1(source, { indentWith: mapIndentWith(source.indentWith) }); - } - - if (typeof source == 'object') { - return override_1(DEFAULTS$2, source); - } - - if (typeof source == 'object') { - return override_1(DEFAULTS$2, source); - } - - if (typeof source == 'string' && source == BEAUTIFY_ALIAS) { - return override_1(DEFAULTS$2, { - breaks: breaks(true), - indentBy: 2, - spaces: spaces(true) - }); - } - - if (typeof source == 'string' && source == KEEP_BREAKS_ALIAS) { - return override_1(DEFAULTS$2, { - breaks: { - afterAtRule: true, - afterBlockBegins: true, - afterBlockEnds: true, - afterComment: true, - afterRuleEnds: true, - beforeBlockEnds: true - } - }); - } - - if (typeof source == 'string') { - return override_1(DEFAULTS$2, toHash(source)); - } - - return DEFAULTS$2; -} - -function toHash(string) { - return string - .split(OPTION_SEPARATOR$1) - .reduce(function (accumulator, directive) { - var parts = directive.split(OPTION_NAME_VALUE_SEPARATOR); - var name = parts[0]; - var value = parts[1]; - - if (name == 'breaks' || name == 'spaces') { - accumulator[name] = hashValuesToHash(value); - } else if (name == 'indentBy' || name == 'wrapAt') { - accumulator[name] = parseInt(value); - } else if (name == 'indentWith') { - accumulator[name] = mapIndentWith(value); - } else if (name == 'breakWith') { - accumulator[name] = mapBreakWith(value); - } - - return accumulator; - }, {}); -} - -function hashValuesToHash(string) { - return string - .split(HASH_VALUES_OPTION_SEPARATOR) - .reduce(function (accumulator, directive) { - var parts = directive.split(HASH_VALUES_NAME_VALUE_SEPARATOR); - var name = parts[0]; - var value = parts[1]; - - accumulator[name] = normalizeValue$1(value); - - return accumulator; - }, {}); -} - - -function normalizeValue$1(value) { - switch (value) { - case FALSE_KEYWORD_1$1: - case FALSE_KEYWORD_2$1: - return false; - case TRUE_KEYWORD_1$1: - case TRUE_KEYWORD_2$1: - return true; - default: - return value; - } -} - -function mapBreakWith(value) { - switch (value) { - case 'windows': - case 'crlf': - case BreakWith.CarriageReturnLineFeed: - return BreakWith.CarriageReturnLineFeed; - case 'unix': - case 'lf': - case BreakWith.LineFeed: - return BreakWith.LineFeed; - default: - return systemLineBreak; - } -} - -function mapIndentWith(value) { - switch (value) { - case 'space': - return IndentWith.Space; - case 'tab': - return IndentWith.Tab; - default: - return value; - } -} - -var format = { - Breaks: Breaks$1, - Spaces: Spaces$2, - formatFrom: formatFrom -}; - -var Marker = { - ASTERISK: '*', - AT: '@', - BACK_SLASH: '\\', - CARRIAGE_RETURN: '\r', - CLOSE_CURLY_BRACKET: '}', - CLOSE_ROUND_BRACKET: ')', - CLOSE_SQUARE_BRACKET: ']', - COLON: ':', - COMMA: ',', - DOUBLE_QUOTE: '"', - EXCLAMATION: '!', - FORWARD_SLASH: '/', - INTERNAL: '-clean-css-', - NEW_LINE_NIX: '\n', - OPEN_CURLY_BRACKET: '{', - OPEN_ROUND_BRACKET: '(', - OPEN_SQUARE_BRACKET: '[', - SEMICOLON: ';', - SINGLE_QUOTE: '\'', - SPACE: ' ', - TAB: '\t', - UNDERSCORE: '_' -}; - -var marker = Marker; - -function formatPosition(metadata) { - var line = metadata[0]; - var column = metadata[1]; - var source = metadata[2]; - - return source ? - source + ':' + line + ':' + column : - line + ':' + column; -} - -var formatPosition_1 = formatPosition; - -var Spaces$1 = format.Spaces; - - - -var CASE_ATTRIBUTE_PATTERN = /[\s"'][iI]\s*\]/; -var CASE_RESTORE_PATTERN = /([\d\w])([iI])\]/g; -var DOUBLE_QUOTE_CASE_PATTERN = /="([a-zA-Z][a-zA-Z\d\-_]+)"([iI])/g; -var DOUBLE_QUOTE_PATTERN = /="([a-zA-Z][a-zA-Z\d\-_]+)"(\s|\])/g; -var HTML_COMMENT_PATTERN = /^(?:(?:)\s*)+/; -var SINGLE_QUOTE_CASE_PATTERN = /='([a-zA-Z][a-zA-Z\d\-_]+)'([iI])/g; -var SINGLE_QUOTE_PATTERN = /='([a-zA-Z][a-zA-Z\d\-_]+)'(\s|\])/g; -var RELATION_PATTERN$1 = /[>\+~]/; -var WHITESPACE_PATTERN$1 = /\s/; - -var ASTERISK_PLUS_HTML_HACK = '*+html '; -var ASTERISK_FIRST_CHILD_PLUS_HTML_HACK = '*:first-child+html '; -var LESS_THAN = '<'; - -function hasInvalidCharacters(value) { - var isEscaped; - var isInvalid = false; - var character; - var isQuote = false; - var i, l; - - for (i = 0, l = value.length; i < l; i++) { - character = value[i]; - - if (isEscaped) ; else if (character == marker.SINGLE_QUOTE || character == marker.DOUBLE_QUOTE) { - isQuote = !isQuote; - } else if (!isQuote && (character == marker.CLOSE_CURLY_BRACKET || character == marker.EXCLAMATION || character == LESS_THAN || character == marker.SEMICOLON)) { - isInvalid = true; - break; - } else if (!isQuote && i === 0 && RELATION_PATTERN$1.test(character)) { - isInvalid = true; - break; - } - - isEscaped = character == marker.BACK_SLASH; - } - - return isInvalid; -} - -function removeWhitespace(value, format) { - var stripped = []; - var character; - var isNewLineNix; - var isNewLineWin; - var isEscaped; - var wasEscaped; - var isQuoted; - var isSingleQuoted; - var isDoubleQuoted; - var isAttribute; - var isRelation; - var isWhitespace; - var roundBracketLevel = 0; - var wasRelation = false; - var wasWhitespace = false; - var withCaseAttribute = CASE_ATTRIBUTE_PATTERN.test(value); - var spaceAroundRelation = format && format.spaces[Spaces$1.AroundSelectorRelation]; - var i, l; - - for (i = 0, l = value.length; i < l; i++) { - character = value[i]; - - isNewLineNix = character == marker.NEW_LINE_NIX; - isNewLineWin = character == marker.NEW_LINE_NIX && value[i - 1] == marker.CARRIAGE_RETURN; - isQuoted = isSingleQuoted || isDoubleQuoted; - isRelation = !isAttribute && !isEscaped && roundBracketLevel === 0 && RELATION_PATTERN$1.test(character); - isWhitespace = WHITESPACE_PATTERN$1.test(character); - - if (wasEscaped && isQuoted && isNewLineWin) { - // swallow escaped new windows lines in comments - stripped.pop(); - stripped.pop(); - } else if (isEscaped && isQuoted && isNewLineNix) { - // swallow escaped new *nix lines in comments - stripped.pop(); - } else if (isEscaped) { - stripped.push(character); - } else if (character == marker.OPEN_SQUARE_BRACKET && !isQuoted) { - stripped.push(character); - isAttribute = true; - } else if (character == marker.CLOSE_SQUARE_BRACKET && !isQuoted) { - stripped.push(character); - isAttribute = false; - } else if (character == marker.OPEN_ROUND_BRACKET && !isQuoted) { - stripped.push(character); - roundBracketLevel++; - } else if (character == marker.CLOSE_ROUND_BRACKET && !isQuoted) { - stripped.push(character); - roundBracketLevel--; - } else if (character == marker.SINGLE_QUOTE && !isQuoted) { - stripped.push(character); - isSingleQuoted = true; - } else if (character == marker.DOUBLE_QUOTE && !isQuoted) { - stripped.push(character); - isDoubleQuoted = true; - } else if (character == marker.SINGLE_QUOTE && isQuoted) { - stripped.push(character); - isSingleQuoted = false; - } else if (character == marker.DOUBLE_QUOTE && isQuoted) { - stripped.push(character); - isDoubleQuoted = false; - } else if (isWhitespace && wasRelation && !spaceAroundRelation) { - continue; - } else if (!isWhitespace && wasRelation && spaceAroundRelation) { - stripped.push(marker.SPACE); - stripped.push(character); - } else if (isWhitespace && (isAttribute || roundBracketLevel > 0) && !isQuoted) ; else if (isWhitespace && wasWhitespace && !isQuoted) ; else if ((isNewLineWin || isNewLineNix) && (isAttribute || roundBracketLevel > 0) && isQuoted) ; else if (isRelation && wasWhitespace && !spaceAroundRelation) { - stripped.pop(); - stripped.push(character); - } else if (isRelation && !wasWhitespace && spaceAroundRelation) { - stripped.push(marker.SPACE); - stripped.push(character); - } else if (isWhitespace) { - stripped.push(marker.SPACE); - } else { - stripped.push(character); - } - - wasEscaped = isEscaped; - isEscaped = character == marker.BACK_SLASH; - wasRelation = isRelation; - wasWhitespace = isWhitespace; - } - - return withCaseAttribute ? - stripped.join('').replace(CASE_RESTORE_PATTERN, '$1 $2]') : - stripped.join(''); -} - -function removeQuotes$1(value) { - if (value.indexOf('\'') == -1 && value.indexOf('"') == -1) { - return value; - } - - return value - .replace(SINGLE_QUOTE_CASE_PATTERN, '=$1 $2') - .replace(SINGLE_QUOTE_PATTERN, '=$1$2') - .replace(DOUBLE_QUOTE_CASE_PATTERN, '=$1 $2') - .replace(DOUBLE_QUOTE_PATTERN, '=$1$2'); -} - -function tidyRules(rules, removeUnsupported, adjacentSpace, format, warnings) { - var list = []; - var repeated = []; - - function removeHTMLComment(rule, match) { - warnings.push('HTML comment \'' + match + '\' at ' + formatPosition_1(rule[2][0]) + '. Removing.'); - return ''; - } - - for (var i = 0, l = rules.length; i < l; i++) { - var rule = rules[i]; - var reduced = rule[1]; - - reduced = reduced.replace(HTML_COMMENT_PATTERN, removeHTMLComment.bind(null, rule)); - - if (hasInvalidCharacters(reduced)) { - warnings.push('Invalid selector \'' + rule[1] + '\' at ' + formatPosition_1(rule[2][0]) + '. Ignoring.'); - continue; - } - - reduced = removeWhitespace(reduced, format); - reduced = removeQuotes$1(reduced); - - if (adjacentSpace && reduced.indexOf('nav') > 0) { - reduced = reduced.replace(/\+nav(\S|$)/, '+ nav$1'); - } - - if (removeUnsupported && reduced.indexOf(ASTERISK_PLUS_HTML_HACK) > -1) { - continue; - } - - if (removeUnsupported && reduced.indexOf(ASTERISK_FIRST_CHILD_PLUS_HTML_HACK) > -1) { - continue; - } - - if (reduced.indexOf('*') > -1) { - reduced = reduced - .replace(/\*([:#\.\[])/g, '$1') - .replace(/^(\:first\-child)?\+html/, '*$1+html'); - } - - if (repeated.indexOf(reduced) > -1) { - continue; - } - - rule[1] = reduced; - repeated.push(reduced); - list.push(rule); - } - - if (list.length == 1 && list[0][1].length === 0) { - warnings.push('Empty selector \'' + list[0][1] + '\' at ' + formatPosition_1(list[0][2][0]) + '. Ignoring.'); - list = []; - } - - return list; -} - -var tidyRules_1 = tidyRules; - -var SUPPORTED_COMPACT_BLOCK_MATCHER = /^@media\W/; - -function tidyBlock(values, spaceAfterClosingBrace) { - var withoutSpaceAfterClosingBrace; - var i; - - for (i = values.length - 1; i >= 0; i--) { - withoutSpaceAfterClosingBrace = !spaceAfterClosingBrace && SUPPORTED_COMPACT_BLOCK_MATCHER.test(values[i][1]); - - values[i][1] = values[i][1] - .replace(/\n|\r\n/g, ' ') - .replace(/\s+/g, ' ') - .replace(/(,|:|\() /g, '$1') - .replace(/ \)/g, ')') - .replace(/'([a-zA-Z][a-zA-Z\d\-_]+)'/, '$1') - .replace(/"([a-zA-Z][a-zA-Z\d\-_]+)"/, '$1') - .replace(withoutSpaceAfterClosingBrace ? /\) /g : null, ')'); - } - - return values; -} - -var tidyBlock_1 = tidyBlock; - -function tidyAtRule(value) { - return value - .replace(/\s+/g, ' ') - .replace(/url\(\s+/g, 'url(') - .replace(/\s+\)/g, ')') - .trim(); -} - -var tidyAtRule_1 = tidyAtRule; - -var Hack = { - ASTERISK: 'asterisk', - BANG: 'bang', - BACKSLASH: 'backslash', - UNDERSCORE: 'underscore' -}; - -var hack = Hack; - -function removeUnused(properties) { - for (var i = properties.length - 1; i >= 0; i--) { - var property = properties[i]; - - if (property.unused) { - property.all.splice(property.position, 1); - } - } -} - -var removeUnused_1 = removeUnused; - -var ASTERISK_HACK = '*'; -var BACKSLASH_HACK = '\\'; -var IMPORTANT_TOKEN = '!important'; -var UNDERSCORE_HACK = '_'; -var BANG_HACK = '!ie'; - -function restoreFromOptimizing(properties, restoreCallback) { - var property; - var restored; - var current; - var i; - - for (i = properties.length - 1; i >= 0; i--) { - property = properties[i]; - - if (property.unused) { - continue; - } - - if (!property.dirty && !property.important && !property.hack) { - continue; - } - - if (restoreCallback) { - restored = restoreCallback(property); - property.value = restored; - } else { - restored = property.value; - } - - if (property.important) { - restoreImportant(property); - } - - if (property.hack) { - restoreHack(property); - } - - if ('all' in property) { - current = property.all[property.position]; - current[1][1] = property.name; - - current.splice(2, current.length - 1); - Array.prototype.push.apply(current, restored); - } - } -} - -function restoreImportant(property) { - property.value[property.value.length - 1][1] += IMPORTANT_TOKEN; -} - -function restoreHack(property) { - if (property.hack[0] == hack.UNDERSCORE) { - property.name = UNDERSCORE_HACK + property.name; - } else if (property.hack[0] == hack.ASTERISK) { - property.name = ASTERISK_HACK + property.name; - } else if (property.hack[0] == hack.BACKSLASH) { - property.value[property.value.length - 1][1] += BACKSLASH_HACK + property.hack[1]; - } else if (property.hack[0] == hack.BANG) { - property.value[property.value.length - 1][1] += marker.SPACE + BANG_HACK; - } -} - -var restoreFromOptimizing_1 = restoreFromOptimizing; - -var Token = { - AT_RULE: 'at-rule', // e.g. `@import`, `@charset` - AT_RULE_BLOCK: 'at-rule-block', // e.g. `@font-face{...}` - AT_RULE_BLOCK_SCOPE: 'at-rule-block-scope', // e.g. `@font-face` - COMMENT: 'comment', // e.g. `/* comment */` - NESTED_BLOCK: 'nested-block', // e.g. `@media screen{...}`, `@keyframes animation {...}` - NESTED_BLOCK_SCOPE: 'nested-block-scope', // e.g. `@media`, `@keyframes` - PROPERTY: 'property', // e.g. `color:red` - PROPERTY_BLOCK: 'property-block', // e.g. `--var:{color:red}` - PROPERTY_NAME: 'property-name', // e.g. `color` - PROPERTY_VALUE: 'property-value', // e.g. `red` - RAW: 'raw', // e.g. anything between /* clean-css ignore:start */ and /* clean-css ignore:end */ comments - RULE: 'rule', // e.g `div > a{...}` - RULE_SCOPE: 'rule-scope' // e.g `div > a` -}; - -var token = Token; - -var Match = { - ASTERISK: '*', - BACKSLASH: '\\', - BANG: '!', - BANG_SUFFIX_PATTERN: /!\w+$/, - IMPORTANT_TOKEN: '!important', - IMPORTANT_TOKEN_PATTERN: new RegExp('!important$', 'i'), - IMPORTANT_WORD: 'important', - IMPORTANT_WORD_PATTERN: new RegExp('important$', 'i'), - SUFFIX_BANG_PATTERN: /!$/, - UNDERSCORE: '_', - VARIABLE_REFERENCE_PATTERN: /var\(--.+\)$/ -}; - -function wrapAll(properties, includeVariable, skipProperties) { - var wrapped = []; - var single; - var property; - var i; - - for (i = properties.length - 1; i >= 0; i--) { - property = properties[i]; - - if (property[0] != token.PROPERTY) { - continue; - } - - if (!includeVariable && someVariableReferences(property)) { - continue; - } - - if (skipProperties && skipProperties.indexOf(property[1][1]) > -1) { - continue; - } - - single = wrapSingle$3(property); - single.all = properties; - single.position = i; - wrapped.unshift(single); - } - - return wrapped; -} - -function someVariableReferences(property) { - var i, l; - var value; - - // skipping `property` and property name tokens - for (i = 2, l = property.length; i < l; i++) { - value = property[i]; - - if (value[0] != token.PROPERTY_VALUE) { - continue; - } - - if (isVariableReference(value[1])) { - return true; - } - } - - return false; -} - -function isVariableReference(value) { - return Match.VARIABLE_REFERENCE_PATTERN.test(value); -} - -function isMultiplex(property) { - var value; - var i, l; - - for (i = 3, l = property.length; i < l; i++) { - value = property[i]; - - if (value[0] == token.PROPERTY_VALUE && (value[1] == marker.COMMA || value[1] == marker.FORWARD_SLASH)) { - return true; - } - } - - return false; -} - -function hackFrom(property) { - var match = false; - var name = property[1][1]; - var lastValue = property[property.length - 1]; - - if (name[0] == Match.UNDERSCORE) { - match = [hack.UNDERSCORE]; - } else if (name[0] == Match.ASTERISK) { - match = [hack.ASTERISK]; - } else if (lastValue[1][0] == Match.BANG && !lastValue[1].match(Match.IMPORTANT_WORD_PATTERN)) { - match = [hack.BANG]; - } else if (lastValue[1].indexOf(Match.BANG) > 0 && !lastValue[1].match(Match.IMPORTANT_WORD_PATTERN) && Match.BANG_SUFFIX_PATTERN.test(lastValue[1])) { - match = [hack.BANG]; - } else if (lastValue[1].indexOf(Match.BACKSLASH) > 0 && lastValue[1].indexOf(Match.BACKSLASH) == lastValue[1].length - Match.BACKSLASH.length - 1) { - match = [hack.BACKSLASH, lastValue[1].substring(lastValue[1].indexOf(Match.BACKSLASH) + 1)]; - } else if (lastValue[1].indexOf(Match.BACKSLASH) === 0 && lastValue[1].length == 2) { - match = [hack.BACKSLASH, lastValue[1].substring(1)]; - } - - return match; -} - -function isImportant(property) { - if (property.length < 3) - return false; - - var lastValue = property[property.length - 1]; - if (Match.IMPORTANT_TOKEN_PATTERN.test(lastValue[1])) { - return true; - } else if (Match.IMPORTANT_WORD_PATTERN.test(lastValue[1]) && Match.SUFFIX_BANG_PATTERN.test(property[property.length - 2][1])) { - return true; - } - - return false; -} - -function stripImportant(property) { - var lastValue = property[property.length - 1]; - var oneButLastValue = property[property.length - 2]; - - if (Match.IMPORTANT_TOKEN_PATTERN.test(lastValue[1])) { - lastValue[1] = lastValue[1].replace(Match.IMPORTANT_TOKEN_PATTERN, ''); - } else { - lastValue[1] = lastValue[1].replace(Match.IMPORTANT_WORD_PATTERN, ''); - oneButLastValue[1] = oneButLastValue[1].replace(Match.SUFFIX_BANG_PATTERN, ''); - } - - if (lastValue[1].length === 0) { - property.pop(); - } - - if (oneButLastValue[1].length === 0) { - property.pop(); - } -} - -function stripPrefixHack(property) { - property[1][1] = property[1][1].substring(1); -} - -function stripSuffixHack(property, hackFrom) { - var lastValue = property[property.length - 1]; - lastValue[1] = lastValue[1] - .substring(0, lastValue[1].indexOf(hackFrom[0] == hack.BACKSLASH ? Match.BACKSLASH : Match.BANG)) - .trim(); - - if (lastValue[1].length === 0) { - property.pop(); - } -} - -function wrapSingle$3(property) { - var importantProperty = isImportant(property); - if (importantProperty) { - stripImportant(property); - } - - var whichHack = hackFrom(property); - if (whichHack[0] == hack.ASTERISK || whichHack[0] == hack.UNDERSCORE) { - stripPrefixHack(property); - } else if (whichHack[0] == hack.BACKSLASH || whichHack[0] == hack.BANG) { - stripSuffixHack(property, whichHack); - } - - return { - block: property[2] && property[2][0] == token.PROPERTY_BLOCK, - components: [], - dirty: false, - hack: whichHack, - important: importantProperty, - name: property[1][1], - multiplex: property.length > 3 ? isMultiplex(property) : false, - position: 0, - shorthand: false, - unused: false, - value: property.slice(2) - }; -} - -var wrapForOptimizing$3 = { - all: wrapAll, - single: wrapSingle$3 -}; - -var INTEGER_PATTERN = /^\d+$/; - -var ALL_UNITS = ['*', 'all']; -var DEFAULT_PRECISION = 'off'; // all precision changes are disabled -var DIRECTIVES_SEPARATOR = ','; // e.g. *=5,px=3 -var DIRECTIVE_VALUE_SEPARATOR = '='; // e.g. *=5 - -function roundingPrecisionFrom$1(source) { - return override_1(defaults$1(DEFAULT_PRECISION), buildPrecisionFrom(source)); -} - -function defaults$1(value) { - return { - 'ch': value, - 'cm': value, - 'em': value, - 'ex': value, - 'in': value, - 'mm': value, - 'pc': value, - 'pt': value, - 'px': value, - 'q': value, - 'rem': value, - 'vh': value, - 'vmax': value, - 'vmin': value, - 'vw': value, - '%': value - }; -} - -function buildPrecisionFrom(source) { - if (source === null || source === undefined) { - return {}; - } - - if (typeof source == 'boolean') { - return {}; - } - - if (typeof source == 'number' && source == -1) { - return defaults$1(DEFAULT_PRECISION); - } - - if (typeof source == 'number') { - return defaults$1(source); - } - - if (typeof source == 'string' && INTEGER_PATTERN.test(source)) { - return defaults$1(parseInt(source)); - } - - if (typeof source == 'string' && source == DEFAULT_PRECISION) { - return defaults$1(DEFAULT_PRECISION); - } - - if (typeof source == 'object') { - return source; - } - - return source - .split(DIRECTIVES_SEPARATOR) - .reduce(function (accumulator, directive) { - var directiveParts = directive.split(DIRECTIVE_VALUE_SEPARATOR); - var name = directiveParts[0]; - var value = parseInt(directiveParts[1]); - - if (isNaN(value) || value == -1) { - value = DEFAULT_PRECISION; - } - - if (ALL_UNITS.indexOf(name) > -1) { - accumulator = override_1(accumulator, defaults$1(value)); - } else { - accumulator[name] = value; - } - - return accumulator; - }, {}); -} - -var roundingPrecision = { - DEFAULT: DEFAULT_PRECISION, - roundingPrecisionFrom: roundingPrecisionFrom$1 -}; - -var roundingPrecisionFrom = roundingPrecision.roundingPrecisionFrom; - - - -var OptimizationLevel$6 = { - Zero: '0', - One: '1', - Two: '2' -}; - -var DEFAULTS$1 = {}; - -DEFAULTS$1[OptimizationLevel$6.Zero] = {}; -DEFAULTS$1[OptimizationLevel$6.One] = { - cleanupCharsets: true, - normalizeUrls: true, - optimizeBackground: true, - optimizeBorderRadius: true, - optimizeFilter: true, - optimizeFontWeight: true, - optimizeOutline: true, - removeEmpty: true, - removeNegativePaddings: true, - removeQuotes: true, - removeWhitespace: true, - replaceMultipleZeros: true, - replaceTimeUnits: true, - replaceZeroUnits: true, - roundingPrecision: roundingPrecisionFrom(undefined), - selectorsSortingMethod: 'standard', - specialComments: 'all', - tidyAtRules: true, - tidyBlockScopes: true, - tidySelectors: true, - transform: noop -}; -DEFAULTS$1[OptimizationLevel$6.Two] = { - mergeAdjacentRules: true, - mergeIntoShorthands: true, - mergeMedia: true, - mergeNonAdjacentRules: true, - mergeSemantically: false, - overrideProperties: true, - removeEmpty: true, - reduceNonAdjacentRules: true, - removeDuplicateFontRules: true, - removeDuplicateMediaBlocks: true, - removeDuplicateRules: true, - removeUnusedAtRules: false, - restructureRules: false, - skipProperties: [] -}; - -var ALL_KEYWORD_1 = '*'; -var ALL_KEYWORD_2 = 'all'; -var FALSE_KEYWORD_1 = 'false'; -var FALSE_KEYWORD_2 = 'off'; -var TRUE_KEYWORD_1 = 'true'; -var TRUE_KEYWORD_2 = 'on'; - -var LIST_VALUE_SEPARATOR = ','; -var OPTION_SEPARATOR = ';'; -var OPTION_VALUE_SEPARATOR = ':'; - -function noop() {} - -function optimizationLevelFrom(source) { - var level = override_1(DEFAULTS$1, {}); - var Zero = OptimizationLevel$6.Zero; - var One = OptimizationLevel$6.One; - var Two = OptimizationLevel$6.Two; - - - if (undefined === source) { - delete level[Two]; - return level; - } - - if (typeof source == 'string') { - source = parseInt(source); - } - - if (typeof source == 'number' && source === parseInt(Two)) { - return level; - } - - if (typeof source == 'number' && source === parseInt(One)) { - delete level[Two]; - return level; - } - - if (typeof source == 'number' && source === parseInt(Zero)) { - delete level[Two]; - delete level[One]; - return level; - } - - if (typeof source == 'object') { - source = covertValuesToHashes(source); - } - - if (One in source && 'roundingPrecision' in source[One]) { - source[One].roundingPrecision = roundingPrecisionFrom(source[One].roundingPrecision); - } - - if (Two in source && 'skipProperties' in source[Two] && typeof(source[Two].skipProperties) == 'string') { - source[Two].skipProperties = source[Two].skipProperties.split(LIST_VALUE_SEPARATOR); - } - - if (Zero in source || One in source || Two in source) { - level[Zero] = override_1(level[Zero], source[Zero]); - } - - if (One in source && ALL_KEYWORD_1 in source[One]) { - level[One] = override_1(level[One], defaults(One, normalizeValue(source[One][ALL_KEYWORD_1]))); - delete source[One][ALL_KEYWORD_1]; - } - - if (One in source && ALL_KEYWORD_2 in source[One]) { - level[One] = override_1(level[One], defaults(One, normalizeValue(source[One][ALL_KEYWORD_2]))); - delete source[One][ALL_KEYWORD_2]; - } - - if (One in source || Two in source) { - level[One] = override_1(level[One], source[One]); - } else { - delete level[One]; - } - - if (Two in source && ALL_KEYWORD_1 in source[Two]) { - level[Two] = override_1(level[Two], defaults(Two, normalizeValue(source[Two][ALL_KEYWORD_1]))); - delete source[Two][ALL_KEYWORD_1]; - } - - if (Two in source && ALL_KEYWORD_2 in source[Two]) { - level[Two] = override_1(level[Two], defaults(Two, normalizeValue(source[Two][ALL_KEYWORD_2]))); - delete source[Two][ALL_KEYWORD_2]; - } - - if (Two in source) { - level[Two] = override_1(level[Two], source[Two]); - } else { - delete level[Two]; - } - - return level; -} - -function defaults(level, value) { - var options = override_1(DEFAULTS$1[level], {}); - var key; - - for (key in options) { - if (typeof options[key] == 'boolean') { - options[key] = value; - } - } - - return options; -} - -function normalizeValue(value) { - switch (value) { - case FALSE_KEYWORD_1: - case FALSE_KEYWORD_2: - return false; - case TRUE_KEYWORD_1: - case TRUE_KEYWORD_2: - return true; - default: - return value; - } -} - -function covertValuesToHashes(source) { - var clonedSource = override_1(source, {}); - var level; - var i; - - for (i = 0; i <= 2; i++) { - level = '' + i; - - if (level in clonedSource && (clonedSource[level] === undefined || clonedSource[level] === false)) { - delete clonedSource[level]; - } - - if (level in clonedSource && clonedSource[level] === true) { - clonedSource[level] = {}; - } - - if (level in clonedSource && typeof clonedSource[level] == 'string') { - clonedSource[level] = covertToHash(clonedSource[level], level); - } - } - - return clonedSource; -} - -function covertToHash(asString, level) { - return asString - .split(OPTION_SEPARATOR) - .reduce(function (accumulator, directive) { - var parts = directive.split(OPTION_VALUE_SEPARATOR); - var name = parts[0]; - var value = parts[1]; - var normalizedValue = normalizeValue(value); - - if (ALL_KEYWORD_1 == name || ALL_KEYWORD_2 == name) { - accumulator = override_1(accumulator, defaults(level, normalizedValue)); - } else { - accumulator[name] = normalizedValue; - } - - return accumulator; - }, {}); -} - -var optimizationLevel = { - OptimizationLevel: OptimizationLevel$6, - optimizationLevelFrom: optimizationLevelFrom, -}; - -function split(value, separator) { - var openLevel = marker.OPEN_ROUND_BRACKET; - var closeLevel = marker.CLOSE_ROUND_BRACKET; - var level = 0; - var cursor = 0; - var lastStart = 0; - var lastValue; - var lastCharacter; - var len = value.length; - var parts = []; - - if (value.indexOf(separator) == -1) { - return [value]; - } - - if (value.indexOf(openLevel) == -1) { - return value.split(separator); - } - - while (cursor < len) { - if (value[cursor] == openLevel) { - level++; - } else if (value[cursor] == closeLevel) { - level--; - } - - if (level === 0 && cursor > 0 && cursor + 1 < len && value[cursor] == separator) { - parts.push(value.substring(lastStart, cursor)); - lastStart = cursor + 1; - } - - cursor++; - } - - if (lastStart < cursor + 1) { - lastValue = value.substring(lastStart); - lastCharacter = lastValue[lastValue.length - 1]; - if (lastCharacter == separator) { - lastValue = lastValue.substring(0, lastValue.length - 1); - } - - parts.push(lastValue); - } - - return parts; -} - -var split_1 = split; - -var emptyCharacter = ''; - -var Breaks = format.Breaks; -var Spaces = format.Spaces; - - - - -function supportsAfterClosingBrace(token) { - return token[1][1] == 'background' || token[1][1] == 'transform' || token[1][1] == 'src'; -} - -function afterClosingBrace(token, valueIndex) { - return token[valueIndex][1][token[valueIndex][1].length - 1] == marker.CLOSE_ROUND_BRACKET; -} - -function afterComma(token, valueIndex) { - return token[valueIndex][1] == marker.COMMA; -} - -function afterSlash(token, valueIndex) { - return token[valueIndex][1] == marker.FORWARD_SLASH; -} - -function beforeComma(token, valueIndex) { - return token[valueIndex + 1] && token[valueIndex + 1][1] == marker.COMMA; -} - -function beforeSlash(token, valueIndex) { - return token[valueIndex + 1] && token[valueIndex + 1][1] == marker.FORWARD_SLASH; -} - -function inFilter(token) { - return token[1][1] == 'filter' || token[1][1] == '-ms-filter'; -} - -function disallowsSpace(context, token, valueIndex) { - return !context.spaceAfterClosingBrace && supportsAfterClosingBrace(token) && afterClosingBrace(token, valueIndex) || - beforeSlash(token, valueIndex) || - afterSlash(token, valueIndex) || - beforeComma(token, valueIndex) || - afterComma(token, valueIndex); -} - -function rules$1(context, tokens) { - var store = context.store; - - for (var i = 0, l = tokens.length; i < l; i++) { - store(context, tokens[i]); - - if (i < l - 1) { - store(context, comma(context)); - } - } -} - -function body$1(context, tokens) { - var lastPropertyAt = lastPropertyIndex(tokens); - - for (var i = 0, l = tokens.length; i < l; i++) { - property$1(context, tokens, i, lastPropertyAt); - } -} - -function lastPropertyIndex(tokens) { - var index = tokens.length - 1; - - for (; index >= 0; index--) { - if (tokens[index][0] != token.COMMENT) { - break; - } - } - - return index; -} - -function property$1(context, tokens, position, lastPropertyAt) { - var store = context.store; - var token$1 = tokens[position]; - - var propertyValue = token$1[2]; - var isPropertyBlock = propertyValue && propertyValue[0] === token.PROPERTY_BLOCK; - - var needsSemicolon; - if ( context.format ) { - if ( context.format.semicolonAfterLastProperty || isPropertyBlock ) { - needsSemicolon = true; - } else if ( position < lastPropertyAt ) { - needsSemicolon = true; - } else { - needsSemicolon = false; - } - } else { - needsSemicolon = position < lastPropertyAt || isPropertyBlock; - } - - var isLast = position === lastPropertyAt; - - switch (token$1[0]) { - case token.AT_RULE: - store(context, token$1); - store(context, semicolon(context, Breaks.AfterProperty, false)); - break; - case token.AT_RULE_BLOCK: - rules$1(context, token$1[1]); - store(context, openBrace(context, Breaks.AfterRuleBegins, true)); - body$1(context, token$1[2]); - store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast)); - break; - case token.COMMENT: - store(context, token$1); - break; - case token.PROPERTY: - store(context, token$1[1]); - store(context, colon(context)); - if (propertyValue) { - value$1(context, token$1); - } - store(context, needsSemicolon ? semicolon(context, Breaks.AfterProperty, isLast) : emptyCharacter); - break; - case token.RAW: - store(context, token$1); - } -} - -function value$1(context, token$1) { - var store = context.store; - var j, m; - - if (token$1[2][0] == token.PROPERTY_BLOCK) { - store(context, openBrace(context, Breaks.AfterBlockBegins, false)); - body$1(context, token$1[2][1]); - store(context, closeBrace(context, Breaks.AfterBlockEnds, false, true)); - } else { - for (j = 2, m = token$1.length; j < m; j++) { - store(context, token$1[j]); - - if (j < m - 1 && (inFilter(token$1) || !disallowsSpace(context, token$1, j))) { - store(context, marker.SPACE); - } - } - } -} - -function allowsBreak(context, where) { - return context.format && context.format.breaks[where]; -} - -function allowsSpace(context, where) { - return context.format && context.format.spaces[where]; -} - -function openBrace(context, where, needsPrefixSpace) { - if (context.format) { - context.indentBy += context.format.indentBy; - context.indentWith = context.format.indentWith.repeat(context.indentBy); - return (needsPrefixSpace && allowsSpace(context, Spaces.BeforeBlockBegins) ? marker.SPACE : emptyCharacter) + - marker.OPEN_CURLY_BRACKET + - (allowsBreak(context, where) ? context.format.breakWith : emptyCharacter) + - context.indentWith; - } else { - return marker.OPEN_CURLY_BRACKET; - } -} - -function closeBrace(context, where, beforeBlockEnd, isLast) { - if (context.format) { - context.indentBy -= context.format.indentBy; - context.indentWith = context.format.indentWith.repeat(context.indentBy); - return (allowsBreak(context, Breaks.AfterProperty) || beforeBlockEnd && allowsBreak(context, Breaks.BeforeBlockEnds) ? context.format.breakWith : emptyCharacter) + - context.indentWith + - marker.CLOSE_CURLY_BRACKET + - (isLast ? emptyCharacter : (allowsBreak(context, where) ? context.format.breakWith : emptyCharacter) + context.indentWith); - } else { - return marker.CLOSE_CURLY_BRACKET; - } -} - -function colon(context) { - return context.format ? - marker.COLON + (allowsSpace(context, Spaces.BeforeValue) ? marker.SPACE : emptyCharacter) : - marker.COLON; -} - -function semicolon(context, where, isLast) { - return context.format ? - marker.SEMICOLON + (isLast || !allowsBreak(context, where) ? emptyCharacter : context.format.breakWith + context.indentWith) : - marker.SEMICOLON; -} - -function comma(context) { - return context.format ? - marker.COMMA + (allowsBreak(context, Breaks.BetweenSelectors) ? context.format.breakWith : emptyCharacter) + context.indentWith : - marker.COMMA; -} - -function all$4(context, tokens) { - var store = context.store; - var token$1; - var isLast; - var i, l; - - for (i = 0, l = tokens.length; i < l; i++) { - token$1 = tokens[i]; - isLast = i == l - 1; - - switch (token$1[0]) { - case token.AT_RULE: - store(context, token$1); - store(context, semicolon(context, Breaks.AfterAtRule, isLast)); - break; - case token.AT_RULE_BLOCK: - rules$1(context, token$1[1]); - store(context, openBrace(context, Breaks.AfterRuleBegins, true)); - body$1(context, token$1[2]); - store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast)); - break; - case token.NESTED_BLOCK: - rules$1(context, token$1[1]); - store(context, openBrace(context, Breaks.AfterBlockBegins, true)); - all$4(context, token$1[2]); - store(context, closeBrace(context, Breaks.AfterBlockEnds, true, isLast)); - break; - case token.COMMENT: - store(context, token$1); - store(context, allowsBreak(context, Breaks.AfterComment) ? context.format.breakWith : emptyCharacter); - break; - case token.RAW: - store(context, token$1); - break; - case token.RULE: - rules$1(context, token$1[1]); - store(context, openBrace(context, Breaks.AfterRuleBegins, true)); - body$1(context, token$1[2]); - store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast)); - break; - } - } -} - -var helpers = { - all: all$4, - body: body$1, - property: property$1, - rules: rules$1, - value: value$1 -}; - -function store$2(serializeContext, token) { - serializeContext.output.push(typeof token == 'string' ? token : token[1]); -} - -function context() { - var newContext = { - output: [], - store: store$2 - }; - - return newContext; -} - -function all$3(tokens) { - var oneTimeContext = context(); - helpers.all(oneTimeContext, tokens); - return oneTimeContext.output.join(''); -} - -function body(tokens) { - var oneTimeContext = context(); - helpers.body(oneTimeContext, tokens); - return oneTimeContext.output.join(''); -} - -function property(tokens, position) { - var oneTimeContext = context(); - helpers.property(oneTimeContext, tokens, position, true); - return oneTimeContext.output.join(''); -} - -function rules(tokens) { - var oneTimeContext = context(); - helpers.rules(oneTimeContext, tokens); - return oneTimeContext.output.join(''); -} - -function value(tokens) { - var oneTimeContext = context(); - helpers.value(oneTimeContext, tokens); - return oneTimeContext.output.join(''); -} - -var oneTime = { - all: all$3, - body: body, - property: property, - rules: rules, - value: value -}; - -var wrapForOptimizing$2 = wrapForOptimizing$3.all; - -var OptimizationLevel$5 = optimizationLevel.OptimizationLevel; - - - - - - - -var serializeRules$9 = oneTime.rules; - -var IgnoreProperty = 'ignore-property'; - -var CHARSET_TOKEN = '@charset'; -var CHARSET_REGEXP = new RegExp('^' + CHARSET_TOKEN, 'i'); - -var DEFAULT_ROUNDING_PRECISION = roundingPrecision.DEFAULT; - -var WHOLE_PIXEL_VALUE = /(?:^|\s|\()(-?\d+)px/; -var TIME_VALUE = /^(\-?[\d\.]+)(m?s)$/; - -var HEX_VALUE_PATTERN = /[0-9a-f]/i; -var PROPERTY_NAME_PATTERN = /^(?:\-chrome\-|\-[\w\-]+\w|\w[\w\-]+\w|\-\-\S+)$/; -var IMPORT_PREFIX_PATTERN$2 = /^@import/i; -var QUOTED_PATTERN = /^('.*'|".*")$/; -var QUOTED_BUT_SAFE_PATTERN = /^['"][a-zA-Z][a-zA-Z\d\-_]+['"]$/; -var URL_PREFIX_PATTERN$2 = /^url\(/i; -var LOCAL_PREFIX_PATTERN = /^local\(/i; -var VARIABLE_NAME_PATTERN = /^--\S+$/; - -function isLocal(value){ - return LOCAL_PREFIX_PATTERN.test(value); -} - -function isNegative(value) { - return value && value[1][0] == '-' && parseFloat(value[1]) < 0; -} - -function isQuoted(value) { - return QUOTED_PATTERN.test(value); -} - -function isUrl$1(value) { - return URL_PREFIX_PATTERN$2.test(value); -} - -function normalizeUrl(value) { - return value - .replace(URL_PREFIX_PATTERN$2, 'url(') - .replace(/\\?\n|\\?\r\n/g, ''); -} - -function optimizeBackground(property) { - var values = property.value; - - if (values.length == 1 && values[0][1] == 'none') { - values[0][1] = '0 0'; - } - - if (values.length == 1 && values[0][1] == 'transparent') { - values[0][1] = '0 0'; - } -} - -function optimizeBorderRadius(property) { - var values = property.value; - var spliceAt; - - if (values.length == 3 && values[1][1] == '/' && values[0][1] == values[2][1]) { - spliceAt = 1; - } else if (values.length == 5 && values[2][1] == '/' && values[0][1] == values[3][1] && values[1][1] == values[4][1]) { - spliceAt = 2; - } else if (values.length == 7 && values[3][1] == '/' && values[0][1] == values[4][1] && values[1][1] == values[5][1] && values[2][1] == values[6][1]) { - spliceAt = 3; - } else if (values.length == 9 && values[4][1] == '/' && values[0][1] == values[5][1] && values[1][1] == values[6][1] && values[2][1] == values[7][1] && values[3][1] == values[8][1]) { - spliceAt = 4; - } - - if (spliceAt) { - property.value.splice(spliceAt); - property.dirty = true; - } -} - -/** - * @param {string} name - * @param {string} value - * @param {Object} compatibility - * @return {string} - */ -function optimizeColors(name, value, compatibility) { - if (!value.match(/#|rgb|hsl/gi)) { - return shortenHex_1(value); - } - - value = value - .replace(/(rgb|hsl)a?\((\-?\d+),(\-?\d+\%?),(\-?\d+\%?),(0*[1-9]+[0-9]*(\.?\d*)?)\)/gi, function (match, colorFn, p1, p2, p3, alpha) { - return (parseInt(alpha, 10) >= 1 ? colorFn + '(' + [p1,p2,p3].join(',') + ')' : match); - }) - .replace(/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/gi, function (match, red, green, blue) { - return shortenRgb_1(red, green, blue); - }) - .replace(/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/gi, function (match, hue, saturation, lightness) { - return shortenHsl_1(hue, saturation, lightness); - }) - .replace(/(^|[^='"])#([0-9a-f]{6})/gi, function (match, prefix, color, at, inputValue) { - var suffix = inputValue[at + match.length]; - - if (suffix && HEX_VALUE_PATTERN.test(suffix)) { - return match; - } else if (color[0] == color[1] && color[2] == color[3] && color[4] == color[5]) { - return (prefix + '#' + color[0] + color[2] + color[4]).toLowerCase(); - } else { - return (prefix + '#' + color).toLowerCase(); - } - }) - .replace(/(^|[^='"])#([0-9a-f]{3})/gi, function (match, prefix, color) { - return prefix + '#' + color.toLowerCase(); - }) - .replace(/(rgb|rgba|hsl|hsla)\(([^\)]+)\)/gi, function (match, colorFunction, colorDef) { - var tokens = colorDef.split(','); - var colorFnLowercase = colorFunction && colorFunction.toLowerCase(); - var applies = (colorFnLowercase == 'hsl' && tokens.length == 3) || - (colorFnLowercase == 'hsla' && tokens.length == 4) || - (colorFnLowercase == 'rgb' && tokens.length === 3 && colorDef.indexOf('%') > 0) || - (colorFnLowercase == 'rgba' && tokens.length == 4 && colorDef.indexOf('%') > 0); - - if (!applies) { - return match; - } - - if (tokens[1].indexOf('%') == -1) { - tokens[1] += '%'; - } - - if (tokens[2].indexOf('%') == -1) { - tokens[2] += '%'; - } - - return colorFunction + '(' + tokens.join(',') + ')'; - }); - - if (compatibility.colors.opacity && name.indexOf('background') == -1) { - value = value.replace(/(?:rgba|hsla)\(0,0%?,0%?,0\)/g, function (match) { - if (split_1(value, ',').pop().indexOf('gradient(') > -1) { - return match; - } - - return 'transparent'; - }); - } - - return shortenHex_1(value); -} - -function optimizeFilter(property) { - if (property.value.length == 1) { - property.value[0][1] = property.value[0][1].replace(/progid:DXImageTransform\.Microsoft\.(Alpha|Chroma)(\W)/, function (match, filter, suffix) { - return filter.toLowerCase() + suffix; - }); - } - - property.value[0][1] = property.value[0][1] - .replace(/,(\S)/g, ', $1') - .replace(/ ?= ?/g, '='); -} - -function optimizeFontWeight(property, atIndex) { - var value = property.value[atIndex][1]; - - if (value == 'normal') { - value = '400'; - } else if (value == 'bold') { - value = '700'; - } - - property.value[atIndex][1] = value; -} - -function optimizeMultipleZeros(property) { - var values = property.value; - var spliceAt; - - if (values.length == 4 && values[0][1] === '0' && values[1][1] === '0' && values[2][1] === '0' && values[3][1] === '0') { - if (property.name.indexOf('box-shadow') > -1) { - spliceAt = 2; - } else { - spliceAt = 1; - } - } - - if (spliceAt) { - property.value.splice(spliceAt); - property.dirty = true; - } -} - -function optimizeOutline(property) { - var values = property.value; - - if (values.length == 1 && values[0][1] == 'none') { - values[0][1] = '0'; - } -} - -function optimizePixelLengths(_, value, compatibility) { - if (!WHOLE_PIXEL_VALUE.test(value)) { - return value; - } - - return value.replace(WHOLE_PIXEL_VALUE, function (match, val) { - var newValue; - var intVal = parseInt(val); - - if (intVal === 0) { - return match; - } - - if (compatibility.properties.shorterLengthUnits && compatibility.units.pt && intVal * 3 % 4 === 0) { - newValue = intVal * 3 / 4 + 'pt'; - } - - if (compatibility.properties.shorterLengthUnits && compatibility.units.pc && intVal % 16 === 0) { - newValue = intVal / 16 + 'pc'; - } - - if (compatibility.properties.shorterLengthUnits && compatibility.units.in && intVal % 96 === 0) { - newValue = intVal / 96 + 'in'; - } - - if (newValue) { - newValue = match.substring(0, match.indexOf(val)) + newValue; - } - - return newValue && newValue.length < match.length ? newValue : match; - }); -} - -function optimizePrecision(_, value, precisionOptions) { - if (!precisionOptions.enabled || value.indexOf('.') === -1) { - return value; - } - - return value - .replace(precisionOptions.decimalPointMatcher, '$1$2$3') - .replace(precisionOptions.zeroMatcher, function (match, integerPart, fractionPart, unit) { - var multiplier = precisionOptions.units[unit].multiplier; - var parsedInteger = parseInt(integerPart); - var integer = isNaN(parsedInteger) ? 0 : parsedInteger; - var fraction = parseFloat(fractionPart); - - return Math.round((integer + fraction) * multiplier) / multiplier + unit; - }); -} - -function optimizeTimeUnits(_, value) { - if (!TIME_VALUE.test(value)) - return value; - - return value.replace(TIME_VALUE, function (match, val, unit) { - var newValue; - - if (unit == 'ms') { - newValue = parseInt(val) / 1000 + 's'; - } else if (unit == 's') { - newValue = parseFloat(val) * 1000 + 'ms'; - } - - return newValue.length < match.length ? newValue : match; - }); -} - -function optimizeUnits(name, value, unitsRegexp) { - if (/^(?:\-moz\-calc|\-webkit\-calc|calc|rgb|hsl|rgba|hsla)\(/.test(value)) { - return value; - } - - if (name == 'flex' || name == '-ms-flex' || name == '-webkit-flex' || name == 'flex-basis' || name == '-webkit-flex-basis') { - return value; - } - - if (value.indexOf('%') > 0 && (name == 'height' || name == 'max-height' || name == 'width' || name == 'max-width')) { - return value; - } - - return value - .replace(unitsRegexp, '$1' + '0' + '$2') - .replace(unitsRegexp, '$1' + '0' + '$2'); -} - -function optimizeWhitespace(name, value) { - if (name.indexOf('filter') > -1 || value.indexOf(' ') == -1 || value.indexOf('expression') === 0) { - return value; - } - - if (value.indexOf(marker.SINGLE_QUOTE) > -1 || value.indexOf(marker.DOUBLE_QUOTE) > -1) { - return value; - } - - value = value.replace(/\s+/g, ' '); - - if (value.indexOf('calc') > -1) { - value = value.replace(/\) ?\/ ?/g, ')/ '); - } - - return value - .replace(/(\(;?)\s+/g, '$1') - .replace(/\s+(;?\))/g, '$1') - .replace(/, /g, ','); -} - -function optimizeZeroDegUnit(_, value) { - if (value.indexOf('0deg') == -1) { - return value; - } - - return value.replace(/\(0deg\)/g, '(0)'); -} - -function optimizeZeroUnits(name, value) { - if (value.indexOf('0') == -1) { - return value; - } - - if (value.indexOf('-') > -1) { - value = value - .replace(/([^\w\d\-]|^)\-0([^\.]|$)/g, '$10$2') - .replace(/([^\w\d\-]|^)\-0([^\.]|$)/g, '$10$2'); - } - - return value - .replace(/(^|\s)0+([1-9])/g, '$1$2') - .replace(/(^|\D)\.0+(\D|$)/g, '$10$2') - .replace(/(^|\D)\.0+(\D|$)/g, '$10$2') - .replace(/\.([1-9]*)0+(\D|$)/g, function (match, nonZeroPart, suffix) { - return (nonZeroPart.length > 0 ? '.' : '') + nonZeroPart + suffix; - }) - .replace(/(^|\D)0\.(\d)/g, '$1.$2'); -} - -function removeQuotes(name, value) { - if (name == 'content' || name.indexOf('font-variation-settings') > -1 || name.indexOf('font-feature-settings') > -1 || name == 'grid' || name.indexOf('grid-') > -1) { - return value; - } - - return QUOTED_BUT_SAFE_PATTERN.test(value) ? - value.substring(1, value.length - 1) : - value; -} - -function removeUrlQuotes(value) { - return /^url\(['"].+['"]\)$/.test(value) && !/^url\(['"].*[\*\s\(\)'"].*['"]\)$/.test(value) && !/^url\(['"]data:[^;]+;charset/.test(value) ? - value.replace(/["']/g, '') : - value; -} - -function transformValue(propertyName, propertyValue, rule, transformCallback) { - var selector = serializeRules$9(rule); - var transformedValue = transformCallback(propertyName, propertyValue, selector); - - if (transformedValue === undefined) { - return propertyValue; - } else if (transformedValue === false) { - return IgnoreProperty; - } else { - return transformedValue; - } -} - -// - -function optimizeBody(rule, properties, context) { - var options = context.options; - var levelOptions = options.level[OptimizationLevel$5.One]; - var property, name, type, value; - var valueIsUrl; - var propertyToken; - var _properties = wrapForOptimizing$2(properties, true); - - propertyLoop: - for (var i = 0, l = _properties.length; i < l; i++) { - property = _properties[i]; - name = property.name; - - if (!PROPERTY_NAME_PATTERN.test(name)) { - propertyToken = property.all[property.position]; - context.warnings.push('Invalid property name \'' + name + '\' at ' + formatPosition_1(propertyToken[1][2][0]) + '. Ignoring.'); - property.unused = true; - } - - if (property.value.length === 0) { - propertyToken = property.all[property.position]; - context.warnings.push('Empty property \'' + name + '\' at ' + formatPosition_1(propertyToken[1][2][0]) + '. Ignoring.'); - property.unused = true; - } - - if (property.hack && ( - (property.hack[0] == hack.ASTERISK || property.hack[0] == hack.UNDERSCORE) && !options.compatibility.properties.iePrefixHack || - property.hack[0] == hack.BACKSLASH && !options.compatibility.properties.ieSuffixHack || - property.hack[0] == hack.BANG && !options.compatibility.properties.ieBangHack)) { - property.unused = true; - } - - if (levelOptions.removeNegativePaddings && name.indexOf('padding') === 0 && (isNegative(property.value[0]) || isNegative(property.value[1]) || isNegative(property.value[2]) || isNegative(property.value[3]))) { - property.unused = true; - } - - if (!options.compatibility.properties.ieFilters && isLegacyFilter(property)) { - property.unused = true; - } - - if (property.unused) { - continue; - } - - if (property.block) { - optimizeBody(rule, property.value[0][1], context); - continue; - } - - if (VARIABLE_NAME_PATTERN.test(name)) { - continue; - } - - for (var j = 0, m = property.value.length; j < m; j++) { - type = property.value[j][0]; - value = property.value[j][1]; - valueIsUrl = isUrl$1(value); - - if (type == token.PROPERTY_BLOCK) { - property.unused = true; - context.warnings.push('Invalid value token at ' + formatPosition_1(value[0][1][2][0]) + '. Ignoring.'); - break; - } - - if (valueIsUrl && !context.validator.isUrl(value)) { - property.unused = true; - context.warnings.push('Broken URL \'' + value + '\' at ' + formatPosition_1(property.value[j][2][0]) + '. Ignoring.'); - break; - } - - if (valueIsUrl) { - value = levelOptions.normalizeUrls ? - normalizeUrl(value) : - value; - value = !options.compatibility.properties.urlQuotes ? - removeUrlQuotes(value) : - value; - } else if (isQuoted(value) || isLocal(value)) { - value = levelOptions.removeQuotes ? - removeQuotes(name, value) : - value; - } else { - value = levelOptions.removeWhitespace ? - optimizeWhitespace(name, value) : - value; - value = optimizePrecision(name, value, options.precision); - value = optimizePixelLengths(name, value, options.compatibility); - value = levelOptions.replaceTimeUnits ? - optimizeTimeUnits(name, value) : - value; - value = levelOptions.replaceZeroUnits ? - optimizeZeroUnits(name, value) : - value; - - if (options.compatibility.properties.zeroUnits) { - value = optimizeZeroDegUnit(name, value); - value = optimizeUnits(name, value, options.unitsRegexp); - } - - if (options.compatibility.properties.colors) { - value = optimizeColors(name, value, options.compatibility); - } - } - - value = transformValue(name, value, rule, levelOptions.transform); - - if (value === IgnoreProperty) { - property.unused = true; - continue propertyLoop; - } - - property.value[j][1] = value; - } - - if (levelOptions.replaceMultipleZeros) { - optimizeMultipleZeros(property); - } - - if (name == 'background' && levelOptions.optimizeBackground) { - optimizeBackground(property); - } else if (name.indexOf('border') === 0 && name.indexOf('radius') > 0 && levelOptions.optimizeBorderRadius) { - optimizeBorderRadius(property); - } else if (name == 'filter'&& levelOptions.optimizeFilter && options.compatibility.properties.ieFilters) { - optimizeFilter(property); - } else if (name == 'font-weight' && levelOptions.optimizeFontWeight) { - optimizeFontWeight(property, 0); - } else if (name == 'outline' && levelOptions.optimizeOutline) { - optimizeOutline(property); - } - } - - restoreFromOptimizing_1(_properties); - removeUnused_1(_properties); - removeComments(properties, options); -} - -function removeComments(tokens, options) { - var token$1; - var i; - - for (i = 0; i < tokens.length; i++) { - token$1 = tokens[i]; - - if (token$1[0] != token.COMMENT) { - continue; - } - - optimizeComment(token$1, options); - - if (token$1[1].length === 0) { - tokens.splice(i, 1); - i--; - } - } -} - -function optimizeComment(token, options) { - if (token[1][2] == marker.EXCLAMATION && (options.level[OptimizationLevel$5.One].specialComments == 'all' || options.commentsKept < options.level[OptimizationLevel$5.One].specialComments)) { - options.commentsKept++; - return; - } - - token[1] = []; -} - -function cleanupCharsets(tokens) { - var hasCharset = false; - - for (var i = 0, l = tokens.length; i < l; i++) { - var token$1 = tokens[i]; - - if (token$1[0] != token.AT_RULE) - continue; - - if (!CHARSET_REGEXP.test(token$1[1])) - continue; - - if (hasCharset || token$1[1].indexOf(CHARSET_TOKEN) == -1) { - tokens.splice(i, 1); - i--; - l--; - } else { - hasCharset = true; - tokens.splice(i, 1); - tokens.unshift([token.AT_RULE, token$1[1].replace(CHARSET_REGEXP, CHARSET_TOKEN)]); - } - } -} - -function buildUnitRegexp(options) { - var units = ['px', 'em', 'ex', 'cm', 'mm', 'in', 'pt', 'pc', '%']; - var otherUnits = ['ch', 'rem', 'vh', 'vm', 'vmax', 'vmin', 'vw']; - - otherUnits.forEach(function (unit) { - if (options.compatibility.units[unit]) { - units.push(unit); - } - }); - - return new RegExp('(^|\\s|\\(|,)0(?:' + units.join('|') + ')(\\W|$)', 'g'); -} - -function buildPrecisionOptions(roundingPrecision) { - var precisionOptions = { - matcher: null, - units: {}, - }; - var optimizable = []; - var unit; - var value; - - for (unit in roundingPrecision) { - value = roundingPrecision[unit]; - - if (value != DEFAULT_ROUNDING_PRECISION) { - precisionOptions.units[unit] = {}; - precisionOptions.units[unit].value = value; - precisionOptions.units[unit].multiplier = Math.pow(10, value); - - optimizable.push(unit); - } - } - - if (optimizable.length > 0) { - precisionOptions.enabled = true; - precisionOptions.decimalPointMatcher = new RegExp('(\\d)\\.($|' + optimizable.join('|') + ')($|\W)', 'g'); - precisionOptions.zeroMatcher = new RegExp('(\\d*)(\\.\\d+)(' + optimizable.join('|') + ')', 'g'); - } - - return precisionOptions; -} - -function isImport$1(token) { - return IMPORT_PREFIX_PATTERN$2.test(token[1]); -} - -function isLegacyFilter(property) { - var value; - - if (property.name == 'filter' || property.name == '-ms-filter') { - value = property.value[0][1]; - - return value.indexOf('progid') > -1 || - value.indexOf('alpha') === 0 || - value.indexOf('chroma') === 0; - } else { - return false; - } -} - -function level1Optimize(tokens, context) { - var options = context.options; - var levelOptions = options.level[OptimizationLevel$5.One]; - var ie7Hack = options.compatibility.selectors.ie7Hack; - var adjacentSpace = options.compatibility.selectors.adjacentSpace; - var spaceAfterClosingBrace = options.compatibility.properties.spaceAfterClosingBrace; - var format = options.format; - var mayHaveCharset = false; - var afterRules = false; - - options.unitsRegexp = options.unitsRegexp || buildUnitRegexp(options); - options.precision = options.precision || buildPrecisionOptions(levelOptions.roundingPrecision); - options.commentsKept = options.commentsKept || 0; - - for (var i = 0, l = tokens.length; i < l; i++) { - var token$1 = tokens[i]; - - switch (token$1[0]) { - case token.AT_RULE: - token$1[1] = isImport$1(token$1) && afterRules ? '' : token$1[1]; - token$1[1] = levelOptions.tidyAtRules ? tidyAtRule_1(token$1[1]) : token$1[1]; - mayHaveCharset = true; - break; - case token.AT_RULE_BLOCK: - optimizeBody(token$1[1], token$1[2], context); - afterRules = true; - break; - case token.NESTED_BLOCK: - token$1[1] = levelOptions.tidyBlockScopes ? tidyBlock_1(token$1[1], spaceAfterClosingBrace) : token$1[1]; - level1Optimize(token$1[2], context); - afterRules = true; - break; - case token.COMMENT: - optimizeComment(token$1, options); - break; - case token.RULE: - token$1[1] = levelOptions.tidySelectors ? tidyRules_1(token$1[1], !ie7Hack, adjacentSpace, format, context.warnings) : token$1[1]; - token$1[1] = token$1[1].length > 1 ? sortSelectors_1(token$1[1], levelOptions.selectorsSortingMethod) : token$1[1]; - optimizeBody(token$1[1], token$1[2], context); - afterRules = true; - break; - } - - if (token$1[0] == token.COMMENT && token$1[1].length === 0 || levelOptions.removeEmpty && (token$1[1].length === 0 || (token$1[2] && token$1[2].length === 0))) { - tokens.splice(i, 1); - i--; - l--; - } - } - - if (levelOptions.cleanupCharsets && mayHaveCharset) { - cleanupCharsets(tokens); - } - - return tokens; -} - -var optimize$2 = level1Optimize; - -var DEEP_SELECTOR_PATTERN = /\/deep\//; -var DOUBLE_COLON_PATTERN = /^::/; -var NOT_PSEUDO = ':not'; -var PSEUDO_CLASSES_WITH_ARGUMENTS = [ - ':dir', - ':lang', - ':not', - ':nth-child', - ':nth-last-child', - ':nth-last-of-type', - ':nth-of-type' -]; -var RELATION_PATTERN = /[>\+~]/; -var UNMIXABLE_PSEUDO_CLASSES = [ - ':after', - ':before', - ':first-letter', - ':first-line', - ':lang' -]; -var UNMIXABLE_PSEUDO_ELEMENTS = [ - '::after', - '::before', - '::first-letter', - '::first-line' -]; - -var Level$1 = { - DOUBLE_QUOTE: 'double-quote', - SINGLE_QUOTE: 'single-quote', - ROOT: 'root' -}; - -function isMergeable(selector, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) { - var singleSelectors = split_1(selector, marker.COMMA); - var singleSelector; - var i, l; - - for (i = 0, l = singleSelectors.length; i < l; i++) { - singleSelector = singleSelectors[i]; - - if (singleSelector.length === 0 || - isDeepSelector(singleSelector) || - (singleSelector.indexOf(marker.COLON) > -1 && !areMergeable(singleSelector, extractPseudoFrom(singleSelector), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging))) { - return false; - } - } - - return true; -} - -function isDeepSelector(selector) { - return DEEP_SELECTOR_PATTERN.test(selector); -} - -function extractPseudoFrom(selector) { - var list = []; - var character; - var buffer = []; - var level = Level$1.ROOT; - var roundBracketLevel = 0; - var isQuoted; - var isEscaped; - var isPseudo = false; - var isRelation; - var wasColon = false; - var index; - var len; - - for (index = 0, len = selector.length; index < len; index++) { - character = selector[index]; - - isRelation = !isEscaped && RELATION_PATTERN.test(character); - isQuoted = level == Level$1.DOUBLE_QUOTE || level == Level$1.SINGLE_QUOTE; - - if (isEscaped) { - buffer.push(character); - } else if (character == marker.DOUBLE_QUOTE && level == Level$1.ROOT) { - buffer.push(character); - level = Level$1.DOUBLE_QUOTE; - } else if (character == marker.DOUBLE_QUOTE && level == Level$1.DOUBLE_QUOTE) { - buffer.push(character); - level = Level$1.ROOT; - } else if (character == marker.SINGLE_QUOTE && level == Level$1.ROOT) { - buffer.push(character); - level = Level$1.SINGLE_QUOTE; - } else if (character == marker.SINGLE_QUOTE && level == Level$1.SINGLE_QUOTE) { - buffer.push(character); - level = Level$1.ROOT; - } else if (isQuoted) { - buffer.push(character); - } else if (character == marker.OPEN_ROUND_BRACKET) { - buffer.push(character); - roundBracketLevel++; - } else if (character == marker.CLOSE_ROUND_BRACKET && roundBracketLevel == 1 && isPseudo) { - buffer.push(character); - list.push(buffer.join('')); - roundBracketLevel--; - buffer = []; - isPseudo = false; - } else if (character == marker.CLOSE_ROUND_BRACKET) { - buffer.push(character); - roundBracketLevel--; - } else if (character == marker.COLON && roundBracketLevel === 0 && isPseudo && !wasColon) { - list.push(buffer.join('')); - buffer = []; - buffer.push(character); - } else if (character == marker.COLON && roundBracketLevel === 0 && !wasColon) { - buffer = []; - buffer.push(character); - isPseudo = true; - } else if (character == marker.SPACE && roundBracketLevel === 0 && isPseudo) { - list.push(buffer.join('')); - buffer = []; - isPseudo = false; - } else if (isRelation && roundBracketLevel === 0 && isPseudo) { - list.push(buffer.join('')); - buffer = []; - isPseudo = false; - } else { - buffer.push(character); - } - - isEscaped = character == marker.BACK_SLASH; - wasColon = character == marker.COLON; - } - - if (buffer.length > 0 && isPseudo) { - list.push(buffer.join('')); - } - - return list; -} - -function areMergeable(selector, matches, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) { - return areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) && - needArguments(matches) && - (matches.length < 2 || !someIncorrectlyChained(selector, matches)) && - (matches.length < 2 || multiplePseudoMerging && allMixable(matches)); -} - -function areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) { - var match; - var name; - var i, l; - - for (i = 0, l = matches.length; i < l; i++) { - match = matches[i]; - name = match.indexOf(marker.OPEN_ROUND_BRACKET) > -1 ? - match.substring(0, match.indexOf(marker.OPEN_ROUND_BRACKET)) : - match; - - if (mergeablePseudoClasses.indexOf(name) === -1 && mergeablePseudoElements.indexOf(name) === -1) { - return false; - } - } - - return true; -} - -function needArguments(matches) { - var match; - var name; - var bracketOpensAt; - var hasArguments; - var i, l; - - for (i = 0, l = matches.length; i < l; i++) { - match = matches[i]; - - bracketOpensAt = match.indexOf(marker.OPEN_ROUND_BRACKET); - hasArguments = bracketOpensAt > -1; - name = hasArguments ? - match.substring(0, bracketOpensAt) : - match; - - if (hasArguments && PSEUDO_CLASSES_WITH_ARGUMENTS.indexOf(name) == -1) { - return false; - } - - if (!hasArguments && PSEUDO_CLASSES_WITH_ARGUMENTS.indexOf(name) > -1) { - return false; - } - } - - return true; -} - -function someIncorrectlyChained(selector, matches) { - var positionInSelector = 0; - var match; - var matchAt; - var nextMatch; - var nextMatchAt; - var name; - var nextName; - var areChained; - var i, l; - - for (i = 0, l = matches.length; i < l; i++) { - match = matches[i]; - nextMatch = matches[i + 1]; - - if (!nextMatch) { - break; - } - - matchAt = selector.indexOf(match, positionInSelector); - nextMatchAt = selector.indexOf(match, matchAt + 1); - positionInSelector = nextMatchAt; - areChained = matchAt + match.length == nextMatchAt; - - if (areChained) { - name = match.indexOf(marker.OPEN_ROUND_BRACKET) > -1 ? - match.substring(0, match.indexOf(marker.OPEN_ROUND_BRACKET)) : - match; - nextName = nextMatch.indexOf(marker.OPEN_ROUND_BRACKET) > -1 ? - nextMatch.substring(0, nextMatch.indexOf(marker.OPEN_ROUND_BRACKET)) : - nextMatch; - - if (name != NOT_PSEUDO || nextName != NOT_PSEUDO) { - return true; - } - } - } - - return false; -} - -function allMixable(matches) { - var unmixableMatches = 0; - var match; - var i, l; - - for (i = 0, l = matches.length; i < l; i++) { - match = matches[i]; - - if (isPseudoElement(match)) { - unmixableMatches += UNMIXABLE_PSEUDO_ELEMENTS.indexOf(match) > -1 ? 1 : 0; - } else { - unmixableMatches += UNMIXABLE_PSEUDO_CLASSES.indexOf(match) > -1 ? 1 : 0; - } - - if (unmixableMatches > 1) { - return false; - } - } - - return true; -} - -function isPseudoElement(pseudo) { - return DOUBLE_COLON_PATTERN.test(pseudo); -} - -var isMergeable_1 = isMergeable; - -function everyValuesPair(fn, left, right) { - var leftSize = left.value.length; - var rightSize = right.value.length; - var total = Math.max(leftSize, rightSize); - var lowerBound = Math.min(leftSize, rightSize) - 1; - var leftValue; - var rightValue; - var position; - - for (position = 0; position < total; position++) { - leftValue = left.value[position] && left.value[position][1] || leftValue; - rightValue = right.value[position] && right.value[position][1] || rightValue; - - if (leftValue == marker.COMMA || rightValue == marker.COMMA) { - continue; - } - - if (!fn(leftValue, rightValue, position, position <= lowerBound)) { - return false; - } - } - - return true; -} - -var everyValuesPair_1 = everyValuesPair; - -function hasInherit(property) { - for (var i = property.value.length - 1; i >= 0; i--) { - if (property.value[i][1] == 'inherit') - return true; - } - - return false; -} - -var hasInherit_1 = hasInherit; - -function InvalidPropertyError(message) { - this.name = 'InvalidPropertyError'; - this.message = message; - this.stack = (new Error()).stack; -} - -InvalidPropertyError.prototype = Object.create(Error.prototype); -InvalidPropertyError.prototype.constructor = InvalidPropertyError; - -var invalidPropertyError = InvalidPropertyError; - -var wrapSingle$2 = wrapForOptimizing$3.single; - - - - - - -function _anyIsInherit(values) { - var i, l; - - for (i = 0, l = values.length; i < l; i++) { - if (values[i][1] == 'inherit') { - return true; - } - } - - return false; -} - -function _colorFilter(validator) { - return function (value) { - return value[1] == 'invert' || validator.isColor(value[1]) || validator.isPrefixed(value[1]); - }; -} - -function _styleFilter(validator) { - return function (value) { - return value[1] != 'inherit' && validator.isStyleKeyword(value[1]) && !validator.isColorFunction(value[1]); - }; -} - -function _wrapDefault(name, property, compactable) { - var descriptor = compactable[name]; - if (descriptor.doubleValues && descriptor.defaultValue.length == 2) { - return wrapSingle$2([ - token.PROPERTY, - [token.PROPERTY_NAME, name], - [token.PROPERTY_VALUE, descriptor.defaultValue[0]], - [token.PROPERTY_VALUE, descriptor.defaultValue[1]] - ]); - } else if (descriptor.doubleValues && descriptor.defaultValue.length == 1) { - return wrapSingle$2([ - token.PROPERTY, - [token.PROPERTY_NAME, name], - [token.PROPERTY_VALUE, descriptor.defaultValue[0]] - ]); - } else { - return wrapSingle$2([ - token.PROPERTY, - [token.PROPERTY_NAME, name], - [token.PROPERTY_VALUE, descriptor.defaultValue] - ]); - } -} - -function _widthFilter(validator) { - return function (value) { - return value[1] != 'inherit' && - (validator.isWidth(value[1]) || validator.isUnit(value[1]) && !validator.isDynamicUnit(value[1])) && - !validator.isStyleKeyword(value[1]) && - !validator.isColorFunction(value[1]); - }; -} - -function animation(property, compactable, validator) { - var duration = _wrapDefault(property.name + '-duration', property, compactable); - var timing = _wrapDefault(property.name + '-timing-function', property, compactable); - var delay = _wrapDefault(property.name + '-delay', property, compactable); - var iteration = _wrapDefault(property.name + '-iteration-count', property, compactable); - var direction = _wrapDefault(property.name + '-direction', property, compactable); - var fill = _wrapDefault(property.name + '-fill-mode', property, compactable); - var play = _wrapDefault(property.name + '-play-state', property, compactable); - var name = _wrapDefault(property.name + '-name', property, compactable); - var components = [duration, timing, delay, iteration, direction, fill, play, name]; - var values = property.value; - var value; - var durationSet = false; - var timingSet = false; - var delaySet = false; - var iterationSet = false; - var directionSet = false; - var fillSet = false; - var playSet = false; - var nameSet = false; - var i; - var l; - - if (property.value.length == 1 && property.value[0][1] == 'inherit') { - duration.value = timing.value = delay.value = iteration.value = direction.value = fill.value = play.value = name.value = property.value; - return components; - } - - if (values.length > 1 && _anyIsInherit(values)) { - throw new invalidPropertyError('Invalid animation values at ' + formatPosition_1(values[0][2][0]) + '. Ignoring.'); - } - - for (i = 0, l = values.length; i < l; i++) { - value = values[i]; - - if (validator.isTime(value[1]) && !durationSet) { - duration.value = [value]; - durationSet = true; - } else if (validator.isTime(value[1]) && !delaySet) { - delay.value = [value]; - delaySet = true; - } else if ((validator.isGlobal(value[1]) || validator.isTimingFunction(value[1])) && !timingSet) { - timing.value = [value]; - timingSet = true; - } else if ((validator.isAnimationIterationCountKeyword(value[1]) || validator.isPositiveNumber(value[1])) && !iterationSet) { - iteration.value = [value]; - iterationSet = true; - } else if (validator.isAnimationDirectionKeyword(value[1]) && !directionSet) { - direction.value = [value]; - directionSet = true; - } else if (validator.isAnimationFillModeKeyword(value[1]) && !fillSet) { - fill.value = [value]; - fillSet = true; - } else if (validator.isAnimationPlayStateKeyword(value[1]) && !playSet) { - play.value = [value]; - playSet = true; - } else if ((validator.isAnimationNameKeyword(value[1]) || validator.isIdentifier(value[1])) && !nameSet) { - name.value = [value]; - nameSet = true; - } else { - throw new invalidPropertyError('Invalid animation value at ' + formatPosition_1(value[2][0]) + '. Ignoring.'); - } - } - - return components; -} - -function background$1(property, compactable, validator) { - var image = _wrapDefault('background-image', property, compactable); - var position = _wrapDefault('background-position', property, compactable); - var size = _wrapDefault('background-size', property, compactable); - var repeat = _wrapDefault('background-repeat', property, compactable); - var attachment = _wrapDefault('background-attachment', property, compactable); - var origin = _wrapDefault('background-origin', property, compactable); - var clip = _wrapDefault('background-clip', property, compactable); - var color = _wrapDefault('background-color', property, compactable); - var components = [image, position, size, repeat, attachment, origin, clip, color]; - var values = property.value; - - var positionSet = false; - var clipSet = false; - var originSet = false; - var repeatSet = false; - - var anyValueSet = false; - - if (property.value.length == 1 && property.value[0][1] == 'inherit') { - // NOTE: 'inherit' is not a valid value for background-attachment - color.value = image.value = repeat.value = position.value = size.value = origin.value = clip.value = property.value; - return components; - } - - if (property.value.length == 1 && property.value[0][1] == '0 0') { - return components; - } - - for (var i = values.length - 1; i >= 0; i--) { - var value = values[i]; - - if (validator.isBackgroundAttachmentKeyword(value[1])) { - attachment.value = [value]; - anyValueSet = true; - } else if (validator.isBackgroundClipKeyword(value[1]) || validator.isBackgroundOriginKeyword(value[1])) { - if (clipSet) { - origin.value = [value]; - originSet = true; - } else { - clip.value = [value]; - clipSet = true; - } - anyValueSet = true; - } else if (validator.isBackgroundRepeatKeyword(value[1])) { - if (repeatSet) { - repeat.value.unshift(value); - } else { - repeat.value = [value]; - repeatSet = true; - } - anyValueSet = true; - } else if (validator.isBackgroundPositionKeyword(value[1]) || validator.isBackgroundSizeKeyword(value[1]) || validator.isUnit(value[1]) || validator.isDynamicUnit(value[1])) { - if (i > 0) { - var previousValue = values[i - 1]; - - if (previousValue[1] == marker.FORWARD_SLASH) { - size.value = [value]; - } else if (i > 1 && values[i - 2][1] == marker.FORWARD_SLASH) { - size.value = [previousValue, value]; - i -= 2; - } else { - if (!positionSet) - position.value = []; - - position.value.unshift(value); - positionSet = true; - } - } else { - if (!positionSet) - position.value = []; - - position.value.unshift(value); - positionSet = true; - } - anyValueSet = true; - } else if ((color.value[0][1] == compactable[color.name].defaultValue || color.value[0][1] == 'none') && (validator.isColor(value[1]) || validator.isPrefixed(value[1]))) { - color.value = [value]; - anyValueSet = true; - } else if (validator.isUrl(value[1]) || validator.isFunction(value[1])) { - image.value = [value]; - anyValueSet = true; - } - } - - if (clipSet && !originSet) - origin.value = clip.value.slice(0); - - if (!anyValueSet) { - throw new invalidPropertyError('Invalid background value at ' + formatPosition_1(values[0][2][0]) + '. Ignoring.'); - } - - return components; -} - -function borderRadius$1(property, compactable) { - var values = property.value; - var splitAt = -1; - - for (var i = 0, l = values.length; i < l; i++) { - if (values[i][1] == marker.FORWARD_SLASH) { - splitAt = i; - break; - } - } - - if (splitAt === 0 || splitAt === values.length - 1) { - throw new invalidPropertyError('Invalid border-radius value at ' + formatPosition_1(values[0][2][0]) + '. Ignoring.'); - } - - var target = _wrapDefault(property.name, property, compactable); - target.value = splitAt > -1 ? - values.slice(0, splitAt) : - values.slice(0); - target.components = fourValues$1(target, compactable); - - var remainder = _wrapDefault(property.name, property, compactable); - remainder.value = splitAt > -1 ? - values.slice(splitAt + 1) : - values.slice(0); - remainder.components = fourValues$1(remainder, compactable); - - for (var j = 0; j < 4; j++) { - target.components[j].multiplex = true; - target.components[j].value = target.components[j].value.concat(remainder.components[j].value); - } - - return target.components; -} - -function font$1(property, compactable, validator) { - var style = _wrapDefault('font-style', property, compactable); - var variant = _wrapDefault('font-variant', property, compactable); - var weight = _wrapDefault('font-weight', property, compactable); - var stretch = _wrapDefault('font-stretch', property, compactable); - var size = _wrapDefault('font-size', property, compactable); - var height = _wrapDefault('line-height', property, compactable); - var family = _wrapDefault('font-family', property, compactable); - var components = [style, variant, weight, stretch, size, height, family]; - var values = property.value; - var fuzzyMatched = 4; // style, variant, weight, and stretch - var index = 0; - var isStretchSet = false; - var isStretchValid; - var isStyleSet = false; - var isStyleValid; - var isVariantSet = false; - var isVariantValid; - var isWeightSet = false; - var isWeightValid; - var isSizeSet = false; - var appendableFamilyName = false; - - if (!values[index]) { - throw new invalidPropertyError('Missing font values at ' + formatPosition_1(property.all[property.position][1][2][0]) + '. Ignoring.'); - } - - if (values.length == 1 && values[0][1] == 'inherit') { - style.value = variant.value = weight.value = stretch.value = size.value = height.value = family.value = values; - return components; - } - - if (values.length == 1 && (validator.isFontKeyword(values[0][1]) || validator.isGlobal(values[0][1]) || validator.isPrefixed(values[0][1]))) { - values[0][1] = marker.INTERNAL + values[0][1]; - style.value = variant.value = weight.value = stretch.value = size.value = height.value = family.value = values; - return components; - } - - if (values.length < 2 || !_anyIsFontSize(values, validator) || !_anyIsFontFamily(values, validator)) { - throw new invalidPropertyError('Invalid font values at ' + formatPosition_1(property.all[property.position][1][2][0]) + '. Ignoring.'); - } - - if (values.length > 1 && _anyIsInherit(values)) { - throw new invalidPropertyError('Invalid font values at ' + formatPosition_1(values[0][2][0]) + '. Ignoring.'); - } - - // fuzzy match style, variant, weight, and stretch on first elements - while (index < fuzzyMatched) { - isStretchValid = validator.isFontStretchKeyword(values[index][1]) || validator.isGlobal(values[index][1]); - isStyleValid = validator.isFontStyleKeyword(values[index][1]) || validator.isGlobal(values[index][1]); - isVariantValid = validator.isFontVariantKeyword(values[index][1]) || validator.isGlobal(values[index][1]); - isWeightValid = validator.isFontWeightKeyword(values[index][1]) || validator.isGlobal(values[index][1]); - - if (isStyleValid && !isStyleSet) { - style.value = [values[index]]; - isStyleSet = true; - } else if (isVariantValid && !isVariantSet) { - variant.value = [values[index]]; - isVariantSet = true; - } else if (isWeightValid && !isWeightSet) { - weight.value = [values[index]]; - isWeightSet = true; - } else if (isStretchValid && !isStretchSet) { - stretch.value = [values[index]]; - isStretchSet = true; - } else if (isStyleValid && isStyleSet || isVariantValid && isVariantSet || isWeightValid && isWeightSet || isStretchValid && isStretchSet) { - throw new invalidPropertyError('Invalid font style / variant / weight / stretch value at ' + formatPosition_1(values[0][2][0]) + '. Ignoring.'); - } else { - break; - } - - index++; - } - - // now comes font-size ... - if (validator.isFontSizeKeyword(values[index][1]) || validator.isUnit(values[index][1]) && !validator.isDynamicUnit(values[index][1])) { - size.value = [values[index]]; - isSizeSet = true; - index++; - } else { - throw new invalidPropertyError('Missing font size at ' + formatPosition_1(values[0][2][0]) + '. Ignoring.'); - } - - if (!values[index]) { - throw new invalidPropertyError('Missing font family at ' + formatPosition_1(values[0][2][0]) + '. Ignoring.'); - } - - // ... and perhaps line-height - if (isSizeSet && values[index] && values[index][1] == marker.FORWARD_SLASH && values[index + 1] && (validator.isLineHeightKeyword(values[index + 1][1]) || validator.isUnit(values[index + 1][1]) || validator.isNumber(values[index + 1][1]))) { - height.value = [values[index + 1]]; - index++; - index++; - } - - // ... and whatever comes next is font-family - family.value = []; - - while (values[index]) { - if (values[index][1] == marker.COMMA) { - appendableFamilyName = false; - } else { - if (appendableFamilyName) { - family.value[family.value.length - 1][1] += marker.SPACE + values[index][1]; - } else { - family.value.push(values[index]); - } - - appendableFamilyName = true; - } - - index++; - } - - if (family.value.length === 0) { - throw new invalidPropertyError('Missing font family at ' + formatPosition_1(values[0][2][0]) + '. Ignoring.'); - } - - return components; -} - -function _anyIsFontSize(values, validator) { - var value; - var i, l; - - for (i = 0, l = values.length; i < l; i++) { - value = values[i]; - - if (validator.isFontSizeKeyword(value[1]) || validator.isUnit(value[1]) && !validator.isDynamicUnit(value[1]) || validator.isFunction(value[1])) { - return true; - } - } - - return false; -} - -function _anyIsFontFamily(values, validator) { - var value; - var i, l; - - for (i = 0, l = values.length; i < l; i++) { - value = values[i]; - - if (validator.isIdentifier(value[1])) { - return true; - } - } - - return false; -} - -function fourValues$1(property, compactable) { - var componentNames = compactable[property.name].components; - var components = []; - var value = property.value; - - if (value.length < 1) - return []; - - if (value.length < 2) - value[1] = value[0].slice(0); - if (value.length < 3) - value[2] = value[0].slice(0); - if (value.length < 4) - value[3] = value[1].slice(0); - - for (var i = componentNames.length - 1; i >= 0; i--) { - var component = wrapSingle$2([ - token.PROPERTY, - [token.PROPERTY_NAME, componentNames[i]] - ]); - component.value = [value[i]]; - components.unshift(component); - } - - return components; -} - -function multiplex$1(splitWith) { - return function (property, compactable, validator) { - var splitsAt = []; - var values = property.value; - var i, j, l, m; - - // find split commas - for (i = 0, l = values.length; i < l; i++) { - if (values[i][1] == ',') - splitsAt.push(i); - } - - if (splitsAt.length === 0) - return splitWith(property, compactable, validator); - - var splitComponents = []; - - // split over commas, and into components - for (i = 0, l = splitsAt.length; i <= l; i++) { - var from = i === 0 ? 0 : splitsAt[i - 1] + 1; - var to = i < l ? splitsAt[i] : values.length; - - var _property = _wrapDefault(property.name, property, compactable); - _property.value = values.slice(from, to); - - splitComponents.push(splitWith(_property, compactable, validator)); - } - - var components = splitComponents[0]; - - // group component values from each split - for (i = 0, l = components.length; i < l; i++) { - components[i].multiplex = true; - - for (j = 1, m = splitComponents.length; j < m; j++) { - components[i].value.push([token.PROPERTY_VALUE, marker.COMMA]); - Array.prototype.push.apply(components[i].value, splitComponents[j][i].value); - } - } - - return components; - }; -} - -function listStyle(property, compactable, validator) { - var type = _wrapDefault('list-style-type', property, compactable); - var position = _wrapDefault('list-style-position', property, compactable); - var image = _wrapDefault('list-style-image', property, compactable); - var components = [type, position, image]; - - if (property.value.length == 1 && property.value[0][1] == 'inherit') { - type.value = position.value = image.value = [property.value[0]]; - return components; - } - - var values = property.value.slice(0); - var total = values.length; - var index = 0; - - // `image` first... - for (index = 0, total = values.length; index < total; index++) { - if (validator.isUrl(values[index][1]) || values[index][1] == '0') { - image.value = [values[index]]; - values.splice(index, 1); - break; - } - } - - // ... then `position` - for (index = 0, total = values.length; index < total; index++) { - if (validator.isListStylePositionKeyword(values[index][1])) { - position.value = [values[index]]; - values.splice(index, 1); - break; - } - } - - // ... and what's left is a `type` - if (values.length > 0 && (validator.isListStyleTypeKeyword(values[0][1]) || validator.isIdentifier(values[0][1]))) { - type.value = [values[0]]; - } - - return components; -} - -function transition(property, compactable, validator) { - var prop = _wrapDefault(property.name + '-property', property, compactable); - var duration = _wrapDefault(property.name + '-duration', property, compactable); - var timing = _wrapDefault(property.name + '-timing-function', property, compactable); - var delay = _wrapDefault(property.name + '-delay', property, compactable); - var components = [prop, duration, timing, delay]; - var values = property.value; - var value; - var durationSet = false; - var delaySet = false; - var propSet = false; - var timingSet = false; - var i; - var l; - - if (property.value.length == 1 && property.value[0][1] == 'inherit') { - prop.value = duration.value = timing.value = delay.value = property.value; - return components; - } - - if (values.length > 1 && _anyIsInherit(values)) { - throw new invalidPropertyError('Invalid animation values at ' + formatPosition_1(values[0][2][0]) + '. Ignoring.'); - } - - for (i = 0, l = values.length; i < l; i++) { - value = values[i]; - - if (validator.isTime(value[1]) && !durationSet) { - duration.value = [value]; - durationSet = true; - } else if (validator.isTime(value[1]) && !delaySet) { - delay.value = [value]; - delaySet = true; - } else if ((validator.isGlobal(value[1]) || validator.isTimingFunction(value[1])) && !timingSet) { - timing.value = [value]; - timingSet = true; - } else if (validator.isIdentifier(value[1]) && !propSet) { - prop.value = [value]; - propSet = true; - } else { - throw new invalidPropertyError('Invalid animation value at ' + formatPosition_1(value[2][0]) + '. Ignoring.'); - } - } - - return components; -} - -function widthStyleColor(property, compactable, validator) { - var descriptor = compactable[property.name]; - var components = [ - _wrapDefault(descriptor.components[0], property, compactable), - _wrapDefault(descriptor.components[1], property, compactable), - _wrapDefault(descriptor.components[2], property, compactable) - ]; - var color, style, width; - - for (var i = 0; i < 3; i++) { - var component = components[i]; - - if (component.name.indexOf('color') > 0) - color = component; - else if (component.name.indexOf('style') > 0) - style = component; - else - width = component; - } - - if ((property.value.length == 1 && property.value[0][1] == 'inherit') || - (property.value.length == 3 && property.value[0][1] == 'inherit' && property.value[1][1] == 'inherit' && property.value[2][1] == 'inherit')) { - color.value = style.value = width.value = [property.value[0]]; - return components; - } - - var values = property.value.slice(0); - var match, matches; - - // NOTE: usually users don't follow the required order of parts in this shorthand, - // so we'll try to parse it caring as little about order as possible - - if (values.length > 0) { - matches = values.filter(_widthFilter(validator)); - match = matches.length > 1 && (matches[0][1] == 'none' || matches[0][1] == 'auto') ? matches[1] : matches[0]; - if (match) { - width.value = [match]; - values.splice(values.indexOf(match), 1); - } - } - - if (values.length > 0) { - match = values.filter(_styleFilter(validator))[0]; - if (match) { - style.value = [match]; - values.splice(values.indexOf(match), 1); - } - } - - if (values.length > 0) { - match = values.filter(_colorFilter(validator))[0]; - if (match) { - color.value = [match]; - values.splice(values.indexOf(match), 1); - } - } - - return components; -} - -var breakUp = { - animation: animation, - background: background$1, - border: widthStyleColor, - borderRadius: borderRadius$1, - font: font$1, - fourValues: fourValues$1, - listStyle: listStyle, - multiplex: multiplex$1, - outline: widthStyleColor, - transition: transition -}; - -var VENDOR_PREFIX_PATTERN = /(?:^|\W)(\-\w+\-)/g; - -function unique(value) { - var prefixes = []; - var match; - - while ((match = VENDOR_PREFIX_PATTERN.exec(value)) !== null) { - if (prefixes.indexOf(match[0]) == -1) { - prefixes.push(match[0]); - } - } - - return prefixes; -} - -function same(value1, value2) { - return unique(value1).sort().join(',') == unique(value2).sort().join(','); -} - -var vendorPrefixes = { - unique: unique, - same: same -}; - -var sameVendorPrefixes = vendorPrefixes.same; - -function understandable(validator, value1, value2, _position, isPaired) { - if (!sameVendorPrefixes(value1, value2)) { - return false; - } - - if (isPaired && validator.isVariable(value1) !== validator.isVariable(value2)) { - return false; - } - - return true; -} - -var understandable_1 = understandable; - -function animationIterationCount(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !(validator.isAnimationIterationCountKeyword(value2) || validator.isPositiveNumber(value2))) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } - - return validator.isAnimationIterationCountKeyword(value2) || validator.isPositiveNumber(value2); -} - -function animationName(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !(validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2))) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } - - return validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2); -} - -function areSameFunction(validator, value1, value2) { - if (!validator.isFunction(value1) || !validator.isFunction(value2)) { - return false; - } - - var function1Name = value1.substring(0, value1.indexOf('(')); - var function2Name = value2.substring(0, value2.indexOf('(')); - - return function1Name === function2Name; -} - -function backgroundPosition(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !(validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2))) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } else if (validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2)) { - return true; - } - - return unit(validator, value1, value2); -} - -function backgroundSize(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !(validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2))) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } else if (validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2)) { - return true; - } - - return unit(validator, value1, value2); -} - -function color(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !validator.isColor(value2)) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } else if (!validator.colorOpacity && (validator.isRgbColor(value1) || validator.isHslColor(value1))) { - return false; - } else if (!validator.colorOpacity && (validator.isRgbColor(value2) || validator.isHslColor(value2))) { - return false; - } else if (validator.isColor(value1) && validator.isColor(value2)) { - return true; - } - - return sameFunctionOrValue(validator, value1, value2); -} - -function components(overrideCheckers) { - return function (validator, value1, value2, position) { - return overrideCheckers[position](validator, value1, value2); - }; -} - -function fontFamily(validator, value1, value2) { - return understandable_1(validator, value1, value2, 0, true); -} - -function image(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !validator.isImage(value2)) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } else if (validator.isImage(value2)) { - return true; - } else if (validator.isImage(value1)) { - return false; - } - - return sameFunctionOrValue(validator, value1, value2); -} - -function keyword(propertyName) { - return function(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !validator.isKeyword(propertyName)(value2)) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } - - return validator.isKeyword(propertyName)(value2); - }; -} - -function keywordWithGlobal(propertyName) { - return function(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !(validator.isKeyword(propertyName)(value2) || validator.isGlobal(value2))) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } - - return validator.isKeyword(propertyName)(value2) || validator.isGlobal(value2); - }; -} - -function propertyName$1(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !validator.isIdentifier(value2)) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } - - return validator.isIdentifier(value2); -} - -function sameFunctionOrValue(validator, value1, value2) { - return areSameFunction(validator, value1, value2) ? - true : - value1 === value2; -} - -function textShadow(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !(validator.isUnit(value2) || validator.isColor(value2) || validator.isGlobal(value2))) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } - - return validator.isUnit(value2) || validator.isColor(value2) || validator.isGlobal(value2); -} - -function time(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !validator.isTime(value2)) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } else if (validator.isTime(value1) && !validator.isTime(value2)) { - return false; - } else if (validator.isTime(value2)) { - return true; - } else if (validator.isTime(value1)) { - return false; - } else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) { - return true; - } - - return sameFunctionOrValue(validator, value1, value2); -} - -function timingFunction(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !(validator.isTimingFunction(value2) || validator.isGlobal(value2))) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } - - return validator.isTimingFunction(value2) || validator.isGlobal(value2); -} - -function unit(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !validator.isUnit(value2)) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } else if (validator.isUnit(value1) && !validator.isUnit(value2)) { - return false; - } else if (validator.isUnit(value2)) { - return true; - } else if (validator.isUnit(value1)) { - return false; - } else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) { - return true; - } - - return sameFunctionOrValue(validator, value1, value2); -} - -function unitOrKeywordWithGlobal(propertyName) { - var byKeyword = keywordWithGlobal(propertyName); - - return function(validator, value1, value2) { - return unit(validator, value1, value2) || byKeyword(validator, value1, value2); - }; -} - -function unitOrNumber(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !(validator.isUnit(value2) || validator.isNumber(value2))) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } else if ((validator.isUnit(value1) || validator.isNumber(value1)) && !(validator.isUnit(value2) || validator.isNumber(value2))) { - return false; - } else if (validator.isUnit(value2) || validator.isNumber(value2)) { - return true; - } else if (validator.isUnit(value1) || validator.isNumber(value1)) { - return false; - } else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) { - return true; - } - - return sameFunctionOrValue(validator, value1, value2); -} - -function zIndex(validator, value1, value2) { - if (!understandable_1(validator, value1, value2, 0, true) && !validator.isZIndex(value2)) { - return false; - } else if (validator.isVariable(value1) && validator.isVariable(value2)) { - return true; - } - - return validator.isZIndex(value2); -} - -var canOverride = { - generic: { - color: color, - components: components, - image: image, - propertyName: propertyName$1, - time: time, - timingFunction: timingFunction, - unit: unit, - unitOrNumber: unitOrNumber - }, - property: { - animationDirection: keywordWithGlobal('animation-direction'), - animationFillMode: keyword('animation-fill-mode'), - animationIterationCount: animationIterationCount, - animationName: animationName, - animationPlayState: keywordWithGlobal('animation-play-state'), - backgroundAttachment: keyword('background-attachment'), - backgroundClip: keywordWithGlobal('background-clip'), - backgroundOrigin: keyword('background-origin'), - backgroundPosition: backgroundPosition, - backgroundRepeat: keyword('background-repeat'), - backgroundSize: backgroundSize, - bottom: unitOrKeywordWithGlobal('bottom'), - borderCollapse: keyword('border-collapse'), - borderStyle: keywordWithGlobal('*-style'), - clear: keywordWithGlobal('clear'), - cursor: keywordWithGlobal('cursor'), - display: keywordWithGlobal('display'), - float: keywordWithGlobal('float'), - left: unitOrKeywordWithGlobal('left'), - fontFamily: fontFamily, - fontStretch: keywordWithGlobal('font-stretch'), - fontStyle: keywordWithGlobal('font-style'), - fontVariant: keywordWithGlobal('font-variant'), - fontWeight: keywordWithGlobal('font-weight'), - listStyleType: keywordWithGlobal('list-style-type'), - listStylePosition: keywordWithGlobal('list-style-position'), - outlineStyle: keywordWithGlobal('*-style'), - overflow: keywordWithGlobal('overflow'), - position: keywordWithGlobal('position'), - right: unitOrKeywordWithGlobal('right'), - textAlign: keywordWithGlobal('text-align'), - textDecoration: keywordWithGlobal('text-decoration'), - textOverflow: keywordWithGlobal('text-overflow'), - textShadow: textShadow, - top: unitOrKeywordWithGlobal('top'), - transform: sameFunctionOrValue, - verticalAlign: unitOrKeywordWithGlobal('vertical-align'), - visibility: keywordWithGlobal('visibility'), - whiteSpace: keywordWithGlobal('white-space'), - zIndex: zIndex - } -}; - -var wrapSingle$1 = wrapForOptimizing$3.single; - - - -function deep(property) { - var cloned = shallow(property); - for (var i = property.components.length - 1; i >= 0; i--) { - var component = shallow(property.components[i]); - component.value = property.components[i].value.slice(0); - cloned.components.unshift(component); - } - - cloned.dirty = true; - cloned.value = property.value.slice(0); - - return cloned; -} - -function shallow(property) { - var cloned = wrapSingle$1([ - token.PROPERTY, - [token.PROPERTY_NAME, property.name] - ]); - cloned.important = property.important; - cloned.hack = property.hack; - cloned.unused = false; - return cloned; -} - -var clone = { - deep: deep, - shallow: shallow -}; - -var shallowClone$1 = clone.shallow; - - - - -function isInheritOnly(values) { - for (var i = 0, l = values.length; i < l; i++) { - var value = values[i][1]; - - if (value != 'inherit' && value != marker.COMMA && value != marker.FORWARD_SLASH) - return false; - } - - return true; -} - -function background(property, compactable, lastInMultiplex) { - var components = property.components; - var restored = []; - var needsOne, needsBoth; - - function restoreValue(component) { - Array.prototype.unshift.apply(restored, component.value); - } - - function isDefaultValue(component) { - var descriptor = compactable[component.name]; - - if (descriptor.doubleValues && descriptor.defaultValue.length == 1) { - return component.value[0][1] == descriptor.defaultValue[0] && (component.value[1] ? component.value[1][1] == descriptor.defaultValue[0] : true); - } else if (descriptor.doubleValues && descriptor.defaultValue.length != 1) { - return component.value[0][1] == descriptor.defaultValue[0] && (component.value[1] ? component.value[1][1] : component.value[0][1]) == descriptor.defaultValue[1]; - } else { - return component.value[0][1] == descriptor.defaultValue; - } - } - - for (var i = components.length - 1; i >= 0; i--) { - var component = components[i]; - var isDefault = isDefaultValue(component); - - if (component.name == 'background-clip') { - var originComponent = components[i - 1]; - var isOriginDefault = isDefaultValue(originComponent); - - needsOne = component.value[0][1] == originComponent.value[0][1]; - - needsBoth = !needsOne && ( - (isOriginDefault && !isDefault) || - (!isOriginDefault && !isDefault) || - (!isOriginDefault && isDefault && component.value[0][1] != originComponent.value[0][1])); - - if (needsOne) { - restoreValue(originComponent); - } else if (needsBoth) { - restoreValue(component); - restoreValue(originComponent); - } - - i--; - } else if (component.name == 'background-size') { - var positionComponent = components[i - 1]; - var isPositionDefault = isDefaultValue(positionComponent); - - needsOne = !isPositionDefault && isDefault; - - needsBoth = !needsOne && - (isPositionDefault && !isDefault || !isPositionDefault && !isDefault); - - if (needsOne) { - restoreValue(positionComponent); - } else if (needsBoth) { - restoreValue(component); - restored.unshift([token.PROPERTY_VALUE, marker.FORWARD_SLASH]); - restoreValue(positionComponent); - } else if (positionComponent.value.length == 1) { - restoreValue(positionComponent); - } - - i--; - } else { - if (isDefault || compactable[component.name].multiplexLastOnly && !lastInMultiplex) - continue; - - restoreValue(component); - } - } - - if (restored.length === 0 && property.value.length == 1 && property.value[0][1] == '0') - restored.push(property.value[0]); - - if (restored.length === 0) - restored.push([token.PROPERTY_VALUE, compactable[property.name].defaultValue]); - - if (isInheritOnly(restored)) - return [restored[0]]; - - return restored; -} - -function borderRadius(property, compactable) { - if (property.multiplex) { - var horizontal = shallowClone$1(property); - var vertical = shallowClone$1(property); - - for (var i = 0; i < 4; i++) { - var component = property.components[i]; - - var horizontalComponent = shallowClone$1(property); - horizontalComponent.value = [component.value[0]]; - horizontal.components.push(horizontalComponent); - - var verticalComponent = shallowClone$1(property); - // FIXME: only shorthand compactor (see breakup#borderRadius) knows that border radius - // longhands have two values, whereas tokenizer does not care about populating 2nd value - // if it's missing, hence this fallback - verticalComponent.value = [component.value[1] || component.value[0]]; - vertical.components.push(verticalComponent); - } - - var horizontalValues = fourValues(horizontal); - var verticalValues = fourValues(vertical); - - if (horizontalValues.length == verticalValues.length && - horizontalValues[0][1] == verticalValues[0][1] && - (horizontalValues.length > 1 ? horizontalValues[1][1] == verticalValues[1][1] : true) && - (horizontalValues.length > 2 ? horizontalValues[2][1] == verticalValues[2][1] : true) && - (horizontalValues.length > 3 ? horizontalValues[3][1] == verticalValues[3][1] : true)) { - return horizontalValues; - } else { - return horizontalValues.concat([[token.PROPERTY_VALUE, marker.FORWARD_SLASH]]).concat(verticalValues); - } - } else { - return fourValues(property); - } -} - -function font(property, compactable) { - var components = property.components; - var restored = []; - var component; - var componentIndex = 0; - var fontFamilyIndex = 0; - - if (property.value[0][1].indexOf(marker.INTERNAL) === 0) { - property.value[0][1] = property.value[0][1].substring(marker.INTERNAL.length); - return property.value; - } - - // first four components are optional - while (componentIndex < 4) { - component = components[componentIndex]; - - if (component.value[0][1] != compactable[component.name].defaultValue) { - Array.prototype.push.apply(restored, component.value); - } - - componentIndex++; - } - - // then comes font-size - Array.prototype.push.apply(restored, components[componentIndex].value); - componentIndex++; - - // then may come line-height - if (components[componentIndex].value[0][1] != compactable[components[componentIndex].name].defaultValue) { - Array.prototype.push.apply(restored, [[token.PROPERTY_VALUE, marker.FORWARD_SLASH]]); - Array.prototype.push.apply(restored, components[componentIndex].value); - } - - componentIndex++; - - // then comes font-family - while (components[componentIndex].value[fontFamilyIndex]) { - restored.push(components[componentIndex].value[fontFamilyIndex]); - - if (components[componentIndex].value[fontFamilyIndex + 1]) { - restored.push([token.PROPERTY_VALUE, marker.COMMA]); - } - - fontFamilyIndex++; - } - - if (isInheritOnly(restored)) { - return [restored[0]]; - } - - return restored; -} - -function fourValues(property) { - var components = property.components; - var value1 = components[0].value[0]; - var value2 = components[1].value[0]; - var value3 = components[2].value[0]; - var value4 = components[3].value[0]; - - if (value1[1] == value2[1] && value1[1] == value3[1] && value1[1] == value4[1]) { - return [value1]; - } else if (value1[1] == value3[1] && value2[1] == value4[1]) { - return [value1, value2]; - } else if (value2[1] == value4[1]) { - return [value1, value2, value3]; - } else { - return [value1, value2, value3, value4]; - } -} - -function multiplex(restoreWith) { - return function (property, compactable) { - if (!property.multiplex) - return restoreWith(property, compactable, true); - - var multiplexSize = 0; - var restored = []; - var componentMultiplexSoFar = {}; - var i, l; - - // At this point we don't know what's the multiplex size, e.g. how many background layers are there - for (i = 0, l = property.components[0].value.length; i < l; i++) { - if (property.components[0].value[i][1] == marker.COMMA) - multiplexSize++; - } - - for (i = 0; i <= multiplexSize; i++) { - var _property = shallowClone$1(property); - - // We split multiplex into parts and restore them one by one - for (var j = 0, m = property.components.length; j < m; j++) { - var componentToClone = property.components[j]; - var _component = shallowClone$1(componentToClone); - _property.components.push(_component); - - // The trick is some properties has more than one value, so we iterate over values looking for - // a multiplex separator - a comma - for (var k = componentMultiplexSoFar[_component.name] || 0, n = componentToClone.value.length; k < n; k++) { - if (componentToClone.value[k][1] == marker.COMMA) { - componentMultiplexSoFar[_component.name] = k + 1; - break; - } - - _component.value.push(componentToClone.value[k]); - } - } - - // No we can restore shorthand value - var lastInMultiplex = i == multiplexSize; - var _restored = restoreWith(_property, compactable, lastInMultiplex); - Array.prototype.push.apply(restored, _restored); - - if (i < multiplexSize) - restored.push([token.PROPERTY_VALUE, marker.COMMA]); - } - - return restored; - }; -} - -function withoutDefaults(property, compactable) { - var components = property.components; - var restored = []; - - for (var i = components.length - 1; i >= 0; i--) { - var component = components[i]; - var descriptor = compactable[component.name]; - - if (component.value[0][1] != descriptor.defaultValue || ('keepUnlessDefault' in descriptor) && !isDefault(components, compactable, descriptor.keepUnlessDefault)) { - restored.unshift(component.value[0]); - } - } - - if (restored.length === 0) - restored.push([token.PROPERTY_VALUE, compactable[property.name].defaultValue]); - - if (isInheritOnly(restored)) - return [restored[0]]; - - return restored; -} - -function isDefault(components, compactable, propertyName) { - var component; - var i, l; - - for (i = 0, l = components.length; i < l; i++) { - component = components[i]; - - if (component.name == propertyName && component.value[0][1] == compactable[propertyName].defaultValue) { - return true; - } - } - - return false; -} - -var restore = { - background: background, - borderRadius: borderRadius, - font: font, - fourValues: fourValues, - multiplex: multiplex, - withoutDefaults: withoutDefaults -}; - -// Contains the interpretation of CSS properties, as used by the property optimizer - - - - - - - -// Properties to process -// Extend this object in order to add support for more properties in the optimizer. -// -// Each key in this object represents a CSS property and should be an object. -// Such an object contains properties that describe how the represented CSS property should be handled. -// Possible options: -// -// * components: array (Only specify for shorthand properties.) -// Contains the names of the granular properties this shorthand compacts. -// -// * canOverride: function -// Returns whether two tokens of this property can be merged with each other. -// This property has no meaning for shorthands. -// -// * defaultValue: string -// Specifies the default value of the property according to the CSS standard. -// For shorthand, this is used when every component is set to its default value, therefore it should be the shortest possible default value of all the components. -// -// * shortestValue: string -// Specifies the shortest possible value the property can possibly have. -// (Falls back to defaultValue if unspecified.) -// -// * breakUp: function (Only specify for shorthand properties.) -// Breaks the shorthand up to its components. -// -// * restore: function (Only specify for shorthand properties.) -// Puts the shorthand together from its components. -// -var compactable = { - 'animation': { - canOverride: canOverride.generic.components([ - canOverride.generic.time, - canOverride.generic.timingFunction, - canOverride.generic.time, - canOverride.property.animationIterationCount, - canOverride.property.animationDirection, - canOverride.property.animationFillMode, - canOverride.property.animationPlayState, - canOverride.property.animationName - ]), - components: [ - 'animation-duration', - 'animation-timing-function', - 'animation-delay', - 'animation-iteration-count', - 'animation-direction', - 'animation-fill-mode', - 'animation-play-state', - 'animation-name' - ], - breakUp: breakUp.multiplex(breakUp.animation), - defaultValue: 'none', - restore: restore.multiplex(restore.withoutDefaults), - shorthand: true, - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'animation-delay': { - canOverride: canOverride.generic.time, - componentOf: [ - 'animation' - ], - defaultValue: '0s', - intoMultiplexMode: 'real', - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'animation-direction': { - canOverride: canOverride.property.animationDirection, - componentOf: [ - 'animation' - ], - defaultValue: 'normal', - intoMultiplexMode: 'real', - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'animation-duration': { - canOverride: canOverride.generic.time, - componentOf: [ - 'animation' - ], - defaultValue: '0s', - intoMultiplexMode: 'real', - keepUnlessDefault: 'animation-delay', - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'animation-fill-mode': { - canOverride: canOverride.property.animationFillMode, - componentOf: [ - 'animation' - ], - defaultValue: 'none', - intoMultiplexMode: 'real', - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'animation-iteration-count': { - canOverride: canOverride.property.animationIterationCount, - componentOf: [ - 'animation' - ], - defaultValue: '1', - intoMultiplexMode: 'real', - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'animation-name': { - canOverride: canOverride.property.animationName, - componentOf: [ - 'animation' - ], - defaultValue: 'none', - intoMultiplexMode: 'real', - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'animation-play-state': { - canOverride: canOverride.property.animationPlayState, - componentOf: [ - 'animation' - ], - defaultValue: 'running', - intoMultiplexMode: 'real', - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'animation-timing-function': { - canOverride: canOverride.generic.timingFunction, - componentOf: [ - 'animation' - ], - defaultValue: 'ease', - intoMultiplexMode: 'real', - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'background': { - canOverride: canOverride.generic.components([ - canOverride.generic.image, - canOverride.property.backgroundPosition, - canOverride.property.backgroundSize, - canOverride.property.backgroundRepeat, - canOverride.property.backgroundAttachment, - canOverride.property.backgroundOrigin, - canOverride.property.backgroundClip, - canOverride.generic.color - ]), - components: [ - 'background-image', - 'background-position', - 'background-size', - 'background-repeat', - 'background-attachment', - 'background-origin', - 'background-clip', - 'background-color' - ], - breakUp: breakUp.multiplex(breakUp.background), - defaultValue: '0 0', - restore: restore.multiplex(restore.background), - shortestValue: '0', - shorthand: true - }, - 'background-attachment': { - canOverride: canOverride.property.backgroundAttachment, - componentOf: [ - 'background' - ], - defaultValue: 'scroll', - intoMultiplexMode: 'real' - }, - 'background-clip': { - canOverride: canOverride.property.backgroundClip, - componentOf: [ - 'background' - ], - defaultValue: 'border-box', - intoMultiplexMode: 'real', - shortestValue: 'border-box' - }, - 'background-color': { - canOverride: canOverride.generic.color, - componentOf: [ - 'background' - ], - defaultValue: 'transparent', - intoMultiplexMode: 'real', // otherwise real color will turn into default since color appears in last multiplex only - multiplexLastOnly: true, - nonMergeableValue: 'none', - shortestValue: 'red' - }, - 'background-image': { - canOverride: canOverride.generic.image, - componentOf: [ - 'background' - ], - defaultValue: 'none', - intoMultiplexMode: 'default' - }, - 'background-origin': { - canOverride: canOverride.property.backgroundOrigin, - componentOf: [ - 'background' - ], - defaultValue: 'padding-box', - intoMultiplexMode: 'real', - shortestValue: 'border-box' - }, - 'background-position': { - canOverride: canOverride.property.backgroundPosition, - componentOf: [ - 'background' - ], - defaultValue: ['0', '0'], - doubleValues: true, - intoMultiplexMode: 'real', - shortestValue: '0' - }, - 'background-repeat': { - canOverride: canOverride.property.backgroundRepeat, - componentOf: [ - 'background' - ], - defaultValue: ['repeat'], - doubleValues: true, - intoMultiplexMode: 'real' - }, - 'background-size': { - canOverride: canOverride.property.backgroundSize, - componentOf: [ - 'background' - ], - defaultValue: ['auto'], - doubleValues: true, - intoMultiplexMode: 'real', - shortestValue: '0 0' - }, - 'bottom': { - canOverride: canOverride.property.bottom, - defaultValue: 'auto' - }, - 'border': { - breakUp: breakUp.border, - canOverride: canOverride.generic.components([ - canOverride.generic.unit, - canOverride.property.borderStyle, - canOverride.generic.color - ]), - components: [ - 'border-width', - 'border-style', - 'border-color' - ], - defaultValue: 'none', - overridesShorthands: [ - 'border-bottom', - 'border-left', - 'border-right', - 'border-top' - ], - restore: restore.withoutDefaults, - shorthand: true, - shorthandComponents: true - }, - 'border-bottom': { - breakUp: breakUp.border, - canOverride: canOverride.generic.components([ - canOverride.generic.unit, - canOverride.property.borderStyle, - canOverride.generic.color - ]), - components: [ - 'border-bottom-width', - 'border-bottom-style', - 'border-bottom-color' - ], - defaultValue: 'none', - restore: restore.withoutDefaults, - shorthand: true - }, - 'border-bottom-color': { - canOverride: canOverride.generic.color, - componentOf: [ - 'border-bottom', - 'border-color' - ], - defaultValue: 'none' - }, - 'border-bottom-left-radius': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'border-radius' - ], - defaultValue: '0', - vendorPrefixes: [ - '-moz-', - '-o-' - ] - }, - 'border-bottom-right-radius': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'border-radius' - ], - defaultValue: '0', - vendorPrefixes: [ - '-moz-', - '-o-' - ] - }, - 'border-bottom-style': { - canOverride: canOverride.property.borderStyle, - componentOf: [ - 'border-bottom', - 'border-style' - ], - defaultValue: 'none' - }, - 'border-bottom-width': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'border-bottom', - 'border-width' - ], - defaultValue: 'medium', - oppositeTo: 'border-top-width', - shortestValue: '0' - }, - 'border-collapse': { - canOverride: canOverride.property.borderCollapse, - defaultValue: 'separate' - }, - 'border-color': { - breakUp: breakUp.fourValues, - canOverride: canOverride.generic.components([ - canOverride.generic.color, - canOverride.generic.color, - canOverride.generic.color, - canOverride.generic.color - ]), - componentOf: [ - 'border' - ], - components: [ - 'border-top-color', - 'border-right-color', - 'border-bottom-color', - 'border-left-color' - ], - defaultValue: 'none', - restore: restore.fourValues, - shortestValue: 'red', - shorthand: true - }, - 'border-left': { - breakUp: breakUp.border, - canOverride: canOverride.generic.components([ - canOverride.generic.unit, - canOverride.property.borderStyle, - canOverride.generic.color - ]), - components: [ - 'border-left-width', - 'border-left-style', - 'border-left-color' - ], - defaultValue: 'none', - restore: restore.withoutDefaults, - shorthand: true - }, - 'border-left-color': { - canOverride: canOverride.generic.color, - componentOf: [ - 'border-color', - 'border-left' - ], - defaultValue: 'none' - }, - 'border-left-style': { - canOverride: canOverride.property.borderStyle, - componentOf: [ - 'border-left', - 'border-style' - ], - defaultValue: 'none' - }, - 'border-left-width': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'border-left', - 'border-width' - ], - defaultValue: 'medium', - oppositeTo: 'border-right-width', - shortestValue: '0' - }, - 'border-radius': { - breakUp: breakUp.borderRadius, - canOverride: canOverride.generic.components([ - canOverride.generic.unit, - canOverride.generic.unit, - canOverride.generic.unit, - canOverride.generic.unit - ]), - components: [ - 'border-top-left-radius', - 'border-top-right-radius', - 'border-bottom-right-radius', - 'border-bottom-left-radius' - ], - defaultValue: '0', - restore: restore.borderRadius, - shorthand: true, - vendorPrefixes: [ - '-moz-', - '-o-' - ] - }, - 'border-right': { - breakUp: breakUp.border, - canOverride: canOverride.generic.components([ - canOverride.generic.unit, - canOverride.property.borderStyle, - canOverride.generic.color - ]), - components: [ - 'border-right-width', - 'border-right-style', - 'border-right-color' - ], - defaultValue: 'none', - restore: restore.withoutDefaults, - shorthand: true - }, - 'border-right-color': { - canOverride: canOverride.generic.color, - componentOf: [ - 'border-color', - 'border-right' - ], - defaultValue: 'none' - }, - 'border-right-style': { - canOverride: canOverride.property.borderStyle, - componentOf: [ - 'border-right', - 'border-style' - ], - defaultValue: 'none' - }, - 'border-right-width': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'border-right', - 'border-width' - ], - defaultValue: 'medium', - oppositeTo: 'border-left-width', - shortestValue: '0' - }, - 'border-style': { - breakUp: breakUp.fourValues, - canOverride: canOverride.generic.components([ - canOverride.property.borderStyle, - canOverride.property.borderStyle, - canOverride.property.borderStyle, - canOverride.property.borderStyle - ]), - componentOf: [ - 'border' - ], - components: [ - 'border-top-style', - 'border-right-style', - 'border-bottom-style', - 'border-left-style' - ], - defaultValue: 'none', - restore: restore.fourValues, - shorthand: true - }, - 'border-top': { - breakUp: breakUp.border, - canOverride: canOverride.generic.components([ - canOverride.generic.unit, - canOverride.property.borderStyle, - canOverride.generic.color - ]), - components: [ - 'border-top-width', - 'border-top-style', - 'border-top-color' - ], - defaultValue: 'none', - restore: restore.withoutDefaults, - shorthand: true - }, - 'border-top-color': { - canOverride: canOverride.generic.color, - componentOf: [ - 'border-color', - 'border-top' - ], - defaultValue: 'none' - }, - 'border-top-left-radius': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'border-radius' - ], - defaultValue: '0', - vendorPrefixes: [ - '-moz-', - '-o-' - ] - }, - 'border-top-right-radius': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'border-radius' - ], - defaultValue: '0', - vendorPrefixes: [ - '-moz-', - '-o-' - ] - }, - 'border-top-style': { - canOverride: canOverride.property.borderStyle, - componentOf: [ - 'border-style', - 'border-top' - ], - defaultValue: 'none' - }, - 'border-top-width': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'border-top', - 'border-width' - ], - defaultValue: 'medium', - oppositeTo: 'border-bottom-width', - shortestValue: '0' - }, - 'border-width': { - breakUp: breakUp.fourValues, - canOverride: canOverride.generic.components([ - canOverride.generic.unit, - canOverride.generic.unit, - canOverride.generic.unit, - canOverride.generic.unit - ]), - componentOf: [ - 'border' - ], - components: [ - 'border-top-width', - 'border-right-width', - 'border-bottom-width', - 'border-left-width' - ], - defaultValue: 'medium', - restore: restore.fourValues, - shortestValue: '0', - shorthand: true - }, - 'clear': { - canOverride: canOverride.property.clear, - defaultValue: 'none' - }, - 'color': { - canOverride: canOverride.generic.color, - defaultValue: 'transparent', - shortestValue: 'red' - }, - 'cursor': { - canOverride: canOverride.property.cursor, - defaultValue: 'auto' - }, - 'display': { - canOverride: canOverride.property.display, - }, - 'float': { - canOverride: canOverride.property.float, - defaultValue: 'none' - }, - 'font': { - breakUp: breakUp.font, - canOverride: canOverride.generic.components([ - canOverride.property.fontStyle, - canOverride.property.fontVariant, - canOverride.property.fontWeight, - canOverride.property.fontStretch, - canOverride.generic.unit, - canOverride.generic.unit, - canOverride.property.fontFamily - ]), - components: [ - 'font-style', - 'font-variant', - 'font-weight', - 'font-stretch', - 'font-size', - 'line-height', - 'font-family' - ], - restore: restore.font, - shorthand: true - }, - 'font-family': { - canOverride: canOverride.property.fontFamily, - defaultValue: 'user|agent|specific' - }, - 'font-size': { - canOverride: canOverride.generic.unit, - defaultValue: 'medium', - shortestValue: '0' - }, - 'font-stretch': { - canOverride: canOverride.property.fontStretch, - defaultValue: 'normal' - }, - 'font-style': { - canOverride: canOverride.property.fontStyle, - defaultValue: 'normal' - }, - 'font-variant': { - canOverride: canOverride.property.fontVariant, - defaultValue: 'normal' - }, - 'font-weight': { - canOverride: canOverride.property.fontWeight, - defaultValue: 'normal', - shortestValue: '400' - }, - 'height': { - canOverride: canOverride.generic.unit, - defaultValue: 'auto', - shortestValue: '0' - }, - 'left': { - canOverride: canOverride.property.left, - defaultValue: 'auto' - }, - 'line-height': { - canOverride: canOverride.generic.unitOrNumber, - defaultValue: 'normal', - shortestValue: '0' - }, - 'list-style': { - canOverride: canOverride.generic.components([ - canOverride.property.listStyleType, - canOverride.property.listStylePosition, - canOverride.property.listStyleImage - ]), - components: [ - 'list-style-type', - 'list-style-position', - 'list-style-image' - ], - breakUp: breakUp.listStyle, - restore: restore.withoutDefaults, - defaultValue: 'outside', // can't use 'disc' because that'd override default 'decimal' for
    - shortestValue: 'none', - shorthand: true - }, - 'list-style-image' : { - canOverride: canOverride.generic.image, - componentOf: [ - 'list-style' - ], - defaultValue: 'none' - }, - 'list-style-position' : { - canOverride: canOverride.property.listStylePosition, - componentOf: [ - 'list-style' - ], - defaultValue: 'outside', - shortestValue: 'inside' - }, - 'list-style-type' : { - canOverride: canOverride.property.listStyleType, - componentOf: [ - 'list-style' - ], - // NOTE: we can't tell the real default value here, it's 'disc' for
      and 'decimal' for
        - // this is a hack, but it doesn't matter because this value will be either overridden or - // it will disappear at the final step anyway - defaultValue: 'decimal|disc', - shortestValue: 'none' - }, - 'margin': { - breakUp: breakUp.fourValues, - canOverride: canOverride.generic.components([ - canOverride.generic.unit, - canOverride.generic.unit, - canOverride.generic.unit, - canOverride.generic.unit - ]), - components: [ - 'margin-top', - 'margin-right', - 'margin-bottom', - 'margin-left' - ], - defaultValue: '0', - restore: restore.fourValues, - shorthand: true - }, - 'margin-bottom': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'margin' - ], - defaultValue: '0', - oppositeTo: 'margin-top' - }, - 'margin-left': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'margin' - ], - defaultValue: '0', - oppositeTo: 'margin-right' - }, - 'margin-right': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'margin' - ], - defaultValue: '0', - oppositeTo: 'margin-left' - }, - 'margin-top': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'margin' - ], - defaultValue: '0', - oppositeTo: 'margin-bottom' - }, - 'outline': { - canOverride: canOverride.generic.components([ - canOverride.generic.color, - canOverride.property.outlineStyle, - canOverride.generic.unit - ]), - components: [ - 'outline-color', - 'outline-style', - 'outline-width' - ], - breakUp: breakUp.outline, - restore: restore.withoutDefaults, - defaultValue: '0', - shorthand: true - }, - 'outline-color': { - canOverride: canOverride.generic.color, - componentOf: [ - 'outline' - ], - defaultValue: 'invert', - shortestValue: 'red' - }, - 'outline-style': { - canOverride: canOverride.property.outlineStyle, - componentOf: [ - 'outline' - ], - defaultValue: 'none' - }, - 'outline-width': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'outline' - ], - defaultValue: 'medium', - shortestValue: '0' - }, - 'overflow': { - canOverride: canOverride.property.overflow, - defaultValue: 'visible' - }, - 'overflow-x': { - canOverride: canOverride.property.overflow, - defaultValue: 'visible' - }, - 'overflow-y': { - canOverride: canOverride.property.overflow, - defaultValue: 'visible' - }, - 'padding': { - breakUp: breakUp.fourValues, - canOverride: canOverride.generic.components([ - canOverride.generic.unit, - canOverride.generic.unit, - canOverride.generic.unit, - canOverride.generic.unit - ]), - components: [ - 'padding-top', - 'padding-right', - 'padding-bottom', - 'padding-left' - ], - defaultValue: '0', - restore: restore.fourValues, - shorthand: true - }, - 'padding-bottom': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'padding' - ], - defaultValue: '0', - oppositeTo: 'padding-top' - }, - 'padding-left': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'padding' - ], - defaultValue: '0', - oppositeTo: 'padding-right' - }, - 'padding-right': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'padding' - ], - defaultValue: '0', - oppositeTo: 'padding-left' - }, - 'padding-top': { - canOverride: canOverride.generic.unit, - componentOf: [ - 'padding' - ], - defaultValue: '0', - oppositeTo: 'padding-bottom' - }, - 'position': { - canOverride: canOverride.property.position, - defaultValue: 'static' - }, - 'right': { - canOverride: canOverride.property.right, - defaultValue: 'auto' - }, - 'text-align': { - canOverride: canOverride.property.textAlign, - // NOTE: we can't tell the real default value here, as it depends on default text direction - // this is a hack, but it doesn't matter because this value will be either overridden or - // it will disappear anyway - defaultValue: 'left|right' - }, - 'text-decoration': { - canOverride: canOverride.property.textDecoration, - defaultValue: 'none' - }, - 'text-overflow': { - canOverride: canOverride.property.textOverflow, - defaultValue: 'none' - }, - 'text-shadow': { - canOverride: canOverride.property.textShadow, - defaultValue: 'none' - }, - 'top': { - canOverride: canOverride.property.top, - defaultValue: 'auto' - }, - 'transform': { - canOverride: canOverride.property.transform, - vendorPrefixes: [ - '-moz-', - '-ms-', - '-webkit-' - ] - }, - 'transition': { - breakUp: breakUp.multiplex(breakUp.transition), - canOverride: canOverride.generic.components([ - canOverride.property.transitionProperty, - canOverride.generic.time, - canOverride.generic.timingFunction, - canOverride.generic.time - ]), - components: [ - 'transition-property', - 'transition-duration', - 'transition-timing-function', - 'transition-delay' - ], - defaultValue: 'none', - restore: restore.multiplex(restore.withoutDefaults), - shorthand: true, - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'transition-delay': { - canOverride: canOverride.generic.time, - componentOf: [ - 'transition' - ], - defaultValue: '0s', - intoMultiplexMode: 'real', - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'transition-duration': { - canOverride: canOverride.generic.time, - componentOf: [ - 'transition' - ], - defaultValue: '0s', - intoMultiplexMode: 'real', - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'transition-property': { - canOverride: canOverride.generic.propertyName, - componentOf: [ - 'transition' - ], - defaultValue: 'all', - intoMultiplexMode: 'placeholder', - placeholderValue: '_', // it's a short value that won't match any property and still be a valid `transition-property` - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'transition-timing-function': { - canOverride: canOverride.generic.timingFunction, - componentOf: [ - 'transition' - ], - defaultValue: 'ease', - intoMultiplexMode: 'real', - vendorPrefixes: [ - '-moz-', - '-o-', - '-webkit-' - ] - }, - 'vertical-align': { - canOverride: canOverride.property.verticalAlign, - defaultValue: 'baseline' - }, - 'visibility': { - canOverride: canOverride.property.visibility, - defaultValue: 'visible' - }, - 'white-space': { - canOverride: canOverride.property.whiteSpace, - defaultValue: 'normal' - }, - 'width': { - canOverride: canOverride.generic.unit, - defaultValue: 'auto', - shortestValue: '0' - }, - 'z-index': { - canOverride: canOverride.property.zIndex, - defaultValue: 'auto' - } -}; - -function cloneDescriptor(propertyName, prefix) { - var clonedDescriptor = override_1(compactable[propertyName], {}); - - if ('componentOf' in clonedDescriptor) { - clonedDescriptor.componentOf = clonedDescriptor.componentOf.map(function (shorthandName) { - return prefix + shorthandName; - }); - } - - if ('components' in clonedDescriptor) { - clonedDescriptor.components = clonedDescriptor.components.map(function (longhandName) { - return prefix + longhandName; - }); - } - - if ('keepUnlessDefault' in clonedDescriptor) { - clonedDescriptor.keepUnlessDefault = prefix + clonedDescriptor.keepUnlessDefault; - } - - return clonedDescriptor; -} - -// generate vendor-prefixed properties -var vendorPrefixedCompactable = {}; - -for (var propertyName in compactable) { - var descriptor = compactable[propertyName]; - - if (!('vendorPrefixes' in descriptor)) { - continue; - } - - for (var i = 0; i < descriptor.vendorPrefixes.length; i++) { - var prefix = descriptor.vendorPrefixes[i]; - var clonedDescriptor = cloneDescriptor(propertyName, prefix); - delete clonedDescriptor.vendorPrefixes; - - vendorPrefixedCompactable[prefix + propertyName] = clonedDescriptor; - } - - delete descriptor.vendorPrefixes; -} - -var compactable_1 = override_1(compactable, vendorPrefixedCompactable); - -function populateComponents(properties, validator, warnings) { - var component; - var j, m; - - for (var i = properties.length - 1; i >= 0; i--) { - var property = properties[i]; - var descriptor = compactable_1[property.name]; - - if (descriptor && descriptor.shorthand) { - property.shorthand = true; - property.dirty = true; - - try { - property.components = descriptor.breakUp(property, compactable_1, validator); - - if (descriptor.shorthandComponents) { - for (j = 0, m = property.components.length; j < m; j++) { - component = property.components[j]; - component.components = compactable_1[component.name].breakUp(component, compactable_1, validator); - } - } - } catch (e) { - if (e instanceof invalidPropertyError) { - property.components = []; // this will set property.unused to true below - warnings.push(e.message); - } else { - throw e; - } - } - - if (property.components.length > 0) - property.multiplex = property.components[0].multiplex; - else - property.unused = true; - } - } -} - -var populateComponents_1 = populateComponents; - -function restoreWithComponents(property) { - var descriptor = compactable_1[property.name]; - - if (descriptor && descriptor.shorthand) { - return descriptor.restore(property, compactable_1); - } else { - return property.value; - } -} - -var restoreWithComponents_1 = restoreWithComponents; - -var deepClone$1 = clone.deep; - - - -var wrapSingle = wrapForOptimizing$3.single; - -var serializeBody$5 = oneTime.body; - - -function mergeIntoShorthands(properties, validator) { - var candidates = {}; - var descriptor; - var componentOf; - var property; - var i, l; - var j, m; - - // there is no shorthand property made up of less than 3 longhands - if (properties.length < 3) { - return; - } - - for (i = 0, l = properties.length; i < l; i++) { - property = properties[i]; - descriptor = compactable_1[property.name]; - - if (property.unused) { - continue; - } - - if (property.hack) { - continue; - } - - if (property.block) { - continue; - } - - invalidateOrCompact(properties, i, candidates, validator); - - if (descriptor && descriptor.componentOf) { - for (j = 0, m = descriptor.componentOf.length; j < m; j++) { - componentOf = descriptor.componentOf[j]; - - candidates[componentOf] = candidates[componentOf] || {}; - candidates[componentOf][property.name] = property; - } - } - } - - invalidateOrCompact(properties, i, candidates, validator); -} - -function invalidateOrCompact(properties, position, candidates, validator) { - var invalidatedBy = properties[position]; - var shorthandName; - var shorthandDescriptor; - var candidateComponents; - - for (shorthandName in candidates) { - if (undefined !== invalidatedBy && shorthandName == invalidatedBy.name) { - continue; - } - - shorthandDescriptor = compactable_1[shorthandName]; - candidateComponents = candidates[shorthandName]; - if (invalidatedBy && invalidates(candidates, shorthandName, invalidatedBy)) { - delete candidates[shorthandName]; - continue; - } - - if (shorthandDescriptor.components.length > Object.keys(candidateComponents).length) { - continue; - } - - if (mixedImportance(candidateComponents)) { - continue; - } - - if (!overridable(candidateComponents, shorthandName, validator)) { - continue; - } - - if (!mergeable(candidateComponents)) { - continue; - } - - if (mixedInherit(candidateComponents)) { - replaceWithInheritBestFit(properties, candidateComponents, shorthandName, validator); - } else { - replaceWithShorthand(properties, candidateComponents, shorthandName, validator); - } - } -} - -function invalidates(candidates, shorthandName, invalidatedBy) { - var shorthandDescriptor = compactable_1[shorthandName]; - var invalidatedByDescriptor = compactable_1[invalidatedBy.name]; - var componentName; - - if ('overridesShorthands' in shorthandDescriptor && shorthandDescriptor.overridesShorthands.indexOf(invalidatedBy.name) > -1) { - return true; - } - - if (invalidatedByDescriptor && 'componentOf' in invalidatedByDescriptor) { - for (componentName in candidates[shorthandName]) { - if (invalidatedByDescriptor.componentOf.indexOf(componentName) > -1) { - return true; - } - } - } - - return false; -} - -function mixedImportance(components) { - var important; - var componentName; - - for (componentName in components) { - if (undefined !== important && components[componentName].important != important) { - return true; - } - - important = components[componentName].important; - } - - return false; -} - -function overridable(components, shorthandName, validator) { - var descriptor = compactable_1[shorthandName]; - var newValuePlaceholder = [ - token.PROPERTY, - [token.PROPERTY_NAME, shorthandName], - [token.PROPERTY_VALUE, descriptor.defaultValue] - ]; - var newProperty = wrapSingle(newValuePlaceholder); - var component; - var mayOverride; - var i, l; - - populateComponents_1([newProperty], validator, []); - - for (i = 0, l = descriptor.components.length; i < l; i++) { - component = components[descriptor.components[i]]; - mayOverride = compactable_1[component.name].canOverride; - - if (!everyValuesPair_1(mayOverride.bind(null, validator), newProperty.components[i], component)) { - return false; - } - } - - return true; -} - -function mergeable(components) { - var lastCount = null; - var currentCount; - var componentName; - var component; - var descriptor; - var values; - - for (componentName in components) { - component = components[componentName]; - descriptor = compactable_1[componentName]; - - if (!('restore' in descriptor)) { - continue; - } - - restoreFromOptimizing_1([component.all[component.position]], restoreWithComponents_1); - values = descriptor.restore(component, compactable_1); - - currentCount = values.length; - - if (lastCount !== null && currentCount !== lastCount) { - return false; - } - - lastCount = currentCount; - } - - return true; -} - -function mixedInherit(components) { - var componentName; - var lastValue = null; - var currentValue; - - for (componentName in components) { - currentValue = hasInherit_1(components[componentName]); - - if (lastValue !== null && lastValue !== currentValue) { - return true; - } - - lastValue = currentValue; - } - - return false; -} - -function replaceWithInheritBestFit(properties, candidateComponents, shorthandName, validator) { - var viaLonghands = buildSequenceWithInheritLonghands(candidateComponents, shorthandName, validator); - var viaShorthand = buildSequenceWithInheritShorthand(candidateComponents, shorthandName, validator); - var longhandTokensSequence = viaLonghands[0]; - var shorthandTokensSequence = viaShorthand[0]; - var isLonghandsShorter = serializeBody$5(longhandTokensSequence).length < serializeBody$5(shorthandTokensSequence).length; - var newTokensSequence = isLonghandsShorter ? longhandTokensSequence : shorthandTokensSequence; - var newProperty = isLonghandsShorter ? viaLonghands[1] : viaShorthand[1]; - var newComponents = isLonghandsShorter ? viaLonghands[2] : viaShorthand[2]; - var all = candidateComponents[Object.keys(candidateComponents)[0]].all; - var componentName; - var oldComponent; - var newComponent; - var newToken; - - newProperty.position = all.length; - newProperty.shorthand = true; - newProperty.dirty = true; - newProperty.all = all; - newProperty.all.push(newTokensSequence[0]); - - properties.push(newProperty); - - for (componentName in candidateComponents) { - oldComponent = candidateComponents[componentName]; - oldComponent.unused = true; - - if (oldComponent.name in newComponents) { - newComponent = newComponents[oldComponent.name]; - newToken = findTokenIn(newTokensSequence, componentName); - - newComponent.position = all.length; - newComponent.all = all; - newComponent.all.push(newToken); - - properties.push(newComponent); - } - } -} - -function buildSequenceWithInheritLonghands(components, shorthandName, validator) { - var tokensSequence = []; - var inheritComponents = {}; - var nonInheritComponents = {}; - var descriptor = compactable_1[shorthandName]; - var shorthandToken = [ - token.PROPERTY, - [token.PROPERTY_NAME, shorthandName], - [token.PROPERTY_VALUE, descriptor.defaultValue] - ]; - var newProperty = wrapSingle(shorthandToken); - var component; - var longhandToken; - var newComponent; - var nameMetadata; - var i, l; - - populateComponents_1([newProperty], validator, []); - - for (i = 0, l = descriptor.components.length; i < l; i++) { - component = components[descriptor.components[i]]; - - if (hasInherit_1(component)) { - longhandToken = component.all[component.position].slice(0, 2); - Array.prototype.push.apply(longhandToken, component.value); - tokensSequence.push(longhandToken); - - newComponent = deepClone$1(component); - newComponent.value = inferComponentValue(components, newComponent.name); - - newProperty.components[i] = newComponent; - inheritComponents[component.name] = deepClone$1(component); - } else { - newComponent = deepClone$1(component); - newComponent.all = component.all; - newProperty.components[i] = newComponent; - - nonInheritComponents[component.name] = component; - } - } - - nameMetadata = joinMetadata(nonInheritComponents, 1); - shorthandToken[1].push(nameMetadata); - - restoreFromOptimizing_1([newProperty], restoreWithComponents_1); - - shorthandToken = shorthandToken.slice(0, 2); - Array.prototype.push.apply(shorthandToken, newProperty.value); - - tokensSequence.unshift(shorthandToken); - - return [tokensSequence, newProperty, inheritComponents]; -} - -function inferComponentValue(components, propertyName) { - var descriptor = compactable_1[propertyName]; - - if ('oppositeTo' in descriptor) { - return components[descriptor.oppositeTo].value; - } else { - return [[token.PROPERTY_VALUE, descriptor.defaultValue]]; - } -} - -function joinMetadata(components, at) { - var metadata = []; - var component; - var originalValue; - var componentMetadata; - var componentName; - - for (componentName in components) { - component = components[componentName]; - originalValue = component.all[component.position]; - componentMetadata = originalValue[at][originalValue[at].length - 1]; - - Array.prototype.push.apply(metadata, componentMetadata); - } - - return metadata.sort(metadataSorter); -} - -function metadataSorter(metadata1, metadata2) { - var line1 = metadata1[0]; - var line2 = metadata2[0]; - var column1 = metadata1[1]; - var column2 = metadata2[1]; - - if (line1 < line2) { - return -1; - } else if (line1 === line2) { - return column1 < column2 ? -1 : 1; - } else { - return 1; - } -} - -function buildSequenceWithInheritShorthand(components, shorthandName, validator) { - var tokensSequence = []; - var inheritComponents = {}; - var nonInheritComponents = {}; - var descriptor = compactable_1[shorthandName]; - var shorthandToken = [ - token.PROPERTY, - [token.PROPERTY_NAME, shorthandName], - [token.PROPERTY_VALUE, 'inherit'] - ]; - var newProperty = wrapSingle(shorthandToken); - var component; - var longhandToken; - var nameMetadata; - var valueMetadata; - var i, l; - - populateComponents_1([newProperty], validator, []); - - for (i = 0, l = descriptor.components.length; i < l; i++) { - component = components[descriptor.components[i]]; - - if (hasInherit_1(component)) { - inheritComponents[component.name] = component; - } else { - longhandToken = component.all[component.position].slice(0, 2); - Array.prototype.push.apply(longhandToken, component.value); - tokensSequence.push(longhandToken); - - nonInheritComponents[component.name] = deepClone$1(component); - } - } - - nameMetadata = joinMetadata(inheritComponents, 1); - shorthandToken[1].push(nameMetadata); - - valueMetadata = joinMetadata(inheritComponents, 2); - shorthandToken[2].push(valueMetadata); - - tokensSequence.unshift(shorthandToken); - - return [tokensSequence, newProperty, nonInheritComponents]; -} - -function findTokenIn(tokens, componentName) { - var i, l; - - for (i = 0, l = tokens.length; i < l; i++) { - if (tokens[i][1][1] == componentName) { - return tokens[i]; - } - } -} - -function replaceWithShorthand(properties, candidateComponents, shorthandName, validator) { - var descriptor = compactable_1[shorthandName]; - var nameMetadata; - var valueMetadata; - var newValuePlaceholder = [ - token.PROPERTY, - [token.PROPERTY_NAME, shorthandName], - [token.PROPERTY_VALUE, descriptor.defaultValue] - ]; - var all; - - var newProperty = wrapSingle(newValuePlaceholder); - newProperty.shorthand = true; - newProperty.dirty = true; - - populateComponents_1([newProperty], validator, []); - - for (var i = 0, l = descriptor.components.length; i < l; i++) { - var component = candidateComponents[descriptor.components[i]]; - - newProperty.components[i] = deepClone$1(component); - newProperty.important = component.important; - - all = component.all; - } - - for (var componentName in candidateComponents) { - candidateComponents[componentName].unused = true; - } - - nameMetadata = joinMetadata(candidateComponents, 1); - newValuePlaceholder[1].push(nameMetadata); - - valueMetadata = joinMetadata(candidateComponents, 2); - newValuePlaceholder[2].push(valueMetadata); - - newProperty.position = all.length; - newProperty.all = all; - newProperty.all.push(newValuePlaceholder); - - properties.push(newProperty); -} - -var mergeIntoShorthands_1 = mergeIntoShorthands; - -function findComponentIn(shorthand, longhand) { - var comparator = nameComparator(longhand); - - return findInDirectComponents(shorthand, comparator) || findInSubComponents(shorthand, comparator); -} - -function nameComparator(to) { - return function (property) { - return to.name === property.name; - }; -} - -function findInDirectComponents(shorthand, comparator) { - return shorthand.components.filter(comparator)[0]; -} - -function findInSubComponents(shorthand, comparator) { - var shorthandComponent; - var longhandMatch; - var i, l; - - if (!compactable_1[shorthand.name].shorthandComponents) { - return; - } - - for (i = 0, l = shorthand.components.length; i < l; i++) { - shorthandComponent = shorthand.components[i]; - longhandMatch = findInDirectComponents(shorthandComponent, comparator); - - if (longhandMatch) { - return longhandMatch; - } - } - - return; -} - -var findComponentIn_1 = findComponentIn; - -function isComponentOf(property1, property2, shallow) { - return isDirectComponentOf(property1, property2) || - !shallow && !!compactable_1[property1.name].shorthandComponents && isSubComponentOf(property1, property2); -} - -function isDirectComponentOf(property1, property2) { - var descriptor = compactable_1[property1.name]; - - return 'components' in descriptor && descriptor.components.indexOf(property2.name) > -1; -} - -function isSubComponentOf(property1, property2) { - return property1 - .components - .some(function (component) { - return isDirectComponentOf(component, property2); - }); -} - -var isComponentOf_1 = isComponentOf; - -function isMergeableShorthand(shorthand) { - if (shorthand.name != 'font') { - return true; - } - - return shorthand.value[0][1].indexOf(marker.INTERNAL) == -1; -} - -var isMergeableShorthand_1 = isMergeableShorthand; - -function overridesNonComponentShorthand(property1, property2) { - return property1.name in compactable_1 && - 'overridesShorthands' in compactable_1[property1.name] && - compactable_1[property1.name].overridesShorthands.indexOf(property2.name) > -1; -} - -var overridesNonComponentShorthand_1 = overridesNonComponentShorthand; - -var sameVendorPrefixesIn = vendorPrefixes.same; - - -var deepClone = clone.deep; - -var shallowClone = clone.shallow; - - - - - - -var serializeProperty = oneTime.property; - -function wouldBreakCompatibility(property, validator) { - for (var i = 0; i < property.components.length; i++) { - var component = property.components[i]; - var descriptor = compactable_1[component.name]; - var canOverride = descriptor && descriptor.canOverride || canOverride.sameValue; - - var _component = shallowClone(component); - _component.value = [[token.PROPERTY_VALUE, descriptor.defaultValue]]; - - if (!everyValuesPair_1(canOverride.bind(null, validator), _component, component)) { - return true; - } - } - - return false; -} - -function overrideIntoMultiplex(property, by) { - by.unused = true; - - turnIntoMultiplex(by, multiplexSize(property)); - property.value = by.value; -} - -function overrideByMultiplex(property, by) { - by.unused = true; - property.multiplex = true; - property.value = by.value; -} - -function overrideSimple(property, by) { - by.unused = true; - property.value = by.value; -} - -function override(property, by) { - if (by.multiplex) - overrideByMultiplex(property, by); - else if (property.multiplex) - overrideIntoMultiplex(property, by); - else - overrideSimple(property, by); -} - -function overrideShorthand(property, by) { - by.unused = true; - - for (var i = 0, l = property.components.length; i < l; i++) { - override(property.components[i], by.components[i]); - } -} - -function turnIntoMultiplex(property, size) { - property.multiplex = true; - - if (compactable_1[property.name].shorthand) { - turnShorthandValueIntoMultiplex(property, size); - } else { - turnLonghandValueIntoMultiplex(property, size); - } -} - -function turnShorthandValueIntoMultiplex(property, size) { - var component; - var i, l; - - for (i = 0, l = property.components.length; i < l; i++) { - component = property.components[i]; - - if (!component.multiplex) { - turnLonghandValueIntoMultiplex(component, size); - } - } -} - -function turnLonghandValueIntoMultiplex(property, size) { - var descriptor = compactable_1[property.name]; - var withRealValue = descriptor.intoMultiplexMode == 'real'; - var withValue = descriptor.intoMultiplexMode == 'real' ? - property.value.slice(0) : - (descriptor.intoMultiplexMode == 'placeholder' ? descriptor.placeholderValue : descriptor.defaultValue); - var i = multiplexSize(property); - var j; - var m = withValue.length; - - for (; i < size; i++) { - property.value.push([token.PROPERTY_VALUE, marker.COMMA]); - - if (Array.isArray(withValue)) { - for (j = 0; j < m; j++) { - property.value.push(withRealValue ? withValue[j] : [token.PROPERTY_VALUE, withValue[j]]); - } - } else { - property.value.push(withRealValue ? withValue : [token.PROPERTY_VALUE, withValue]); - } - } -} - -function multiplexSize(component) { - var size = 0; - - for (var i = 0, l = component.value.length; i < l; i++) { - if (component.value[i][1] == marker.COMMA) - size++; - } - - return size + 1; -} - -function lengthOf(property) { - var fakeAsArray = [ - token.PROPERTY, - [token.PROPERTY_NAME, property.name] - ].concat(property.value); - return serializeProperty([fakeAsArray], 0).length; -} - -function moreSameShorthands(properties, startAt, name) { - // Since we run the main loop in `compactOverrides` backwards, at this point some - // properties may not be marked as unused. - // We should consider reverting the order if possible - var count = 0; - - for (var i = startAt; i >= 0; i--) { - if (properties[i].name == name && !properties[i].unused) - count++; - if (count > 1) - break; - } - - return count > 1; -} - -function overridingFunction(shorthand, validator) { - for (var i = 0, l = shorthand.components.length; i < l; i++) { - if (!anyValue(validator.isUrl, shorthand.components[i]) && anyValue(validator.isFunction, shorthand.components[i])) { - return true; - } - } - - return false; -} - -function anyValue(fn, property) { - for (var i = 0, l = property.value.length; i < l; i++) { - if (property.value[i][1] == marker.COMMA) - continue; - - if (fn(property.value[i][1])) - return true; - } - - return false; -} - -function wouldResultInLongerValue(left, right) { - if (!left.multiplex && !right.multiplex || left.multiplex && right.multiplex) - return false; - - var multiplex = left.multiplex ? left : right; - var simple = left.multiplex ? right : left; - var component; - - var multiplexClone = deepClone(multiplex); - restoreFromOptimizing_1([multiplexClone], restoreWithComponents_1); - - var simpleClone = deepClone(simple); - restoreFromOptimizing_1([simpleClone], restoreWithComponents_1); - - var lengthBefore = lengthOf(multiplexClone) + 1 + lengthOf(simpleClone); - - if (left.multiplex) { - component = findComponentIn_1(multiplexClone, simpleClone); - overrideIntoMultiplex(component, simpleClone); - } else { - component = findComponentIn_1(simpleClone, multiplexClone); - turnIntoMultiplex(simpleClone, multiplexSize(multiplexClone)); - overrideByMultiplex(component, multiplexClone); - } - - restoreFromOptimizing_1([simpleClone], restoreWithComponents_1); - - var lengthAfter = lengthOf(simpleClone); - - return lengthBefore <= lengthAfter; -} - -function isCompactable(property) { - return property.name in compactable_1; -} - -function noneOverrideHack(left, right) { - return !left.multiplex && - (left.name == 'background' || left.name == 'background-image') && - right.multiplex && - (right.name == 'background' || right.name == 'background-image') && - anyLayerIsNone(right.value); -} - -function anyLayerIsNone(values) { - var layers = intoLayers(values); - - for (var i = 0, l = layers.length; i < l; i++) { - if (layers[i].length == 1 && layers[i][0][1] == 'none') - return true; - } - - return false; -} - -function intoLayers(values) { - var layers = []; - - for (var i = 0, layer = [], l = values.length; i < l; i++) { - var value = values[i]; - if (value[1] == marker.COMMA) { - layers.push(layer); - layer = []; - } else { - layer.push(value); - } - } - - layers.push(layer); - return layers; -} - -function overrideProperties(properties, withMerging, compatibility, validator) { - var mayOverride, right, left, component; - var overriddenComponents; - var overriddenComponent; - var overridingComponent; - var overridable; - var i, j, k; - - propertyLoop: - for (i = properties.length - 1; i >= 0; i--) { - right = properties[i]; - - if (!isCompactable(right)) - continue; - - if (right.block) - continue; - - mayOverride = compactable_1[right.name].canOverride; - - traverseLoop: - for (j = i - 1; j >= 0; j--) { - left = properties[j]; - - if (!isCompactable(left)) - continue; - - if (left.block) - continue; - - if (left.unused || right.unused) - continue; - - if (left.hack && !right.hack && !right.important || !left.hack && !left.important && right.hack) - continue; - - if (left.important == right.important && left.hack[0] != right.hack[0]) - continue; - - if (left.important == right.important && (left.hack[0] != right.hack[0] || (left.hack[1] && left.hack[1] != right.hack[1]))) - continue; - - if (hasInherit_1(right)) - continue; - - if (noneOverrideHack(left, right)) - continue; - - if (right.shorthand && isComponentOf_1(right, left)) { - // maybe `left` can be overridden by `right` which is a shorthand? - if (!right.important && left.important) - continue; - - if (!sameVendorPrefixesIn([left], right.components)) - continue; - - if (!anyValue(validator.isFunction, left) && overridingFunction(right, validator)) - continue; - - if (!isMergeableShorthand_1(right)) { - left.unused = true; - continue; - } - - component = findComponentIn_1(right, left); - mayOverride = compactable_1[left.name].canOverride; - if (everyValuesPair_1(mayOverride.bind(null, validator), left, component)) { - left.unused = true; - } - } else if (right.shorthand && overridesNonComponentShorthand_1(right, left)) { - // `right` is a shorthand while `left` can be overriden by it, think `border` and `border-top` - if (!right.important && left.important) { - continue; - } - - if (!sameVendorPrefixesIn([left], right.components)) { - continue; - } - - if (!anyValue(validator.isFunction, left) && overridingFunction(right, validator)) { - continue; - } - - overriddenComponents = left.shorthand ? - left.components: - [left]; - - for (k = overriddenComponents.length - 1; k >= 0; k--) { - overriddenComponent = overriddenComponents[k]; - overridingComponent = findComponentIn_1(right, overriddenComponent); - mayOverride = compactable_1[overriddenComponent.name].canOverride; - - if (!everyValuesPair_1(mayOverride.bind(null, validator), left, overridingComponent)) { - continue traverseLoop; - } - } - - left.unused = true; - } else if (withMerging && left.shorthand && !right.shorthand && isComponentOf_1(left, right, true)) { - // maybe `right` can be pulled into `left` which is a shorthand? - if (right.important && !left.important) - continue; - - if (!right.important && left.important) { - right.unused = true; - continue; - } - - // Pending more clever algorithm in #527 - if (moreSameShorthands(properties, i - 1, left.name)) - continue; - - if (overridingFunction(left, validator)) - continue; - - if (!isMergeableShorthand_1(left)) - continue; - - component = findComponentIn_1(left, right); - if (everyValuesPair_1(mayOverride.bind(null, validator), component, right)) { - var disabledBackgroundMerging = - !compatibility.properties.backgroundClipMerging && component.name.indexOf('background-clip') > -1 || - !compatibility.properties.backgroundOriginMerging && component.name.indexOf('background-origin') > -1 || - !compatibility.properties.backgroundSizeMerging && component.name.indexOf('background-size') > -1; - var nonMergeableValue = compactable_1[right.name].nonMergeableValue === right.value[0][1]; - - if (disabledBackgroundMerging || nonMergeableValue) - continue; - - if (!compatibility.properties.merging && wouldBreakCompatibility(left, validator)) - continue; - - if (component.value[0][1] != right.value[0][1] && (hasInherit_1(left) || hasInherit_1(right))) - continue; - - if (wouldResultInLongerValue(left, right)) - continue; - - if (!left.multiplex && right.multiplex) - turnIntoMultiplex(left, multiplexSize(right)); - - override(component, right); - left.dirty = true; - } - } else if (withMerging && left.shorthand && right.shorthand && left.name == right.name) { - // merge if all components can be merged - - if (!left.multiplex && right.multiplex) - continue; - - if (!right.important && left.important) { - right.unused = true; - continue propertyLoop; - } - - if (right.important && !left.important) { - left.unused = true; - continue; - } - - if (!isMergeableShorthand_1(right)) { - left.unused = true; - continue; - } - - for (k = left.components.length - 1; k >= 0; k--) { - var leftComponent = left.components[k]; - var rightComponent = right.components[k]; - - mayOverride = compactable_1[leftComponent.name].canOverride; - if (!everyValuesPair_1(mayOverride.bind(null, validator), leftComponent, rightComponent)) - continue propertyLoop; - } - - overrideShorthand(left, right); - left.dirty = true; - } else if (withMerging && left.shorthand && right.shorthand && isComponentOf_1(left, right)) { - // border is a shorthand but any of its components is a shorthand too - - if (!left.important && right.important) - continue; - - component = findComponentIn_1(left, right); - mayOverride = compactable_1[right.name].canOverride; - if (!everyValuesPair_1(mayOverride.bind(null, validator), component, right)) - continue; - - if (left.important && !right.important) { - right.unused = true; - continue; - } - - var rightRestored = compactable_1[right.name].restore(right, compactable_1); - if (rightRestored.length > 1) - continue; - - component = findComponentIn_1(left, right); - override(component, right); - right.dirty = true; - } else if (left.name == right.name) { - // two non-shorthands should be merged based on understandability - overridable = true; - - if (right.shorthand) { - for (k = right.components.length - 1; k >= 0 && overridable; k--) { - overriddenComponent = left.components[k]; - overridingComponent = right.components[k]; - mayOverride = compactable_1[overridingComponent.name].canOverride; - - overridable = overridable && everyValuesPair_1(mayOverride.bind(null, validator), overriddenComponent, overridingComponent); - } - } else { - mayOverride = compactable_1[right.name].canOverride; - overridable = everyValuesPair_1(mayOverride.bind(null, validator), left, right); - } - - if (left.important && !right.important && overridable) { - right.unused = true; - continue; - } - - if (!left.important && right.important && overridable) { - left.unused = true; - continue; - } - - if (!overridable) { - continue; - } - - left.unused = true; - } - } - } -} - -var overrideProperties_1 = overrideProperties; - -var wrapForOptimizing$1 = wrapForOptimizing$3.all; - - - -var OptimizationLevel$4 = optimizationLevel.OptimizationLevel; - -function optimizeProperties(properties, withOverriding, withMerging, context) { - var levelOptions = context.options.level[OptimizationLevel$4.Two]; - var _properties = wrapForOptimizing$1(properties, false, levelOptions.skipProperties); - var _property; - var i, l; - - populateComponents_1(_properties, context.validator, context.warnings); - - for (i = 0, l = _properties.length; i < l; i++) { - _property = _properties[i]; - if (_property.block) { - optimizeProperties(_property.value[0][1], withOverriding, withMerging, context); - } - } - - if (withMerging && levelOptions.mergeIntoShorthands) { - mergeIntoShorthands_1(_properties, context.validator); - } - - if (withOverriding && levelOptions.overrideProperties) { - overrideProperties_1(_properties, withMerging, context.options.compatibility, context.validator); - } - - restoreFromOptimizing_1(_properties, restoreWithComponents_1); - removeUnused_1(_properties); -} - -var optimize$1 = optimizeProperties; - -var OptimizationLevel$3 = optimizationLevel.OptimizationLevel; - -var serializeBody$4 = oneTime.body; -var serializeRules$8 = oneTime.rules; - - - -function mergeAdjacent(tokens, context) { - var lastToken = [null, [], []]; - var options = context.options; - var adjacentSpace = options.compatibility.selectors.adjacentSpace; - var selectorsSortingMethod = options.level[OptimizationLevel$3.One].selectorsSortingMethod; - var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses; - var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements; - var mergeLimit = options.compatibility.selectors.mergeLimit; - var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging; - - for (var i = 0, l = tokens.length; i < l; i++) { - var token$1 = tokens[i]; - - if (token$1[0] != token.RULE) { - lastToken = [null, [], []]; - continue; - } - - if (lastToken[0] == token.RULE && serializeRules$8(token$1[1]) == serializeRules$8(lastToken[1])) { - Array.prototype.push.apply(lastToken[2], token$1[2]); - optimize$1(lastToken[2], true, true, context); - token$1[2] = []; - } else if (lastToken[0] == token.RULE && serializeBody$4(token$1[2]) == serializeBody$4(lastToken[2]) && - isMergeable_1(serializeRules$8(token$1[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) && - isMergeable_1(serializeRules$8(lastToken[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) && - lastToken[1].length < mergeLimit) { - lastToken[1] = tidyRules_1(lastToken[1].concat(token$1[1]), false, adjacentSpace, false, context.warnings); - lastToken[1] = lastToken.length > 1 ? sortSelectors_1(lastToken[1], selectorsSortingMethod) : lastToken[1]; - token$1[2] = []; - } else { - lastToken = token$1; - } - } -} - -var mergeAdjacent_1 = mergeAdjacent; - -var MODIFIER_PATTERN = /\-\-.+$/; - -function rulesOverlap(rule1, rule2, bemMode) { - var scope1; - var scope2; - var i, l; - var j, m; - - for (i = 0, l = rule1.length; i < l; i++) { - scope1 = rule1[i][1]; - - for (j = 0, m = rule2.length; j < m; j++) { - scope2 = rule2[j][1]; - - if (scope1 == scope2) { - return true; - } - - if (bemMode && withoutModifiers(scope1) == withoutModifiers(scope2)) { - return true; - } - } - } - - return false; -} - -function withoutModifiers(scope) { - return scope.replace(MODIFIER_PATTERN, ''); -} - -var rulesOverlap_1 = rulesOverlap; - -var Selector = { - ADJACENT_SIBLING: '+', - DESCENDANT: '>', - DOT: '.', - HASH: '#', - NON_ADJACENT_SIBLING: '~', - PSEUDO: ':' -}; - -var LETTER_PATTERN = /[a-zA-Z]/; -var NOT_PREFIX = ':not('; -var SEPARATOR_PATTERN = /[\s,\(>~\+]/; - -function specificity(selector) { - var result = [0, 0, 0]; - var character; - var isEscaped; - var isSingleQuoted; - var isDoubleQuoted; - var roundBracketLevel = 0; - var couldIntroduceNewTypeSelector; - var withinNotPseudoClass = false; - var wasPseudoClass = false; - var i, l; - - for (i = 0, l = selector.length; i < l; i++) { - character = selector[i]; - - if (isEscaped) ; else if (character == marker.SINGLE_QUOTE && !isDoubleQuoted && !isSingleQuoted) { - isSingleQuoted = true; - } else if (character == marker.SINGLE_QUOTE && !isDoubleQuoted && isSingleQuoted) { - isSingleQuoted = false; - } else if (character == marker.DOUBLE_QUOTE && !isDoubleQuoted && !isSingleQuoted) { - isDoubleQuoted = true; - } else if (character == marker.DOUBLE_QUOTE && isDoubleQuoted && !isSingleQuoted) { - isDoubleQuoted = false; - } else if (isSingleQuoted || isDoubleQuoted) { - continue; - } else if (roundBracketLevel > 0 && !withinNotPseudoClass) ; else if (character == marker.OPEN_ROUND_BRACKET) { - roundBracketLevel++; - } else if (character == marker.CLOSE_ROUND_BRACKET && roundBracketLevel == 1) { - roundBracketLevel--; - withinNotPseudoClass = false; - } else if (character == marker.CLOSE_ROUND_BRACKET) { - roundBracketLevel--; - } else if (character == Selector.HASH) { - result[0]++; - } else if (character == Selector.DOT || character == marker.OPEN_SQUARE_BRACKET) { - result[1]++; - } else if (character == Selector.PSEUDO && !wasPseudoClass && !isNotPseudoClass(selector, i)) { - result[1]++; - withinNotPseudoClass = false; - } else if (character == Selector.PSEUDO) { - withinNotPseudoClass = true; - } else if ((i === 0 || couldIntroduceNewTypeSelector) && LETTER_PATTERN.test(character)) { - result[2]++; - } - - isEscaped = character == marker.BACK_SLASH; - wasPseudoClass = character == Selector.PSEUDO; - couldIntroduceNewTypeSelector = !isEscaped && SEPARATOR_PATTERN.test(character); - } - - return result; -} - -function isNotPseudoClass(selector, index) { - return selector.indexOf(NOT_PREFIX, index) === index; -} - -var specificity_1 = specificity; - -function specificitiesOverlap(selector1, selector2, cache) { - var specificity1; - var specificity2; - var i, l; - var j, m; - - for (i = 0, l = selector1.length; i < l; i++) { - specificity1 = findSpecificity(selector1[i][1], cache); - - for (j = 0, m = selector2.length; j < m; j++) { - specificity2 = findSpecificity(selector2[j][1], cache); - - if (specificity1[0] === specificity2[0] && specificity1[1] === specificity2[1] && specificity1[2] === specificity2[2]) { - return true; - } - } - } - - return false; -} - -function findSpecificity(selector, cache) { - var value; - - if (!(selector in cache)) { - cache[selector] = value = specificity_1(selector); - } - - return value || cache[selector]; -} - -var specificitiesOverlap_1 = specificitiesOverlap; - -// TODO: it'd be great to merge it with the other canReorder functionality - - - - -var FLEX_PROPERTIES = /align\-items|box\-align|box\-pack|flex|justify/; -var BORDER_PROPERTIES = /^border\-(top|right|bottom|left|color|style|width|radius)/; - -function canReorder$2(left, right, cache) { - for (var i = right.length - 1; i >= 0; i--) { - for (var j = left.length - 1; j >= 0; j--) { - if (!canReorderSingle$2(left[j], right[i], cache)) - return false; - } - } - - return true; -} - -function canReorderSingle$2(left, right, cache) { - var leftName = left[0]; - var leftValue = left[1]; - var leftNameRoot = left[2]; - var leftSelector = left[5]; - var leftInSpecificSelector = left[6]; - var rightName = right[0]; - var rightValue = right[1]; - var rightNameRoot = right[2]; - var rightSelector = right[5]; - var rightInSpecificSelector = right[6]; - - if (leftName == 'font' && rightName == 'line-height' || rightName == 'font' && leftName == 'line-height') - return false; - if (FLEX_PROPERTIES.test(leftName) && FLEX_PROPERTIES.test(rightName)) - return false; - if (leftNameRoot == rightNameRoot && unprefixed(leftName) == unprefixed(rightName) && (vendorPrefixed(leftName) ^ vendorPrefixed(rightName))) - return false; - if (leftNameRoot == 'border' && BORDER_PROPERTIES.test(rightNameRoot) && (leftName == 'border' || leftName == rightNameRoot || (leftValue != rightValue && sameBorderComponent(leftName, rightName)))) - return false; - if (rightNameRoot == 'border' && BORDER_PROPERTIES.test(leftNameRoot) && (rightName == 'border' || rightName == leftNameRoot || (leftValue != rightValue && sameBorderComponent(leftName, rightName)))) - return false; - if (leftNameRoot == 'border' && rightNameRoot == 'border' && leftName != rightName && (isSideBorder(leftName) && isStyleBorder(rightName) || isStyleBorder(leftName) && isSideBorder(rightName))) - return false; - if (leftNameRoot != rightNameRoot) - return true; - if (leftName == rightName && leftNameRoot == rightNameRoot && (leftValue == rightValue || withDifferentVendorPrefix(leftValue, rightValue))) - return true; - if (leftName != rightName && leftNameRoot == rightNameRoot && leftName != leftNameRoot && rightName != rightNameRoot) - return true; - if (leftName != rightName && leftNameRoot == rightNameRoot && leftValue == rightValue) - return true; - if (rightInSpecificSelector && leftInSpecificSelector && !inheritable(leftNameRoot) && !inheritable(rightNameRoot) && !rulesOverlap_1(rightSelector, leftSelector, false)) - return true; - if (!specificitiesOverlap_1(leftSelector, rightSelector, cache)) - return true; - - return false; -} - -function vendorPrefixed(name) { - return /^\-(?:moz|webkit|ms|o)\-/.test(name); -} - -function unprefixed(name) { - return name.replace(/^\-(?:moz|webkit|ms|o)\-/, ''); -} - -function sameBorderComponent(name1, name2) { - return name1.split('-').pop() == name2.split('-').pop(); -} - -function isSideBorder(name) { - return name == 'border-top' || name == 'border-right' || name == 'border-bottom' || name == 'border-left'; -} - -function isStyleBorder(name) { - return name == 'border-color' || name == 'border-style' || name == 'border-width'; -} - -function withDifferentVendorPrefix(value1, value2) { - return vendorPrefixed(value1) && vendorPrefixed(value2) && value1.split('-')[1] != value2.split('-')[2]; -} - -function inheritable(name) { - // According to http://www.w3.org/TR/CSS21/propidx.html - // Others will be catched by other, preceeding rules - return name == 'font' || name == 'line-height' || name == 'list-style'; -} - -var reorderable = { - canReorder: canReorder$2, - canReorderSingle: canReorderSingle$2 -}; - -// This extractor is used in level 2 optimizations -// IMPORTANT: Mind Token class and this code is not related! -// Properties will be tokenized in one step, see #429 - - -var serializeRules$7 = oneTime.rules; -var serializeValue = oneTime.value; - -function extractProperties(token$1) { - var properties = []; - var inSpecificSelector; - var property; - var name; - var value; - var i, l; - - if (token$1[0] == token.RULE) { - inSpecificSelector = !/[\.\+>~]/.test(serializeRules$7(token$1[1])); - - for (i = 0, l = token$1[2].length; i < l; i++) { - property = token$1[2][i]; - - if (property[0] != token.PROPERTY) - continue; - - name = property[1][1]; - if (name.length === 0) - continue; - - if (name.indexOf('--') === 0) - continue; - - value = serializeValue(property, i); - - properties.push([ - name, - value, - findNameRoot(name), - token$1[2][i], - name + ':' + value, - token$1[1], - inSpecificSelector - ]); - } - } else if (token$1[0] == token.NESTED_BLOCK) { - for (i = 0, l = token$1[2].length; i < l; i++) { - properties = properties.concat(extractProperties(token$1[2][i])); - } - } - - return properties; -} - -function findNameRoot(name) { - if (name == 'list-style') - return name; - if (name.indexOf('-radius') > 0) - return 'border-radius'; - if (name == 'border-collapse' || name == 'border-spacing' || name == 'border-image') - return name; - if (name.indexOf('border-') === 0 && /^border\-\w+\-\w+$/.test(name)) - return name.match(/border\-\w+/)[0]; - if (name.indexOf('border-') === 0 && /^border\-\w+$/.test(name)) - return 'border'; - if (name.indexOf('text-') === 0) - return name; - if (name == '-chrome-') - return name; - - return name.replace(/^\-\w+\-/, '').match(/([a-zA-Z]+)/)[0].toLowerCase(); -} - -var extractProperties_1 = extractProperties; - -var canReorder$1 = reorderable.canReorder; -var canReorderSingle$1 = reorderable.canReorderSingle; - - - -var serializeRules$6 = oneTime.rules; -var OptimizationLevel$2 = optimizationLevel.OptimizationLevel; - - -function mergeMediaQueries(tokens, context) { - var mergeSemantically = context.options.level[OptimizationLevel$2.Two].mergeSemantically; - var specificityCache = context.cache.specificity; - var candidates = {}; - var reduced = []; - - for (var i = tokens.length - 1; i >= 0; i--) { - var token$1 = tokens[i]; - if (token$1[0] != token.NESTED_BLOCK) { - continue; - } - - var key = serializeRules$6(token$1[1]); - var candidate = candidates[key]; - if (!candidate) { - candidate = []; - candidates[key] = candidate; - } - - candidate.push(i); - } - - for (var name in candidates) { - var positions = candidates[name]; - - positionLoop: - for (var j = positions.length - 1; j > 0; j--) { - var positionOne = positions[j]; - var tokenOne = tokens[positionOne]; - var positionTwo = positions[j - 1]; - var tokenTwo = tokens[positionTwo]; - - directionLoop: - for (var direction = 1; direction >= -1; direction -= 2) { - var topToBottom = direction == 1; - var from = topToBottom ? positionOne + 1 : positionTwo - 1; - var to = topToBottom ? positionTwo : positionOne; - var delta = topToBottom ? 1 : -1; - var source = topToBottom ? tokenOne : tokenTwo; - var target = topToBottom ? tokenTwo : tokenOne; - var movedProperties = extractProperties_1(source); - - while (from != to) { - var traversedProperties = extractProperties_1(tokens[from]); - from += delta; - - if (mergeSemantically && allSameRulePropertiesCanBeReordered(movedProperties, traversedProperties, specificityCache)) { - continue; - } - - if (!canReorder$1(movedProperties, traversedProperties, specificityCache)) - continue directionLoop; - } - - target[2] = topToBottom ? - source[2].concat(target[2]) : - target[2].concat(source[2]); - source[2] = []; - - reduced.push(target); - continue positionLoop; - } - } - } - - return reduced; -} - -function allSameRulePropertiesCanBeReordered(movedProperties, traversedProperties, specificityCache) { - var movedProperty; - var movedRule; - var traversedProperty; - var traversedRule; - var i, l; - var j, m; - - for (i = 0, l = movedProperties.length; i < l; i++) { - movedProperty = movedProperties[i]; - movedRule = movedProperty[5]; - - for (j = 0, m = traversedProperties.length; j < m; j++) { - traversedProperty = traversedProperties[j]; - traversedRule = traversedProperty[5]; - - if (rulesOverlap_1(movedRule, traversedRule, true) && !canReorderSingle$1(movedProperty, traversedProperty, specificityCache)) { - return false; - } - } - } - - return true; -} - -var mergeMediaQueries_1 = mergeMediaQueries; - -var OptimizationLevel$1 = optimizationLevel.OptimizationLevel; - -var serializeBody$3 = oneTime.body; -var serializeRules$5 = oneTime.rules; - - - -function unsafeSelector(value) { - return /\.|\*| :/.test(value); -} - -function isBemElement(token) { - var asString = serializeRules$5(token[1]); - return asString.indexOf('__') > -1 || asString.indexOf('--') > -1; -} - -function withoutModifier(selector) { - return selector.replace(/--[^ ,>\+~:]+/g, ''); -} - -function removeAnyUnsafeElements(left, candidates) { - var leftSelector = withoutModifier(serializeRules$5(left[1])); - - for (var body in candidates) { - var right = candidates[body]; - var rightSelector = withoutModifier(serializeRules$5(right[1])); - - if (rightSelector.indexOf(leftSelector) > -1 || leftSelector.indexOf(rightSelector) > -1) - delete candidates[body]; - } -} - -function mergeNonAdjacentByBody(tokens, context) { - var options = context.options; - var mergeSemantically = options.level[OptimizationLevel$1.Two].mergeSemantically; - var adjacentSpace = options.compatibility.selectors.adjacentSpace; - var selectorsSortingMethod = options.level[OptimizationLevel$1.One].selectorsSortingMethod; - var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses; - var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements; - var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging; - var candidates = {}; - - for (var i = tokens.length - 1; i >= 0; i--) { - var token$1 = tokens[i]; - if (token$1[0] != token.RULE) - continue; - - if (token$1[2].length > 0 && (!mergeSemantically && unsafeSelector(serializeRules$5(token$1[1])))) - candidates = {}; - - if (token$1[2].length > 0 && mergeSemantically && isBemElement(token$1)) - removeAnyUnsafeElements(token$1, candidates); - - var candidateBody = serializeBody$3(token$1[2]); - var oldToken = candidates[candidateBody]; - if (oldToken && - isMergeable_1(serializeRules$5(token$1[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) && - isMergeable_1(serializeRules$5(oldToken[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)) { - - if (token$1[2].length > 0) { - token$1[1] = tidyRules_1(oldToken[1].concat(token$1[1]), false, adjacentSpace, false, context.warnings); - token$1[1] = token$1[1].length > 1 ? sortSelectors_1(token$1[1], selectorsSortingMethod) : token$1[1]; - } else { - token$1[1] = oldToken[1].concat(token$1[1]); - } - - oldToken[2] = []; - candidates[candidateBody] = null; - } - - candidates[serializeBody$3(token$1[2])] = token$1; - } -} - -var mergeNonAdjacentByBody_1 = mergeNonAdjacentByBody; - -var canReorder = reorderable.canReorder; - - - - -var serializeRules$4 = oneTime.rules; - - - -function mergeNonAdjacentBySelector(tokens, context) { - var specificityCache = context.cache.specificity; - var allSelectors = {}; - var repeatedSelectors = []; - var i; - - for (i = tokens.length - 1; i >= 0; i--) { - if (tokens[i][0] != token.RULE) - continue; - if (tokens[i][2].length === 0) - continue; - - var selector = serializeRules$4(tokens[i][1]); - allSelectors[selector] = [i].concat(allSelectors[selector] || []); - - if (allSelectors[selector].length == 2) - repeatedSelectors.push(selector); - } - - for (i = repeatedSelectors.length - 1; i >= 0; i--) { - var positions = allSelectors[repeatedSelectors[i]]; - - selectorIterator: - for (var j = positions.length - 1; j > 0; j--) { - var positionOne = positions[j - 1]; - var tokenOne = tokens[positionOne]; - var positionTwo = positions[j]; - var tokenTwo = tokens[positionTwo]; - - directionIterator: - for (var direction = 1; direction >= -1; direction -= 2) { - var topToBottom = direction == 1; - var from = topToBottom ? positionOne + 1 : positionTwo - 1; - var to = topToBottom ? positionTwo : positionOne; - var delta = topToBottom ? 1 : -1; - var moved = topToBottom ? tokenOne : tokenTwo; - var target = topToBottom ? tokenTwo : tokenOne; - var movedProperties = extractProperties_1(moved); - - while (from != to) { - var traversedProperties = extractProperties_1(tokens[from]); - from += delta; - - // traversed then moved as we move selectors towards the start - var reorderable = topToBottom ? - canReorder(movedProperties, traversedProperties, specificityCache) : - canReorder(traversedProperties, movedProperties, specificityCache); - - if (!reorderable && !topToBottom) - continue selectorIterator; - if (!reorderable && topToBottom) - continue directionIterator; - } - - if (topToBottom) { - Array.prototype.push.apply(moved[2], target[2]); - target[2] = moved[2]; - } else { - Array.prototype.push.apply(target[2], moved[2]); - } - - optimize$1(target[2], true, true, context); - moved[2] = []; - } - } - } -} - -var mergeNonAdjacentBySelector_1 = mergeNonAdjacentBySelector; - -function cloneArray(array) { - var cloned = array.slice(0); - - for (var i = 0, l = cloned.length; i < l; i++) { - if (Array.isArray(cloned[i])) - cloned[i] = cloneArray(cloned[i]); - } - - return cloned; -} - -var cloneArray_1 = cloneArray; - -var serializeBody$2 = oneTime.body; -var serializeRules$3 = oneTime.rules; - -function reduceNonAdjacent(tokens, context) { - var options = context.options; - var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses; - var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements; - var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging; - var candidates = {}; - var repeated = []; - - for (var i = tokens.length - 1; i >= 0; i--) { - var token$1 = tokens[i]; - - if (token$1[0] != token.RULE) { - continue; - } else if (token$1[2].length === 0) { - continue; - } - - var selectorAsString = serializeRules$3(token$1[1]); - var isComplexAndNotSpecial = token$1[1].length > 1 && - isMergeable_1(selectorAsString, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging); - var wrappedSelectors = wrappedSelectorsFrom(token$1[1]); - var selectors = isComplexAndNotSpecial ? - [selectorAsString].concat(wrappedSelectors) : - [selectorAsString]; - - for (var j = 0, m = selectors.length; j < m; j++) { - var selector = selectors[j]; - - if (!candidates[selector]) - candidates[selector] = []; - else - repeated.push(selector); - - candidates[selector].push({ - where: i, - list: wrappedSelectors, - isPartial: isComplexAndNotSpecial && j > 0, - isComplex: isComplexAndNotSpecial && j === 0 - }); - } - } - - reduceSimpleNonAdjacentCases(tokens, repeated, candidates, options, context); - reduceComplexNonAdjacentCases(tokens, candidates, options, context); -} - -function wrappedSelectorsFrom(list) { - var wrapped = []; - - for (var i = 0; i < list.length; i++) { - wrapped.push([list[i][1]]); - } - - return wrapped; -} - -function reduceSimpleNonAdjacentCases(tokens, repeated, candidates, options, context) { - function filterOut(idx, bodies) { - return data[idx].isPartial && bodies.length === 0; - } - - function reduceBody(token, newBody, processedCount, tokenIdx) { - if (!data[processedCount - tokenIdx - 1].isPartial) - token[2] = newBody; - } - - for (var i = 0, l = repeated.length; i < l; i++) { - var selector = repeated[i]; - var data = candidates[selector]; - - reduceSelector(tokens, data, { - filterOut: filterOut, - callback: reduceBody - }, options, context); - } -} - -function reduceComplexNonAdjacentCases(tokens, candidates, options, context) { - var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses; - var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements; - var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging; - var localContext = {}; - - function filterOut(idx) { - return localContext.data[idx].where < localContext.intoPosition; - } - - function collectReducedBodies(token, newBody, processedCount, tokenIdx) { - if (tokenIdx === 0) - localContext.reducedBodies.push(newBody); - } - - allSelectors: - for (var complexSelector in candidates) { - var into = candidates[complexSelector]; - if (!into[0].isComplex) - continue; - - var intoPosition = into[into.length - 1].where; - var intoToken = tokens[intoPosition]; - var reducedBodies = []; - - var selectors = isMergeable_1(complexSelector, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) ? - into[0].list : - [complexSelector]; - - localContext.intoPosition = intoPosition; - localContext.reducedBodies = reducedBodies; - - for (var j = 0, m = selectors.length; j < m; j++) { - var selector = selectors[j]; - var data = candidates[selector]; - - if (data.length < 2) - continue allSelectors; - - localContext.data = data; - - reduceSelector(tokens, data, { - filterOut: filterOut, - callback: collectReducedBodies - }, options, context); - - if (serializeBody$2(reducedBodies[reducedBodies.length - 1]) != serializeBody$2(reducedBodies[0])) - continue allSelectors; - } - - intoToken[2] = reducedBodies[0]; - } -} - -function reduceSelector(tokens, data, context, options, outerContext) { - var bodies = []; - var bodiesAsList = []; - var processedTokens = []; - - for (var j = data.length - 1; j >= 0; j--) { - if (context.filterOut(j, bodies)) - continue; - - var where = data[j].where; - var token = tokens[where]; - var clonedBody = cloneArray_1(token[2]); - - bodies = bodies.concat(clonedBody); - bodiesAsList.push(clonedBody); - processedTokens.push(where); - } - - optimize$1(bodies, true, false, outerContext); - - var processedCount = processedTokens.length; - var propertyIdx = bodies.length - 1; - var tokenIdx = processedCount - 1; - - while (tokenIdx >= 0) { - if ((tokenIdx === 0 || (bodies[propertyIdx] && bodiesAsList[tokenIdx].indexOf(bodies[propertyIdx]) > -1)) && propertyIdx > -1) { - propertyIdx--; - continue; - } - - var newBody = bodies.splice(propertyIdx + 1); - context.callback(tokens[processedTokens[tokenIdx]], newBody, processedCount, tokenIdx); - - tokenIdx--; - } -} - -var reduceNonAdjacent_1 = reduceNonAdjacent; - -var serializeAll$1 = oneTime.all; - -var FONT_FACE_SCOPE = '@font-face'; - -function removeDuplicateFontAtRules(tokens) { - var fontAtRules = []; - var token$1; - var key; - var i, l; - - for (i = 0, l = tokens.length; i < l; i++) { - token$1 = tokens[i]; - - if (token$1[0] != token.AT_RULE_BLOCK && token$1[1][0][1] != FONT_FACE_SCOPE) { - continue; - } - - key = serializeAll$1([token$1]); - - if (fontAtRules.indexOf(key) > -1) { - token$1[2] = []; - } else { - fontAtRules.push(key); - } - } -} - -var removeDuplicateFontAtRules_1 = removeDuplicateFontAtRules; - -var serializeAll = oneTime.all; -var serializeRules$2 = oneTime.rules; - -function removeDuplicateMediaQueries(tokens) { - var candidates = {}; - var candidate; - var token$1; - var key; - var i, l; - - for (i = 0, l = tokens.length; i < l; i++) { - token$1 = tokens[i]; - if (token$1[0] != token.NESTED_BLOCK) { - continue; - } - - key = serializeRules$2(token$1[1]) + '%' + serializeAll(token$1[2]); - candidate = candidates[key]; - - if (candidate) { - candidate[2] = []; - } - - candidates[key] = token$1; - } -} - -var removeDuplicateMediaQueries_1 = removeDuplicateMediaQueries; - -var serializeBody$1 = oneTime.body; -var serializeRules$1 = oneTime.rules; - -function removeDuplicates(tokens) { - var matched = {}; - var moreThanOnce = []; - var id, token$1; - var body, bodies; - - for (var i = 0, l = tokens.length; i < l; i++) { - token$1 = tokens[i]; - if (token$1[0] != token.RULE) - continue; - - id = serializeRules$1(token$1[1]); - - if (matched[id] && matched[id].length == 1) - moreThanOnce.push(id); - else - matched[id] = matched[id] || []; - - matched[id].push(i); - } - - for (i = 0, l = moreThanOnce.length; i < l; i++) { - id = moreThanOnce[i]; - bodies = []; - - for (var j = matched[id].length - 1; j >= 0; j--) { - token$1 = tokens[matched[id][j]]; - body = serializeBody$1(token$1[2]); - - if (bodies.indexOf(body) > -1) - token$1[2] = []; - else - bodies.push(body); - } - } -} - -var removeDuplicates_1 = removeDuplicates; - -var wrapForOptimizing = wrapForOptimizing$3.single; - - - - -var animationNameRegex = /^(\-moz\-|\-o\-|\-webkit\-)?animation-name$/; -var animationRegex = /^(\-moz\-|\-o\-|\-webkit\-)?animation$/; -var keyframeRegex = /^@(\-moz\-|\-o\-|\-webkit\-)?keyframes /; -var importantRegex = /\s{0,31}!important$/; -var optionalMatchingQuotesRegex = /^(['"]?)(.*)\1$/; - -function normalize$1(value) { - return value - .replace(optionalMatchingQuotesRegex, '$2') - .replace(importantRegex, ''); -} - -function removeUnusedAtRules(tokens, context) { - removeUnusedAtRule(tokens, matchCounterStyle, markCounterStylesAsUsed, context); - removeUnusedAtRule(tokens, matchFontFace, markFontFacesAsUsed, context); - removeUnusedAtRule(tokens, matchKeyframe, markKeyframesAsUsed, context); - removeUnusedAtRule(tokens, matchNamespace, markNamespacesAsUsed, context); -} - -function removeUnusedAtRule(tokens, matchCallback, markCallback, context) { - var atRules = {}; - var atRule; - var atRuleTokens; - var atRuleToken; - var zeroAt; - var i, l; - - for (i = 0, l = tokens.length; i < l; i++) { - matchCallback(tokens[i], atRules); - } - - if (Object.keys(atRules).length === 0) { - return; - } - - markUsedAtRules(tokens, markCallback, atRules, context); - - for (atRule in atRules) { - atRuleTokens = atRules[atRule]; - - for (i = 0, l = atRuleTokens.length; i < l; i++) { - atRuleToken = atRuleTokens[i]; - zeroAt = atRuleToken[0] == token.AT_RULE ? 1 : 2; - atRuleToken[zeroAt] = []; - } - } -} - -function markUsedAtRules(tokens, markCallback, atRules, context) { - var boundMarkCallback = markCallback(atRules); - var i, l; - - for (i = 0, l = tokens.length; i < l; i++) { - switch (tokens[i][0]) { - case token.RULE: - boundMarkCallback(tokens[i], context); - break; - case token.NESTED_BLOCK: - markUsedAtRules(tokens[i][2], markCallback, atRules, context); - } - } -} - -function matchCounterStyle(token$1, atRules) { - var match; - - if (token$1[0] == token.AT_RULE_BLOCK && token$1[1][0][1].indexOf('@counter-style') === 0) { - match = token$1[1][0][1].split(' ')[1]; - atRules[match] = atRules[match] || []; - atRules[match].push(token$1); - } -} - -function markCounterStylesAsUsed(atRules) { - return function (token, context) { - var property; - var wrappedProperty; - var i, l; - - for (i = 0, l = token[2].length; i < l; i++) { - property = token[2][i]; - - if (property[1][1] == 'list-style') { - wrappedProperty = wrapForOptimizing(property); - populateComponents_1([wrappedProperty], context.validator, context.warnings); - - if (wrappedProperty.components[0].value[0][1] in atRules) { - delete atRules[property[2][1]]; - } - - restoreFromOptimizing_1([wrappedProperty]); - } - - if (property[1][1] == 'list-style-type' && property[2][1] in atRules) { - delete atRules[property[2][1]]; - } - } - }; -} - -function matchFontFace(token$1, atRules) { - var property; - var match; - var i, l; - - if (token$1[0] == token.AT_RULE_BLOCK && token$1[1][0][1] == '@font-face') { - for (i = 0, l = token$1[2].length; i < l; i++) { - property = token$1[2][i]; - - if (property[1][1] == 'font-family') { - match = normalize$1(property[2][1].toLowerCase()); - atRules[match] = atRules[match] || []; - atRules[match].push(token$1); - break; - } - } - } -} - -function markFontFacesAsUsed(atRules) { - return function (token, context) { - var property; - var wrappedProperty; - var component; - var normalizedMatch; - var i, l; - var j, m; - - for (i = 0, l = token[2].length; i < l; i++) { - property = token[2][i]; - - if (property[1][1] == 'font') { - wrappedProperty = wrapForOptimizing(property); - populateComponents_1([wrappedProperty], context.validator, context.warnings); - component = wrappedProperty.components[6]; - - for (j = 0, m = component.value.length; j < m; j++) { - normalizedMatch = normalize$1(component.value[j][1].toLowerCase()); - - if (normalizedMatch in atRules) { - delete atRules[normalizedMatch]; - } - } - - restoreFromOptimizing_1([wrappedProperty]); - } - - if (property[1][1] == 'font-family') { - for (j = 2, m = property.length; j < m; j++) { - normalizedMatch = normalize$1(property[j][1].toLowerCase()); - - if (normalizedMatch in atRules) { - delete atRules[normalizedMatch]; - } - } - } - } - }; -} - -function matchKeyframe(token$1, atRules) { - var match; - - if (token$1[0] == token.NESTED_BLOCK && keyframeRegex.test(token$1[1][0][1])) { - match = token$1[1][0][1].split(' ')[1]; - atRules[match] = atRules[match] || []; - atRules[match].push(token$1); - } -} - -function markKeyframesAsUsed(atRules) { - return function (token, context) { - var property; - var wrappedProperty; - var component; - var i, l; - var j, m; - - for (i = 0, l = token[2].length; i < l; i++) { - property = token[2][i]; - - if (animationRegex.test(property[1][1])) { - wrappedProperty = wrapForOptimizing(property); - populateComponents_1([wrappedProperty], context.validator, context.warnings); - component = wrappedProperty.components[7]; - - for (j = 0, m = component.value.length; j < m; j++) { - if (component.value[j][1] in atRules) { - delete atRules[component.value[j][1]]; - } - } - - restoreFromOptimizing_1([wrappedProperty]); - } - - if (animationNameRegex.test(property[1][1])) { - for (j = 2, m = property.length; j < m; j++) { - if (property[j][1] in atRules) { - delete atRules[property[j][1]]; - } - } - } - } - }; -} - -function matchNamespace(token$1, atRules) { - var match; - - if (token$1[0] == token.AT_RULE && token$1[1].indexOf('@namespace') === 0) { - match = token$1[1].split(' ')[1]; - atRules[match] = atRules[match] || []; - atRules[match].push(token$1); - } -} - -function markNamespacesAsUsed(atRules) { - var namespaceRegex = new RegExp(Object.keys(atRules).join('\\\||') + '\\\|', 'g'); - - return function (token) { - var match; - var scope; - var normalizedMatch; - var i, l; - var j, m; - - for (i = 0, l = token[1].length; i < l; i++) { - scope = token[1][i]; - match = scope[1].match(namespaceRegex); - - for (j = 0, m = match.length; j < m; j++) { - normalizedMatch = match[j].substring(0, match[j].length - 1); - - if (normalizedMatch in atRules) { - delete atRules[normalizedMatch]; - } - } - } - }; -} - -var removeUnusedAtRules_1 = removeUnusedAtRules; - -function ruleSorter(s1, s2) { - return s1[1] > s2[1] ? 1 : -1; -} - -function tidyRuleDuplicates(rules) { - var list = []; - var repeated = []; - - for (var i = 0, l = rules.length; i < l; i++) { - var rule = rules[i]; - - if (repeated.indexOf(rule[1]) == -1) { - repeated.push(rule[1]); - list.push(rule); - } - } - - return list.sort(ruleSorter); -} - -var tidyRuleDuplicates_1 = tidyRuleDuplicates; - -var canReorderSingle = reorderable.canReorderSingle; - - - - - - - - -var serializeBody = oneTime.body; -var serializeRules = oneTime.rules; - -function naturalSorter(a, b) { - return a > b ? 1 : -1; -} - -function cloneAndMergeSelectors(propertyA, propertyB) { - var cloned = cloneArray_1(propertyA); - cloned[5] = cloned[5].concat(propertyB[5]); - - return cloned; -} - -function restructure(tokens, context) { - var options = context.options; - var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses; - var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements; - var mergeLimit = options.compatibility.selectors.mergeLimit; - var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging; - var specificityCache = context.cache.specificity; - var movableTokens = {}; - var movedProperties = []; - var multiPropertyMoveCache = {}; - var movedToBeDropped = []; - var maxCombinationsLevel = 2; - var ID_JOIN_CHARACTER = '%'; - - function sendToMultiPropertyMoveCache(position, movedProperty, allFits) { - for (var i = allFits.length - 1; i >= 0; i--) { - var fit = allFits[i][0]; - var id = addToCache(movedProperty, fit); - - if (multiPropertyMoveCache[id].length > 1 && processMultiPropertyMove(position, multiPropertyMoveCache[id])) { - removeAllMatchingFromCache(id); - break; - } - } - } - - function addToCache(movedProperty, fit) { - var id = cacheId(fit); - multiPropertyMoveCache[id] = multiPropertyMoveCache[id] || []; - multiPropertyMoveCache[id].push([movedProperty, fit]); - return id; - } - - function removeAllMatchingFromCache(matchId) { - var matchSelectors = matchId.split(ID_JOIN_CHARACTER); - var forRemoval = []; - var i; - - for (var id in multiPropertyMoveCache) { - var selectors = id.split(ID_JOIN_CHARACTER); - for (i = selectors.length - 1; i >= 0; i--) { - if (matchSelectors.indexOf(selectors[i]) > -1) { - forRemoval.push(id); - break; - } - } - } - - for (i = forRemoval.length - 1; i >= 0; i--) { - delete multiPropertyMoveCache[forRemoval[i]]; - } - } - - function cacheId(cachedTokens) { - var id = []; - for (var i = 0, l = cachedTokens.length; i < l; i++) { - id.push(serializeRules(cachedTokens[i][1])); - } - return id.join(ID_JOIN_CHARACTER); - } - - function tokensToMerge(sourceTokens) { - var uniqueTokensWithBody = []; - var mergeableTokens = []; - - for (var i = sourceTokens.length - 1; i >= 0; i--) { - if (!isMergeable_1(serializeRules(sourceTokens[i][1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)) { - continue; - } - - mergeableTokens.unshift(sourceTokens[i]); - if (sourceTokens[i][2].length > 0 && uniqueTokensWithBody.indexOf(sourceTokens[i]) == -1) - uniqueTokensWithBody.push(sourceTokens[i]); - } - - return uniqueTokensWithBody.length > 1 ? - mergeableTokens : - []; - } - - function shortenIfPossible(position, movedProperty) { - var name = movedProperty[0]; - var value = movedProperty[1]; - var key = movedProperty[4]; - var valueSize = name.length + value.length + 1; - var allSelectors = []; - var qualifiedTokens = []; - - var mergeableTokens = tokensToMerge(movableTokens[key]); - if (mergeableTokens.length < 2) - return; - - var allFits = findAllFits(mergeableTokens, valueSize, 1); - var bestFit = allFits[0]; - if (bestFit[1] > 0) - return sendToMultiPropertyMoveCache(position, movedProperty, allFits); - - for (var i = bestFit[0].length - 1; i >=0; i--) { - allSelectors = bestFit[0][i][1].concat(allSelectors); - qualifiedTokens.unshift(bestFit[0][i]); - } - - allSelectors = tidyRuleDuplicates_1(allSelectors); - dropAsNewTokenAt(position, [movedProperty], allSelectors, qualifiedTokens); - } - - function fitSorter(fit1, fit2) { - return fit1[1] > fit2[1] ? 1 : (fit1[1] == fit2[1] ? 0 : -1); - } - - function findAllFits(mergeableTokens, propertySize, propertiesCount) { - var combinations = allCombinations(mergeableTokens, propertySize, propertiesCount, maxCombinationsLevel - 1); - return combinations.sort(fitSorter); - } - - function allCombinations(tokensVariant, propertySize, propertiesCount, level) { - var differenceVariants = [[tokensVariant, sizeDifference(tokensVariant, propertySize, propertiesCount)]]; - if (tokensVariant.length > 2 && level > 0) { - for (var i = tokensVariant.length - 1; i >= 0; i--) { - var subVariant = Array.prototype.slice.call(tokensVariant, 0); - subVariant.splice(i, 1); - differenceVariants = differenceVariants.concat(allCombinations(subVariant, propertySize, propertiesCount, level - 1)); - } - } - - return differenceVariants; - } - - function sizeDifference(tokensVariant, propertySize, propertiesCount) { - var allSelectorsSize = 0; - for (var i = tokensVariant.length - 1; i >= 0; i--) { - allSelectorsSize += tokensVariant[i][2].length > propertiesCount ? serializeRules(tokensVariant[i][1]).length : -1; - } - return allSelectorsSize - (tokensVariant.length - 1) * propertySize + 1; - } - - function dropAsNewTokenAt(position, properties, allSelectors, mergeableTokens) { - var i, j, k, m; - var allProperties = []; - - for (i = mergeableTokens.length - 1; i >= 0; i--) { - var mergeableToken = mergeableTokens[i]; - - for (j = mergeableToken[2].length - 1; j >= 0; j--) { - var mergeableProperty = mergeableToken[2][j]; - - for (k = 0, m = properties.length; k < m; k++) { - var property = properties[k]; - - var mergeablePropertyName = mergeableProperty[1][1]; - var propertyName = property[0]; - var propertyBody = property[4]; - if (mergeablePropertyName == propertyName && serializeBody([mergeableProperty]) == propertyBody) { - mergeableToken[2].splice(j, 1); - break; - } - } - } - } - - for (i = properties.length - 1; i >= 0; i--) { - allProperties.unshift(properties[i][3]); - } - - var newToken = [token.RULE, allSelectors, allProperties]; - tokens.splice(position, 0, newToken); - } - - function dropPropertiesAt(position, movedProperty) { - var key = movedProperty[4]; - var toMove = movableTokens[key]; - - if (toMove && toMove.length > 1) { - if (!shortenMultiMovesIfPossible(position, movedProperty)) - shortenIfPossible(position, movedProperty); - } - } - - function shortenMultiMovesIfPossible(position, movedProperty) { - var candidates = []; - var propertiesAndMergableTokens = []; - var key = movedProperty[4]; - var j, k; - - var mergeableTokens = tokensToMerge(movableTokens[key]); - if (mergeableTokens.length < 2) - return; - - movableLoop: - for (var value in movableTokens) { - var tokensList = movableTokens[value]; - - for (j = mergeableTokens.length - 1; j >= 0; j--) { - if (tokensList.indexOf(mergeableTokens[j]) == -1) - continue movableLoop; - } - - candidates.push(value); - } - - if (candidates.length < 2) - return false; - - for (j = candidates.length - 1; j >= 0; j--) { - for (k = movedProperties.length - 1; k >= 0; k--) { - if (movedProperties[k][4] == candidates[j]) { - propertiesAndMergableTokens.unshift([movedProperties[k], mergeableTokens]); - break; - } - } - } - - return processMultiPropertyMove(position, propertiesAndMergableTokens); - } - - function processMultiPropertyMove(position, propertiesAndMergableTokens) { - var valueSize = 0; - var properties = []; - var property; - - for (var i = propertiesAndMergableTokens.length - 1; i >= 0; i--) { - property = propertiesAndMergableTokens[i][0]; - var fullValue = property[4]; - valueSize += fullValue.length + (i > 0 ? 1 : 0); - - properties.push(property); - } - - var mergeableTokens = propertiesAndMergableTokens[0][1]; - var bestFit = findAllFits(mergeableTokens, valueSize, properties.length)[0]; - if (bestFit[1] > 0) - return false; - - var allSelectors = []; - var qualifiedTokens = []; - for (i = bestFit[0].length - 1; i >= 0; i--) { - allSelectors = bestFit[0][i][1].concat(allSelectors); - qualifiedTokens.unshift(bestFit[0][i]); - } - - allSelectors = tidyRuleDuplicates_1(allSelectors); - dropAsNewTokenAt(position, properties, allSelectors, qualifiedTokens); - - for (i = properties.length - 1; i >= 0; i--) { - property = properties[i]; - var index = movedProperties.indexOf(property); - - delete movableTokens[property[4]]; - - if (index > -1 && movedToBeDropped.indexOf(index) == -1) - movedToBeDropped.push(index); - } - - return true; - } - - function boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) { - var propertyName = property[0]; - var movedPropertyName = movedProperty[0]; - if (propertyName != movedPropertyName) - return false; - - var key = movedProperty[4]; - var toMove = movableTokens[key]; - return toMove && toMove.indexOf(token) > -1; - } - - for (var i = tokens.length - 1; i >= 0; i--) { - var token$1 = tokens[i]; - var isRule; - var j, k, m; - var samePropertyAt; - - if (token$1[0] == token.RULE) { - isRule = true; - } else if (token$1[0] == token.NESTED_BLOCK) { - isRule = false; - } else { - continue; - } - - // We cache movedProperties.length as it may change in the loop - var movedCount = movedProperties.length; - - var properties = extractProperties_1(token$1); - movedToBeDropped = []; - - var unmovableInCurrentToken = []; - for (j = properties.length - 1; j >= 0; j--) { - for (k = j - 1; k >= 0; k--) { - if (!canReorderSingle(properties[j], properties[k], specificityCache)) { - unmovableInCurrentToken.push(j); - break; - } - } - } - - for (j = properties.length - 1; j >= 0; j--) { - var property = properties[j]; - var movedSameProperty = false; - - for (k = 0; k < movedCount; k++) { - var movedProperty = movedProperties[k]; - - if (movedToBeDropped.indexOf(k) == -1 && (!canReorderSingle(property, movedProperty, specificityCache) && !boundToAnotherPropertyInCurrrentToken(property, movedProperty, token$1) || - movableTokens[movedProperty[4]] && movableTokens[movedProperty[4]].length === mergeLimit)) { - dropPropertiesAt(i + 1, movedProperty); - - if (movedToBeDropped.indexOf(k) == -1) { - movedToBeDropped.push(k); - delete movableTokens[movedProperty[4]]; - } - } - - if (!movedSameProperty) { - movedSameProperty = property[0] == movedProperty[0] && property[1] == movedProperty[1]; - - if (movedSameProperty) { - samePropertyAt = k; - } - } - } - - if (!isRule || unmovableInCurrentToken.indexOf(j) > -1) - continue; - - var key = property[4]; - - if (movedSameProperty && movedProperties[samePropertyAt][5].length + property[5].length > mergeLimit) { - dropPropertiesAt(i + 1, movedProperties[samePropertyAt]); - movedProperties.splice(samePropertyAt, 1); - movableTokens[key] = [token$1]; - movedSameProperty = false; - } else { - movableTokens[key] = movableTokens[key] || []; - movableTokens[key].push(token$1); - } - - if (movedSameProperty) { - movedProperties[samePropertyAt] = cloneAndMergeSelectors(movedProperties[samePropertyAt], property); - } else { - movedProperties.push(property); - } - } - - movedToBeDropped = movedToBeDropped.sort(naturalSorter); - for (j = 0, m = movedToBeDropped.length; j < m; j++) { - var dropAt = movedToBeDropped[j] - j; - movedProperties.splice(dropAt, 1); - } - } - - var position = tokens[0] && tokens[0][0] == token.AT_RULE && tokens[0][1].indexOf('@charset') === 0 ? 1 : 0; - for (; position < tokens.length - 1; position++) { - var isImportRule = tokens[position][0] === token.AT_RULE && tokens[position][1].indexOf('@import') === 0; - var isComment = tokens[position][0] === token.COMMENT; - if (!(isImportRule || isComment)) - break; - } - - for (i = 0; i < movedProperties.length; i++) { - dropPropertiesAt(position, movedProperties[i]); - } -} - -var restructure_1 = restructure; - -var OptimizationLevel = optimizationLevel.OptimizationLevel; - - - -function removeEmpty(tokens) { - for (var i = 0, l = tokens.length; i < l; i++) { - var token$1 = tokens[i]; - var isEmpty = false; - - switch (token$1[0]) { - case token.RULE: - isEmpty = token$1[1].length === 0 || token$1[2].length === 0; - break; - case token.NESTED_BLOCK: - removeEmpty(token$1[2]); - isEmpty = token$1[2].length === 0; - break; - case token.AT_RULE: - isEmpty = token$1[1].length === 0; - break; - case token.AT_RULE_BLOCK: - isEmpty = token$1[2].length === 0; - } - - if (isEmpty) { - tokens.splice(i, 1); - i--; - l--; - } - } -} - -function recursivelyOptimizeBlocks(tokens, context) { - for (var i = 0, l = tokens.length; i < l; i++) { - var token$1 = tokens[i]; - - if (token$1[0] == token.NESTED_BLOCK) { - var isKeyframes = /@(-moz-|-o-|-webkit-)?keyframes/.test(token$1[1][0][1]); - level2Optimize(token$1[2], context, !isKeyframes); - } - } -} - -function recursivelyOptimizeProperties(tokens, context) { - for (var i = 0, l = tokens.length; i < l; i++) { - var token$1 = tokens[i]; - - switch (token$1[0]) { - case token.RULE: - optimize$1(token$1[2], true, true, context); - break; - case token.NESTED_BLOCK: - recursivelyOptimizeProperties(token$1[2], context); - } - } -} - -function level2Optimize(tokens, context, withRestructuring) { - var levelOptions = context.options.level[OptimizationLevel.Two]; - var reduced; - var i; - - recursivelyOptimizeBlocks(tokens, context); - recursivelyOptimizeProperties(tokens, context); - - if (levelOptions.removeDuplicateRules) { - removeDuplicates_1(tokens); - } - - if (levelOptions.mergeAdjacentRules) { - mergeAdjacent_1(tokens, context); - } - - if (levelOptions.reduceNonAdjacentRules) { - reduceNonAdjacent_1(tokens, context); - } - - if (levelOptions.mergeNonAdjacentRules && levelOptions.mergeNonAdjacentRules != 'body') { - mergeNonAdjacentBySelector_1(tokens, context); - } - - if (levelOptions.mergeNonAdjacentRules && levelOptions.mergeNonAdjacentRules != 'selector') { - mergeNonAdjacentByBody_1(tokens, context); - } - - if (levelOptions.restructureRules && levelOptions.mergeAdjacentRules && withRestructuring) { - restructure_1(tokens, context); - mergeAdjacent_1(tokens, context); - } - - if (levelOptions.restructureRules && !levelOptions.mergeAdjacentRules && withRestructuring) { - restructure_1(tokens, context); - } - - if (levelOptions.removeDuplicateFontRules) { - removeDuplicateFontAtRules_1(tokens); - } - - if (levelOptions.removeDuplicateMediaBlocks) { - removeDuplicateMediaQueries_1(tokens); - } - - if (levelOptions.removeUnusedAtRules) { - removeUnusedAtRules_1(tokens, context); - } - - if (levelOptions.mergeMedia) { - reduced = mergeMediaQueries_1(tokens, context); - for (i = reduced.length - 1; i >= 0; i--) { - level2Optimize(reduced[i][2], context, false); - } - } - - if (levelOptions.removeEmpty) { - removeEmpty(tokens); - } - - return tokens; -} - -var optimize = level2Optimize; - -var functionNoVendorRegexStr = '[A-Z]+(\\-|[A-Z]|[0-9])+\\(.*?\\)'; -var functionVendorRegexStr = '\\-(\\-|[A-Z]|[0-9])+\\(.*?\\)'; -var variableRegexStr = 'var\\(\\-\\-[^\\)]+\\)'; -var functionAnyRegexStr = '(' + variableRegexStr + '|' + functionNoVendorRegexStr + '|' + functionVendorRegexStr + ')'; - -var calcRegex = new RegExp('^(\\-moz\\-|\\-webkit\\-)?calc\\([^\\)]+\\)$', 'i'); -var decimalRegex = /[0-9]/; -var functionAnyRegex = new RegExp('^' + functionAnyRegexStr + '$', 'i'); -var hslColorRegex = /^hsl\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+%\s{0,31}\)|hsla\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+\s{0,31}\)$/i; -var identifierRegex = /^(\-[a-z0-9_][a-z0-9\-_]*|[a-z][a-z0-9\-_]*)$/i; -var namedEntityRegex = /^[a-z]+$/i; -var prefixRegex = /^-([a-z0-9]|-)*$/i; -var rgbColorRegex = /^rgb\(\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31}\)|rgba\(\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\.\d]+\s{0,31}\)$/i; -var timingFunctionRegex = /^(cubic\-bezier|steps)\([^\)]+\)$/; -var validTimeUnits = ['ms', 's']; -var urlRegex = /^url\([\s\S]+\)$/i; -var variableRegex = new RegExp('^' + variableRegexStr + '$', 'i'); - -var eightValueColorRegex = /^#[0-9a-f]{8}$/i; -var fourValueColorRegex = /^#[0-9a-f]{4}$/i; -var sixValueColorRegex = /^#[0-9a-f]{6}$/i; -var threeValueColorRegex = /^#[0-9a-f]{3}$/i; - -var DECIMAL_DOT = '.'; -var MINUS_SIGN = '-'; -var PLUS_SIGN = '+'; - -var Keywords = { - '^': [ - 'inherit', - 'initial', - 'unset' - ], - '*-style': [ - 'auto', - 'dashed', - 'dotted', - 'double', - 'groove', - 'hidden', - 'inset', - 'none', - 'outset', - 'ridge', - 'solid' - ], - '*-timing-function': [ - 'ease', - 'ease-in', - 'ease-in-out', - 'ease-out', - 'linear', - 'step-end', - 'step-start' - ], - 'animation-direction': [ - 'alternate', - 'alternate-reverse', - 'normal', - 'reverse' - ], - 'animation-fill-mode': [ - 'backwards', - 'both', - 'forwards', - 'none' - ], - 'animation-iteration-count': [ - 'infinite' - ], - 'animation-name': [ - 'none' - ], - 'animation-play-state': [ - 'paused', - 'running' - ], - 'background-attachment': [ - 'fixed', - 'inherit', - 'local', - 'scroll' - ], - 'background-clip': [ - 'border-box', - 'content-box', - 'inherit', - 'padding-box', - 'text' - ], - 'background-origin': [ - 'border-box', - 'content-box', - 'inherit', - 'padding-box' - ], - 'background-position': [ - 'bottom', - 'center', - 'left', - 'right', - 'top' - ], - 'background-repeat': [ - 'no-repeat', - 'inherit', - 'repeat', - 'repeat-x', - 'repeat-y', - 'round', - 'space' - ], - 'background-size': [ - 'auto', - 'cover', - 'contain' - ], - 'border-collapse': [ - 'collapse', - 'inherit', - 'separate' - ], - 'bottom': [ - 'auto' - ], - 'clear': [ - 'both', - 'left', - 'none', - 'right' - ], - 'color': [ - 'transparent' - ], - 'cursor': [ - 'all-scroll', - 'auto', - 'col-resize', - 'crosshair', - 'default', - 'e-resize', - 'help', - 'move', - 'n-resize', - 'ne-resize', - 'no-drop', - 'not-allowed', - 'nw-resize', - 'pointer', - 'progress', - 'row-resize', - 's-resize', - 'se-resize', - 'sw-resize', - 'text', - 'vertical-text', - 'w-resize', - 'wait' - ], - 'display': [ - 'block', - 'inline', - 'inline-block', - 'inline-table', - 'list-item', - 'none', - 'table', - 'table-caption', - 'table-cell', - 'table-column', - 'table-column-group', - 'table-footer-group', - 'table-header-group', - 'table-row', - 'table-row-group' - ], - 'float': [ - 'left', - 'none', - 'right' - ], - 'left': [ - 'auto' - ], - 'font': [ - 'caption', - 'icon', - 'menu', - 'message-box', - 'small-caption', - 'status-bar', - 'unset' - ], - 'font-size': [ - 'large', - 'larger', - 'medium', - 'small', - 'smaller', - 'x-large', - 'x-small', - 'xx-large', - 'xx-small' - ], - 'font-stretch': [ - 'condensed', - 'expanded', - 'extra-condensed', - 'extra-expanded', - 'normal', - 'semi-condensed', - 'semi-expanded', - 'ultra-condensed', - 'ultra-expanded' - ], - 'font-style': [ - 'italic', - 'normal', - 'oblique' - ], - 'font-variant': [ - 'normal', - 'small-caps' - ], - 'font-weight': [ - '100', - '200', - '300', - '400', - '500', - '600', - '700', - '800', - '900', - 'bold', - 'bolder', - 'lighter', - 'normal' - ], - 'line-height': [ - 'normal' - ], - 'list-style-position': [ - 'inside', - 'outside' - ], - 'list-style-type': [ - 'armenian', - 'circle', - 'decimal', - 'decimal-leading-zero', - 'disc', - 'decimal|disc', // this is the default value of list-style-type, see comment in compactable.js - 'georgian', - 'lower-alpha', - 'lower-greek', - 'lower-latin', - 'lower-roman', - 'none', - 'square', - 'upper-alpha', - 'upper-latin', - 'upper-roman' - ], - 'overflow': [ - 'auto', - 'hidden', - 'scroll', - 'visible' - ], - 'position': [ - 'absolute', - 'fixed', - 'relative', - 'static' - ], - 'right': [ - 'auto' - ], - 'text-align': [ - 'center', - 'justify', - 'left', - 'left|right', // this is the default value of list-style-type, see comment in compactable.js - 'right' - ], - 'text-decoration': [ - 'line-through', - 'none', - 'overline', - 'underline' - ], - 'text-overflow': [ - 'clip', - 'ellipsis' - ], - 'top': [ - 'auto' - ], - 'vertical-align': [ - 'baseline', - 'bottom', - 'middle', - 'sub', - 'super', - 'text-bottom', - 'text-top', - 'top' - ], - 'visibility': [ - 'collapse', - 'hidden', - 'visible' - ], - 'white-space': [ - 'normal', - 'nowrap', - 'pre' - ], - 'width': [ - 'inherit', - 'initial', - 'medium', - 'thick', - 'thin' - ] -}; - -var Units = [ - '%', - 'ch', - 'cm', - 'em', - 'ex', - 'in', - 'mm', - 'pc', - 'pt', - 'px', - 'rem', - 'vh', - 'vm', - 'vmax', - 'vmin', - 'vw' -]; - -function isColor(value) { - return value != 'auto' && - ( - isKeyword('color')(value) || - isHexColor(value) || - isColorFunction(value) || - isNamedEntity(value) - ); -} - -function isColorFunction(value) { - return isRgbColor(value) || isHslColor(value); -} - -function isDynamicUnit(value) { - return calcRegex.test(value); -} - -function isFunction(value) { - return functionAnyRegex.test(value); -} - -function isHexColor(value) { - return threeValueColorRegex.test(value) || fourValueColorRegex.test(value) || sixValueColorRegex.test(value) || eightValueColorRegex.test(value); -} - -function isHslColor(value) { - return hslColorRegex.test(value); -} - -function isIdentifier(value) { - return identifierRegex.test(value); -} - -function isImage(value) { - return value == 'none' || value == 'inherit' || isUrl(value); -} - -function isKeyword(propertyName) { - return function(value) { - return Keywords[propertyName].indexOf(value) > -1; - }; -} - -function isNamedEntity(value) { - return namedEntityRegex.test(value); -} - -function isNumber(value) { - return scanForNumber(value) == value.length; -} - -function isRgbColor(value) { - return rgbColorRegex.test(value); -} - -function isPrefixed(value) { - return prefixRegex.test(value); -} - -function isPositiveNumber(value) { - return isNumber(value) && - parseFloat(value) >= 0; -} - -function isVariable(value) { - return variableRegex.test(value); -} - -function isTime(value) { - var numberUpTo = scanForNumber(value); - - return numberUpTo == value.length && parseInt(value) === 0 || - numberUpTo > -1 && validTimeUnits.indexOf(value.slice(numberUpTo + 1)) > -1; -} - -function isTimingFunction() { - var isTimingFunctionKeyword = isKeyword('*-timing-function'); - - return function (value) { - return isTimingFunctionKeyword(value) || timingFunctionRegex.test(value); - }; -} - -function isUnit(validUnits, value) { - var numberUpTo = scanForNumber(value); - - return numberUpTo == value.length && parseInt(value) === 0 || - numberUpTo > -1 && validUnits.indexOf(value.slice(numberUpTo + 1)) > -1 || - value == 'auto' || - value == 'inherit'; -} - -function isUrl(value) { - return urlRegex.test(value); -} - -function isZIndex(value) { - return value == 'auto' || - isNumber(value) || - isKeyword('^')(value); -} - -function scanForNumber(value) { - var hasDot = false; - var hasSign = false; - var character; - var i, l; - - for (i = 0, l = value.length; i < l; i++) { - character = value[i]; - - if (i === 0 && (character == PLUS_SIGN || character == MINUS_SIGN)) { - hasSign = true; - } else if (i > 0 && hasSign && (character == PLUS_SIGN || character == MINUS_SIGN)) { - return i - 1; - } else if (character == DECIMAL_DOT && !hasDot) { - hasDot = true; - } else if (character == DECIMAL_DOT && hasDot) { - return i - 1; - } else if (decimalRegex.test(character)) { - continue; - } else { - return i - 1; - } - } - - return i; -} - -function validator(compatibility) { - var validUnits = Units.slice(0).filter(function (value) { - return !(value in compatibility.units) || compatibility.units[value] === true; - }); - - return { - colorOpacity: compatibility.colors.opacity, - isAnimationDirectionKeyword: isKeyword('animation-direction'), - isAnimationFillModeKeyword: isKeyword('animation-fill-mode'), - isAnimationIterationCountKeyword: isKeyword('animation-iteration-count'), - isAnimationNameKeyword: isKeyword('animation-name'), - isAnimationPlayStateKeyword: isKeyword('animation-play-state'), - isTimingFunction: isTimingFunction(), - isBackgroundAttachmentKeyword: isKeyword('background-attachment'), - isBackgroundClipKeyword: isKeyword('background-clip'), - isBackgroundOriginKeyword: isKeyword('background-origin'), - isBackgroundPositionKeyword: isKeyword('background-position'), - isBackgroundRepeatKeyword: isKeyword('background-repeat'), - isBackgroundSizeKeyword: isKeyword('background-size'), - isColor: isColor, - isColorFunction: isColorFunction, - isDynamicUnit: isDynamicUnit, - isFontKeyword: isKeyword('font'), - isFontSizeKeyword: isKeyword('font-size'), - isFontStretchKeyword: isKeyword('font-stretch'), - isFontStyleKeyword: isKeyword('font-style'), - isFontVariantKeyword: isKeyword('font-variant'), - isFontWeightKeyword: isKeyword('font-weight'), - isFunction: isFunction, - isGlobal: isKeyword('^'), - isHslColor: isHslColor, - isIdentifier: isIdentifier, - isImage: isImage, - isKeyword: isKeyword, - isLineHeightKeyword: isKeyword('line-height'), - isListStylePositionKeyword: isKeyword('list-style-position'), - isListStyleTypeKeyword: isKeyword('list-style-type'), - isNumber: isNumber, - isPrefixed: isPrefixed, - isPositiveNumber: isPositiveNumber, - isRgbColor: isRgbColor, - isStyleKeyword: isKeyword('*-style'), - isTime: isTime, - isUnit: isUnit.bind(null, validUnits), - isUrl: isUrl, - isVariable: isVariable, - isWidth: isKeyword('width'), - isZIndex: isZIndex - }; -} - -var validator_1 = validator; - -var DEFAULTS = { - '*': { - colors: { - opacity: true // rgba / hsla - }, - properties: { - backgroundClipMerging: true, // background-clip to shorthand - backgroundOriginMerging: true, // background-origin to shorthand - backgroundSizeMerging: true, // background-size to shorthand - colors: true, // any kind of color transformations, like `#ff00ff` to `#f0f` or `#fff` into `red` - ieBangHack: false, // !ie suffix hacks on IE<8 - ieFilters: false, // whether to preserve `filter` and `-ms-filter` properties - iePrefixHack: false, // underscore / asterisk prefix hacks on IE - ieSuffixHack: false, // \9 suffix hacks on IE6-9 - merging: true, // merging properties into one - shorterLengthUnits: false, // optimize pixel units into `pt`, `pc` or `in` units - spaceAfterClosingBrace: true, // 'url() no-repeat' to 'url()no-repeat' - urlQuotes: false, // whether to wrap content of `url()` into quotes or not - zeroUnits: true // 0[unit] -> 0 - }, - selectors: { - adjacentSpace: false, // div+ nav Android stock browser hack - ie7Hack: false, // *+html hack - mergeablePseudoClasses: [ - ':active', - ':after', - ':before', - ':empty', - ':checked', - ':disabled', - ':empty', - ':enabled', - ':first-child', - ':first-letter', - ':first-line', - ':first-of-type', - ':focus', - ':hover', - ':lang', - ':last-child', - ':last-of-type', - ':link', - ':not', - ':nth-child', - ':nth-last-child', - ':nth-last-of-type', - ':nth-of-type', - ':only-child', - ':only-of-type', - ':root', - ':target', - ':visited' - ], // selectors with these pseudo-classes can be merged as these are universally supported - mergeablePseudoElements: [ - '::after', - '::before', - '::first-letter', - '::first-line' - ], // selectors with these pseudo-elements can be merged as these are universally supported - mergeLimit: 8191, // number of rules that can be safely merged together - multiplePseudoMerging: true - }, - units: { - ch: true, - in: true, - pc: true, - pt: true, - rem: true, - vh: true, - vm: true, // vm is vmin on IE9+ see https://developer.mozilla.org/en-US/docs/Web/CSS/length - vmax: true, - vmin: true, - vw: true - } - } -}; - -DEFAULTS.ie11 = DEFAULTS['*']; - -DEFAULTS.ie10 = DEFAULTS['*']; - -DEFAULTS.ie9 = merge(DEFAULTS['*'], { - properties: { - ieFilters: true, - ieSuffixHack: true - } -}); - -DEFAULTS.ie8 = merge(DEFAULTS.ie9, { - colors: { - opacity: false - }, - properties: { - backgroundClipMerging: false, - backgroundOriginMerging: false, - backgroundSizeMerging: false, - iePrefixHack: true, - merging: false - }, - selectors: { - mergeablePseudoClasses: [ - ':after', - ':before', - ':first-child', - ':first-letter', - ':focus', - ':hover', - ':visited' - ], - mergeablePseudoElements: [] - }, - units: { - ch: false, - rem: false, - vh: false, - vm: false, - vmax: false, - vmin: false, - vw: false - } -}); - -DEFAULTS.ie7 = merge(DEFAULTS.ie8, { - properties: { - ieBangHack: true - }, - selectors: { - ie7Hack: true, - mergeablePseudoClasses: [ - ':first-child', - ':first-letter', - ':hover', - ':visited' - ] - }, -}); - -function compatibilityFrom(source) { - return merge(DEFAULTS['*'], calculateSource(source)); -} - -function merge(source, target) { - for (var key in source) { - var value = source[key]; - - if (typeof value === 'object' && !Array.isArray(value)) { - target[key] = merge(value, target[key] || {}); - } else { - target[key] = key in target ? target[key] : value; - } - } - - return target; -} - -function calculateSource(source) { - if (typeof source == 'object') - return source; - - if (!/[,\+\-]/.test(source)) - return DEFAULTS[source] || DEFAULTS['*']; - - var parts = source.split(','); - var template = parts[0] in DEFAULTS ? - DEFAULTS[parts.shift()] : - DEFAULTS['*']; - - source = {}; - - parts.forEach(function (part) { - var isAdd = part[0] == '+'; - var key = part.substring(1).split('.'); - var group = key[0]; - var option = key[1]; - - source[group] = source[group] || {}; - source[group][option] = isAdd; - }); - - return merge(template, source); -} - -var compatibility = compatibilityFrom; - -var HTTP_RESOURCE_PATTERN = /^http:\/\//; - -function isHttpResource(uri) { - return HTTP_RESOURCE_PATTERN.test(uri); -} - -var isHttpResource_1 = isHttpResource; - -var HTTPS_RESOURCE_PATTERN = /^https:\/\//; - -function isHttpsResource(uri) { - return HTTPS_RESOURCE_PATTERN.test(uri); -} - -var isHttpsResource_1 = isHttpsResource; - -var HTTP_PROTOCOL$1 = 'http:'; - -function loadRemoteResource(uri, inlineRequest, inlineTimeout, callback) { - var proxyProtocol = inlineRequest.protocol || inlineRequest.hostname; - var errorHandled = false; - var requestOptions; - var fetch; - - requestOptions = override_1( - url__default.parse(uri), - inlineRequest || {} - ); - - if (inlineRequest.hostname !== undefined) { - // overwrite as we always expect a http proxy currently - requestOptions.protocol = inlineRequest.protocol || HTTP_PROTOCOL$1; - requestOptions.path = requestOptions.href; - } - - fetch = (proxyProtocol && !isHttpsResource_1(proxyProtocol)) || isHttpResource_1(uri) ? - http__default.get : - https__default.get; - - fetch(requestOptions, function (res) { - var chunks = []; - var movedUri; - - if (errorHandled) { - return; - } - - if (res.statusCode < 200 || res.statusCode > 399) { - return callback(res.statusCode, null); - } else if (res.statusCode > 299) { - movedUri = url__default.resolve(uri, res.headers.location); - return loadRemoteResource(movedUri, inlineRequest, inlineTimeout, callback); - } - - res.on('data', function (chunk) { - chunks.push(chunk.toString()); - }); - res.on('end', function () { - var body = chunks.join(''); - callback(null, body); - }); - }) - .on('error', function (res) { - if (errorHandled) { - return; - } - - errorHandled = true; - callback(res.message, null); - }) - .on('timeout', function () { - if (errorHandled) { - return; - } - - errorHandled = true; - callback('timeout', null); - }) - .setTimeout(inlineTimeout); -} - -var loadRemoteResource_1 = loadRemoteResource; - -function fetchFrom(callback) { - return callback || loadRemoteResource_1; -} - -var fetch = fetchFrom; - -function inlineOptionsFrom(rules) { - if (Array.isArray(rules)) { - return rules; - } - - if (rules === false) { - return ['none']; - } - - return undefined === rules ? - ['local'] : - rules.split(','); -} - -var inline$1 = inlineOptionsFrom; - -function inlineRequestFrom(option) { - return override_1( - /* jshint camelcase: false */ - proxyOptionsFrom(process.env.HTTP_PROXY || process.env.http_proxy), - option || {} - ); -} - -function proxyOptionsFrom(httpProxy) { - return httpProxy ? - { - hostname: url__default.parse(httpProxy).hostname, - port: parseInt(url__default.parse(httpProxy).port) - } : - {}; -} - -var inlineRequest = inlineRequestFrom; - -var DEFAULT_TIMEOUT = 5000; - -function inlineTimeoutFrom(option) { - return option || DEFAULT_TIMEOUT; -} - -var inlineTimeout = inlineTimeoutFrom; - -function rebaseFrom(rebaseOption) { - return undefined === rebaseOption ? true : !!rebaseOption; -} - -var rebase$2 = rebaseFrom; - -function rebaseToFrom(option) { - return option ? path__default.resolve(option) : process.cwd(); -} - -var rebaseTo = rebaseToFrom; - -var SourceMapConsumer = build.sourceMap.SourceMapConsumer; - -function inputSourceMapTracker() { - var maps = {}; - - return { - all: all$2.bind(null, maps), - isTracking: isTracking.bind(null, maps), - originalPositionFor: originalPositionFor.bind(null, maps), - track: track$2.bind(null, maps) - }; -} - -function all$2(maps) { - return maps; -} - -function isTracking(maps, source) { - return source in maps; -} - -function originalPositionFor(maps, metadata, range, selectorFallbacks) { - var line = metadata[0]; - var column = metadata[1]; - var source = metadata[2]; - var position = { - line: line, - column: column + range - }; - var originalPosition; - - while (!originalPosition && position.column > column) { - position.column--; - originalPosition = maps[source].originalPositionFor(position); - } - - if (!originalPosition || originalPosition.column < 0) { - return metadata; - } - - if (originalPosition.line === null && line > 1 && selectorFallbacks > 0) { - return originalPositionFor(maps, [line - 1, column, source], range, selectorFallbacks - 1); - } - - return originalPosition.line !== null ? - toMetadata(originalPosition) : - metadata; -} - -function toMetadata(asHash) { - return [asHash.line, asHash.column, asHash.source]; -} - -function track$2(maps, source, data) { - maps[source] = new SourceMapConsumer(data); -} - -var inputSourceMapTracker_1 = inputSourceMapTracker; - -var REMOTE_RESOURCE_PATTERN = /^(\w+:\/\/|\/\/)/; - -function isRemoteResource(uri) { - return REMOTE_RESOURCE_PATTERN.test(uri); -} - -var isRemoteResource_1 = isRemoteResource; - -var NO_PROTOCOL_RESOURCE_PATTERN = /^\/\//; - -function hasProtocol(uri) { - return !NO_PROTOCOL_RESOURCE_PATTERN.test(uri); -} - -var hasProtocol_1 = hasProtocol; - -var HTTP_PROTOCOL = 'http:'; - -function isAllowedResource(uri, isRemote, rules) { - var match; - var absoluteUri; - var allowed = isRemote ? false : true; - var rule; - var isNegated; - var normalizedRule; - var i; - - if (rules.length === 0) { - return false; - } - - if (isRemote && !hasProtocol_1(uri)) { - uri = HTTP_PROTOCOL + uri; - } - - match = isRemote ? - url__default.parse(uri).host : - uri; - - absoluteUri = isRemote ? - uri : - path__default.resolve(uri); - - for (i = 0; i < rules.length; i++) { - rule = rules[i]; - isNegated = rule[0] == '!'; - normalizedRule = rule.substring(1); - - if (isNegated && isRemote && isRemoteRule(normalizedRule)) { - allowed = allowed && !isAllowedResource(uri, true, [normalizedRule]); - } else if (isNegated && !isRemote && !isRemoteRule(normalizedRule)) { - allowed = allowed && !isAllowedResource(uri, false, [normalizedRule]); - } else if (isNegated) { - allowed = allowed && true; - } else if (rule == 'all') { - allowed = true; - } else if (isRemote && rule == 'local') { - allowed = allowed || false; - } else if (isRemote && rule == 'remote') { - allowed = true; - } else if (!isRemote && rule == 'remote') { - allowed = false; - } else if (!isRemote && rule == 'local') { - allowed = true; - } else if (rule === match) { - allowed = true; - } else if (rule === uri) { - allowed = true; - } else if (isRemote && absoluteUri.indexOf(rule) === 0) { - allowed = true; - } else if (!isRemote && absoluteUri.indexOf(path__default.resolve(rule)) === 0) { - allowed = true; - } else if (isRemote != isRemoteRule(normalizedRule)) { - allowed = allowed && true; - } else { - allowed = false; - } - } - - return allowed; -} - -function isRemoteRule(rule) { - return isRemoteResource_1(rule) || url__default.parse(HTTP_PROTOCOL + '//' + rule).host == rule; -} - -var isAllowedResource_1 = isAllowedResource; - -var DATA_URI_PATTERN$1 = /^data:(\S*?)?(;charset=[^;]+)?(;[^,]+?)?,(.+)/; - -function matchDataUri(uri) { - return DATA_URI_PATTERN$1.exec(uri); -} - -var matchDataUri_1 = matchDataUri; - -function rebaseLocalMap(sourceMap, sourceUri, rebaseTo) { - var currentPath = path__default.resolve(''); - var absoluteUri = path__default.resolve(currentPath, sourceUri); - var absoluteUriDirectory = path__default.dirname(absoluteUri); - - sourceMap.sources = sourceMap.sources.map(function(source) { - return path__default.relative(rebaseTo, path__default.resolve(absoluteUriDirectory, source)); - }); - - return sourceMap; -} - -var rebaseLocalMap_1 = rebaseLocalMap; - -function rebaseRemoteMap(sourceMap, sourceUri) { - var sourceDirectory = path__default.dirname(sourceUri); - - sourceMap.sources = sourceMap.sources.map(function(source) { - return url__default.resolve(sourceDirectory, source); - }); - - return sourceMap; -} - -var rebaseRemoteMap_1 = rebaseRemoteMap; - -var DATA_URI_PATTERN = /^data:(\S*?)?(;charset=[^;]+)?(;[^,]+?)?,(.+)/; - -function isDataUriResource(uri) { - return DATA_URI_PATTERN.test(uri); -} - -var isDataUriResource_1 = isDataUriResource; - -var MAP_MARKER_PATTERN = /^\/\*# sourceMappingURL=(\S+) \*\/$/; - -function applySourceMaps(tokens, context, callback) { - var applyContext = { - callback: callback, - fetch: context.options.fetch, - index: 0, - inline: context.options.inline, - inlineRequest: context.options.inlineRequest, - inlineTimeout: context.options.inlineTimeout, - inputSourceMapTracker: context.inputSourceMapTracker, - localOnly: context.localOnly, - processedTokens: [], - rebaseTo: context.options.rebaseTo, - sourceTokens: tokens, - warnings: context.warnings - }; - - return context.options.sourceMap && tokens.length > 0 ? - doApplySourceMaps(applyContext) : - callback(tokens); -} - -function doApplySourceMaps(applyContext) { - var singleSourceTokens = []; - var lastSource = findTokenSource(applyContext.sourceTokens[0]); - var source; - var token$1; - var l; - - for (l = applyContext.sourceTokens.length; applyContext.index < l; applyContext.index++) { - token$1 = applyContext.sourceTokens[applyContext.index]; - source = findTokenSource(token$1); - - if (source != lastSource) { - singleSourceTokens = []; - lastSource = source; - } - - singleSourceTokens.push(token$1); - applyContext.processedTokens.push(token$1); - - if (token$1[0] == token.COMMENT && MAP_MARKER_PATTERN.test(token$1[1])) { - return fetchAndApplySourceMap(token$1[1], source, singleSourceTokens, applyContext); - } - } - - return applyContext.callback(applyContext.processedTokens); -} - -function findTokenSource(token$1) { - var scope; - var metadata; - - if (token$1[0] == token.AT_RULE || token$1[0] == token.COMMENT) { - metadata = token$1[2][0]; - } else { - scope = token$1[1][0]; - metadata = scope[2][0]; - } - - return metadata[2]; -} - -function fetchAndApplySourceMap(sourceMapComment, source, singleSourceTokens, applyContext) { - return extractInputSourceMapFrom(sourceMapComment, applyContext, function (inputSourceMap) { - if (inputSourceMap) { - applyContext.inputSourceMapTracker.track(source, inputSourceMap); - applySourceMapRecursively(singleSourceTokens, applyContext.inputSourceMapTracker); - } - - applyContext.index++; - return doApplySourceMaps(applyContext); - }); -} - -function extractInputSourceMapFrom(sourceMapComment, applyContext, whenSourceMapReady) { - var uri = MAP_MARKER_PATTERN.exec(sourceMapComment)[1]; - var absoluteUri; - var sourceMap; - var rebasedMap; - - if (isDataUriResource_1(uri)) { - sourceMap = extractInputSourceMapFromDataUri(uri); - return whenSourceMapReady(sourceMap); - } else if (isRemoteResource_1(uri)) { - return loadInputSourceMapFromRemoteUri(uri, applyContext, function (sourceMap) { - var parsedMap; - - if (sourceMap) { - parsedMap = JSON.parse(sourceMap); - rebasedMap = rebaseRemoteMap_1(parsedMap, uri); - whenSourceMapReady(rebasedMap); - } else { - whenSourceMapReady(null); - } - }); - } else { - // at this point `uri` is already rebased, see lib/reader/rebase.js#rebaseSourceMapComment - // it is rebased to be consistent with rebasing other URIs - // however here we need to resolve it back to read it from disk - absoluteUri = path__default.resolve(applyContext.rebaseTo, uri); - sourceMap = loadInputSourceMapFromLocalUri(absoluteUri, applyContext); - - if (sourceMap) { - rebasedMap = rebaseLocalMap_1(sourceMap, absoluteUri, applyContext.rebaseTo); - return whenSourceMapReady(rebasedMap); - } else { - return whenSourceMapReady(null); - } - } -} - -function extractInputSourceMapFromDataUri(uri) { - var dataUriMatch = matchDataUri_1(uri); - var charset = dataUriMatch[2] ? dataUriMatch[2].split(/[=;]/)[2] : 'us-ascii'; - var encoding = dataUriMatch[3] ? dataUriMatch[3].split(';')[1] : 'utf8'; - var data = encoding == 'utf8' ? build.commonjsGlobal.unescape(dataUriMatch[4]) : dataUriMatch[4]; - - var buffer = new Buffer(data, encoding); - buffer.charset = charset; - - return JSON.parse(buffer.toString()); -} - -function loadInputSourceMapFromRemoteUri(uri, applyContext, whenLoaded) { - var isAllowed = isAllowedResource_1(uri, true, applyContext.inline); - var isRuntimeResource = !hasProtocol_1(uri); - - if (applyContext.localOnly) { - applyContext.warnings.push('Cannot fetch remote resource from "' + uri + '" as no callback given.'); - return whenLoaded(null); - } else if (isRuntimeResource) { - applyContext.warnings.push('Cannot fetch "' + uri + '" as no protocol given.'); - return whenLoaded(null); - } else if (!isAllowed) { - applyContext.warnings.push('Cannot fetch "' + uri + '" as resource is not allowed.'); - return whenLoaded(null); - } - - applyContext.fetch(uri, applyContext.inlineRequest, applyContext.inlineTimeout, function (error, body) { - if (error) { - applyContext.warnings.push('Missing source map at "' + uri + '" - ' + error); - return whenLoaded(null); - } - - whenLoaded(body); - }); -} - -function loadInputSourceMapFromLocalUri(uri, applyContext) { - var isAllowed = isAllowedResource_1(uri, false, applyContext.inline); - var sourceMap; - - if (!fs__default.existsSync(uri) || !fs__default.statSync(uri).isFile()) { - applyContext.warnings.push('Ignoring local source map at "' + uri + '" as resource is missing.'); - return null; - } else if (!isAllowed) { - applyContext.warnings.push('Cannot fetch "' + uri + '" as resource is not allowed.'); - return null; - } - - sourceMap = fs__default.readFileSync(uri, 'utf-8'); - return JSON.parse(sourceMap); -} - -function applySourceMapRecursively(tokens, inputSourceMapTracker) { - var token$1; - var i, l; - - for (i = 0, l = tokens.length; i < l; i++) { - token$1 = tokens[i]; - - switch (token$1[0]) { - case token.AT_RULE: - applySourceMapTo(token$1, inputSourceMapTracker); - break; - case token.AT_RULE_BLOCK: - applySourceMapRecursively(token$1[1], inputSourceMapTracker); - applySourceMapRecursively(token$1[2], inputSourceMapTracker); - break; - case token.AT_RULE_BLOCK_SCOPE: - applySourceMapTo(token$1, inputSourceMapTracker); - break; - case token.NESTED_BLOCK: - applySourceMapRecursively(token$1[1], inputSourceMapTracker); - applySourceMapRecursively(token$1[2], inputSourceMapTracker); - break; - case token.NESTED_BLOCK_SCOPE: - applySourceMapTo(token$1, inputSourceMapTracker); - break; - case token.COMMENT: - applySourceMapTo(token$1, inputSourceMapTracker); - break; - case token.PROPERTY: - applySourceMapRecursively(token$1, inputSourceMapTracker); - break; - case token.PROPERTY_BLOCK: - applySourceMapRecursively(token$1[1], inputSourceMapTracker); - break; - case token.PROPERTY_NAME: - applySourceMapTo(token$1, inputSourceMapTracker); - break; - case token.PROPERTY_VALUE: - applySourceMapTo(token$1, inputSourceMapTracker); - break; - case token.RULE: - applySourceMapRecursively(token$1[1], inputSourceMapTracker); - applySourceMapRecursively(token$1[2], inputSourceMapTracker); - break; - case token.RULE_SCOPE: - applySourceMapTo(token$1, inputSourceMapTracker); - } - } - - return tokens; -} - -function applySourceMapTo(token, inputSourceMapTracker) { - var value = token[1]; - var metadata = token[2]; - var newMetadata = []; - var i, l; - - for (i = 0, l = metadata.length; i < l; i++) { - newMetadata.push(inputSourceMapTracker.originalPositionFor(metadata[i], value.length)); - } - - token[2] = newMetadata; -} - -var applySourceMaps_1 = applySourceMaps; - -var BRACE_PREFIX = /^\(/; -var BRACE_SUFFIX = /\)$/; -var IMPORT_PREFIX_PATTERN$1 = /^@import/i; -var QUOTE_PREFIX_PATTERN$1 = /['"]\s*/; -var QUOTE_SUFFIX_PATTERN$1 = /\s*['"]/; -var URL_PREFIX_PATTERN$1 = /^url\(\s*/i; -var URL_SUFFIX_PATTERN$1 = /\s*\)/i; - -function extractImportUrlAndMedia(atRuleValue) { - var uri; - var mediaQuery; - var stripped; - var parts; - - stripped = atRuleValue - .replace(IMPORT_PREFIX_PATTERN$1, '') - .trim() - .replace(URL_PREFIX_PATTERN$1, '(') - .replace(URL_SUFFIX_PATTERN$1, ')') - .replace(QUOTE_PREFIX_PATTERN$1, '') - .replace(QUOTE_SUFFIX_PATTERN$1, ''); - - parts = split_1(stripped, ' '); - - uri = parts[0] - .replace(BRACE_PREFIX, '') - .replace(BRACE_SUFFIX, ''); - mediaQuery = parts.slice(1).join(' '); - - return [uri, mediaQuery]; -} - -var extractImportUrlAndMedia_1 = extractImportUrlAndMedia; - -function loadOriginalSources(context, callback) { - var loadContext = { - callback: callback, - fetch: context.options.fetch, - index: 0, - inline: context.options.inline, - inlineRequest: context.options.inlineRequest, - inlineTimeout: context.options.inlineTimeout, - localOnly: context.localOnly, - rebaseTo: context.options.rebaseTo, - sourcesContent: context.sourcesContent, - uriToSource: uriToSourceMapping(context.inputSourceMapTracker.all()), - warnings: context.warnings - }; - - return context.options.sourceMap && context.options.sourceMapInlineSources ? - doLoadOriginalSources(loadContext) : - callback(); -} - -function uriToSourceMapping(allSourceMapConsumers) { - var mapping = {}; - var consumer; - var uri; - var source; - var i, l; - - for (source in allSourceMapConsumers) { - consumer = allSourceMapConsumers[source]; - - for (i = 0, l = consumer.sources.length; i < l; i++) { - uri = consumer.sources[i]; - source = consumer.sourceContentFor(uri, true); - - mapping[uri] = source; - } - } - - return mapping; -} - -function doLoadOriginalSources(loadContext) { - var uris = Object.keys(loadContext.uriToSource); - var uri; - var source; - var total; - - for (total = uris.length; loadContext.index < total; loadContext.index++) { - uri = uris[loadContext.index]; - source = loadContext.uriToSource[uri]; - - if (source) { - loadContext.sourcesContent[uri] = source; - } else { - return loadOriginalSource(uri, loadContext); - } - } - - return loadContext.callback(); -} - -function loadOriginalSource(uri, loadContext) { - var content; - - if (isRemoteResource_1(uri)) { - return loadOriginalSourceFromRemoteUri(uri, loadContext, function (content) { - loadContext.index++; - loadContext.sourcesContent[uri] = content; - return doLoadOriginalSources(loadContext); - }); - } else { - content = loadOriginalSourceFromLocalUri(uri, loadContext); - loadContext.index++; - loadContext.sourcesContent[uri] = content; - return doLoadOriginalSources(loadContext); - } -} - -function loadOriginalSourceFromRemoteUri(uri, loadContext, whenLoaded) { - var isAllowed = isAllowedResource_1(uri, true, loadContext.inline); - var isRuntimeResource = !hasProtocol_1(uri); - - if (loadContext.localOnly) { - loadContext.warnings.push('Cannot fetch remote resource from "' + uri + '" as no callback given.'); - return whenLoaded(null); - } else if (isRuntimeResource) { - loadContext.warnings.push('Cannot fetch "' + uri + '" as no protocol given.'); - return whenLoaded(null); - } else if (!isAllowed) { - loadContext.warnings.push('Cannot fetch "' + uri + '" as resource is not allowed.'); - return whenLoaded(null); - } - - loadContext.fetch(uri, loadContext.inlineRequest, loadContext.inlineTimeout, function (error, content) { - if (error) { - loadContext.warnings.push('Missing original source at "' + uri + '" - ' + error); - } - - whenLoaded(content); - }); -} - -function loadOriginalSourceFromLocalUri(relativeUri, loadContext) { - var isAllowed = isAllowedResource_1(relativeUri, false, loadContext.inline); - var absoluteUri = path__default.resolve(loadContext.rebaseTo, relativeUri); - - if (!fs__default.existsSync(absoluteUri) || !fs__default.statSync(absoluteUri).isFile()) { - loadContext.warnings.push('Ignoring local source map at "' + absoluteUri + '" as resource is missing.'); - return null; - } else if (!isAllowed) { - loadContext.warnings.push('Cannot fetch "' + absoluteUri + '" as resource is not allowed.'); - return null; - } - - return fs__default.readFileSync(absoluteUri, 'utf8'); -} - -var loadOriginalSources_1 = loadOriginalSources; - -var UNIX_SEPARATOR = '/'; -var WINDOWS_SEPARATOR_PATTERN = /\\/g; - -function normalizePath(path) { - return path.replace(WINDOWS_SEPARATOR_PATTERN, UNIX_SEPARATOR); -} - -var normalizePath_1 = normalizePath; - -function restoreImport(uri, mediaQuery) { - return ('@import ' + uri + ' ' + mediaQuery).trim(); -} - -var restoreImport_1 = restoreImport; - -var DOUBLE_QUOTE = '"'; -var SINGLE_QUOTE = '\''; -var URL_PREFIX = 'url('; -var URL_SUFFIX = ')'; - -var QUOTE_PREFIX_PATTERN = /^["']/; -var QUOTE_SUFFIX_PATTERN = /["']$/; -var ROUND_BRACKETS_PATTERN = /[\(\)]/; -var URL_PREFIX_PATTERN = /^url\(/i; -var URL_SUFFIX_PATTERN = /\)$/; -var WHITESPACE_PATTERN = /\s/; - -var isWindows$1 = process.platform == 'win32'; - -function rebase$1(uri, rebaseConfig) { - if (!rebaseConfig) { - return uri; - } - - if (isAbsolute(uri) && !isRemote(rebaseConfig.toBase)) { - return uri; - } - - if (isRemote(uri) || isSVGMarker(uri) || isInternal(uri)) { - return uri; - } - - if (isData(uri)) { - return '\'' + uri + '\''; - } - - if (isRemote(rebaseConfig.toBase)) { - return url__default.resolve(rebaseConfig.toBase, uri); - } - - return rebaseConfig.absolute ? - normalize(absolute(uri, rebaseConfig)) : - normalize(relative(uri, rebaseConfig)); -} - -function isAbsolute(uri) { - return path__default.isAbsolute(uri); -} - -function isSVGMarker(uri) { - return uri[0] == '#'; -} - -function isInternal(uri) { - return /^\w+:\w+/.test(uri); -} - -function isRemote(uri) { - return /^[^:]+?:\/\//.test(uri) || uri.indexOf('//') === 0; -} - -function isData(uri) { - return uri.indexOf('data:') === 0; -} - -function absolute(uri, rebaseConfig) { - return path__default - .resolve(path__default.join(rebaseConfig.fromBase || '', uri)) - .replace(rebaseConfig.toBase, ''); -} - -function relative(uri, rebaseConfig) { - return path__default.relative(rebaseConfig.toBase, path__default.join(rebaseConfig.fromBase || '', uri)); -} - -function normalize(uri) { - return isWindows$1 ? uri.replace(/\\/g, '/') : uri; -} - -function quoteFor(unquotedUrl) { - if (unquotedUrl.indexOf(SINGLE_QUOTE) > -1) { - return DOUBLE_QUOTE; - } else if (unquotedUrl.indexOf(DOUBLE_QUOTE) > -1) { - return SINGLE_QUOTE; - } else if (hasWhitespace(unquotedUrl) || hasRoundBrackets(unquotedUrl)) { - return SINGLE_QUOTE; - } else { - return ''; - } -} - -function hasWhitespace(url) { - return WHITESPACE_PATTERN.test(url); -} - -function hasRoundBrackets(url) { - return ROUND_BRACKETS_PATTERN.test(url); -} - -function rewriteUrl(originalUrl, rebaseConfig, pathOnly) { - var strippedUrl = originalUrl - .replace(URL_PREFIX_PATTERN, '') - .replace(URL_SUFFIX_PATTERN, '') - .trim(); - - var unquotedUrl = strippedUrl - .replace(QUOTE_PREFIX_PATTERN, '') - .replace(QUOTE_SUFFIX_PATTERN, '') - .trim(); - - var quote = strippedUrl[0] == SINGLE_QUOTE || strippedUrl[0] == DOUBLE_QUOTE ? - strippedUrl[0] : - quoteFor(unquotedUrl); - - return pathOnly ? - rebase$1(unquotedUrl, rebaseConfig) : - URL_PREFIX + quote + rebase$1(unquotedUrl, rebaseConfig) + quote + URL_SUFFIX; -} - -var rewriteUrl_1 = rewriteUrl; - -var IMPORT_PREFIX_PATTERN = /^@import/i; - -function isImport(value) { - return IMPORT_PREFIX_PATTERN.test(value); -} - -var isImport_1 = isImport; - -var SOURCE_MAP_COMMENT_PATTERN = /^\/\*# sourceMappingURL=(\S+) \*\/$/; - -function rebase(tokens, rebaseAll, validator, rebaseConfig) { - return rebaseAll ? - rebaseEverything(tokens, validator, rebaseConfig) : - rebaseAtRules(tokens, validator, rebaseConfig); -} - -function rebaseEverything(tokens, validator, rebaseConfig) { - var token$1; - var i, l; - - for (i = 0, l = tokens.length; i < l; i++) { - token$1 = tokens[i]; - - switch (token$1[0]) { - case token.AT_RULE: - rebaseAtRule(token$1, validator, rebaseConfig); - break; - case token.AT_RULE_BLOCK: - rebaseProperties(token$1[2], validator, rebaseConfig); - break; - case token.COMMENT: - rebaseSourceMapComment(token$1, rebaseConfig); - break; - case token.NESTED_BLOCK: - rebaseEverything(token$1[2], validator, rebaseConfig); - break; - case token.RULE: - rebaseProperties(token$1[2], validator, rebaseConfig); - break; - } - } - - return tokens; -} - -function rebaseAtRules(tokens, validator, rebaseConfig) { - var token$1; - var i, l; - - for (i = 0, l = tokens.length; i < l; i++) { - token$1 = tokens[i]; - - switch (token$1[0]) { - case token.AT_RULE: - rebaseAtRule(token$1, validator, rebaseConfig); - break; - } - } - - return tokens; -} - -function rebaseAtRule(token, validator, rebaseConfig) { - if (!isImport_1(token[1])) { - return; - } - - var uriAndMediaQuery = extractImportUrlAndMedia_1(token[1]); - var newUrl = rewriteUrl_1(uriAndMediaQuery[0], rebaseConfig); - var mediaQuery = uriAndMediaQuery[1]; - - token[1] = restoreImport_1(newUrl, mediaQuery); -} - -function rebaseSourceMapComment(token, rebaseConfig) { - var matches = SOURCE_MAP_COMMENT_PATTERN.exec(token[1]); - - if (matches && matches[1].indexOf('data:') === -1) { - token[1] = token[1].replace(matches[1], rewriteUrl_1(matches[1], rebaseConfig, true)); - } -} - -function rebaseProperties(properties, validator, rebaseConfig) { - var property; - var value; - var i, l; - var j, m; - - for (i = 0, l = properties.length; i < l; i++) { - property = properties[i]; - - for (j = 2 /* 0 is Token.PROPERTY, 1 is name */, m = property.length; j < m; j++) { - value = property[j][1]; - - if (validator.isUrl(value)) { - property[j][1] = rewriteUrl_1(value, rebaseConfig); - } - } - } -} - -var rebase_1 = rebase; - -var Level = { - BLOCK: 'block', - COMMENT: 'comment', - DOUBLE_QUOTE: 'double-quote', - RULE: 'rule', - SINGLE_QUOTE: 'single-quote' -}; - -var AT_RULES = [ - '@charset', - '@import' -]; - -var BLOCK_RULES = [ - '@-moz-document', - '@document', - '@-moz-keyframes', - '@-ms-keyframes', - '@-o-keyframes', - '@-webkit-keyframes', - '@keyframes', - '@media', - '@supports' -]; - -var IGNORE_END_COMMENT_PATTERN = /\/\* clean\-css ignore:end \*\/$/; -var IGNORE_START_COMMENT_PATTERN = /^\/\* clean\-css ignore:start \*\//; - -var PAGE_MARGIN_BOXES = [ - '@bottom-center', - '@bottom-left', - '@bottom-left-corner', - '@bottom-right', - '@bottom-right-corner', - '@left-bottom', - '@left-middle', - '@left-top', - '@right-bottom', - '@right-middle', - '@right-top', - '@top-center', - '@top-left', - '@top-left-corner', - '@top-right', - '@top-right-corner' -]; - -var EXTRA_PAGE_BOXES = [ - '@footnote', - '@footnotes', - '@left', - '@page-float-bottom', - '@page-float-top', - '@right' -]; - -var REPEAT_PATTERN = /^\[\s{0,31}\d+\s{0,31}\]$/; -var RULE_WORD_SEPARATOR_PATTERN = /[\s\(]/; -var TAIL_BROKEN_VALUE_PATTERN = /[\s|\}]*$/; - -function tokenize(source, externalContext) { - var internalContext = { - level: Level.BLOCK, - position: { - source: externalContext.source || undefined, - line: 1, - column: 0, - index: 0 - } - }; - - return intoTokens(source, externalContext, internalContext, false); -} - -function intoTokens(source, externalContext, internalContext, isNested) { - var allTokens = []; - var newTokens = allTokens; - var lastToken; - var ruleToken; - var ruleTokens = []; - var propertyToken; - var metadata; - var metadatas = []; - var level = internalContext.level; - var levels = []; - var buffer = []; - var buffers = []; - var serializedBuffer; - var serializedBufferPart; - var roundBracketLevel = 0; - var isQuoted; - var isSpace; - var isNewLineNix; - var isNewLineWin; - var isCarriageReturn; - var isCommentStart; - var wasCommentStart = false; - var isCommentEnd; - var wasCommentEnd = false; - var isCommentEndMarker; - var isEscaped; - var wasEscaped = false; - var isRaw = false; - var seekingValue = false; - var seekingPropertyBlockClosing = false; - var position = internalContext.position; - var lastCommentStartAt; - - for (; position.index < source.length; position.index++) { - var character = source[position.index]; - - isQuoted = level == Level.SINGLE_QUOTE || level == Level.DOUBLE_QUOTE; - isSpace = character == marker.SPACE || character == marker.TAB; - isNewLineNix = character == marker.NEW_LINE_NIX; - isNewLineWin = character == marker.NEW_LINE_NIX && source[position.index - 1] == marker.CARRIAGE_RETURN; - isCarriageReturn = character == marker.CARRIAGE_RETURN && source[position.index + 1] && source[position.index + 1] != marker.NEW_LINE_NIX; - isCommentStart = !wasCommentEnd && level != Level.COMMENT && !isQuoted && character == marker.ASTERISK && source[position.index - 1] == marker.FORWARD_SLASH; - isCommentEndMarker = !wasCommentStart && !isQuoted && character == marker.FORWARD_SLASH && source[position.index - 1] == marker.ASTERISK; - isCommentEnd = level == Level.COMMENT && isCommentEndMarker; - roundBracketLevel = Math.max(roundBracketLevel, 0); - - metadata = buffer.length === 0 ? - [position.line, position.column, position.source] : - metadata; - - if (isEscaped) { - // previous character was a backslash - buffer.push(character); - } else if (!isCommentEnd && level == Level.COMMENT) { - buffer.push(character); - } else if (!isCommentStart && !isCommentEnd && isRaw) { - buffer.push(character); - } else if (isCommentStart && (level == Level.BLOCK || level == Level.RULE) && buffer.length > 1) { - // comment start within block preceded by some content, e.g. div/*<-- - metadatas.push(metadata); - buffer.push(character); - buffers.push(buffer.slice(0, buffer.length - 2)); - - buffer = buffer.slice(buffer.length - 2); - metadata = [position.line, position.column - 1, position.source]; - - levels.push(level); - level = Level.COMMENT; - } else if (isCommentStart) { - // comment start, e.g. /*<-- - levels.push(level); - level = Level.COMMENT; - buffer.push(character); - } else if (isCommentEnd && isIgnoreStartComment(buffer)) { - // ignore:start comment end, e.g. /* clean-css ignore:start */<-- - serializedBuffer = buffer.join('').trim() + character; - lastToken = [token.COMMENT, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]; - newTokens.push(lastToken); - - isRaw = true; - metadata = metadatas.pop() || null; - buffer = buffers.pop() || []; - } else if (isCommentEnd && isIgnoreEndComment(buffer)) { - // ignore:start comment end, e.g. /* clean-css ignore:end */<-- - serializedBuffer = buffer.join('') + character; - lastCommentStartAt = serializedBuffer.lastIndexOf(marker.FORWARD_SLASH + marker.ASTERISK); - - serializedBufferPart = serializedBuffer.substring(0, lastCommentStartAt); - lastToken = [token.RAW, serializedBufferPart, [originalMetadata(metadata, serializedBufferPart, externalContext)]]; - newTokens.push(lastToken); - - serializedBufferPart = serializedBuffer.substring(lastCommentStartAt); - metadata = [position.line, position.column - serializedBufferPart.length + 1, position.source]; - lastToken = [token.COMMENT, serializedBufferPart, [originalMetadata(metadata, serializedBufferPart, externalContext)]]; - newTokens.push(lastToken); - - isRaw = false; - level = levels.pop(); - metadata = metadatas.pop() || null; - buffer = buffers.pop() || []; - } else if (isCommentEnd) { - // comment end, e.g. /* comment */<-- - serializedBuffer = buffer.join('').trim() + character; - lastToken = [token.COMMENT, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]; - newTokens.push(lastToken); - - level = levels.pop(); - metadata = metadatas.pop() || null; - buffer = buffers.pop() || []; - } else if (isCommentEndMarker && source[position.index + 1] != marker.ASTERISK) { - externalContext.warnings.push('Unexpected \'*/\' at ' + formatPosition_1([position.line, position.column, position.source]) + '.'); - buffer = []; - } else if (character == marker.SINGLE_QUOTE && !isQuoted) { - // single quotation start, e.g. a[href^='https<-- - levels.push(level); - level = Level.SINGLE_QUOTE; - buffer.push(character); - } else if (character == marker.SINGLE_QUOTE && level == Level.SINGLE_QUOTE) { - // single quotation end, e.g. a[href^='https'<-- - level = levels.pop(); - buffer.push(character); - } else if (character == marker.DOUBLE_QUOTE && !isQuoted) { - // double quotation start, e.g. a[href^="<-- - levels.push(level); - level = Level.DOUBLE_QUOTE; - buffer.push(character); - } else if (character == marker.DOUBLE_QUOTE && level == Level.DOUBLE_QUOTE) { - // double quotation end, e.g. a[href^="https"<-- - level = levels.pop(); - buffer.push(character); - } else if (!isCommentStart && !isCommentEnd && character != marker.CLOSE_ROUND_BRACKET && character != marker.OPEN_ROUND_BRACKET && level != Level.COMMENT && !isQuoted && roundBracketLevel > 0) { - // character inside any function, e.g. hsla(.<-- - buffer.push(character); - } else if (character == marker.OPEN_ROUND_BRACKET && !isQuoted && level != Level.COMMENT && !seekingValue) { - // round open bracket, e.g. @import url(<-- - buffer.push(character); - - roundBracketLevel++; - } else if (character == marker.CLOSE_ROUND_BRACKET && !isQuoted && level != Level.COMMENT && !seekingValue) { - // round open bracket, e.g. @import url(test.css)<-- - buffer.push(character); - - roundBracketLevel--; - } else if (character == marker.SEMICOLON && level == Level.BLOCK && buffer[0] == marker.AT) { - // semicolon ending rule at block level, e.g. @import '...';<-- - serializedBuffer = buffer.join('').trim(); - allTokens.push([token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - - buffer = []; - } else if (character == marker.COMMA && level == Level.BLOCK && ruleToken) { - // comma separator at block level, e.g. a,div,<-- - serializedBuffer = buffer.join('').trim(); - ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, ruleToken[1].length)]]); - - buffer = []; - } else if (character == marker.COMMA && level == Level.BLOCK && tokenTypeFrom(buffer) == token.AT_RULE) { - // comma separator at block level, e.g. @import url(...) screen,<-- - // keep iterating as end semicolon will create the token - buffer.push(character); - } else if (character == marker.COMMA && level == Level.BLOCK) { - // comma separator at block level, e.g. a,<-- - ruleToken = [tokenTypeFrom(buffer), [], []]; - serializedBuffer = buffer.join('').trim(); - ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, 0)]]); - - buffer = []; - } else if (character == marker.OPEN_CURLY_BRACKET && level == Level.BLOCK && ruleToken && ruleToken[0] == token.NESTED_BLOCK) { - // open brace opening at-rule at block level, e.g. @media{<-- - serializedBuffer = buffer.join('').trim(); - ruleToken[1].push([token.NESTED_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - allTokens.push(ruleToken); - - levels.push(level); - position.column++; - position.index++; - buffer = []; - - ruleToken[2] = intoTokens(source, externalContext, internalContext, true); - ruleToken = null; - } else if (character == marker.OPEN_CURLY_BRACKET && level == Level.BLOCK && tokenTypeFrom(buffer) == token.NESTED_BLOCK) { - // open brace opening at-rule at block level, e.g. @media{<-- - serializedBuffer = buffer.join('').trim(); - ruleToken = ruleToken || [token.NESTED_BLOCK, [], []]; - ruleToken[1].push([token.NESTED_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - allTokens.push(ruleToken); - - levels.push(level); - position.column++; - position.index++; - buffer = []; - - ruleToken[2] = intoTokens(source, externalContext, internalContext, true); - ruleToken = null; - } else if (character == marker.OPEN_CURLY_BRACKET && level == Level.BLOCK) { - // open brace opening rule at block level, e.g. div{<-- - serializedBuffer = buffer.join('').trim(); - ruleToken = ruleToken || [tokenTypeFrom(buffer), [], []]; - ruleToken[1].push([tokenScopeFrom(ruleToken[0]), serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext, ruleToken[1].length)]]); - newTokens = ruleToken[2]; - allTokens.push(ruleToken); - - levels.push(level); - level = Level.RULE; - buffer = []; - } else if (character == marker.OPEN_CURLY_BRACKET && level == Level.RULE && seekingValue) { - // open brace opening rule at rule level, e.g. div{--variable:{<-- - ruleTokens.push(ruleToken); - ruleToken = [token.PROPERTY_BLOCK, []]; - propertyToken.push(ruleToken); - newTokens = ruleToken[1]; - - levels.push(level); - level = Level.RULE; - seekingValue = false; - } else if (character == marker.OPEN_CURLY_BRACKET && level == Level.RULE && isPageMarginBox(buffer)) { - // open brace opening page-margin box at rule level, e.g. @page{@top-center{<-- - serializedBuffer = buffer.join('').trim(); - ruleTokens.push(ruleToken); - ruleToken = [token.AT_RULE_BLOCK, [], []]; - ruleToken[1].push([token.AT_RULE_BLOCK_SCOPE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - newTokens.push(ruleToken); - newTokens = ruleToken[2]; - - levels.push(level); - level = Level.RULE; - buffer = []; - } else if (character == marker.COLON && level == Level.RULE && !seekingValue) { - // colon at rule level, e.g. a{color:<-- - serializedBuffer = buffer.join('').trim(); - propertyToken = [token.PROPERTY, [token.PROPERTY_NAME, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]]; - newTokens.push(propertyToken); - - seekingValue = true; - buffer = []; - } else if (character == marker.SEMICOLON && level == Level.RULE && propertyToken && ruleTokens.length > 0 && buffer.length > 0 && buffer[0] == marker.AT) { - // semicolon at rule level for at-rule, e.g. a{--color:{@apply(--other-color);<-- - serializedBuffer = buffer.join('').trim(); - ruleToken[1].push([token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - - buffer = []; - } else if (character == marker.SEMICOLON && level == Level.RULE && propertyToken && buffer.length > 0) { - // semicolon at rule level, e.g. a{color:red;<-- - serializedBuffer = buffer.join('').trim(); - propertyToken.push([token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - - propertyToken = null; - seekingValue = false; - buffer = []; - } else if (character == marker.SEMICOLON && level == Level.RULE && propertyToken && buffer.length === 0) { - // semicolon after bracketed value at rule level, e.g. a{color:rgb(...);<-- - propertyToken = null; - seekingValue = false; - } else if (character == marker.SEMICOLON && level == Level.RULE && buffer.length > 0 && buffer[0] == marker.AT) { - // semicolon for at-rule at rule level, e.g. a{@apply(--variable);<-- - serializedBuffer = buffer.join(''); - newTokens.push([token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - - seekingValue = false; - buffer = []; - } else if (character == marker.SEMICOLON && level == Level.RULE && seekingPropertyBlockClosing) { - // close brace after a property block at rule level, e.g. a{--custom:{color:red;};<-- - seekingPropertyBlockClosing = false; - buffer = []; - } else if (character == marker.SEMICOLON && level == Level.RULE && buffer.length === 0) ; else if (character == marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && seekingValue && buffer.length > 0 && ruleTokens.length > 0) { - // close brace at rule level, e.g. a{--color:{color:red}<-- - serializedBuffer = buffer.join(''); - propertyToken.push([token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - propertyToken = null; - ruleToken = ruleTokens.pop(); - newTokens = ruleToken[2]; - - level = levels.pop(); - seekingValue = false; - buffer = []; - } else if (character == marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && buffer.length > 0 && buffer[0] == marker.AT && ruleTokens.length > 0) { - // close brace at rule level for at-rule, e.g. a{--color:{@apply(--other-color)}<-- - serializedBuffer = buffer.join(''); - ruleToken[1].push([token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - propertyToken = null; - ruleToken = ruleTokens.pop(); - newTokens = ruleToken[2]; - - level = levels.pop(); - seekingValue = false; - buffer = []; - } else if (character == marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && ruleTokens.length > 0) { - // close brace at rule level after space, e.g. a{--color:{color:red }<-- - propertyToken = null; - ruleToken = ruleTokens.pop(); - newTokens = ruleToken[2]; - - level = levels.pop(); - seekingValue = false; - } else if (character == marker.CLOSE_CURLY_BRACKET && level == Level.RULE && propertyToken && buffer.length > 0) { - // close brace at rule level, e.g. a{color:red}<-- - serializedBuffer = buffer.join(''); - propertyToken.push([token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - propertyToken = null; - ruleToken = ruleTokens.pop(); - newTokens = allTokens; - - level = levels.pop(); - seekingValue = false; - buffer = []; - } else if (character == marker.CLOSE_CURLY_BRACKET && level == Level.RULE && buffer.length > 0 && buffer[0] == marker.AT) { - // close brace after at-rule at rule level, e.g. a{@apply(--variable)}<-- - propertyToken = null; - ruleToken = null; - serializedBuffer = buffer.join('').trim(); - newTokens.push([token.AT_RULE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - newTokens = allTokens; - - level = levels.pop(); - seekingValue = false; - buffer = []; - } else if (character == marker.CLOSE_CURLY_BRACKET && level == Level.RULE && levels[levels.length - 1] == Level.RULE) { - // close brace after a property block at rule level, e.g. a{--custom:{color:red;}<-- - propertyToken = null; - ruleToken = ruleTokens.pop(); - newTokens = ruleToken[2]; - - level = levels.pop(); - seekingValue = false; - seekingPropertyBlockClosing = true; - buffer = []; - } else if (character == marker.CLOSE_CURLY_BRACKET && level == Level.RULE) { - // close brace after a rule, e.g. a{color:red;}<-- - propertyToken = null; - ruleToken = null; - newTokens = allTokens; - - level = levels.pop(); - seekingValue = false; - } else if (character == marker.CLOSE_CURLY_BRACKET && level == Level.BLOCK && !isNested && position.index <= source.length - 1) { - // stray close brace at block level, e.g. a{color:red}color:blue}<-- - externalContext.warnings.push('Unexpected \'}\' at ' + formatPosition_1([position.line, position.column, position.source]) + '.'); - buffer.push(character); - } else if (character == marker.CLOSE_CURLY_BRACKET && level == Level.BLOCK) { - // close brace at block level, e.g. @media screen {...}<-- - break; - } else if (character == marker.OPEN_ROUND_BRACKET && level == Level.RULE && seekingValue) { - // round open bracket, e.g. a{color:hsla(<-- - buffer.push(character); - roundBracketLevel++; - } else if (character == marker.CLOSE_ROUND_BRACKET && level == Level.RULE && seekingValue && roundBracketLevel == 1) { - // round close bracket, e.g. a{color:hsla(0,0%,0%)<-- - buffer.push(character); - serializedBuffer = buffer.join('').trim(); - propertyToken.push([token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - - roundBracketLevel--; - buffer = []; - } else if (character == marker.CLOSE_ROUND_BRACKET && level == Level.RULE && seekingValue) { - // round close bracket within other brackets, e.g. a{width:calc((10rem / 2)<-- - buffer.push(character); - roundBracketLevel--; - } else if (character == marker.FORWARD_SLASH && source[position.index + 1] != marker.ASTERISK && level == Level.RULE && seekingValue && buffer.length > 0) { - // forward slash within a property, e.g. a{background:url(image.png) 0 0/<-- - serializedBuffer = buffer.join('').trim(); - propertyToken.push([token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - propertyToken.push([token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]); - - buffer = []; - } else if (character == marker.FORWARD_SLASH && source[position.index + 1] != marker.ASTERISK && level == Level.RULE && seekingValue) { - // forward slash within a property after space, e.g. a{background:url(image.png) 0 0 /<-- - propertyToken.push([token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]); - - buffer = []; - } else if (character == marker.COMMA && level == Level.RULE && seekingValue && buffer.length > 0) { - // comma within a property, e.g. a{background:url(image.png),<-- - serializedBuffer = buffer.join('').trim(); - propertyToken.push([token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - propertyToken.push([token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]); - - buffer = []; - } else if (character == marker.COMMA && level == Level.RULE && seekingValue) { - // comma within a property after space, e.g. a{background:url(image.png) ,<-- - propertyToken.push([token.PROPERTY_VALUE, character, [[position.line, position.column, position.source]]]); - - buffer = []; - } else if (character == marker.CLOSE_SQUARE_BRACKET && propertyToken && propertyToken.length > 1 && buffer.length > 0 && isRepeatToken(buffer)) { - buffer.push(character); - serializedBuffer = buffer.join('').trim(); - propertyToken[propertyToken.length - 1][1] += serializedBuffer; - - buffer = []; - } else if ((isSpace || (isNewLineNix && !isNewLineWin)) && level == Level.RULE && seekingValue && propertyToken && buffer.length > 0) { - // space or *nix newline within property, e.g. a{margin:0 <-- - serializedBuffer = buffer.join('').trim(); - propertyToken.push([token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - - buffer = []; - } else if (isNewLineWin && level == Level.RULE && seekingValue && propertyToken && buffer.length > 1) { - // win newline within property, e.g. a{margin:0\r\n<-- - serializedBuffer = buffer.join('').trim(); - propertyToken.push([token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - - buffer = []; - } else if (isNewLineWin && level == Level.RULE && seekingValue) { - // win newline - buffer = []; - } else if (buffer.length == 1 && isNewLineWin) { - // ignore windows newline which is composed of two characters - buffer.pop(); - } else if (buffer.length > 0 || !isSpace && !isNewLineNix && !isNewLineWin && !isCarriageReturn) { - // any character - buffer.push(character); - } - - wasEscaped = isEscaped; - isEscaped = !wasEscaped && character == marker.BACK_SLASH; - wasCommentStart = isCommentStart; - wasCommentEnd = isCommentEnd; - - position.line = (isNewLineWin || isNewLineNix || isCarriageReturn) ? position.line + 1 : position.line; - position.column = (isNewLineWin || isNewLineNix || isCarriageReturn) ? 0 : position.column + 1; - } - - if (seekingValue) { - externalContext.warnings.push('Missing \'}\' at ' + formatPosition_1([position.line, position.column, position.source]) + '.'); - } - - if (seekingValue && buffer.length > 0) { - serializedBuffer = buffer.join('').replace(TAIL_BROKEN_VALUE_PATTERN, ''); - propertyToken.push([token.PROPERTY_VALUE, serializedBuffer, [originalMetadata(metadata, serializedBuffer, externalContext)]]); - - buffer = []; - } - - if (buffer.length > 0) { - externalContext.warnings.push('Invalid character(s) \'' + buffer.join('') + '\' at ' + formatPosition_1(metadata) + '. Ignoring.'); - } - - return allTokens; -} - -function isIgnoreStartComment(buffer) { - return IGNORE_START_COMMENT_PATTERN.test(buffer.join('') + marker.FORWARD_SLASH); -} - -function isIgnoreEndComment(buffer) { - return IGNORE_END_COMMENT_PATTERN.test(buffer.join('') + marker.FORWARD_SLASH); -} - -function originalMetadata(metadata, value, externalContext, selectorFallbacks) { - var source = metadata[2]; - - return externalContext.inputSourceMapTracker.isTracking(source) ? - externalContext.inputSourceMapTracker.originalPositionFor(metadata, value.length, selectorFallbacks) : - metadata; -} - -function tokenTypeFrom(buffer) { - var isAtRule = buffer[0] == marker.AT || buffer[0] == marker.UNDERSCORE; - var ruleWord = buffer.join('').split(RULE_WORD_SEPARATOR_PATTERN)[0]; - - if (isAtRule && BLOCK_RULES.indexOf(ruleWord) > -1) { - return token.NESTED_BLOCK; - } else if (isAtRule && AT_RULES.indexOf(ruleWord) > -1) { - return token.AT_RULE; - } else if (isAtRule) { - return token.AT_RULE_BLOCK; - } else { - return token.RULE; - } -} - -function tokenScopeFrom(tokenType) { - if (tokenType == token.RULE) { - return token.RULE_SCOPE; - } else if (tokenType == token.NESTED_BLOCK) { - return token.NESTED_BLOCK_SCOPE; - } else if (tokenType == token.AT_RULE_BLOCK) { - return token.AT_RULE_BLOCK_SCOPE; - } -} - -function isPageMarginBox(buffer) { - var serializedBuffer = buffer.join('').trim(); - - return PAGE_MARGIN_BOXES.indexOf(serializedBuffer) > -1 || EXTRA_PAGE_BOXES.indexOf(serializedBuffer) > -1; -} - -function isRepeatToken(buffer) { - return REPEAT_PATTERN.test(buffer.join('') + marker.CLOSE_SQUARE_BRACKET); -} - -var tokenize_1 = tokenize; - -var UNKNOWN_URI = 'uri:unknown'; - -function readSources(input, context, callback) { - return doReadSources(input, context, function (tokens) { - return applySourceMaps_1(tokens, context, function () { - return loadOriginalSources_1(context, function () { return callback(tokens); }); - }); - }); -} - -function doReadSources(input, context, callback) { - if (typeof input == 'string') { - return fromString(input, context, callback); - } else if (Buffer.isBuffer(input)) { - return fromString(input.toString(), context, callback); - } else if (Array.isArray(input)) { - return fromArray(input, context, callback); - } else if (typeof input == 'object') { - return fromHash(input, context, callback); - } -} - -function fromString(input, context, callback) { - context.source = undefined; - context.sourcesContent[undefined] = input; - context.stats.originalSize += input.length; - - return fromStyles(input, context, { inline: context.options.inline }, callback); -} - -function fromArray(input, context, callback) { - var inputAsImports = input.reduce(function (accumulator, uriOrHash) { - if (typeof uriOrHash === 'string') { - return addStringSource(uriOrHash, accumulator); - } else { - return addHashSource(uriOrHash, context, accumulator); - } - - }, []); - - return fromStyles(inputAsImports.join(''), context, { inline: ['all'] }, callback); -} - -function fromHash(input, context, callback) { - var inputAsImports = addHashSource(input, context, []); - return fromStyles(inputAsImports.join(''), context, { inline: ['all'] }, callback); -} - -function addStringSource(input, imports) { - imports.push(restoreAsImport(normalizeUri(input))); - return imports; -} - -function addHashSource(input, context, imports) { - var uri; - var normalizedUri; - var source; - - for (uri in input) { - source = input[uri]; - normalizedUri = normalizeUri(uri); - - imports.push(restoreAsImport(normalizedUri)); - - context.sourcesContent[normalizedUri] = source.styles; - - if (source.sourceMap) { - trackSourceMap(source.sourceMap, normalizedUri, context); - } - } - - return imports; -} - -function normalizeUri(uri) { - var currentPath = path__default.resolve(''); - var absoluteUri; - var relativeToCurrentPath; - var normalizedUri; - - if (isRemoteResource_1(uri)) { - return uri; - } - - absoluteUri = path__default.isAbsolute(uri) ? - uri : - path__default.resolve(uri); - relativeToCurrentPath = path__default.relative(currentPath, absoluteUri); - normalizedUri = normalizePath_1(relativeToCurrentPath); - - return normalizedUri; -} - -function trackSourceMap(sourceMap, uri, context) { - var parsedMap = typeof sourceMap == 'string' ? - JSON.parse(sourceMap) : - sourceMap; - var rebasedMap = isRemoteResource_1(uri) ? - rebaseRemoteMap_1(parsedMap, uri) : - rebaseLocalMap_1(parsedMap, uri || UNKNOWN_URI, context.options.rebaseTo); - - context.inputSourceMapTracker.track(uri, rebasedMap); -} - -function restoreAsImport(uri) { - return restoreImport_1('url(' + uri + ')', '') + marker.SEMICOLON; -} - -function fromStyles(styles, context, parentInlinerContext, callback) { - var tokens; - var rebaseConfig = {}; - - if (!context.source) { - rebaseConfig.fromBase = path__default.resolve(''); - rebaseConfig.toBase = context.options.rebaseTo; - } else if (isRemoteResource_1(context.source)) { - rebaseConfig.fromBase = context.source; - rebaseConfig.toBase = context.source; - } else if (path__default.isAbsolute(context.source)) { - rebaseConfig.fromBase = path__default.dirname(context.source); - rebaseConfig.toBase = context.options.rebaseTo; - } else { - rebaseConfig.fromBase = path__default.dirname(path__default.resolve(context.source)); - rebaseConfig.toBase = context.options.rebaseTo; - } - - tokens = tokenize_1(styles, context); - tokens = rebase_1(tokens, context.options.rebase, context.validator, rebaseConfig); - - return allowsAnyImports(parentInlinerContext.inline) ? - inline(tokens, context, parentInlinerContext, callback) : - callback(tokens); -} - -function allowsAnyImports(inline) { - return !(inline.length == 1 && inline[0] == 'none'); -} - -function inline(tokens, externalContext, parentInlinerContext, callback) { - var inlinerContext = { - afterContent: false, - callback: callback, - errors: externalContext.errors, - externalContext: externalContext, - fetch: externalContext.options.fetch, - inlinedStylesheets: parentInlinerContext.inlinedStylesheets || externalContext.inlinedStylesheets, - inline: parentInlinerContext.inline, - inlineRequest: externalContext.options.inlineRequest, - inlineTimeout: externalContext.options.inlineTimeout, - isRemote: parentInlinerContext.isRemote || false, - localOnly: externalContext.localOnly, - outputTokens: [], - rebaseTo: externalContext.options.rebaseTo, - sourceTokens: tokens, - warnings: externalContext.warnings - }; - - return doInlineImports(inlinerContext); -} - -function doInlineImports(inlinerContext) { - var token$1; - var i, l; - - for (i = 0, l = inlinerContext.sourceTokens.length; i < l; i++) { - token$1 = inlinerContext.sourceTokens[i]; - - if (token$1[0] == token.AT_RULE && isImport_1(token$1[1])) { - inlinerContext.sourceTokens.splice(0, i); - return inlineStylesheet(token$1, inlinerContext); - } else if (token$1[0] == token.AT_RULE || token$1[0] == token.COMMENT) { - inlinerContext.outputTokens.push(token$1); - } else { - inlinerContext.outputTokens.push(token$1); - inlinerContext.afterContent = true; - } - } - - inlinerContext.sourceTokens = []; - return inlinerContext.callback(inlinerContext.outputTokens); -} - -function inlineStylesheet(token, inlinerContext) { - var uriAndMediaQuery = extractImportUrlAndMedia_1(token[1]); - var uri = uriAndMediaQuery[0]; - var mediaQuery = uriAndMediaQuery[1]; - var metadata = token[2]; - - return isRemoteResource_1(uri) ? - inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) : - inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext); -} - -function inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) { - var isAllowed = isAllowedResource_1(uri, true, inlinerContext.inline); - var originalUri = uri; - var isLoaded = uri in inlinerContext.externalContext.sourcesContent; - var isRuntimeResource = !hasProtocol_1(uri); - - if (inlinerContext.inlinedStylesheets.indexOf(uri) > -1) { - inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as it has already been imported.'); - inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); - return doInlineImports(inlinerContext); - } else if (inlinerContext.localOnly && inlinerContext.afterContent) { - inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as no callback given and after other content.'); - inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); - return doInlineImports(inlinerContext); - } else if (isRuntimeResource) { - inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as no protocol given.'); - inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1)); - inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); - return doInlineImports(inlinerContext); - } else if (inlinerContext.localOnly && !isLoaded) { - inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as no callback given.'); - inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1)); - inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); - return doInlineImports(inlinerContext); - } else if (!isAllowed && inlinerContext.afterContent) { - inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as resource is not allowed and after other content.'); - inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); - return doInlineImports(inlinerContext); - } else if (!isAllowed) { - inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as resource is not allowed.'); - inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1)); - inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); - return doInlineImports(inlinerContext); - } - - inlinerContext.inlinedStylesheets.push(uri); - - function whenLoaded(error, importedStyles) { - if (error) { - inlinerContext.errors.push('Broken @import declaration of "' + uri + '" - ' + error); - - return process.nextTick(function () { - inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1)); - inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); - doInlineImports(inlinerContext); - }); - } - - inlinerContext.inline = inlinerContext.externalContext.options.inline; - inlinerContext.isRemote = true; - - inlinerContext.externalContext.source = originalUri; - inlinerContext.externalContext.sourcesContent[uri] = importedStyles; - inlinerContext.externalContext.stats.originalSize += importedStyles.length; - - return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function (importedTokens) { - importedTokens = wrapInMedia(importedTokens, mediaQuery, metadata); - - inlinerContext.outputTokens = inlinerContext.outputTokens.concat(importedTokens); - inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); - - return doInlineImports(inlinerContext); - }); - } - - return isLoaded ? - whenLoaded(null, inlinerContext.externalContext.sourcesContent[uri]) : - inlinerContext.fetch(uri, inlinerContext.inlineRequest, inlinerContext.inlineTimeout, whenLoaded); -} - -function inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext) { - var currentPath = path__default.resolve(''); - var absoluteUri = path__default.isAbsolute(uri) ? - path__default.resolve(currentPath, uri[0] == '/' ? uri.substring(1) : uri) : - path__default.resolve(inlinerContext.rebaseTo, uri); - var relativeToCurrentPath = path__default.relative(currentPath, absoluteUri); - var importedStyles; - var isAllowed = isAllowedResource_1(uri, false, inlinerContext.inline); - var normalizedPath = normalizePath_1(relativeToCurrentPath); - var isLoaded = normalizedPath in inlinerContext.externalContext.sourcesContent; - - if (inlinerContext.inlinedStylesheets.indexOf(absoluteUri) > -1) { - inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as it has already been imported.'); - } else if (!isLoaded && (!fs__default.existsSync(absoluteUri) || !fs__default.statSync(absoluteUri).isFile())) { - inlinerContext.errors.push('Ignoring local @import of "' + uri + '" as resource is missing.'); - } else if (!isAllowed && inlinerContext.afterContent) { - inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as resource is not allowed and after other content.'); - } else if (inlinerContext.afterContent) { - inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as after other content.'); - } else if (!isAllowed) { - inlinerContext.warnings.push('Skipping local @import of "' + uri + '" as resource is not allowed.'); - inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1)); - } else { - importedStyles = isLoaded ? - inlinerContext.externalContext.sourcesContent[normalizedPath] : - fs__default.readFileSync(absoluteUri, 'utf-8'); - - inlinerContext.inlinedStylesheets.push(absoluteUri); - inlinerContext.inline = inlinerContext.externalContext.options.inline; - - inlinerContext.externalContext.source = normalizedPath; - inlinerContext.externalContext.sourcesContent[normalizedPath] = importedStyles; - inlinerContext.externalContext.stats.originalSize += importedStyles.length; - - return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function (importedTokens) { - importedTokens = wrapInMedia(importedTokens, mediaQuery, metadata); - - inlinerContext.outputTokens = inlinerContext.outputTokens.concat(importedTokens); - inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); - - return doInlineImports(inlinerContext); - }); - } - - inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1); - - return doInlineImports(inlinerContext); -} - -function wrapInMedia(tokens, mediaQuery, metadata) { - if (mediaQuery) { - return [[token.NESTED_BLOCK, [[token.NESTED_BLOCK_SCOPE, '@media ' + mediaQuery, metadata]], tokens]]; - } else { - return tokens; - } -} - -var readSources_1 = readSources; - -var all$1 = helpers.all; - -function store$1(serializeContext, token) { - var value = typeof token == 'string' ? - token : - token[1]; - var wrap = serializeContext.wrap; - - wrap(serializeContext, value); - track$1(serializeContext, value); - serializeContext.output.push(value); -} - -function wrap$1(serializeContext, value) { - if (serializeContext.column + value.length > serializeContext.format.wrapAt) { - track$1(serializeContext, serializeContext.format.breakWith); - serializeContext.output.push(serializeContext.format.breakWith); - } -} - -function track$1(serializeContext, value) { - var parts = value.split('\n'); - - serializeContext.line += parts.length - 1; - serializeContext.column = parts.length > 1 ? 0 : (serializeContext.column + parts.pop().length); -} - -function serializeStyles(tokens, context) { - var serializeContext = { - column: 0, - format: context.options.format, - indentBy: 0, - indentWith: '', - line: 1, - output: [], - spaceAfterClosingBrace: context.options.compatibility.properties.spaceAfterClosingBrace, - store: store$1, - wrap: context.options.format.wrapAt ? - wrap$1 : - function () { /* noop */ } - }; - - all$1(serializeContext, tokens); - - return { - styles: serializeContext.output.join('') - }; -} - -var simple = serializeStyles; - -var SourceMapGenerator = build.sourceMap.SourceMapGenerator; -var all = helpers.all; - - - -var isWindows = process.platform == 'win32'; - -var NIX_SEPARATOR_PATTERN = /\//g; -var UNKNOWN_SOURCE = '$stdin'; -var WINDOWS_SEPARATOR = '\\'; - -function store(serializeContext, element) { - var fromString = typeof element == 'string'; - var value = fromString ? element : element[1]; - var mappings = fromString ? null : element[2]; - var wrap = serializeContext.wrap; - - wrap(serializeContext, value); - track(serializeContext, value, mappings); - serializeContext.output.push(value); -} - -function wrap(serializeContext, value) { - if (serializeContext.column + value.length > serializeContext.format.wrapAt) { - track(serializeContext, serializeContext.format.breakWith, false); - serializeContext.output.push(serializeContext.format.breakWith); - } -} - -function track(serializeContext, value, mappings) { - var parts = value.split('\n'); - - if (mappings) { - trackAllMappings(serializeContext, mappings); - } - - serializeContext.line += parts.length - 1; - serializeContext.column = parts.length > 1 ? 0 : (serializeContext.column + parts.pop().length); -} - -function trackAllMappings(serializeContext, mappings) { - for (var i = 0, l = mappings.length; i < l; i++) { - trackMapping(serializeContext, mappings[i]); - } -} - -function trackMapping(serializeContext, mapping) { - var line = mapping[0]; - var column = mapping[1]; - var originalSource = mapping[2]; - var source = originalSource; - var storedSource = source || UNKNOWN_SOURCE; - - if (isWindows && source && !isRemoteResource_1(source)) { - storedSource = source.replace(NIX_SEPARATOR_PATTERN, WINDOWS_SEPARATOR); - } - - serializeContext.outputMap.addMapping({ - generated: { - line: serializeContext.line, - column: serializeContext.column - }, - source: storedSource, - original: { - line: line, - column: column - } - }); - - if (serializeContext.inlineSources && (originalSource in serializeContext.sourcesContent)) { - serializeContext.outputMap.setSourceContent(storedSource, serializeContext.sourcesContent[originalSource]); - } -} - -function serializeStylesAndSourceMap(tokens, context) { - var serializeContext = { - column: 0, - format: context.options.format, - indentBy: 0, - indentWith: '', - inlineSources: context.options.sourceMapInlineSources, - line: 1, - output: [], - outputMap: new SourceMapGenerator(), - sourcesContent: context.sourcesContent, - spaceAfterClosingBrace: context.options.compatibility.properties.spaceAfterClosingBrace, - store: store, - wrap: context.options.format.wrapAt ? - wrap : - function () { /* noop */ } - }; - - all(serializeContext, tokens); - - return { - sourceMap: serializeContext.outputMap, - styles: serializeContext.output.join('') - }; -} - -var sourceMaps = serializeStylesAndSourceMap; - -/** - * Clean-css - https://github.com/jakubpawlowicz/clean-css - * Released under the terms of MIT license - * - * Copyright (C) 2017 JakubPawlowicz.com - */ - -var clean = build.createCommonjsModule(function (module) { -var formatFrom = format.formatFrom; - - - -var OptimizationLevel = optimizationLevel.OptimizationLevel; -var optimizationLevelFrom = optimizationLevel.optimizationLevelFrom; - - - - - - - - - -var CleanCSS = module.exports = function CleanCSS(options) { - options = options || {}; - - this.options = { - compatibility: compatibility(options.compatibility), - fetch: fetch(options.fetch), - format: formatFrom(options.format), - inline: inline$1(options.inline), - inlineRequest: inlineRequest(options.inlineRequest), - inlineTimeout: inlineTimeout(options.inlineTimeout), - level: optimizationLevelFrom(options.level), - rebase: rebase$2(options.rebase), - rebaseTo: rebaseTo(options.rebaseTo), - returnPromise: !!options.returnPromise, - sourceMap: !!options.sourceMap, - sourceMapInlineSources: !!options.sourceMapInlineSources - }; -}; - - -// for compatibility with optimize-css-assets-webpack-plugin -CleanCSS.process = function (input, opts) { - var cleanCss; - var optsTo = opts.to; - - delete opts.to; - cleanCss = new CleanCSS(Object.assign({ returnPromise: true, rebaseTo: optsTo }, opts)); - - return cleanCss.minify(input) - .then(function(output) { - return { css: output.styles }; - }); -}; - - -CleanCSS.prototype.minify = function (input, maybeSourceMap, maybeCallback) { - var options = this.options; - - if (options.returnPromise) { - return new Promise(function (resolve, reject) { - minify(input, options, maybeSourceMap, function (errors, output) { - return errors ? - reject(errors) : - resolve(output); - }); - }); - } else { - return minify(input, options, maybeSourceMap, maybeCallback); - } -}; - -function minify(input, options, maybeSourceMap, maybeCallback) { - var sourceMap = typeof maybeSourceMap != 'function' ? - maybeSourceMap : - null; - var callback = typeof maybeCallback == 'function' ? - maybeCallback : - (typeof maybeSourceMap == 'function' ? maybeSourceMap : null); - var context = { - stats: { - efficiency: 0, - minifiedSize: 0, - originalSize: 0, - startedAt: Date.now(), - timeSpent: 0 - }, - cache: { - specificity: {} - }, - errors: [], - inlinedStylesheets: [], - inputSourceMapTracker: inputSourceMapTracker_1(), - localOnly: !callback, - options: options, - source: null, - sourcesContent: {}, - validator: validator_1(options.compatibility), - warnings: [] - }; - - if (sourceMap) { - context.inputSourceMapTracker.track(undefined, sourceMap); - } - - return runner(context.localOnly)(function () { - return readSources_1(input, context, function (tokens) { - var serialize = context.options.sourceMap ? - sourceMaps : - simple; - - var optimizedTokens = optimize$1(tokens, context); - var optimizedStyles = serialize(optimizedTokens, context); - var output = withMetadata(optimizedStyles, context); - - return callback ? - callback(context.errors.length > 0 ? context.errors : null, output) : - output; - }); - }); -} - -function runner(localOnly) { - // to always execute code asynchronously when a callback is given - // more at blog.izs.me/post/59142742143/designing-apis-for-asynchrony - return localOnly ? - function (callback) { return callback(); } : - process.nextTick; -} - -function optimize$1(tokens, context) { - var optimized; - - optimized = optimize$3(tokens); - optimized = OptimizationLevel.One in context.options.level ? - optimize$2(tokens, context) : - tokens; - optimized = OptimizationLevel.Two in context.options.level ? - optimize(tokens, context, true) : - optimized; - - return optimized; -} - -function withMetadata(output, context) { - output.stats = calculateStatsFrom(output.styles, context); - output.errors = context.errors; - output.inlinedStylesheets = context.inlinedStylesheets; - output.warnings = context.warnings; - - return output; -} - -function calculateStatsFrom(styles, context) { - var finishedAt = Date.now(); - var timeSpent = finishedAt - context.stats.startedAt; - - delete context.stats.startedAt; - context.stats.timeSpent = timeSpent; - context.stats.efficiency = 1 - styles.length / context.stats.originalSize; - context.stats.minifiedSize = styles.length; - - return context.stats; -} -}); - -var cleanCss = clean; - -var index = /*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), cleanCss, { - 'default': cleanCss -}); - -exports.index = index; diff --git a/node_modules/vite/dist/node/chunks/dep-b8a69f7c.js b/node_modules/vite/dist/node/chunks/dep-b8a69f7c.js deleted file mode 100644 index 6947e48..0000000 --- a/node_modules/vite/dist/node/chunks/dep-b8a69f7c.js +++ /dev/null @@ -1,707 +0,0 @@ -'use strict'; - -var path$1 = require('path'); -var resolve$1 = require('resolve'); -var fs = require('fs'); -var build = require('./dep-66eb515d.js'); -var _postcss = require('postcss'); -var index$1 = require('./dep-685e7ba2.js'); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; } - -var path__default = /*#__PURE__*/_interopDefaultLegacy(path$1); -var resolve__default = /*#__PURE__*/_interopDefaultLegacy(resolve$1); -var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); -var _postcss__default = /*#__PURE__*/_interopDefaultLegacy(_postcss); - -var joinMedia = function (parentMedia, childMedia) { - if (!parentMedia.length && childMedia.length) return childMedia - if (parentMedia.length && !childMedia.length) return parentMedia - if (!parentMedia.length && !childMedia.length) return [] - - const media = []; - - parentMedia.forEach(parentItem => { - childMedia.forEach(childItem => { - if (parentItem !== childItem) media.push(`${parentItem} and ${childItem}`); - }); - }); - - return media -}; - -// external tooling - - -const moduleDirectories = ["web_modules", "node_modules"]; - -function resolveModule(id, opts) { - return new Promise((res, rej) => { - resolve__default(id, opts, (err, path) => (err ? rej(err) : res(path))); - }) -} - -var resolveId = function (id, base, options) { - const paths = options.path; - - const resolveOpts = { - basedir: base, - moduleDirectory: moduleDirectories.concat(options.addModulesDirectories), - paths: paths, - extensions: [".css"], - packageFilter: function processPackage(pkg) { - if (pkg.style) pkg.main = pkg.style; - else if (!pkg.main || !/\.css$/.test(pkg.main)) pkg.main = "index.css"; - return pkg - }, - preserveSymlinks: false, - }; - - return resolveModule(`./${id}`, resolveOpts) - .catch(() => resolveModule(id, resolveOpts)) - .catch(() => { - if (paths.indexOf(base) === -1) paths.unshift(base); - - throw new Error( - `Failed to find '${id}' - in [ - ${paths.join(",\n ")} - ]` - ) - }) -}; - -var pify_1 = build.createCommonjsModule(function (module) { - -var processFn = function (fn, P, opts) { - return function () { - var that = this; - var args = new Array(arguments.length); - - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } - - return new P(function (resolve, reject) { - args.push(function (err, result) { - if (err) { - reject(err); - } else if (opts.multiArgs) { - var results = new Array(arguments.length - 1); - - for (var i = 1; i < arguments.length; i++) { - results[i - 1] = arguments[i]; - } - - resolve(results); - } else { - resolve(result); - } - }); - - fn.apply(that, args); - }); - }; -}; - -var pify = module.exports = function (obj, P, opts) { - if (typeof P !== 'function') { - opts = P; - P = Promise; - } - - opts = opts || {}; - opts.exclude = opts.exclude || [/.+Sync$/]; - - var filter = function (key) { - var match = function (pattern) { - return typeof pattern === 'string' ? key === pattern : pattern.test(key); - }; - - return opts.include ? opts.include.some(match) : !opts.exclude.some(match); - }; - - var ret = typeof obj === 'function' ? function () { - if (opts.excludeMain) { - return obj.apply(this, arguments); - } - - return processFn(obj, P, opts).apply(this, arguments); - } : {}; - - return Object.keys(obj).reduce(function (ret, key) { - var x = obj[key]; - - ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x; - - return ret; - }, ret); -}; - -pify.all = pify; -}); - -var path = path__default; - - -var stat = pify_1(fs__default.stat); -var readFile = pify_1(fs__default.readFile); -var resolve = path.resolve; - -var cache = Object.create(null); - -function convert(content, encoding) { - if (Buffer.isEncoding(encoding)) { - return content.toString(encoding); - } - return content; -} - -var readCache = function (path, encoding) { - path = resolve(path); - - return stat(path).then(function (stats) { - var item = cache[path]; - - if (item && item.mtime.getTime() === stats.mtime.getTime()) { - return convert(item.content, encoding); - } - - return readFile(path).then(function (data) { - cache[path] = { - mtime: stats.mtime, - content: data - }; - - return convert(data, encoding); - }); - }).catch(function (err) { - cache[path] = null; - return Promise.reject(err); - }); -}; - -var sync = function (path, encoding) { - path = resolve(path); - - try { - var stats = fs__default.statSync(path); - var item = cache[path]; - - if (item && item.mtime.getTime() === stats.mtime.getTime()) { - return convert(item.content, encoding); - } - - var data = fs__default.readFileSync(path); - - cache[path] = { - mtime: stats.mtime, - content: data - }; - - return convert(data, encoding); - } catch (err) { - cache[path] = null; - throw err; - } - -}; - -var get = function (path, encoding) { - path = resolve(path); - if (cache[path]) { - return convert(cache[path].content, encoding); - } - return null; -}; - -var clear = function () { - cache = Object.create(null); -}; -readCache.sync = sync; -readCache.get = get; -readCache.clear = clear; - -var loadContent = filename => readCache(filename, "utf-8"); - -// builtin tooling - - -// external tooling - - -// placeholder tooling -let sugarss; - -var processContent = function processContent(result, content, filename, options) { - const plugins = options.plugins; - const ext = path__default.extname(filename); - - const parserList = []; - - // SugarSS support: - if (ext === ".sss") { - if (!sugarss) { - try { - sugarss = eval('require')('sugarss'); - } catch (e) { - // Ignore - } - } - if (sugarss) return runPostcss(content, filename, plugins, [sugarss]) - } - - // Syntax support: - if (result.opts.syntax && result.opts.syntax.parse) { - parserList.push(result.opts.syntax.parse); - } - - // Parser support: - if (result.opts.parser) parserList.push(result.opts.parser); - // Try the default as a last resort: - parserList.push(null); - - return runPostcss(content, filename, plugins, parserList) -}; - -function runPostcss(content, filename, plugins, parsers, index) { - if (!index) index = 0; - return _postcss__default(plugins) - .process(content, { - from: filename, - parser: parsers[index], - }) - .catch(err => { - // If there's an error, try the next parser - index++; - // If there are no parsers left, throw it - if (index === parsers.length) throw err - return runPostcss(content, filename, plugins, parsers, index) - }) -} - -// external tooling - - -// extended tooling -const stringify = index$1.lib.stringify; - -function split(params, start) { - const list = []; - const last = params.reduce((item, node, index) => { - if (index < start) return "" - if (node.type === "div" && node.value === ",") { - list.push(item); - return "" - } - return item + stringify(node) - }, ""); - list.push(last); - return list -} - -var parseStatements = function (result, styles) { - const statements = []; - let nodes = []; - - styles.each(node => { - let stmt; - if (node.type === "atrule") { - if (node.name === "import") stmt = parseImport(result, node); - else if (node.name === "media") stmt = parseMedia(result, node); - } - - if (stmt) { - if (nodes.length) { - statements.push({ - type: "nodes", - nodes: nodes, - media: [], - }); - nodes = []; - } - statements.push(stmt); - } else nodes.push(node); - }); - - if (nodes.length) { - statements.push({ - type: "nodes", - nodes: nodes, - media: [], - }); - } - - return statements -}; - -function parseMedia(result, atRule) { - const params = index$1.lib(atRule.params).nodes; - return { - type: "media", - node: atRule, - media: split(params, 0), - } -} - -function parseImport(result, atRule) { - let prev = getPrev(atRule); - if (prev) { - do { - if ( - prev.type !== "atrule" || - (prev.name !== "import" && prev.name !== "charset") - ) { - return result.warn( - "@import must precede all other statements (besides @charset)", - { node: atRule } - ) - } else prev = getPrev(prev); - } while (prev) - } - - if (atRule.nodes) { - return result.warn( - "It looks like you didn't end your @import statement correctly. " + - "Child nodes are attached to it.", - { node: atRule } - ) - } - - const params = index$1.lib(atRule.params).nodes; - const stmt = { - type: "import", - node: atRule, - media: [], - }; - - // prettier-ignore - if ( - !params.length || - ( - params[0].type !== "string" || - !params[0].value - ) && - ( - params[0].type !== "function" || - params[0].value !== "url" || - !params[0].nodes.length || - !params[0].nodes[0].value - ) - ) { - return result.warn(`Unable to find uri in '${ atRule.toString() }'`, { - node: atRule, - }) - } - - if (params[0].type === "string") stmt.uri = params[0].value; - else stmt.uri = params[0].nodes[0].value; - stmt.fullUri = stringify(params[0]); - - if (params.length > 2) { - if (params[1].type !== "space") { - return result.warn("Invalid import media statement", { node: atRule }) - } - stmt.media = split(params, 2); - } - - return stmt -} - -function getPrev(item) { - let prev = item.prev(); - while (prev && prev.type === "comment") { - prev = prev.prev(); - } - return prev -} - -// builtin tooling - - -// internal tooling - - - - - - -function AtImport(options) { - options = Object.assign( - { - root: process.cwd(), - path: [], - skipDuplicates: true, - resolve: resolveId, - load: loadContent, - plugins: [], - addModulesDirectories: [], - }, - options - ); - - options.root = path__default.resolve(options.root); - - // convert string to an array of a single element - if (typeof options.path === "string") options.path = [options.path]; - - if (!Array.isArray(options.path)) options.path = []; - - options.path = options.path.map(p => path__default.resolve(options.root, p)); - - return { - postcssPlugin: "postcss-import", - Once(styles, { result, atRule }) { - const state = { - importedFiles: {}, - hashFiles: {}, - }; - - if (styles.source && styles.source.input && styles.source.input.file) { - state.importedFiles[styles.source.input.file] = {}; - } - - if (options.plugins && !Array.isArray(options.plugins)) { - throw new Error("plugins option must be an array") - } - - return parseStyles(result, styles, options, state, []).then(bundle => { - applyRaws(bundle); - applyMedia(bundle); - applyStyles(bundle, styles); - }) - - function applyRaws(bundle) { - bundle.forEach((stmt, index) => { - if (index === 0) return - - if (stmt.parent) { - const before = stmt.parent.node.raws.before; - if (stmt.type === "nodes") stmt.nodes[0].raws.before = before; - else stmt.node.raws.before = before; - } else if (stmt.type === "nodes") { - stmt.nodes[0].raws.before = stmt.nodes[0].raws.before || "\n"; - } - }); - } - - function applyMedia(bundle) { - bundle.forEach(stmt => { - if (!stmt.media.length) return - if (stmt.type === "import") { - stmt.node.params = `${stmt.fullUri} ${stmt.media.join(", ")}`; - } else if (stmt.type === "media") - stmt.node.params = stmt.media.join(", "); - else { - const nodes = stmt.nodes; - const parent = nodes[0].parent; - const mediaNode = atRule({ - name: "media", - params: stmt.media.join(", "), - source: parent.source, - }); - - parent.insertBefore(nodes[0], mediaNode); - - // remove nodes - nodes.forEach(node => { - node.parent = undefined; - }); - - // better output - nodes[0].raws.before = nodes[0].raws.before || "\n"; - - // wrap new rules with media query - mediaNode.append(nodes); - - stmt.type = "media"; - stmt.node = mediaNode; - delete stmt.nodes; - } - }); - } - - function applyStyles(bundle, styles) { - styles.nodes = []; - - // Strip additional statements. - bundle.forEach(stmt => { - if (stmt.type === "import") { - stmt.node.parent = undefined; - styles.append(stmt.node); - } else if (stmt.type === "media") { - stmt.node.parent = undefined; - styles.append(stmt.node); - } else if (stmt.type === "nodes") { - stmt.nodes.forEach(node => { - node.parent = undefined; - styles.append(node); - }); - } - }); - } - - function parseStyles(result, styles, options, state, media) { - const statements = parseStatements(result, styles); - - return Promise.resolve(statements) - .then(stmts => { - // process each statement in series - return stmts.reduce((promise, stmt) => { - return promise.then(() => { - stmt.media = joinMedia(media, stmt.media || []); - - // skip protocol base uri (protocol://url) or protocol-relative - if ( - stmt.type !== "import" || - /^(?:[a-z]+:)?\/\//i.test(stmt.uri) - ) { - return - } - - if (options.filter && !options.filter(stmt.uri)) { - // rejected by filter - return - } - - return resolveImportId(result, stmt, options, state) - }) - }, Promise.resolve()) - }) - .then(() => { - const imports = []; - const bundle = []; - - // squash statements and their children - statements.forEach(stmt => { - if (stmt.type === "import") { - if (stmt.children) { - stmt.children.forEach((child, index) => { - if (child.type === "import") imports.push(child); - else bundle.push(child); - // For better output - if (index === 0) child.parent = stmt; - }); - } else imports.push(stmt); - } else if (stmt.type === "media" || stmt.type === "nodes") { - bundle.push(stmt); - } - }); - - return imports.concat(bundle) - }) - } - - function resolveImportId(result, stmt, options, state) { - const atRule = stmt.node; - let sourceFile; - if (atRule.source && atRule.source.input && atRule.source.input.file) { - sourceFile = atRule.source.input.file; - } - const base = sourceFile - ? path__default.dirname(atRule.source.input.file) - : options.root; - - return Promise.resolve(options.resolve(stmt.uri, base, options)) - .then(paths => { - if (!Array.isArray(paths)) paths = [paths]; - // Ensure that each path is absolute: - return Promise.all( - paths.map(file => { - return !path__default.isAbsolute(file) - ? resolveId(file, base, options) - : file - }) - ) - }) - .then(resolved => { - // Add dependency messages: - resolved.forEach(file => { - result.messages.push({ - type: "dependency", - plugin: "postcss-import", - file: file, - parent: sourceFile, - }); - }); - - return Promise.all( - resolved.map(file => { - return loadImportContent(result, stmt, file, options, state) - }) - ) - }) - .then(result => { - // Merge loaded statements - stmt.children = result.reduce((result, statements) => { - return statements ? result.concat(statements) : result - }, []); - }) - } - - function loadImportContent(result, stmt, filename, options, state) { - const atRule = stmt.node; - const media = stmt.media; - if (options.skipDuplicates) { - // skip files already imported at the same scope - if ( - state.importedFiles[filename] && - state.importedFiles[filename][media] - ) { - return - } - - // save imported files to skip them next time - if (!state.importedFiles[filename]) state.importedFiles[filename] = {}; - state.importedFiles[filename][media] = true; - } - - return Promise.resolve(options.load(filename, options)).then( - content => { - if (content.trim() === "") { - result.warn(`${filename} is empty`, { node: atRule }); - return - } - - // skip previous imported files not containing @import rules - if (state.hashFiles[content] && state.hashFiles[content][media]) - return - - return processContent(result, content, filename, options).then( - importedResult => { - const styles = importedResult.root; - result.messages = result.messages.concat( - importedResult.messages - ); - - if (options.skipDuplicates) { - const hasImport = styles.some(child => { - return child.type === "atrule" && child.name === "import" - }); - if (!hasImport) { - // save hash files to skip them next time - if (!state.hashFiles[content]) state.hashFiles[content] = {}; - state.hashFiles[content][media] = true; - } - } - - // recursion: import @import from imported file - return parseStyles(result, styles, options, state, media) - } - ) - } - ) - } - }, - } -} - -AtImport.postcss = true; - -var postcssImport = AtImport; - -var index = /*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), postcssImport, { - 'default': postcssImport -}); - -exports.index = index; diff --git a/node_modules/vite/dist/node/chunks/dep-ea87ce95.js b/node_modules/vite/dist/node/chunks/dep-ea87ce95.js deleted file mode 100644 index 9c54f0f..0000000 --- a/node_modules/vite/dist/node/chunks/dep-ea87ce95.js +++ /dev/null @@ -1,11238 +0,0 @@ -'use strict'; - -var _postcss = require('postcss'); -var build$1 = require('./dep-66eb515d.js'); -var path = require('path'); -var require$$0 = require('crypto'); -var fs = require('fs'); -var util$2 = require('util'); -var index$1 = require('./dep-685e7ba2.js'); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; } - -var _postcss__default = /*#__PURE__*/_interopDefaultLegacy(_postcss); -var path__default = /*#__PURE__*/_interopDefaultLegacy(path); -var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0); -var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); -var util__default = /*#__PURE__*/_interopDefaultLegacy(util$2); - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** Used to match words composed of alphanumeric characters. */ -var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - -/** Used to match Latin Unicode letters (excluding mathematical operators). */ -var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', - rsComboSymbolsRange = '\\u20d0-\\u20f0', - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - -/** Used to compose unicode capture groups. */ -var rsApos = "['\u2019]", - rsAstral = '[' + rsAstralRange + ']', - rsBreak = '[' + rsBreakRange + ']', - rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ = '\\u200d'; - -/** Used to compose unicode regexes. */ -var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', - rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - -/** Used to match apostrophes. */ -var reApos = RegExp(rsApos, 'g'); - -/** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ -var reComboMark = RegExp(rsCombo, 'g'); - -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - -/** Used to match complex or compound words. */ -var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', - rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr, - rsUpper + '+' + rsOptUpperContr, - rsDigits, - rsEmoji -].join('|'), 'g'); - -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); - -/** Used to detect strings that need a more robust regexp to match words. */ -var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - -/** Used to map Latin Unicode letters to basic Latin letters. */ -var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 'ss' -}; - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof build$1.commonjsGlobal == 'object' && build$1.commonjsGlobal && build$1.commonjsGlobal.Object === Object && build$1.commonjsGlobal; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root$1 = freeGlobal || freeSelf || Function('return this')(); - -/** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ -function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array ? array.length : 0; - - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; -} - -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function asciiToArray(string) { - return string.split(''); -} - -/** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ -function asciiWords(string) { - return string.match(reAsciiWord) || []; -} - -/** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ -function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; -} - -/** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ -var deburrLetter = basePropertyOf(deburredLetters); - -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode(string) { - return reHasUnicode.test(string); -} - -/** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ -function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); -} - -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); -} - -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; -} - -/** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ -function unicodeWords(string) { - return string.match(reUnicodeWord) || []; -} - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** Built-in value references. */ -var Symbol$1 = root$1.Symbol; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} - -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} - -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); -} - -/** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ -function createCaseFirst(methodName) { - return function(string) { - string = toString(string); - - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; - - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); - - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); - - return chr[methodName]() + trailing; - }; -} - -/** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ -function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); - }; -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); -} - -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {string} Returns the string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); -} - -/** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' - */ -var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); -}); - -/** - * Converts the first character of `string` to upper case and the remaining - * to lower case. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example - * - * _.capitalize('FRED'); - * // => 'Fred' - */ -function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); -} - -/** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example - * - * _.deburr('déjà vu'); - * // => 'deja vu' - */ -function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); -} - -/** - * Converts the first character of `string` to upper case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.upperFirst('fred'); - * // => 'Fred' - * - * _.upperFirst('FRED'); - * // => 'FRED' - */ -var upperFirst = createCaseFirst('toUpperCase'); - -/** - * Splits `string` into an array of its words. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {RegExp|string} [pattern] The pattern to match words. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the words of `string`. - * @example - * - * _.words('fred, barney, & pebbles'); - * // => ['fred', 'barney', 'pebbles'] - * - * _.words('fred, barney, & pebbles', /[^, ]+/g); - * // => ['fred', 'barney', '&', 'pebbles'] - */ -function words(string, pattern, guard) { - string = toString(string); - pattern = guard ? undefined : pattern; - - if (pattern === undefined) { - return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); - } - return string.match(pattern) || []; -} - -var lodash_camelcase = camelCase; - -var unicode$1 = build$1.createCommonjsModule(function (module, exports) { -Object.defineProperty(exports,"__esModule",{value:true});exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/;exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; -}); - -var isSpaceSeparator_1=isSpaceSeparator;var isIdStartChar_1=isIdStartChar;var isIdContinueChar_1=isIdContinueChar;var isDigit_1=isDigit;var isHexDigit_1=isHexDigit;var unicode=_interopRequireWildcard(unicode$1);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else {var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj}}function isSpaceSeparator(c){return unicode.Space_Separator.test(c)}function isIdStartChar(c){return c>='a'&&c<='z'||c>='A'&&c<='Z'||c==='$'||c==='_'||unicode.ID_Start.test(c)}function isIdContinueChar(c){return c>='a'&&c<='z'||c>='A'&&c<='Z'||c>='0'&&c<='9'||c==='$'||c==='_'||c==='\u200C'||c==='\u200D'||unicode.ID_Continue.test(c)}function isDigit(c){return /[0-9]/.test(c)}function isHexDigit(c){return /[0-9A-Fa-f]/.test(c)} - -var util$1 = /*#__PURE__*/Object.defineProperty({ - isSpaceSeparator: isSpaceSeparator_1, - isIdStartChar: isIdStartChar_1, - isIdContinueChar: isIdContinueChar_1, - isDigit: isDigit_1, - isHexDigit: isHexDigit_1 -}, '__esModule', {value: true}); - -var parse_1 = build$1.createCommonjsModule(function (module, exports) { -Object.defineProperty(exports,'__esModule',{value:true});var _typeof=typeof Symbol==='function'&&typeof Symbol.iterator==='symbol'?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==='function'&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj};exports.default=parse;var util=_interopRequireWildcard(util$1);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else {var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj}}var source=void 0;var parseState=void 0;var stack=void 0;var pos=void 0;var line=void 0;var column=void 0;var token=void 0;var key=void 0;var root=void 0;function parse(text,reviver){source=String(text);parseState='start';stack=[];pos=0;line=1;column=0;token=undefined;key=undefined;root=undefined;do{token=lex();parseStates[parseState]();}while(token.type!=='eof');if(typeof reviver==='function'){return internalize({'':root},'',reviver)}return root}function internalize(holder,name,reviver){var value=holder[name];if(value!=null&&(typeof value==='undefined'?'undefined':_typeof(value))==='object'){for(var _key in value){var replacement=internalize(value,_key,reviver);if(replacement===undefined){delete value[_key];}else {value[_key]=replacement;}}}return reviver.call(holder,name,value)}var lexState=void 0;var buffer=void 0;var doubleQuote=void 0;var _sign=void 0;var c=void 0;function lex(){lexState='default';buffer='';doubleQuote=false;_sign=1;for(;;){c=peek();var _token=lexStates[lexState]();if(_token){return _token}}}function peek(){if(source[pos]){return String.fromCodePoint(source.codePointAt(pos))}}function read(){var c=peek();if(c==='\n'){line++;column=0;}else if(c){column+=c.length;}else {column++;}if(c){pos+=c.length;}return c}var lexStates={default:function _default(){switch(c){case'\t':case'\x0B':case'\f':case' ':case'\xA0':case'\uFEFF':case'\n':case'\r':case'\u2028':case'\u2029':read();return;case'/':read();lexState='comment';return;case undefined:read();return newToken('eof');}if(util.isSpaceSeparator(c)){read();return}return lexStates[parseState]()},comment:function comment(){switch(c){case'*':read();lexState='multiLineComment';return;case'/':read();lexState='singleLineComment';return;}throw invalidChar(read())},multiLineComment:function multiLineComment(){switch(c){case'*':read();lexState='multiLineCommentAsterisk';return;case undefined:throw invalidChar(read());}read();},multiLineCommentAsterisk:function multiLineCommentAsterisk(){switch(c){case'*':read();return;case'/':read();lexState='default';return;case undefined:throw invalidChar(read());}read();lexState='multiLineComment';},singleLineComment:function singleLineComment(){switch(c){case'\n':case'\r':case'\u2028':case'\u2029':read();lexState='default';return;case undefined:read();return newToken('eof');}read();},value:function value(){switch(c){case'{':case'[':return newToken('punctuator',read());case'n':read();literal('ull');return newToken('null',null);case't':read();literal('rue');return newToken('boolean',true);case'f':read();literal('alse');return newToken('boolean',false);case'-':case'+':if(read()==='-'){_sign=-1;}lexState='sign';return;case'.':buffer=read();lexState='decimalPointLeading';return;case'0':buffer=read();lexState='zero';return;case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':buffer=read();lexState='decimalInteger';return;case'I':read();literal('nfinity');return newToken('numeric',Infinity);case'N':read();literal('aN');return newToken('numeric',NaN);case'"':case'\'':doubleQuote=read()==='"';buffer='';lexState='string';return;}throw invalidChar(read())},identifierNameStartEscape:function identifierNameStartEscape(){if(c!=='u'){throw invalidChar(read())}read();var u=unicodeEscape();switch(u){case'$':case'_':break;default:if(!util.isIdStartChar(u)){throw invalidIdentifier()}break;}buffer+=u;lexState='identifierName';},identifierName:function identifierName(){switch(c){case'$':case'_':case'\u200C':case'\u200D':buffer+=read();return;case'\\':read();lexState='identifierNameEscape';return;}if(util.isIdContinueChar(c)){buffer+=read();return}return newToken('identifier',buffer)},identifierNameEscape:function identifierNameEscape(){if(c!=='u'){throw invalidChar(read())}read();var u=unicodeEscape();switch(u){case'$':case'_':case'\u200C':case'\u200D':break;default:if(!util.isIdContinueChar(u)){throw invalidIdentifier()}break;}buffer+=u;lexState='identifierName';},sign:function sign(){switch(c){case'.':buffer=read();lexState='decimalPointLeading';return;case'0':buffer=read();lexState='zero';return;case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':buffer=read();lexState='decimalInteger';return;case'I':read();literal('nfinity');return newToken('numeric',_sign*Infinity);case'N':read();literal('aN');return newToken('numeric',NaN);}throw invalidChar(read())},zero:function zero(){switch(c){case'.':buffer+=read();lexState='decimalPoint';return;case'e':case'E':buffer+=read();lexState='decimalExponent';return;case'x':case'X':buffer+=read();lexState='hexadecimal';return;}return newToken('numeric',_sign*0)},decimalInteger:function decimalInteger(){switch(c){case'.':buffer+=read();lexState='decimalPoint';return;case'e':case'E':buffer+=read();lexState='decimalExponent';return;}if(util.isDigit(c)){buffer+=read();return}return newToken('numeric',_sign*Number(buffer))},decimalPointLeading:function decimalPointLeading(){if(util.isDigit(c)){buffer+=read();lexState='decimalFraction';return}throw invalidChar(read())},decimalPoint:function decimalPoint(){switch(c){case'e':case'E':buffer+=read();lexState='decimalExponent';return;}if(util.isDigit(c)){buffer+=read();lexState='decimalFraction';return}return newToken('numeric',_sign*Number(buffer))},decimalFraction:function decimalFraction(){switch(c){case'e':case'E':buffer+=read();lexState='decimalExponent';return;}if(util.isDigit(c)){buffer+=read();return}return newToken('numeric',_sign*Number(buffer))},decimalExponent:function decimalExponent(){switch(c){case'+':case'-':buffer+=read();lexState='decimalExponentSign';return;}if(util.isDigit(c)){buffer+=read();lexState='decimalExponentInteger';return}throw invalidChar(read())},decimalExponentSign:function decimalExponentSign(){if(util.isDigit(c)){buffer+=read();lexState='decimalExponentInteger';return}throw invalidChar(read())},decimalExponentInteger:function decimalExponentInteger(){if(util.isDigit(c)){buffer+=read();return}return newToken('numeric',_sign*Number(buffer))},hexadecimal:function hexadecimal(){if(util.isHexDigit(c)){buffer+=read();lexState='hexadecimalInteger';return}throw invalidChar(read())},hexadecimalInteger:function hexadecimalInteger(){if(util.isHexDigit(c)){buffer+=read();return}return newToken('numeric',_sign*Number(buffer))},string:function string(){switch(c){case'\\':read();buffer+=escape();return;case'"':if(doubleQuote){read();return newToken('string',buffer)}buffer+=read();return;case'\'':if(!doubleQuote){read();return newToken('string',buffer)}buffer+=read();return;case'\n':case'\r':throw invalidChar(read());case'\u2028':case'\u2029':separatorChar(c);break;case undefined:throw invalidChar(read());}buffer+=read();},start:function start(){switch(c){case'{':case'[':return newToken('punctuator',read());}lexState='value';},beforePropertyName:function beforePropertyName(){switch(c){case'$':case'_':buffer=read();lexState='identifierName';return;case'\\':read();lexState='identifierNameStartEscape';return;case'}':return newToken('punctuator',read());case'"':case'\'':doubleQuote=read()==='"';lexState='string';return;}if(util.isIdStartChar(c)){buffer+=read();lexState='identifierName';return}throw invalidChar(read())},afterPropertyName:function afterPropertyName(){if(c===':'){return newToken('punctuator',read())}throw invalidChar(read())},beforePropertyValue:function beforePropertyValue(){lexState='value';},afterPropertyValue:function afterPropertyValue(){switch(c){case',':case'}':return newToken('punctuator',read());}throw invalidChar(read())},beforeArrayValue:function beforeArrayValue(){if(c===']'){return newToken('punctuator',read())}lexState='value';},afterArrayValue:function afterArrayValue(){switch(c){case',':case']':return newToken('punctuator',read());}throw invalidChar(read())},end:function end(){throw invalidChar(read())}};function newToken(type,value){return {type:type,value:value,line:line,column:column}}function literal(s){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=s[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var _c=_step.value;var p=peek();if(p!==_c){throw invalidChar(read())}read();}}catch(err){_didIteratorError=true;_iteratorError=err;}finally{try{if(!_iteratorNormalCompletion&&_iterator.return){_iterator.return();}}finally{if(_didIteratorError){throw _iteratorError}}}}function escape(){var c=peek();switch(c){case'b':read();return '\b';case'f':read();return '\f';case'n':read();return '\n';case'r':read();return '\r';case't':read();return '\t';case'v':read();return '\x0B';case'0':read();if(util.isDigit(peek())){throw invalidChar(read())}return '\0';case'x':read();return hexEscape();case'u':read();return unicodeEscape();case'\n':case'\u2028':case'\u2029':read();return '';case'\r':read();if(peek()==='\n'){read();}return '';case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':throw invalidChar(read());case undefined:throw invalidChar(read());}return read()}function hexEscape(){var buffer='';var c=peek();if(!util.isHexDigit(c)){throw invalidChar(read())}buffer+=read();c=peek();if(!util.isHexDigit(c)){throw invalidChar(read())}buffer+=read();return String.fromCodePoint(parseInt(buffer,16))}function unicodeEscape(){var buffer='';var count=4;while(count-->0){var _c2=peek();if(!util.isHexDigit(_c2)){throw invalidChar(read())}buffer+=read();}return String.fromCodePoint(parseInt(buffer,16))}var parseStates={start:function start(){if(token.type==='eof'){throw invalidEOF()}push();},beforePropertyName:function beforePropertyName(){switch(token.type){case'identifier':case'string':key=token.value;parseState='afterPropertyName';return;case'punctuator':pop();return;case'eof':throw invalidEOF();}},afterPropertyName:function afterPropertyName(){if(token.type==='eof'){throw invalidEOF()}parseState='beforePropertyValue';},beforePropertyValue:function beforePropertyValue(){if(token.type==='eof'){throw invalidEOF()}push();},beforeArrayValue:function beforeArrayValue(){if(token.type==='eof'){throw invalidEOF()}if(token.type==='punctuator'&&token.value===']'){pop();return}push();},afterPropertyValue:function afterPropertyValue(){if(token.type==='eof'){throw invalidEOF()}switch(token.value){case',':parseState='beforePropertyName';return;case'}':pop();}},afterArrayValue:function afterArrayValue(){if(token.type==='eof'){throw invalidEOF()}switch(token.value){case',':parseState='beforeArrayValue';return;case']':pop();}},end:function end(){}};function push(){var value=void 0;switch(token.type){case'punctuator':switch(token.value){case'{':value={};break;case'[':value=[];break;}break;case'null':case'boolean':case'numeric':case'string':value=token.value;break;}if(root===undefined){root=value;}else {var parent=stack[stack.length-1];if(Array.isArray(parent)){parent.push(value);}else {parent[key]=value;}}if(value!==null&&(typeof value==='undefined'?'undefined':_typeof(value))==='object'){stack.push(value);if(Array.isArray(value)){parseState='beforeArrayValue';}else {parseState='beforePropertyName';}}else {var current=stack[stack.length-1];if(current==null){parseState='end';}else if(Array.isArray(current)){parseState='afterArrayValue';}else {parseState='afterPropertyValue';}}}function pop(){stack.pop();var current=stack[stack.length-1];if(current==null){parseState='end';}else if(Array.isArray(current)){parseState='afterArrayValue';}else {parseState='afterPropertyValue';}}function invalidChar(c){if(c===undefined){return syntaxError('JSON5: invalid end of input at '+line+':'+column)}return syntaxError('JSON5: invalid character \''+formatChar(c)+'\' at '+line+':'+column)}function invalidEOF(){return syntaxError('JSON5: invalid end of input at '+line+':'+column)}function invalidIdentifier(){column-=5;return syntaxError('JSON5: invalid identifier character at '+line+':'+column)}function separatorChar(c){console.warn('JSON5: \''+c+'\' is not valid ECMAScript; consider escaping');}function formatChar(c){var replacements={'\'':'\\\'','"':'\\"','\\':'\\\\','\b':'\\b','\f':'\\f','\n':'\\n','\r':'\\r','\t':'\\t','\x0B':'\\v','\0':'\\0','\u2028':'\\u2028','\u2029':'\\u2029'};if(replacements[c]){return replacements[c]}if(c<' '){var hexString=c.charCodeAt(0).toString(16);return '\\x'+('00'+hexString).substring(hexString.length)}return c}function syntaxError(message){var err=new SyntaxError(message);err.lineNumber=line;err.columnNumber=column;return err}module.exports=exports['default']; -}); - -var stringify_1 = build$1.createCommonjsModule(function (module, exports) { -Object.defineProperty(exports,'__esModule',{value:true});var _typeof=typeof Symbol==='function'&&typeof Symbol.iterator==='symbol'?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==='function'&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj};exports.default=stringify;var util=_interopRequireWildcard(util$1);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else {var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key];}}newObj.default=obj;return newObj}}function stringify(value,replacer,space){var stack=[];var indent='';var propertyList=void 0;var replacerFunc=void 0;var gap='';var quote=void 0;if(replacer!=null&&(typeof replacer==='undefined'?'undefined':_typeof(replacer))==='object'&&!Array.isArray(replacer)){space=replacer.space;quote=replacer.quote;replacer=replacer.replacer;}if(typeof replacer==='function'){replacerFunc=replacer;}else if(Array.isArray(replacer)){propertyList=[];var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=replacer[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var v=_step.value;var item=void 0;if(typeof v==='string'){item=v;}else if(typeof v==='number'||v instanceof String||v instanceof Number){item=String(v);}if(item!==undefined&&propertyList.indexOf(item)<0){propertyList.push(item);}}}catch(err){_didIteratorError=true;_iteratorError=err;}finally{try{if(!_iteratorNormalCompletion&&_iterator.return){_iterator.return();}}finally{if(_didIteratorError){throw _iteratorError}}}}if(space instanceof Number){space=Number(space);}else if(space instanceof String){space=String(space);}if(typeof space==='number'){if(space>0){space=Math.min(10,Math.floor(space));gap=' '.substr(0,space);}}else if(typeof space==='string'){gap=space.substr(0,10);}return serializeProperty('',{'':value});function serializeProperty(key,holder){var value=holder[key];if(value!=null){if(typeof value.toJSON5==='function'){value=value.toJSON5(key);}else if(typeof value.toJSON==='function'){value=value.toJSON(key);}}if(replacerFunc){value=replacerFunc.call(holder,key,value);}if(value instanceof Number){value=Number(value);}else if(value instanceof String){value=String(value);}else if(value instanceof Boolean){value=value.valueOf();}switch(value){case null:return 'null';case true:return 'true';case false:return 'false';}if(typeof value==='string'){return quoteString(value)}if(typeof value==='number'){return String(value)}if((typeof value==='undefined'?'undefined':_typeof(value))==='object'){return Array.isArray(value)?serializeArray(value):serializeObject(value)}return undefined}function quoteString(value){var quotes={'\'':0.1,'"':0.2};var replacements={'\'':'\\\'','"':'\\"','\\':'\\\\','\b':'\\b','\f':'\\f','\n':'\\n','\r':'\\r','\t':'\\t','\x0B':'\\v','\0':'\\0','\u2028':'\\u2028','\u2029':'\\u2029'};var product='';var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=value[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var c=_step2.value;switch(c){case'\'':case'"':quotes[c]++;product+=c;continue;}if(replacements[c]){product+=replacements[c];continue}if(c<' '){var hexString=c.charCodeAt(0).toString(16);product+='\\x'+('00'+hexString).substring(hexString.length);continue}product+=c;}}catch(err){_didIteratorError2=true;_iteratorError2=err;}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return){_iterator2.return();}}finally{if(_didIteratorError2){throw _iteratorError2}}}var quoteChar=quote||Object.keys(quotes).reduce(function(a,b){return quotes[a]=0){throw TypeError('Converting circular structure to JSON5')}stack.push(value);var stepback=indent;indent=indent+gap;var keys=propertyList||Object.keys(value);var partial=[];var _iteratorNormalCompletion3=true;var _didIteratorError3=false;var _iteratorError3=undefined;try{for(var _iterator3=keys[Symbol.iterator](),_step3;!(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done);_iteratorNormalCompletion3=true){var key=_step3.value;var propertyString=serializeProperty(key,value);if(propertyString!==undefined){var member=serializeKey(key)+':';if(gap!==''){member+=' ';}member+=propertyString;partial.push(member);}}}catch(err){_didIteratorError3=true;_iteratorError3=err;}finally{try{if(!_iteratorNormalCompletion3&&_iterator3.return){_iterator3.return();}}finally{if(_didIteratorError3){throw _iteratorError3}}}var final=void 0;if(partial.length===0){final='{}';}else {var properties=void 0;if(gap===''){properties=partial.join(',');final='{'+properties+'}';}else {var separator=',\n'+indent;properties=partial.join(separator);final='{\n'+indent+properties+',\n'+stepback+'}';}}stack.pop();indent=stepback;return final}function serializeKey(key){if(key.length===0){return quoteString(key)}var firstChar=String.fromCodePoint(key.codePointAt(0));if(!util.isIdStartChar(firstChar)){return quoteString(key)}for(var i=firstChar.length;i=0){throw TypeError('Converting circular structure to JSON5')}stack.push(value);var stepback=indent;indent=indent+gap;var partial=[];for(var i=0;i { - const idx = arg.indexOf('='); - - if (idx >= 0) { - let name = arg.substr(0, idx); - let value = decodeURIComponent(arg.substr(idx + 1)); - - if (specialValues.hasOwnProperty(value)) { - value = specialValues[value]; - } - - if (name.substr(-2) === '[]') { - name = decodeURIComponent(name.substr(0, name.length - 2)); - - if (!Array.isArray(result[name])) { - result[name] = []; - } - - result[name].push(value); - } else { - name = decodeURIComponent(name); - result[name] = value; - } - } else { - if (arg.substr(0, 1) === '-') { - result[decodeURIComponent(arg.substr(1))] = false; - } else if (arg.substr(0, 1) === '+') { - result[decodeURIComponent(arg.substr(1))] = true; - } else { - result[decodeURIComponent(arg)] = true; - } - } - }); - - return result; -} - -var parseQuery_1$1 = parseQuery; - -function getOptions(loaderContext) { - const query = loaderContext.query; - - if (typeof query === 'string' && query !== '') { - return parseQuery_1$1(loaderContext.query); - } - - if (!query || typeof query !== 'object') { - // Not object-like queries are not supported. - return null; - } - - return query; -} - -var getOptions_1$1 = getOptions; - -const matchRelativePath = /^\.\.?[/\\]/; - -function isAbsolutePath(str) { - return path__default.posix.isAbsolute(str) || path__default.win32.isAbsolute(str); -} - -function isRelativePath(str) { - return matchRelativePath.test(str); -} - -function stringifyRequest(loaderContext, request) { - const splitted = request.split('!'); - const context = - loaderContext.context || - (loaderContext.options && loaderContext.options.context); - - return JSON.stringify( - splitted - .map((part) => { - // First, separate singlePath from query, because the query might contain paths again - const splittedPart = part.match(/^(.*?)(\?.*)/); - const query = splittedPart ? splittedPart[2] : ''; - let singlePath = splittedPart ? splittedPart[1] : part; - - if (isAbsolutePath(singlePath) && context) { - singlePath = path__default.relative(context, singlePath); - - if (isAbsolutePath(singlePath)) { - // If singlePath still matches an absolute path, singlePath was on a different drive than context. - // In this case, we leave the path platform-specific without replacing any separators. - // @see https://github.com/webpack/loader-utils/pull/14 - return singlePath + query; - } - - if (isRelativePath(singlePath) === false) { - // Ensure that the relative path starts at least with ./ otherwise it would be a request into the modules directory (like node_modules). - singlePath = './' + singlePath; - } - } - - return singlePath.replace(/\\/g, '/') + query; - }) - .join('!') - ); -} - -var stringifyRequest_1$1 = stringifyRequest; - -function getRemainingRequest(loaderContext) { - if (loaderContext.remainingRequest) { - return loaderContext.remainingRequest; - } - - const request = loaderContext.loaders - .slice(loaderContext.loaderIndex + 1) - .map((obj) => obj.request) - .concat([loaderContext.resource]); - - return request.join('!'); -} - -var getRemainingRequest_1$1 = getRemainingRequest; - -function getCurrentRequest(loaderContext) { - if (loaderContext.currentRequest) { - return loaderContext.currentRequest; - } - - const request = loaderContext.loaders - .slice(loaderContext.loaderIndex) - .map((obj) => obj.request) - .concat([loaderContext.resource]); - - return request.join('!'); -} - -var getCurrentRequest_1$1 = getCurrentRequest; - -function isUrlRequest(url, root) { - // An URL is not an request if - - // 1. It's an absolute url and it is not `windows` path like `C:\dir\file` - if (/^[a-z][a-z0-9+.-]*:/i.test(url) && !path__default.win32.isAbsolute(url)) { - return false; - } - - // 2. It's a protocol-relative - if (/^\/\//.test(url)) { - return false; - } - - // 3. It's some kind of url for a template - if (/^[{}[\]#*;,'§$%&(=?`´^°<>]/.test(url)) { - return false; - } - - // 4. It's also not an request if root isn't set and it's a root-relative url - if ((root === undefined || root === false) && /^\//.test(url)) { - return false; - } - - return true; -} - -var isUrlRequest_1$1 = isUrlRequest; - -// we can't use path.win32.isAbsolute because it also matches paths starting with a forward slash -const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i; - -function urlToRequest(url, root) { - // Do not rewrite an empty url - if (url === '') { - return ''; - } - - const moduleRequestRegex = /^[^?]*~/; - let request; - - if (matchNativeWin32Path.test(url)) { - // absolute windows path, keep it - request = url; - } else if (root !== undefined && root !== false && /^\//.test(url)) { - // if root is set and the url is root-relative - switch (typeof root) { - // 1. root is a string: root is prefixed to the url - case 'string': - // special case: `~` roots convert to module request - if (moduleRequestRegex.test(root)) { - request = root.replace(/([^~/])$/, '$1/') + url.slice(1); - } else { - request = root + url; - } - break; - // 2. root is `true`: absolute paths are allowed - // *nix only, windows-style absolute paths are always allowed as they doesn't start with a `/` - case 'boolean': - request = url; - break; - default: - throw new Error( - "Unexpected parameters to loader-utils 'urlToRequest': url = " + - url + - ', root = ' + - root + - '.' - ); - } - } else if (/^\.\.?\//.test(url)) { - // A relative url stays - request = url; - } else { - // every other url is threaded like a relative url - request = './' + url; - } - - // A `~` makes the url an module - if (moduleRequestRegex.test(request)) { - request = request.replace(moduleRequestRegex, ''); - } - - return request; -} - -var urlToRequest_1$1 = urlToRequest; - -function parseString(str) { - try { - if (str[0] === '"') { - return JSON.parse(str); - } - - if (str[0] === "'" && str.substr(str.length - 1) === "'") { - return parseString( - str - .replace(/\\.|"/g, (x) => (x === '"' ? '\\"' : x)) - .replace(/^'|'$/g, '"') - ); - } - - return JSON.parse('"' + str + '"'); - } catch (e) { - return str; - } -} - -var parseString_1$1 = parseString; - -/* - * big.js v5.2.2 - * A small, fast, easy-to-use library for arbitrary-precision decimal arithmetic. - * Copyright (c) 2018 Michael Mclaughlin - * https://github.com/MikeMcl/big.js/LICENCE - */ - -var big = build$1.createCommonjsModule(function (module) { -(function (GLOBAL) { - var Big, - - -/************************************** EDITABLE DEFAULTS *****************************************/ - - - // The default values below must be integers within the stated ranges. - - /* - * The maximum number of decimal places (DP) of the results of operations involving division: - * div and sqrt, and pow with negative exponents. - */ - DP = 20, // 0 to MAX_DP - - /* - * The rounding mode (RM) used when rounding to the above decimal places. - * - * 0 Towards zero (i.e. truncate, no rounding). (ROUND_DOWN) - * 1 To nearest neighbour. If equidistant, round up. (ROUND_HALF_UP) - * 2 To nearest neighbour. If equidistant, to even. (ROUND_HALF_EVEN) - * 3 Away from zero. (ROUND_UP) - */ - RM = 1, // 0, 1, 2 or 3 - - // The maximum value of DP and Big.DP. - MAX_DP = 1E6, // 0 to 1000000 - - // The maximum magnitude of the exponent argument to the pow method. - MAX_POWER = 1E6, // 1 to 1000000 - - /* - * The negative exponent (NE) at and beneath which toString returns exponential notation. - * (JavaScript numbers: -7) - * -1000000 is the minimum recommended exponent value of a Big. - */ - NE = -7, // 0 to -1000000 - - /* - * The positive exponent (PE) at and above which toString returns exponential notation. - * (JavaScript numbers: 21) - * 1000000 is the maximum recommended exponent value of a Big. - * (This limit is not enforced or checked.) - */ - PE = 21, // 0 to 1000000 - - -/**************************************************************************************************/ - - - // Error messages. - NAME = '[big.js] ', - INVALID = NAME + 'Invalid ', - INVALID_DP = INVALID + 'decimal places', - INVALID_RM = INVALID + 'rounding mode', - DIV_BY_ZERO = NAME + 'Division by zero', - - // The shared prototype object. - P = {}, - UNDEFINED = void 0, - NUMERIC = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i; - - - /* - * Create and return a Big constructor. - * - */ - function _Big_() { - - /* - * The Big constructor and exported function. - * Create and return a new instance of a Big number object. - * - * n {number|string|Big} A numeric value. - */ - function Big(n) { - var x = this; - - // Enable constructor usage without new. - if (!(x instanceof Big)) return n === UNDEFINED ? _Big_() : new Big(n); - - // Duplicate. - if (n instanceof Big) { - x.s = n.s; - x.e = n.e; - x.c = n.c.slice(); - } else { - parse(x, n); - } - - /* - * Retain a reference to this Big constructor, and shadow Big.prototype.constructor which - * points to Object. - */ - x.constructor = Big; - } - - Big.prototype = P; - Big.DP = DP; - Big.RM = RM; - Big.NE = NE; - Big.PE = PE; - Big.version = '5.2.2'; - - return Big; - } - - - /* - * Parse the number or string value passed to a Big constructor. - * - * x {Big} A Big number instance. - * n {number|string} A numeric value. - */ - function parse(x, n) { - var e, i, nl; - - // Minus zero? - if (n === 0 && 1 / n < 0) n = '-0'; - else if (!NUMERIC.test(n += '')) throw Error(INVALID + 'number'); - - // Determine sign. - x.s = n.charAt(0) == '-' ? (n = n.slice(1), -1) : 1; - - // Decimal point? - if ((e = n.indexOf('.')) > -1) n = n.replace('.', ''); - - // Exponential form? - if ((i = n.search(/e/i)) > 0) { - - // Determine exponent. - if (e < 0) e = i; - e += +n.slice(i + 1); - n = n.substring(0, i); - } else if (e < 0) { - - // Integer. - e = n.length; - } - - nl = n.length; - - // Determine leading zeros. - for (i = 0; i < nl && n.charAt(i) == '0';) ++i; - - if (i == nl) { - - // Zero. - x.c = [x.e = 0]; - } else { - - // Determine trailing zeros. - for (; nl > 0 && n.charAt(--nl) == '0';); - x.e = e - i - 1; - x.c = []; - - // Convert string to array of digits without leading/trailing zeros. - for (e = 0; i <= nl;) x.c[e++] = +n.charAt(i++); - } - - return x; - } - - - /* - * Round Big x to a maximum of dp decimal places using rounding mode rm. - * Called by stringify, P.div, P.round and P.sqrt. - * - * x {Big} The Big to round. - * dp {number} Integer, 0 to MAX_DP inclusive. - * rm {number} 0, 1, 2 or 3 (DOWN, HALF_UP, HALF_EVEN, UP) - * [more] {boolean} Whether the result of division was truncated. - */ - function round(x, dp, rm, more) { - var xc = x.c, - i = x.e + dp + 1; - - if (i < xc.length) { - if (rm === 1) { - - // xc[i] is the digit after the digit that may be rounded up. - more = xc[i] >= 5; - } else if (rm === 2) { - more = xc[i] > 5 || xc[i] == 5 && - (more || i < 0 || xc[i + 1] !== UNDEFINED || xc[i - 1] & 1); - } else if (rm === 3) { - more = more || !!xc[0]; - } else { - more = false; - if (rm !== 0) throw Error(INVALID_RM); - } - - if (i < 1) { - xc.length = 1; - - if (more) { - - // 1, 0.1, 0.01, 0.001, 0.0001 etc. - x.e = -dp; - xc[0] = 1; - } else { - - // Zero. - xc[0] = x.e = 0; - } - } else { - - // Remove any digits after the required decimal places. - xc.length = i--; - - // Round up? - if (more) { - - // Rounding up may mean the previous digit has to be rounded up. - for (; ++xc[i] > 9;) { - xc[i] = 0; - if (!i--) { - ++x.e; - xc.unshift(1); - } - } - } - - // Remove trailing zeros. - for (i = xc.length; !xc[--i];) xc.pop(); - } - } else if (rm < 0 || rm > 3 || rm !== ~~rm) { - throw Error(INVALID_RM); - } - - return x; - } - - - /* - * Return a string representing the value of Big x in normal or exponential notation. - * Handles P.toExponential, P.toFixed, P.toJSON, P.toPrecision, P.toString and P.valueOf. - * - * x {Big} - * id? {number} Caller id. - * 1 toExponential - * 2 toFixed - * 3 toPrecision - * 4 valueOf - * n? {number|undefined} Caller's argument. - * k? {number|undefined} - */ - function stringify(x, id, n, k) { - var e, s, - Big = x.constructor, - z = !x.c[0]; - - if (n !== UNDEFINED) { - if (n !== ~~n || n < (id == 3) || n > MAX_DP) { - throw Error(id == 3 ? INVALID + 'precision' : INVALID_DP); - } - - x = new Big(x); - - // The index of the digit that may be rounded up. - n = k - x.e; - - // Round? - if (x.c.length > ++k) round(x, n, Big.RM); - - // toFixed: recalculate k as x.e may have changed if value rounded up. - if (id == 2) k = x.e + n + 1; - - // Append zeros? - for (; x.c.length < k;) x.c.push(0); - } - - e = x.e; - s = x.c.join(''); - n = s.length; - - // Exponential notation? - if (id != 2 && (id == 1 || id == 3 && k <= e || e <= Big.NE || e >= Big.PE)) { - s = s.charAt(0) + (n > 1 ? '.' + s.slice(1) : '') + (e < 0 ? 'e' : 'e+') + e; - - // Normal notation. - } else if (e < 0) { - for (; ++e;) s = '0' + s; - s = '0.' + s; - } else if (e > 0) { - if (++e > n) for (e -= n; e--;) s += '0'; - else if (e < n) s = s.slice(0, e) + '.' + s.slice(e); - } else if (n > 1) { - s = s.charAt(0) + '.' + s.slice(1); - } - - return x.s < 0 && (!z || id == 4) ? '-' + s : s; - } - - - // Prototype/instance methods - - - /* - * Return a new Big whose value is the absolute value of this Big. - */ - P.abs = function () { - var x = new this.constructor(this); - x.s = 1; - return x; - }; - - - /* - * Return 1 if the value of this Big is greater than the value of Big y, - * -1 if the value of this Big is less than the value of Big y, or - * 0 if they have the same value. - */ - P.cmp = function (y) { - var isneg, - x = this, - xc = x.c, - yc = (y = new x.constructor(y)).c, - i = x.s, - j = y.s, - k = x.e, - l = y.e; - - // Either zero? - if (!xc[0] || !yc[0]) return !xc[0] ? !yc[0] ? 0 : -j : i; - - // Signs differ? - if (i != j) return i; - - isneg = i < 0; - - // Compare exponents. - if (k != l) return k > l ^ isneg ? 1 : -1; - - j = (k = xc.length) < (l = yc.length) ? k : l; - - // Compare digit by digit. - for (i = -1; ++i < j;) { - if (xc[i] != yc[i]) return xc[i] > yc[i] ^ isneg ? 1 : -1; - } - - // Compare lengths. - return k == l ? 0 : k > l ^ isneg ? 1 : -1; - }; - - - /* - * Return a new Big whose value is the value of this Big divided by the value of Big y, rounded, - * if necessary, to a maximum of Big.DP decimal places using rounding mode Big.RM. - */ - P.div = function (y) { - var x = this, - Big = x.constructor, - a = x.c, // dividend - b = (y = new Big(y)).c, // divisor - k = x.s == y.s ? 1 : -1, - dp = Big.DP; - - if (dp !== ~~dp || dp < 0 || dp > MAX_DP) throw Error(INVALID_DP); - - // Divisor is zero? - if (!b[0]) throw Error(DIV_BY_ZERO); - - // Dividend is 0? Return +-0. - if (!a[0]) return new Big(k * 0); - - var bl, bt, n, cmp, ri, - bz = b.slice(), - ai = bl = b.length, - al = a.length, - r = a.slice(0, bl), // remainder - rl = r.length, - q = y, // quotient - qc = q.c = [], - qi = 0, - d = dp + (q.e = x.e - y.e) + 1; // number of digits of the result - - q.s = k; - k = d < 0 ? 0 : d; - - // Create version of divisor with leading zero. - bz.unshift(0); - - // Add zeros to make remainder as long as divisor. - for (; rl++ < bl;) r.push(0); - - do { - - // n is how many times the divisor goes into current remainder. - for (n = 0; n < 10; n++) { - - // Compare divisor and remainder. - if (bl != (rl = r.length)) { - cmp = bl > rl ? 1 : -1; - } else { - for (ri = -1, cmp = 0; ++ri < bl;) { - if (b[ri] != r[ri]) { - cmp = b[ri] > r[ri] ? 1 : -1; - break; - } - } - } - - // If divisor < remainder, subtract divisor from remainder. - if (cmp < 0) { - - // Remainder can't be more than 1 digit longer than divisor. - // Equalise lengths using divisor with extra leading zero? - for (bt = rl == bl ? b : bz; rl;) { - if (r[--rl] < bt[rl]) { - ri = rl; - for (; ri && !r[--ri];) r[ri] = 9; - --r[ri]; - r[rl] += 10; - } - r[rl] -= bt[rl]; - } - - for (; !r[0];) r.shift(); - } else { - break; - } - } - - // Add the digit n to the result array. - qc[qi++] = cmp ? n : ++n; - - // Update the remainder. - if (r[0] && cmp) r[rl] = a[ai] || 0; - else r = [a[ai]]; - - } while ((ai++ < al || r[0] !== UNDEFINED) && k--); - - // Leading zero? Do not remove if result is simply zero (qi == 1). - if (!qc[0] && qi != 1) { - - // There can't be more than one zero. - qc.shift(); - q.e--; - } - - // Round? - if (qi > d) round(q, dp, Big.RM, r[0] !== UNDEFINED); - - return q; - }; - - - /* - * Return true if the value of this Big is equal to the value of Big y, otherwise return false. - */ - P.eq = function (y) { - return !this.cmp(y); - }; - - - /* - * Return true if the value of this Big is greater than the value of Big y, otherwise return - * false. - */ - P.gt = function (y) { - return this.cmp(y) > 0; - }; - - - /* - * Return true if the value of this Big is greater than or equal to the value of Big y, otherwise - * return false. - */ - P.gte = function (y) { - return this.cmp(y) > -1; - }; - - - /* - * Return true if the value of this Big is less than the value of Big y, otherwise return false. - */ - P.lt = function (y) { - return this.cmp(y) < 0; - }; - - - /* - * Return true if the value of this Big is less than or equal to the value of Big y, otherwise - * return false. - */ - P.lte = function (y) { - return this.cmp(y) < 1; - }; - - - /* - * Return a new Big whose value is the value of this Big minus the value of Big y. - */ - P.minus = P.sub = function (y) { - var i, j, t, xlty, - x = this, - Big = x.constructor, - a = x.s, - b = (y = new Big(y)).s; - - // Signs differ? - if (a != b) { - y.s = -b; - return x.plus(y); - } - - var xc = x.c.slice(), - xe = x.e, - yc = y.c, - ye = y.e; - - // Either zero? - if (!xc[0] || !yc[0]) { - - // y is non-zero? x is non-zero? Or both are zero. - return yc[0] ? (y.s = -b, y) : new Big(xc[0] ? x : 0); - } - - // Determine which is the bigger number. Prepend zeros to equalise exponents. - if (a = xe - ye) { - - if (xlty = a < 0) { - a = -a; - t = xc; - } else { - ye = xe; - t = yc; - } - - t.reverse(); - for (b = a; b--;) t.push(0); - t.reverse(); - } else { - - // Exponents equal. Check digit by digit. - j = ((xlty = xc.length < yc.length) ? xc : yc).length; - - for (a = b = 0; b < j; b++) { - if (xc[b] != yc[b]) { - xlty = xc[b] < yc[b]; - break; - } - } - } - - // x < y? Point xc to the array of the bigger number. - if (xlty) { - t = xc; - xc = yc; - yc = t; - y.s = -y.s; - } - - /* - * Append zeros to xc if shorter. No need to add zeros to yc if shorter as subtraction only - * needs to start at yc.length. - */ - if ((b = (j = yc.length) - (i = xc.length)) > 0) for (; b--;) xc[i++] = 0; - - // Subtract yc from xc. - for (b = i; j > a;) { - if (xc[--j] < yc[j]) { - for (i = j; i && !xc[--i];) xc[i] = 9; - --xc[i]; - xc[j] += 10; - } - - xc[j] -= yc[j]; - } - - // Remove trailing zeros. - for (; xc[--b] === 0;) xc.pop(); - - // Remove leading zeros and adjust exponent accordingly. - for (; xc[0] === 0;) { - xc.shift(); - --ye; - } - - if (!xc[0]) { - - // n - n = +0 - y.s = 1; - - // Result must be zero. - xc = [ye = 0]; - } - - y.c = xc; - y.e = ye; - - return y; - }; - - - /* - * Return a new Big whose value is the value of this Big modulo the value of Big y. - */ - P.mod = function (y) { - var ygtx, - x = this, - Big = x.constructor, - a = x.s, - b = (y = new Big(y)).s; - - if (!y.c[0]) throw Error(DIV_BY_ZERO); - - x.s = y.s = 1; - ygtx = y.cmp(x) == 1; - x.s = a; - y.s = b; - - if (ygtx) return new Big(x); - - a = Big.DP; - b = Big.RM; - Big.DP = Big.RM = 0; - x = x.div(y); - Big.DP = a; - Big.RM = b; - - return this.minus(x.times(y)); - }; - - - /* - * Return a new Big whose value is the value of this Big plus the value of Big y. - */ - P.plus = P.add = function (y) { - var t, - x = this, - Big = x.constructor, - a = x.s, - b = (y = new Big(y)).s; - - // Signs differ? - if (a != b) { - y.s = -b; - return x.minus(y); - } - - var xe = x.e, - xc = x.c, - ye = y.e, - yc = y.c; - - // Either zero? y is non-zero? x is non-zero? Or both are zero. - if (!xc[0] || !yc[0]) return yc[0] ? y : new Big(xc[0] ? x : a * 0); - - xc = xc.slice(); - - // Prepend zeros to equalise exponents. - // Note: reverse faster than unshifts. - if (a = xe - ye) { - if (a > 0) { - ye = xe; - t = yc; - } else { - a = -a; - t = xc; - } - - t.reverse(); - for (; a--;) t.push(0); - t.reverse(); - } - - // Point xc to the longer array. - if (xc.length - yc.length < 0) { - t = yc; - yc = xc; - xc = t; - } - - a = yc.length; - - // Only start adding at yc.length - 1 as the further digits of xc can be left as they are. - for (b = 0; a; xc[a] %= 10) b = (xc[--a] = xc[a] + yc[a] + b) / 10 | 0; - - // No need to check for zero, as +x + +y != 0 && -x + -y != 0 - - if (b) { - xc.unshift(b); - ++ye; - } - - // Remove trailing zeros. - for (a = xc.length; xc[--a] === 0;) xc.pop(); - - y.c = xc; - y.e = ye; - - return y; - }; - - - /* - * Return a Big whose value is the value of this Big raised to the power n. - * If n is negative, round to a maximum of Big.DP decimal places using rounding - * mode Big.RM. - * - * n {number} Integer, -MAX_POWER to MAX_POWER inclusive. - */ - P.pow = function (n) { - var x = this, - one = new x.constructor(1), - y = one, - isneg = n < 0; - - if (n !== ~~n || n < -MAX_POWER || n > MAX_POWER) throw Error(INVALID + 'exponent'); - if (isneg) n = -n; - - for (;;) { - if (n & 1) y = y.times(x); - n >>= 1; - if (!n) break; - x = x.times(x); - } - - return isneg ? one.div(y) : y; - }; - - - /* - * Return a new Big whose value is the value of this Big rounded using rounding mode rm - * to a maximum of dp decimal places, or, if dp is negative, to an integer which is a - * multiple of 10**-dp. - * If dp is not specified, round to 0 decimal places. - * If rm is not specified, use Big.RM. - * - * dp? {number} Integer, -MAX_DP to MAX_DP inclusive. - * rm? 0, 1, 2 or 3 (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_UP) - */ - P.round = function (dp, rm) { - var Big = this.constructor; - if (dp === UNDEFINED) dp = 0; - else if (dp !== ~~dp || dp < -MAX_DP || dp > MAX_DP) throw Error(INVALID_DP); - return round(new Big(this), dp, rm === UNDEFINED ? Big.RM : rm); - }; - - - /* - * Return a new Big whose value is the square root of the value of this Big, rounded, if - * necessary, to a maximum of Big.DP decimal places using rounding mode Big.RM. - */ - P.sqrt = function () { - var r, c, t, - x = this, - Big = x.constructor, - s = x.s, - e = x.e, - half = new Big(0.5); - - // Zero? - if (!x.c[0]) return new Big(x); - - // Negative? - if (s < 0) throw Error(NAME + 'No square root'); - - // Estimate. - s = Math.sqrt(x + ''); - - // Math.sqrt underflow/overflow? - // Re-estimate: pass x coefficient to Math.sqrt as integer, then adjust the result exponent. - if (s === 0 || s === 1 / 0) { - c = x.c.join(''); - if (!(c.length + e & 1)) c += '0'; - s = Math.sqrt(c); - e = ((e + 1) / 2 | 0) - (e < 0 || e & 1); - r = new Big((s == 1 / 0 ? '1e' : (s = s.toExponential()).slice(0, s.indexOf('e') + 1)) + e); - } else { - r = new Big(s); - } - - e = r.e + (Big.DP += 4); - - // Newton-Raphson iteration. - do { - t = r; - r = half.times(t.plus(x.div(t))); - } while (t.c.slice(0, e).join('') !== r.c.slice(0, e).join('')); - - return round(r, Big.DP -= 4, Big.RM); - }; - - - /* - * Return a new Big whose value is the value of this Big times the value of Big y. - */ - P.times = P.mul = function (y) { - var c, - x = this, - Big = x.constructor, - xc = x.c, - yc = (y = new Big(y)).c, - a = xc.length, - b = yc.length, - i = x.e, - j = y.e; - - // Determine sign of result. - y.s = x.s == y.s ? 1 : -1; - - // Return signed 0 if either 0. - if (!xc[0] || !yc[0]) return new Big(y.s * 0); - - // Initialise exponent of result as x.e + y.e. - y.e = i + j; - - // If array xc has fewer digits than yc, swap xc and yc, and lengths. - if (a < b) { - c = xc; - xc = yc; - yc = c; - j = a; - a = b; - b = j; - } - - // Initialise coefficient array of result with zeros. - for (c = new Array(j = a + b); j--;) c[j] = 0; - - // Multiply. - - // i is initially xc.length. - for (i = b; i--;) { - b = 0; - - // a is yc.length. - for (j = a + i; j > i;) { - - // Current sum of products at this digit position, plus carry. - b = c[j] + yc[i] * xc[j - i - 1] + b; - c[j--] = b % 10; - - // carry - b = b / 10 | 0; - } - - c[j] = (c[j] + b) % 10; - } - - // Increment result exponent if there is a final carry, otherwise remove leading zero. - if (b) ++y.e; - else c.shift(); - - // Remove trailing zeros. - for (i = c.length; !c[--i];) c.pop(); - y.c = c; - - return y; - }; - - - /* - * Return a string representing the value of this Big in exponential notation to dp fixed decimal - * places and rounded using Big.RM. - * - * dp? {number} Integer, 0 to MAX_DP inclusive. - */ - P.toExponential = function (dp) { - return stringify(this, 1, dp, dp); - }; - - - /* - * Return a string representing the value of this Big in normal notation to dp fixed decimal - * places and rounded using Big.RM. - * - * dp? {number} Integer, 0 to MAX_DP inclusive. - * - * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'. - * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'. - */ - P.toFixed = function (dp) { - return stringify(this, 2, dp, this.e + dp); - }; - - - /* - * Return a string representing the value of this Big rounded to sd significant digits using - * Big.RM. Use exponential notation if sd is less than the number of digits necessary to represent - * the integer part of the value in normal notation. - * - * sd {number} Integer, 1 to MAX_DP inclusive. - */ - P.toPrecision = function (sd) { - return stringify(this, 3, sd, sd - 1); - }; - - - /* - * Return a string representing the value of this Big. - * Return exponential notation if this Big has a positive exponent equal to or greater than - * Big.PE, or a negative exponent equal to or less than Big.NE. - * Omit the sign for negative zero. - */ - P.toString = function () { - return stringify(this); - }; - - - /* - * Return a string representing the value of this Big. - * Return exponential notation if this Big has a positive exponent equal to or greater than - * Big.PE, or a negative exponent equal to or less than Big.NE. - * Include the sign for negative zero. - */ - P.valueOf = P.toJSON = function () { - return stringify(this, 4); - }; - - - // Export - - - Big = _Big_(); - - Big['default'] = Big.Big = Big; - - //AMD. - if (module.exports) { - module.exports = Big; - - //Browser. - } else { - GLOBAL.Big = Big; - } -})(build$1.commonjsGlobal); -}); - -const baseEncodeTables = { - 26: 'abcdefghijklmnopqrstuvwxyz', - 32: '123456789abcdefghjkmnpqrstuvwxyz', // no 0lio - 36: '0123456789abcdefghijklmnopqrstuvwxyz', - 49: 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ', // no lIO - 52: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', - 58: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ', // no 0lIO - 62: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', - 64: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_', -}; - -function encodeBufferToBase(buffer, base) { - const encodeTable = baseEncodeTables[base]; - if (!encodeTable) { - throw new Error('Unknown encoding base' + base); - } - - const readLength = buffer.length; - const Big = big; - - Big.RM = Big.DP = 0; - let b = new Big(0); - - for (let i = readLength - 1; i >= 0; i--) { - b = b.times(256).plus(buffer[i]); - } - - let output = ''; - while (b.gt(0)) { - output = encodeTable[b.mod(base)] + output; - b = b.div(base); - } - - Big.DP = 20; - Big.RM = 1; - - return output; -} - -function getHashDigest(buffer, hashType, digestType, maxLength) { - hashType = hashType || 'md5'; - maxLength = maxLength || 9999; - - const hash = require$$0__default.createHash(hashType); - - hash.update(buffer); - - if ( - digestType === 'base26' || - digestType === 'base32' || - digestType === 'base36' || - digestType === 'base49' || - digestType === 'base52' || - digestType === 'base58' || - digestType === 'base62' || - digestType === 'base64' - ) { - return encodeBufferToBase(hash.digest(), digestType.substr(4)).substr( - 0, - maxLength - ); - } else { - return hash.digest(digestType || 'hex').substr(0, maxLength); - } -} - -var getHashDigest_1$1 = getHashDigest; - -var emojisList = [ - "🀄️", - "🃏", - "🅰️", - "🅱️", - "🅾️", - "🅿️", - "🆎", - "🆑", - "🆒", - "🆓", - "🆔", - "🆕", - "🆖", - "🆗", - "🆘", - "🆙", - "🆚", - "🇦🇨", - "🇦🇩", - "🇦🇪", - "🇦🇫", - "🇦🇬", - "🇦🇮", - "🇦🇱", - "🇦🇲", - "🇦🇴", - "🇦🇶", - "🇦🇷", - "🇦🇸", - "🇦🇹", - "🇦🇺", - "🇦🇼", - "🇦🇽", - "🇦🇿", - "🇦", - "🇧🇦", - "🇧🇧", - "🇧🇩", - "🇧🇪", - "🇧🇫", - "🇧🇬", - "🇧🇭", - "🇧🇮", - "🇧🇯", - "🇧🇱", - "🇧🇲", - "🇧🇳", - "🇧🇴", - "🇧🇶", - "🇧🇷", - "🇧🇸", - "🇧🇹", - "🇧🇻", - "🇧🇼", - "🇧🇾", - "🇧🇿", - "🇧", - "🇨🇦", - "🇨🇨", - "🇨🇩", - "🇨🇫", - "🇨🇬", - "🇨🇭", - "🇨🇮", - "🇨🇰", - "🇨🇱", - "🇨🇲", - "🇨🇳", - "🇨🇴", - "🇨🇵", - "🇨🇷", - "🇨🇺", - "🇨🇻", - "🇨🇼", - "🇨🇽", - "🇨🇾", - "🇨🇿", - "🇨", - "🇩🇪", - "🇩🇬", - "🇩🇯", - "🇩🇰", - "🇩🇲", - "🇩🇴", - "🇩🇿", - "🇩", - "🇪🇦", - "🇪🇨", - "🇪🇪", - "🇪🇬", - "🇪🇭", - "🇪🇷", - "🇪🇸", - "🇪🇹", - "🇪🇺", - "🇪", - "🇫🇮", - "🇫🇯", - "🇫🇰", - "🇫🇲", - "🇫🇴", - "🇫🇷", - "🇫", - "🇬🇦", - "🇬🇧", - "🇬🇩", - "🇬🇪", - "🇬🇫", - "🇬🇬", - "🇬🇭", - "🇬🇮", - "🇬🇱", - "🇬🇲", - "🇬🇳", - "🇬🇵", - "🇬🇶", - "🇬🇷", - "🇬🇸", - "🇬🇹", - "🇬🇺", - "🇬🇼", - "🇬🇾", - "🇬", - "🇭🇰", - "🇭🇲", - "🇭🇳", - "🇭🇷", - "🇭🇹", - "🇭🇺", - "🇭", - "🇮🇨", - "🇮🇩", - "🇮🇪", - "🇮🇱", - "🇮🇲", - "🇮🇳", - "🇮🇴", - "🇮🇶", - "🇮🇷", - "🇮🇸", - "🇮🇹", - "🇮", - "🇯🇪", - "🇯🇲", - "🇯🇴", - "🇯🇵", - "🇯", - "🇰🇪", - "🇰🇬", - "🇰🇭", - "🇰🇮", - "🇰🇲", - "🇰🇳", - "🇰🇵", - "🇰🇷", - "🇰🇼", - "🇰🇾", - "🇰🇿", - "🇰", - "🇱🇦", - "🇱🇧", - "🇱🇨", - "🇱🇮", - "🇱🇰", - "🇱🇷", - "🇱🇸", - "🇱🇹", - "🇱🇺", - "🇱🇻", - "🇱🇾", - "🇱", - "🇲🇦", - "🇲🇨", - "🇲🇩", - "🇲🇪", - "🇲🇫", - "🇲🇬", - "🇲🇭", - "🇲🇰", - "🇲🇱", - "🇲🇲", - "🇲🇳", - "🇲🇴", - "🇲🇵", - "🇲🇶", - "🇲🇷", - "🇲🇸", - "🇲🇹", - "🇲🇺", - "🇲🇻", - "🇲🇼", - "🇲🇽", - "🇲🇾", - "🇲🇿", - "🇲", - "🇳🇦", - "🇳🇨", - "🇳🇪", - "🇳🇫", - "🇳🇬", - "🇳🇮", - "🇳🇱", - "🇳🇴", - "🇳🇵", - "🇳🇷", - "🇳🇺", - "🇳🇿", - "🇳", - "🇴🇲", - "🇴", - "🇵🇦", - "🇵🇪", - "🇵🇫", - "🇵🇬", - "🇵🇭", - "🇵🇰", - "🇵🇱", - "🇵🇲", - "🇵🇳", - "🇵🇷", - "🇵🇸", - "🇵🇹", - "🇵🇼", - "🇵🇾", - "🇵", - "🇶🇦", - "🇶", - "🇷🇪", - "🇷🇴", - "🇷🇸", - "🇷🇺", - "🇷🇼", - "🇷", - "🇸🇦", - "🇸🇧", - "🇸🇨", - "🇸🇩", - "🇸🇪", - "🇸🇬", - "🇸🇭", - "🇸🇮", - "🇸🇯", - "🇸🇰", - "🇸🇱", - "🇸🇲", - "🇸🇳", - "🇸🇴", - "🇸🇷", - "🇸🇸", - "🇸🇹", - "🇸🇻", - "🇸🇽", - "🇸🇾", - "🇸🇿", - "🇸", - "🇹🇦", - "🇹🇨", - "🇹🇩", - "🇹🇫", - "🇹🇬", - "🇹🇭", - "🇹🇯", - "🇹🇰", - "🇹🇱", - "🇹🇲", - "🇹🇳", - "🇹🇴", - "🇹🇷", - "🇹🇹", - "🇹🇻", - "🇹🇼", - "🇹🇿", - "🇹", - "🇺🇦", - "🇺🇬", - "🇺🇲", - "🇺🇳", - "🇺🇸", - "🇺🇾", - "🇺🇿", - "🇺", - "🇻🇦", - "🇻🇨", - "🇻🇪", - "🇻🇬", - "🇻🇮", - "🇻🇳", - "🇻🇺", - "🇻", - "🇼🇫", - "🇼🇸", - "🇼", - "🇽🇰", - "🇽", - "🇾🇪", - "🇾🇹", - "🇾", - "🇿🇦", - "🇿🇲", - "🇿🇼", - "🇿", - "🈁", - "🈂️", - "🈚️", - "🈯️", - "🈲", - "🈳", - "🈴", - "🈵", - "🈶", - "🈷️", - "🈸", - "🈹", - "🈺", - "🉐", - "🉑", - "🌀", - "🌁", - "🌂", - "🌃", - "🌄", - "🌅", - "🌆", - "🌇", - "🌈", - "🌉", - "🌊", - "🌋", - "🌌", - "🌍", - "🌎", - "🌏", - "🌐", - "🌑", - "🌒", - "🌓", - "🌔", - "🌕", - "🌖", - "🌗", - "🌘", - "🌙", - "🌚", - "🌛", - "🌜", - "🌝", - "🌞", - "🌟", - "🌠", - "🌡️", - "🌤️", - "🌥️", - "🌦️", - "🌧️", - "🌨️", - "🌩️", - "🌪️", - "🌫️", - "🌬️", - "🌭", - "🌮", - "🌯", - "🌰", - "🌱", - "🌲", - "🌳", - "🌴", - "🌵", - "🌶️", - "🌷", - "🌸", - "🌹", - "🌺", - "🌻", - "🌼", - "🌽", - "🌾", - "🌿", - "🍀", - "🍁", - "🍂", - "🍃", - "🍄", - "🍅", - "🍆", - "🍇", - "🍈", - "🍉", - "🍊", - "🍋", - "🍌", - "🍍", - "🍎", - "🍏", - "🍐", - "🍑", - "🍒", - "🍓", - "🍔", - "🍕", - "🍖", - "🍗", - "🍘", - "🍙", - "🍚", - "🍛", - "🍜", - "🍝", - "🍞", - "🍟", - "🍠", - "🍡", - "🍢", - "🍣", - "🍤", - "🍥", - "🍦", - "🍧", - "🍨", - "🍩", - "🍪", - "🍫", - "🍬", - "🍭", - "🍮", - "🍯", - "🍰", - "🍱", - "🍲", - "🍳", - "🍴", - "🍵", - "🍶", - "🍷", - "🍸", - "🍹", - "🍺", - "🍻", - "🍼", - "🍽️", - "🍾", - "🍿", - "🎀", - "🎁", - "🎂", - "🎃", - "🎄", - "🎅🏻", - "🎅🏼", - "🎅🏽", - "🎅🏾", - "🎅🏿", - "🎅", - "🎆", - "🎇", - "🎈", - "🎉", - "🎊", - "🎋", - "🎌", - "🎍", - "🎎", - "🎏", - "🎐", - "🎑", - "🎒", - "🎓", - "🎖️", - "🎗️", - "🎙️", - "🎚️", - "🎛️", - "🎞️", - "🎟️", - "🎠", - "🎡", - "🎢", - "🎣", - "🎤", - "🎥", - "🎦", - "🎧", - "🎨", - "🎩", - "🎪", - "🎫", - "🎬", - "🎭", - "🎮", - "🎯", - "🎰", - "🎱", - "🎲", - "🎳", - "🎴", - "🎵", - "🎶", - "🎷", - "🎸", - "🎹", - "🎺", - "🎻", - "🎼", - "🎽", - "🎾", - "🎿", - "🏀", - "🏁", - "🏂🏻", - "🏂🏼", - "🏂🏽", - "🏂🏾", - "🏂🏿", - "🏂", - "🏃🏻‍♀️", - "🏃🏻‍♂️", - "🏃🏻", - "🏃🏼‍♀️", - "🏃🏼‍♂️", - "🏃🏼", - "🏃🏽‍♀️", - "🏃🏽‍♂️", - "🏃🏽", - "🏃🏾‍♀️", - "🏃🏾‍♂️", - "🏃🏾", - "🏃🏿‍♀️", - "🏃🏿‍♂️", - "🏃🏿", - "🏃‍♀️", - "🏃‍♂️", - "🏃", - "🏄🏻‍♀️", - "🏄🏻‍♂️", - "🏄🏻", - "🏄🏼‍♀️", - "🏄🏼‍♂️", - "🏄🏼", - "🏄🏽‍♀️", - "🏄🏽‍♂️", - "🏄🏽", - "🏄🏾‍♀️", - "🏄🏾‍♂️", - "🏄🏾", - "🏄🏿‍♀️", - "🏄🏿‍♂️", - "🏄🏿", - "🏄‍♀️", - "🏄‍♂️", - "🏄", - "🏅", - "🏆", - "🏇🏻", - "🏇🏼", - "🏇🏽", - "🏇🏾", - "🏇🏿", - "🏇", - "🏈", - "🏉", - "🏊🏻‍♀️", - "🏊🏻‍♂️", - "🏊🏻", - "🏊🏼‍♀️", - "🏊🏼‍♂️", - "🏊🏼", - "🏊🏽‍♀️", - "🏊🏽‍♂️", - "🏊🏽", - "🏊🏾‍♀️", - "🏊🏾‍♂️", - "🏊🏾", - "🏊🏿‍♀️", - "🏊🏿‍♂️", - "🏊🏿", - "🏊‍♀️", - "🏊‍♂️", - "🏊", - "🏋🏻‍♀️", - "🏋🏻‍♂️", - "🏋🏻", - "🏋🏼‍♀️", - "🏋🏼‍♂️", - "🏋🏼", - "🏋🏽‍♀️", - "🏋🏽‍♂️", - "🏋🏽", - "🏋🏾‍♀️", - "🏋🏾‍♂️", - "🏋🏾", - "🏋🏿‍♀️", - "🏋🏿‍♂️", - "🏋🏿", - "🏋️‍♀️", - "🏋️‍♂️", - "🏋️", - "🏌🏻‍♀️", - "🏌🏻‍♂️", - "🏌🏻", - "🏌🏼‍♀️", - "🏌🏼‍♂️", - "🏌🏼", - "🏌🏽‍♀️", - "🏌🏽‍♂️", - "🏌🏽", - "🏌🏾‍♀️", - "🏌🏾‍♂️", - "🏌🏾", - "🏌🏿‍♀️", - "🏌🏿‍♂️", - "🏌🏿", - "🏌️‍♀️", - "🏌️‍♂️", - "🏌️", - "🏍️", - "🏎️", - "🏏", - "🏐", - "🏑", - "🏒", - "🏓", - "🏔️", - "🏕️", - "🏖️", - "🏗️", - "🏘️", - "🏙️", - "🏚️", - "🏛️", - "🏜️", - "🏝️", - "🏞️", - "🏟️", - "🏠", - "🏡", - "🏢", - "🏣", - "🏤", - "🏥", - "🏦", - "🏧", - "🏨", - "🏩", - "🏪", - "🏫", - "🏬", - "🏭", - "🏮", - "🏯", - "🏰", - "🏳️‍🌈", - "🏳️", - "🏴‍☠️", - "🏴󠁧󠁢󠁥󠁮󠁧󠁿", - "🏴󠁧󠁢󠁳󠁣󠁴󠁿", - "🏴󠁧󠁢󠁷󠁬󠁳󠁿", - "🏴", - "🏵️", - "🏷️", - "🏸", - "🏹", - "🏺", - "🏻", - "🏼", - "🏽", - "🏾", - "🏿", - "🐀", - "🐁", - "🐂", - "🐃", - "🐄", - "🐅", - "🐆", - "🐇", - "🐈", - "🐉", - "🐊", - "🐋", - "🐌", - "🐍", - "🐎", - "🐏", - "🐐", - "🐑", - "🐒", - "🐓", - "🐔", - "🐕‍🦺", - "🐕", - "🐖", - "🐗", - "🐘", - "🐙", - "🐚", - "🐛", - "🐜", - "🐝", - "🐞", - "🐟", - "🐠", - "🐡", - "🐢", - "🐣", - "🐤", - "🐥", - "🐦", - "🐧", - "🐨", - "🐩", - "🐪", - "🐫", - "🐬", - "🐭", - "🐮", - "🐯", - "🐰", - "🐱", - "🐲", - "🐳", - "🐴", - "🐵", - "🐶", - "🐷", - "🐸", - "🐹", - "🐺", - "🐻", - "🐼", - "🐽", - "🐾", - "🐿️", - "👀", - "👁‍🗨", - "👁️", - "👂🏻", - "👂🏼", - "👂🏽", - "👂🏾", - "👂🏿", - "👂", - "👃🏻", - "👃🏼", - "👃🏽", - "👃🏾", - "👃🏿", - "👃", - "👄", - "👅", - "👆🏻", - "👆🏼", - "👆🏽", - "👆🏾", - "👆🏿", - "👆", - "👇🏻", - "👇🏼", - "👇🏽", - "👇🏾", - "👇🏿", - "👇", - "👈🏻", - "👈🏼", - "👈🏽", - "👈🏾", - "👈🏿", - "👈", - "👉🏻", - "👉🏼", - "👉🏽", - "👉🏾", - "👉🏿", - "👉", - "👊🏻", - "👊🏼", - "👊🏽", - "👊🏾", - "👊🏿", - "👊", - "👋🏻", - "👋🏼", - "👋🏽", - "👋🏾", - "👋🏿", - "👋", - "👌🏻", - "👌🏼", - "👌🏽", - "👌🏾", - "👌🏿", - "👌", - "👍🏻", - "👍🏼", - "👍🏽", - "👍🏾", - "👍🏿", - "👍", - "👎🏻", - "👎🏼", - "👎🏽", - "👎🏾", - "👎🏿", - "👎", - "👏🏻", - "👏🏼", - "👏🏽", - "👏🏾", - "👏🏿", - "👏", - "👐🏻", - "👐🏼", - "👐🏽", - "👐🏾", - "👐🏿", - "👐", - "👑", - "👒", - "👓", - "👔", - "👕", - "👖", - "👗", - "👘", - "👙", - "👚", - "👛", - "👜", - "👝", - "👞", - "👟", - "👠", - "👡", - "👢", - "👣", - "👤", - "👥", - "👦🏻", - "👦🏼", - "👦🏽", - "👦🏾", - "👦🏿", - "👦", - "👧🏻", - "👧🏼", - "👧🏽", - "👧🏾", - "👧🏿", - "👧", - "👨🏻‍🌾", - "👨🏻‍🍳", - "👨🏻‍🎓", - "👨🏻‍🎤", - "👨🏻‍🎨", - "👨🏻‍🏫", - "👨🏻‍🏭", - "👨🏻‍💻", - "👨🏻‍💼", - "👨🏻‍🔧", - "👨🏻‍🔬", - "👨🏻‍🚀", - "👨🏻‍🚒", - "👨🏻‍🦯", - "👨🏻‍🦰", - "👨🏻‍🦱", - "👨🏻‍🦲", - "👨🏻‍🦳", - "👨🏻‍🦼", - "👨🏻‍🦽", - "👨🏻‍⚕️", - "👨🏻‍⚖️", - "👨🏻‍✈️", - "👨🏻", - "👨🏼‍🌾", - "👨🏼‍🍳", - "👨🏼‍🎓", - "👨🏼‍🎤", - "👨🏼‍🎨", - "👨🏼‍🏫", - "👨🏼‍🏭", - "👨🏼‍💻", - "👨🏼‍💼", - "👨🏼‍🔧", - "👨🏼‍🔬", - "👨🏼‍🚀", - "👨🏼‍🚒", - "👨🏼‍🤝‍👨🏻", - "👨🏼‍🦯", - "👨🏼‍🦰", - "👨🏼‍🦱", - "👨🏼‍🦲", - "👨🏼‍🦳", - "👨🏼‍🦼", - "👨🏼‍🦽", - "👨🏼‍⚕️", - "👨🏼‍⚖️", - "👨🏼‍✈️", - "👨🏼", - "👨🏽‍🌾", - "👨🏽‍🍳", - "👨🏽‍🎓", - "👨🏽‍🎤", - "👨🏽‍🎨", - "👨🏽‍🏫", - "👨🏽‍🏭", - "👨🏽‍💻", - "👨🏽‍💼", - "👨🏽‍🔧", - "👨🏽‍🔬", - "👨🏽‍🚀", - "👨🏽‍🚒", - "👨🏽‍🤝‍👨🏻", - "👨🏽‍🤝‍👨🏼", - "👨🏽‍🦯", - "👨🏽‍🦰", - "👨🏽‍🦱", - "👨🏽‍🦲", - "👨🏽‍🦳", - "👨🏽‍🦼", - "👨🏽‍🦽", - "👨🏽‍⚕️", - "👨🏽‍⚖️", - "👨🏽‍✈️", - "👨🏽", - "👨🏾‍🌾", - "👨🏾‍🍳", - "👨🏾‍🎓", - "👨🏾‍🎤", - "👨🏾‍🎨", - "👨🏾‍🏫", - "👨🏾‍🏭", - "👨🏾‍💻", - "👨🏾‍💼", - "👨🏾‍🔧", - "👨🏾‍🔬", - "👨🏾‍🚀", - "👨🏾‍🚒", - "👨🏾‍🤝‍👨🏻", - "👨🏾‍🤝‍👨🏼", - "👨🏾‍🤝‍👨🏽", - "👨🏾‍🦯", - "👨🏾‍🦰", - "👨🏾‍🦱", - "👨🏾‍🦲", - "👨🏾‍🦳", - "👨🏾‍🦼", - "👨🏾‍🦽", - "👨🏾‍⚕️", - "👨🏾‍⚖️", - "👨🏾‍✈️", - "👨🏾", - "👨🏿‍🌾", - "👨🏿‍🍳", - "👨🏿‍🎓", - "👨🏿‍🎤", - "👨🏿‍🎨", - "👨🏿‍🏫", - "👨🏿‍🏭", - "👨🏿‍💻", - "👨🏿‍💼", - "👨🏿‍🔧", - "👨🏿‍🔬", - "👨🏿‍🚀", - "👨🏿‍🚒", - "👨🏿‍🤝‍👨🏻", - "👨🏿‍🤝‍👨🏼", - "👨🏿‍🤝‍👨🏽", - "👨🏿‍🤝‍👨🏾", - "👨🏿‍🦯", - "👨🏿‍🦰", - "👨🏿‍🦱", - "👨🏿‍🦲", - "👨🏿‍🦳", - "👨🏿‍🦼", - "👨🏿‍🦽", - "👨🏿‍⚕️", - "👨🏿‍⚖️", - "👨🏿‍✈️", - "👨🏿", - "👨‍🌾", - "👨‍🍳", - "👨‍🎓", - "👨‍🎤", - "👨‍🎨", - "👨‍🏫", - "👨‍🏭", - "👨‍👦‍👦", - "👨‍👦", - "👨‍👧‍👦", - "👨‍👧‍👧", - "👨‍👧", - "👨‍👨‍👦‍👦", - "👨‍👨‍👦", - "👨‍👨‍👧‍👦", - "👨‍👨‍👧‍👧", - "👨‍👨‍👧", - "👨‍👩‍👦‍👦", - "👨‍👩‍👦", - "👨‍👩‍👧‍👦", - "👨‍👩‍👧‍👧", - "👨‍👩‍👧", - "👨‍💻", - "👨‍💼", - "👨‍🔧", - "👨‍🔬", - "👨‍🚀", - "👨‍🚒", - "👨‍🦯", - "👨‍🦰", - "👨‍🦱", - "👨‍🦲", - "👨‍🦳", - "👨‍🦼", - "👨‍🦽", - "👨‍⚕️", - "👨‍⚖️", - "👨‍✈️", - "👨‍❤️‍👨", - "👨‍❤️‍💋‍👨", - "👨", - "👩🏻‍🌾", - "👩🏻‍🍳", - "👩🏻‍🎓", - "👩🏻‍🎤", - "👩🏻‍🎨", - "👩🏻‍🏫", - "👩🏻‍🏭", - "👩🏻‍💻", - "👩🏻‍💼", - "👩🏻‍🔧", - "👩🏻‍🔬", - "👩🏻‍🚀", - "👩🏻‍🚒", - "👩🏻‍🤝‍👨🏼", - "👩🏻‍🤝‍👨🏽", - "👩🏻‍🤝‍👨🏾", - "👩🏻‍🤝‍👨🏿", - "👩🏻‍🦯", - "👩🏻‍🦰", - "👩🏻‍🦱", - "👩🏻‍🦲", - "👩🏻‍🦳", - "👩🏻‍🦼", - "👩🏻‍🦽", - "👩🏻‍⚕️", - "👩🏻‍⚖️", - "👩🏻‍✈️", - "👩🏻", - "👩🏼‍🌾", - "👩🏼‍🍳", - "👩🏼‍🎓", - "👩🏼‍🎤", - "👩🏼‍🎨", - "👩🏼‍🏫", - "👩🏼‍🏭", - "👩🏼‍💻", - "👩🏼‍💼", - "👩🏼‍🔧", - "👩🏼‍🔬", - "👩🏼‍🚀", - "👩🏼‍🚒", - "👩🏼‍🤝‍👨🏻", - "👩🏼‍🤝‍👨🏽", - "👩🏼‍🤝‍👨🏾", - "👩🏼‍🤝‍👨🏿", - "👩🏼‍🤝‍👩🏻", - "👩🏼‍🦯", - "👩🏼‍🦰", - "👩🏼‍🦱", - "👩🏼‍🦲", - "👩🏼‍🦳", - "👩🏼‍🦼", - "👩🏼‍🦽", - "👩🏼‍⚕️", - "👩🏼‍⚖️", - "👩🏼‍✈️", - "👩🏼", - "👩🏽‍🌾", - "👩🏽‍🍳", - "👩🏽‍🎓", - "👩🏽‍🎤", - "👩🏽‍🎨", - "👩🏽‍🏫", - "👩🏽‍🏭", - "👩🏽‍💻", - "👩🏽‍💼", - "👩🏽‍🔧", - "👩🏽‍🔬", - "👩🏽‍🚀", - "👩🏽‍🚒", - "👩🏽‍🤝‍👨🏻", - "👩🏽‍🤝‍👨🏼", - "👩🏽‍🤝‍👨🏾", - "👩🏽‍🤝‍👨🏿", - "👩🏽‍🤝‍👩🏻", - "👩🏽‍🤝‍👩🏼", - "👩🏽‍🦯", - "👩🏽‍🦰", - "👩🏽‍🦱", - "👩🏽‍🦲", - "👩🏽‍🦳", - "👩🏽‍🦼", - "👩🏽‍🦽", - "👩🏽‍⚕️", - "👩🏽‍⚖️", - "👩🏽‍✈️", - "👩🏽", - "👩🏾‍🌾", - "👩🏾‍🍳", - "👩🏾‍🎓", - "👩🏾‍🎤", - "👩🏾‍🎨", - "👩🏾‍🏫", - "👩🏾‍🏭", - "👩🏾‍💻", - "👩🏾‍💼", - "👩🏾‍🔧", - "👩🏾‍🔬", - "👩🏾‍🚀", - "👩🏾‍🚒", - "👩🏾‍🤝‍👨🏻", - "👩🏾‍🤝‍👨🏼", - "👩🏾‍🤝‍👨🏽", - "👩🏾‍🤝‍👨🏿", - "👩🏾‍🤝‍👩🏻", - "👩🏾‍🤝‍👩🏼", - "👩🏾‍🤝‍👩🏽", - "👩🏾‍🦯", - "👩🏾‍🦰", - "👩🏾‍🦱", - "👩🏾‍🦲", - "👩🏾‍🦳", - "👩🏾‍🦼", - "👩🏾‍🦽", - "👩🏾‍⚕️", - "👩🏾‍⚖️", - "👩🏾‍✈️", - "👩🏾", - "👩🏿‍🌾", - "👩🏿‍🍳", - "👩🏿‍🎓", - "👩🏿‍🎤", - "👩🏿‍🎨", - "👩🏿‍🏫", - "👩🏿‍🏭", - "👩🏿‍💻", - "👩🏿‍💼", - "👩🏿‍🔧", - "👩🏿‍🔬", - "👩🏿‍🚀", - "👩🏿‍🚒", - "👩🏿‍🤝‍👨🏻", - "👩🏿‍🤝‍👨🏼", - "👩🏿‍🤝‍👨🏽", - "👩🏿‍🤝‍👨🏾", - "👩🏿‍🤝‍👩🏻", - "👩🏿‍🤝‍👩🏼", - "👩🏿‍🤝‍👩🏽", - "👩🏿‍🤝‍👩🏾", - "👩🏿‍🦯", - "👩🏿‍🦰", - "👩🏿‍🦱", - "👩🏿‍🦲", - "👩🏿‍🦳", - "👩🏿‍🦼", - "👩🏿‍🦽", - "👩🏿‍⚕️", - "👩🏿‍⚖️", - "👩🏿‍✈️", - "👩🏿", - "👩‍🌾", - "👩‍🍳", - "👩‍🎓", - "👩‍🎤", - "👩‍🎨", - "👩‍🏫", - "👩‍🏭", - "👩‍👦‍👦", - "👩‍👦", - "👩‍👧‍👦", - "👩‍👧‍👧", - "👩‍👧", - "👩‍👩‍👦‍👦", - "👩‍👩‍👦", - "👩‍👩‍👧‍👦", - "👩‍👩‍👧‍👧", - "👩‍👩‍👧", - "👩‍💻", - "👩‍💼", - "👩‍🔧", - "👩‍🔬", - "👩‍🚀", - "👩‍🚒", - "👩‍🦯", - "👩‍🦰", - "👩‍🦱", - "👩‍🦲", - "👩‍🦳", - "👩‍🦼", - "👩‍🦽", - "👩‍⚕️", - "👩‍⚖️", - "👩‍✈️", - "👩‍❤️‍👨", - "👩‍❤️‍👩", - "👩‍❤️‍💋‍👨", - "👩‍❤️‍💋‍👩", - "👩", - "👪", - "👫🏻", - "👫🏼", - "👫🏽", - "👫🏾", - "👫🏿", - "👫", - "👬🏻", - "👬🏼", - "👬🏽", - "👬🏾", - "👬🏿", - "👬", - "👭🏻", - "👭🏼", - "👭🏽", - "👭🏾", - "👭🏿", - "👭", - "👮🏻‍♀️", - "👮🏻‍♂️", - "👮🏻", - "👮🏼‍♀️", - "👮🏼‍♂️", - "👮🏼", - "👮🏽‍♀️", - "👮🏽‍♂️", - "👮🏽", - "👮🏾‍♀️", - "👮🏾‍♂️", - "👮🏾", - "👮🏿‍♀️", - "👮🏿‍♂️", - "👮🏿", - "👮‍♀️", - "👮‍♂️", - "👮", - "👯‍♀️", - "👯‍♂️", - "👯", - "👰🏻", - "👰🏼", - "👰🏽", - "👰🏾", - "👰🏿", - "👰", - "👱🏻‍♀️", - "👱🏻‍♂️", - "👱🏻", - "👱🏼‍♀️", - "👱🏼‍♂️", - "👱🏼", - "👱🏽‍♀️", - "👱🏽‍♂️", - "👱🏽", - "👱🏾‍♀️", - "👱🏾‍♂️", - "👱🏾", - "👱🏿‍♀️", - "👱🏿‍♂️", - "👱🏿", - "👱‍♀️", - "👱‍♂️", - "👱", - "👲🏻", - "👲🏼", - "👲🏽", - "👲🏾", - "👲🏿", - "👲", - "👳🏻‍♀️", - "👳🏻‍♂️", - "👳🏻", - "👳🏼‍♀️", - "👳🏼‍♂️", - "👳🏼", - "👳🏽‍♀️", - "👳🏽‍♂️", - "👳🏽", - "👳🏾‍♀️", - "👳🏾‍♂️", - "👳🏾", - "👳🏿‍♀️", - "👳🏿‍♂️", - "👳🏿", - "👳‍♀️", - "👳‍♂️", - "👳", - "👴🏻", - "👴🏼", - "👴🏽", - "👴🏾", - "👴🏿", - "👴", - "👵🏻", - "👵🏼", - "👵🏽", - "👵🏾", - "👵🏿", - "👵", - "👶🏻", - "👶🏼", - "👶🏽", - "👶🏾", - "👶🏿", - "👶", - "👷🏻‍♀️", - "👷🏻‍♂️", - "👷🏻", - "👷🏼‍♀️", - "👷🏼‍♂️", - "👷🏼", - "👷🏽‍♀️", - "👷🏽‍♂️", - "👷🏽", - "👷🏾‍♀️", - "👷🏾‍♂️", - "👷🏾", - "👷🏿‍♀️", - "👷🏿‍♂️", - "👷🏿", - "👷‍♀️", - "👷‍♂️", - "👷", - "👸🏻", - "👸🏼", - "👸🏽", - "👸🏾", - "👸🏿", - "👸", - "👹", - "👺", - "👻", - "👼🏻", - "👼🏼", - "👼🏽", - "👼🏾", - "👼🏿", - "👼", - "👽", - "👾", - "👿", - "💀", - "💁🏻‍♀️", - "💁🏻‍♂️", - "💁🏻", - "💁🏼‍♀️", - "💁🏼‍♂️", - "💁🏼", - "💁🏽‍♀️", - "💁🏽‍♂️", - "💁🏽", - "💁🏾‍♀️", - "💁🏾‍♂️", - "💁🏾", - "💁🏿‍♀️", - "💁🏿‍♂️", - "💁🏿", - "💁‍♀️", - "💁‍♂️", - "💁", - "💂🏻‍♀️", - "💂🏻‍♂️", - "💂🏻", - "💂🏼‍♀️", - "💂🏼‍♂️", - "💂🏼", - "💂🏽‍♀️", - "💂🏽‍♂️", - "💂🏽", - "💂🏾‍♀️", - "💂🏾‍♂️", - "💂🏾", - "💂🏿‍♀️", - "💂🏿‍♂️", - "💂🏿", - "💂‍♀️", - "💂‍♂️", - "💂", - "💃🏻", - "💃🏼", - "💃🏽", - "💃🏾", - "💃🏿", - "💃", - "💄", - "💅🏻", - "💅🏼", - "💅🏽", - "💅🏾", - "💅🏿", - "💅", - "💆🏻‍♀️", - "💆🏻‍♂️", - "💆🏻", - "💆🏼‍♀️", - "💆🏼‍♂️", - "💆🏼", - "💆🏽‍♀️", - "💆🏽‍♂️", - "💆🏽", - "💆🏾‍♀️", - "💆🏾‍♂️", - "💆🏾", - "💆🏿‍♀️", - "💆🏿‍♂️", - "💆🏿", - "💆‍♀️", - "💆‍♂️", - "💆", - "💇🏻‍♀️", - "💇🏻‍♂️", - "💇🏻", - "💇🏼‍♀️", - "💇🏼‍♂️", - "💇🏼", - "💇🏽‍♀️", - "💇🏽‍♂️", - "💇🏽", - "💇🏾‍♀️", - "💇🏾‍♂️", - "💇🏾", - "💇🏿‍♀️", - "💇🏿‍♂️", - "💇🏿", - "💇‍♀️", - "💇‍♂️", - "💇", - "💈", - "💉", - "💊", - "💋", - "💌", - "💍", - "💎", - "💏", - "💐", - "💑", - "💒", - "💓", - "💔", - "💕", - "💖", - "💗", - "💘", - "💙", - "💚", - "💛", - "💜", - "💝", - "💞", - "💟", - "💠", - "💡", - "💢", - "💣", - "💤", - "💥", - "💦", - "💧", - "💨", - "💩", - "💪🏻", - "💪🏼", - "💪🏽", - "💪🏾", - "💪🏿", - "💪", - "💫", - "💬", - "💭", - "💮", - "💯", - "💰", - "💱", - "💲", - "💳", - "💴", - "💵", - "💶", - "💷", - "💸", - "💹", - "💺", - "💻", - "💼", - "💽", - "💾", - "💿", - "📀", - "📁", - "📂", - "📃", - "📄", - "📅", - "📆", - "📇", - "📈", - "📉", - "📊", - "📋", - "📌", - "📍", - "📎", - "📏", - "📐", - "📑", - "📒", - "📓", - "📔", - "📕", - "📖", - "📗", - "📘", - "📙", - "📚", - "📛", - "📜", - "📝", - "📞", - "📟", - "📠", - "📡", - "📢", - "📣", - "📤", - "📥", - "📦", - "📧", - "📨", - "📩", - "📪", - "📫", - "📬", - "📭", - "📮", - "📯", - "📰", - "📱", - "📲", - "📳", - "📴", - "📵", - "📶", - "📷", - "📸", - "📹", - "📺", - "📻", - "📼", - "📽️", - "📿", - "🔀", - "🔁", - "🔂", - "🔃", - "🔄", - "🔅", - "🔆", - "🔇", - "🔈", - "🔉", - "🔊", - "🔋", - "🔌", - "🔍", - "🔎", - "🔏", - "🔐", - "🔑", - "🔒", - "🔓", - "🔔", - "🔕", - "🔖", - "🔗", - "🔘", - "🔙", - "🔚", - "🔛", - "🔜", - "🔝", - "🔞", - "🔟", - "🔠", - "🔡", - "🔢", - "🔣", - "🔤", - "🔥", - "🔦", - "🔧", - "🔨", - "🔩", - "🔪", - "🔫", - "🔬", - "🔭", - "🔮", - "🔯", - "🔰", - "🔱", - "🔲", - "🔳", - "🔴", - "🔵", - "🔶", - "🔷", - "🔸", - "🔹", - "🔺", - "🔻", - "🔼", - "🔽", - "🕉️", - "🕊️", - "🕋", - "🕌", - "🕍", - "🕎", - "🕐", - "🕑", - "🕒", - "🕓", - "🕔", - "🕕", - "🕖", - "🕗", - "🕘", - "🕙", - "🕚", - "🕛", - "🕜", - "🕝", - "🕞", - "🕟", - "🕠", - "🕡", - "🕢", - "🕣", - "🕤", - "🕥", - "🕦", - "🕧", - "🕯️", - "🕰️", - "🕳️", - "🕴🏻‍♀️", - "🕴🏻‍♂️", - "🕴🏻", - "🕴🏼‍♀️", - "🕴🏼‍♂️", - "🕴🏼", - "🕴🏽‍♀️", - "🕴🏽‍♂️", - "🕴🏽", - "🕴🏾‍♀️", - "🕴🏾‍♂️", - "🕴🏾", - "🕴🏿‍♀️", - "🕴🏿‍♂️", - "🕴🏿", - "🕴️‍♀️", - "🕴️‍♂️", - "🕴️", - "🕵🏻‍♀️", - "🕵🏻‍♂️", - "🕵🏻", - "🕵🏼‍♀️", - "🕵🏼‍♂️", - "🕵🏼", - "🕵🏽‍♀️", - "🕵🏽‍♂️", - "🕵🏽", - "🕵🏾‍♀️", - "🕵🏾‍♂️", - "🕵🏾", - "🕵🏿‍♀️", - "🕵🏿‍♂️", - "🕵🏿", - "🕵️‍♀️", - "🕵️‍♂️", - "🕵️", - "🕶️", - "🕷️", - "🕸️", - "🕹️", - "🕺🏻", - "🕺🏼", - "🕺🏽", - "🕺🏾", - "🕺🏿", - "🕺", - "🖇️", - "🖊️", - "🖋️", - "🖌️", - "🖍️", - "🖐🏻", - "🖐🏼", - "🖐🏽", - "🖐🏾", - "🖐🏿", - "🖐️", - "🖕🏻", - "🖕🏼", - "🖕🏽", - "🖕🏾", - "🖕🏿", - "🖕", - "🖖🏻", - "🖖🏼", - "🖖🏽", - "🖖🏾", - "🖖🏿", - "🖖", - "🖤", - "🖥️", - "🖨️", - "🖱️", - "🖲️", - "🖼️", - "🗂️", - "🗃️", - "🗄️", - "🗑️", - "🗒️", - "🗓️", - "🗜️", - "🗝️", - "🗞️", - "🗡️", - "🗣️", - "🗨️", - "🗯️", - "🗳️", - "🗺️", - "🗻", - "🗼", - "🗽", - "🗾", - "🗿", - "😀", - "😁", - "😂", - "😃", - "😄", - "😅", - "😆", - "😇", - "😈", - "😉", - "😊", - "😋", - "😌", - "😍", - "😎", - "😏", - "😐", - "😑", - "😒", - "😓", - "😔", - "😕", - "😖", - "😗", - "😘", - "😙", - "😚", - "😛", - "😜", - "😝", - "😞", - "😟", - "😠", - "😡", - "😢", - "😣", - "😤", - "😥", - "😦", - "😧", - "😨", - "😩", - "😪", - "😫", - "😬", - "😭", - "😮", - "😯", - "😰", - "😱", - "😲", - "😳", - "😴", - "😵", - "😶", - "😷", - "😸", - "😹", - "😺", - "😻", - "😼", - "😽", - "😾", - "😿", - "🙀", - "🙁", - "🙂", - "🙃", - "🙄", - "🙅🏻‍♀️", - "🙅🏻‍♂️", - "🙅🏻", - "🙅🏼‍♀️", - "🙅🏼‍♂️", - "🙅🏼", - "🙅🏽‍♀️", - "🙅🏽‍♂️", - "🙅🏽", - "🙅🏾‍♀️", - "🙅🏾‍♂️", - "🙅🏾", - "🙅🏿‍♀️", - "🙅🏿‍♂️", - "🙅🏿", - "🙅‍♀️", - "🙅‍♂️", - "🙅", - "🙆🏻‍♀️", - "🙆🏻‍♂️", - "🙆🏻", - "🙆🏼‍♀️", - "🙆🏼‍♂️", - "🙆🏼", - "🙆🏽‍♀️", - "🙆🏽‍♂️", - "🙆🏽", - "🙆🏾‍♀️", - "🙆🏾‍♂️", - "🙆🏾", - "🙆🏿‍♀️", - "🙆🏿‍♂️", - "🙆🏿", - "🙆‍♀️", - "🙆‍♂️", - "🙆", - "🙇🏻‍♀️", - "🙇🏻‍♂️", - "🙇🏻", - "🙇🏼‍♀️", - "🙇🏼‍♂️", - "🙇🏼", - "🙇🏽‍♀️", - "🙇🏽‍♂️", - "🙇🏽", - "🙇🏾‍♀️", - "🙇🏾‍♂️", - "🙇🏾", - "🙇🏿‍♀️", - "🙇🏿‍♂️", - "🙇🏿", - "🙇‍♀️", - "🙇‍♂️", - "🙇", - "🙈", - "🙉", - "🙊", - "🙋🏻‍♀️", - "🙋🏻‍♂️", - "🙋🏻", - "🙋🏼‍♀️", - "🙋🏼‍♂️", - "🙋🏼", - "🙋🏽‍♀️", - "🙋🏽‍♂️", - "🙋🏽", - "🙋🏾‍♀️", - "🙋🏾‍♂️", - "🙋🏾", - "🙋🏿‍♀️", - "🙋🏿‍♂️", - "🙋🏿", - "🙋‍♀️", - "🙋‍♂️", - "🙋", - "🙌🏻", - "🙌🏼", - "🙌🏽", - "🙌🏾", - "🙌🏿", - "🙌", - "🙍🏻‍♀️", - "🙍🏻‍♂️", - "🙍🏻", - "🙍🏼‍♀️", - "🙍🏼‍♂️", - "🙍🏼", - "🙍🏽‍♀️", - "🙍🏽‍♂️", - "🙍🏽", - "🙍🏾‍♀️", - "🙍🏾‍♂️", - "🙍🏾", - "🙍🏿‍♀️", - "🙍🏿‍♂️", - "🙍🏿", - "🙍‍♀️", - "🙍‍♂️", - "🙍", - "🙎🏻‍♀️", - "🙎🏻‍♂️", - "🙎🏻", - "🙎🏼‍♀️", - "🙎🏼‍♂️", - "🙎🏼", - "🙎🏽‍♀️", - "🙎🏽‍♂️", - "🙎🏽", - "🙎🏾‍♀️", - "🙎🏾‍♂️", - "🙎🏾", - "🙎🏿‍♀️", - "🙎🏿‍♂️", - "🙎🏿", - "🙎‍♀️", - "🙎‍♂️", - "🙎", - "🙏🏻", - "🙏🏼", - "🙏🏽", - "🙏🏾", - "🙏🏿", - "🙏", - "🚀", - "🚁", - "🚂", - "🚃", - "🚄", - "🚅", - "🚆", - "🚇", - "🚈", - "🚉", - "🚊", - "🚋", - "🚌", - "🚍", - "🚎", - "🚏", - "🚐", - "🚑", - "🚒", - "🚓", - "🚔", - "🚕", - "🚖", - "🚗", - "🚘", - "🚙", - "🚚", - "🚛", - "🚜", - "🚝", - "🚞", - "🚟", - "🚠", - "🚡", - "🚢", - "🚣🏻‍♀️", - "🚣🏻‍♂️", - "🚣🏻", - "🚣🏼‍♀️", - "🚣🏼‍♂️", - "🚣🏼", - "🚣🏽‍♀️", - "🚣🏽‍♂️", - "🚣🏽", - "🚣🏾‍♀️", - "🚣🏾‍♂️", - "🚣🏾", - "🚣🏿‍♀️", - "🚣🏿‍♂️", - "🚣🏿", - "🚣‍♀️", - "🚣‍♂️", - "🚣", - "🚤", - "🚥", - "🚦", - "🚧", - "🚨", - "🚩", - "🚪", - "🚫", - "🚬", - "🚭", - "🚮", - "🚯", - "🚰", - "🚱", - "🚲", - "🚳", - "🚴🏻‍♀️", - "🚴🏻‍♂️", - "🚴🏻", - "🚴🏼‍♀️", - "🚴🏼‍♂️", - "🚴🏼", - "🚴🏽‍♀️", - "🚴🏽‍♂️", - "🚴🏽", - "🚴🏾‍♀️", - "🚴🏾‍♂️", - "🚴🏾", - "🚴🏿‍♀️", - "🚴🏿‍♂️", - "🚴🏿", - "🚴‍♀️", - "🚴‍♂️", - "🚴", - "🚵🏻‍♀️", - "🚵🏻‍♂️", - "🚵🏻", - "🚵🏼‍♀️", - "🚵🏼‍♂️", - "🚵🏼", - "🚵🏽‍♀️", - "🚵🏽‍♂️", - "🚵🏽", - "🚵🏾‍♀️", - "🚵🏾‍♂️", - "🚵🏾", - "🚵🏿‍♀️", - "🚵🏿‍♂️", - "🚵🏿", - "🚵‍♀️", - "🚵‍♂️", - "🚵", - "🚶🏻‍♀️", - "🚶🏻‍♂️", - "🚶🏻", - "🚶🏼‍♀️", - "🚶🏼‍♂️", - "🚶🏼", - "🚶🏽‍♀️", - "🚶🏽‍♂️", - "🚶🏽", - "🚶🏾‍♀️", - "🚶🏾‍♂️", - "🚶🏾", - "🚶🏿‍♀️", - "🚶🏿‍♂️", - "🚶🏿", - "🚶‍♀️", - "🚶‍♂️", - "🚶", - "🚷", - "🚸", - "🚹", - "🚺", - "🚻", - "🚼", - "🚽", - "🚾", - "🚿", - "🛀🏻", - "🛀🏼", - "🛀🏽", - "🛀🏾", - "🛀🏿", - "🛀", - "🛁", - "🛂", - "🛃", - "🛄", - "🛅", - "🛋️", - "🛌🏻", - "🛌🏼", - "🛌🏽", - "🛌🏾", - "🛌🏿", - "🛌", - "🛍️", - "🛎️", - "🛏️", - "🛐", - "🛑", - "🛒", - "🛕", - "🛠️", - "🛡️", - "🛢️", - "🛣️", - "🛤️", - "🛥️", - "🛩️", - "🛫", - "🛬", - "🛰️", - "🛳️", - "🛴", - "🛵", - "🛶", - "🛷", - "🛸", - "🛹", - "🛺", - "🟠", - "🟡", - "🟢", - "🟣", - "🟤", - "🟥", - "🟦", - "🟧", - "🟨", - "🟩", - "🟪", - "🟫", - "🤍", - "🤎", - "🤏🏻", - "🤏🏼", - "🤏🏽", - "🤏🏾", - "🤏🏿", - "🤏", - "🤐", - "🤑", - "🤒", - "🤓", - "🤔", - "🤕", - "🤖", - "🤗", - "🤘🏻", - "🤘🏼", - "🤘🏽", - "🤘🏾", - "🤘🏿", - "🤘", - "🤙🏻", - "🤙🏼", - "🤙🏽", - "🤙🏾", - "🤙🏿", - "🤙", - "🤚🏻", - "🤚🏼", - "🤚🏽", - "🤚🏾", - "🤚🏿", - "🤚", - "🤛🏻", - "🤛🏼", - "🤛🏽", - "🤛🏾", - "🤛🏿", - "🤛", - "🤜🏻", - "🤜🏼", - "🤜🏽", - "🤜🏾", - "🤜🏿", - "🤜", - "🤝", - "🤞🏻", - "🤞🏼", - "🤞🏽", - "🤞🏾", - "🤞🏿", - "🤞", - "🤟🏻", - "🤟🏼", - "🤟🏽", - "🤟🏾", - "🤟🏿", - "🤟", - "🤠", - "🤡", - "🤢", - "🤣", - "🤤", - "🤥", - "🤦🏻‍♀️", - "🤦🏻‍♂️", - "🤦🏻", - "🤦🏼‍♀️", - "🤦🏼‍♂️", - "🤦🏼", - "🤦🏽‍♀️", - "🤦🏽‍♂️", - "🤦🏽", - "🤦🏾‍♀️", - "🤦🏾‍♂️", - "🤦🏾", - "🤦🏿‍♀️", - "🤦🏿‍♂️", - "🤦🏿", - "🤦‍♀️", - "🤦‍♂️", - "🤦", - "🤧", - "🤨", - "🤩", - "🤪", - "🤫", - "🤬", - "🤭", - "🤮", - "🤯", - "🤰🏻", - "🤰🏼", - "🤰🏽", - "🤰🏾", - "🤰🏿", - "🤰", - "🤱🏻", - "🤱🏼", - "🤱🏽", - "🤱🏾", - "🤱🏿", - "🤱", - "🤲🏻", - "🤲🏼", - "🤲🏽", - "🤲🏾", - "🤲🏿", - "🤲", - "🤳🏻", - "🤳🏼", - "🤳🏽", - "🤳🏾", - "🤳🏿", - "🤳", - "🤴🏻", - "🤴🏼", - "🤴🏽", - "🤴🏾", - "🤴🏿", - "🤴", - "🤵🏻‍♀️", - "🤵🏻‍♂️", - "🤵🏻", - "🤵🏼‍♀️", - "🤵🏼‍♂️", - "🤵🏼", - "🤵🏽‍♀️", - "🤵🏽‍♂️", - "🤵🏽", - "🤵🏾‍♀️", - "🤵🏾‍♂️", - "🤵🏾", - "🤵🏿‍♀️", - "🤵🏿‍♂️", - "🤵🏿", - "🤵‍♀️", - "🤵‍♂️", - "🤵", - "🤶🏻", - "🤶🏼", - "🤶🏽", - "🤶🏾", - "🤶🏿", - "🤶", - "🤷🏻‍♀️", - "🤷🏻‍♂️", - "🤷🏻", - "🤷🏼‍♀️", - "🤷🏼‍♂️", - "🤷🏼", - "🤷🏽‍♀️", - "🤷🏽‍♂️", - "🤷🏽", - "🤷🏾‍♀️", - "🤷🏾‍♂️", - "🤷🏾", - "🤷🏿‍♀️", - "🤷🏿‍♂️", - "🤷🏿", - "🤷‍♀️", - "🤷‍♂️", - "🤷", - "🤸🏻‍♀️", - "🤸🏻‍♂️", - "🤸🏻", - "🤸🏼‍♀️", - "🤸🏼‍♂️", - "🤸🏼", - "🤸🏽‍♀️", - "🤸🏽‍♂️", - "🤸🏽", - "🤸🏾‍♀️", - "🤸🏾‍♂️", - "🤸🏾", - "🤸🏿‍♀️", - "🤸🏿‍♂️", - "🤸🏿", - "🤸‍♀️", - "🤸‍♂️", - "🤸", - "🤹🏻‍♀️", - "🤹🏻‍♂️", - "🤹🏻", - "🤹🏼‍♀️", - "🤹🏼‍♂️", - "🤹🏼", - "🤹🏽‍♀️", - "🤹🏽‍♂️", - "🤹🏽", - "🤹🏾‍♀️", - "🤹🏾‍♂️", - "🤹🏾", - "🤹🏿‍♀️", - "🤹🏿‍♂️", - "🤹🏿", - "🤹‍♀️", - "🤹‍♂️", - "🤹", - "🤺", - "🤼‍♀️", - "🤼‍♂️", - "🤼", - "🤽🏻‍♀️", - "🤽🏻‍♂️", - "🤽🏻", - "🤽🏼‍♀️", - "🤽🏼‍♂️", - "🤽🏼", - "🤽🏽‍♀️", - "🤽🏽‍♂️", - "🤽🏽", - "🤽🏾‍♀️", - "🤽🏾‍♂️", - "🤽🏾", - "🤽🏿‍♀️", - "🤽🏿‍♂️", - "🤽🏿", - "🤽‍♀️", - "🤽‍♂️", - "🤽", - "🤾🏻‍♀️", - "🤾🏻‍♂️", - "🤾🏻", - "🤾🏼‍♀️", - "🤾🏼‍♂️", - "🤾🏼", - "🤾🏽‍♀️", - "🤾🏽‍♂️", - "🤾🏽", - "🤾🏾‍♀️", - "🤾🏾‍♂️", - "🤾🏾", - "🤾🏿‍♀️", - "🤾🏿‍♂️", - "🤾🏿", - "🤾‍♀️", - "🤾‍♂️", - "🤾", - "🤿", - "🥀", - "🥁", - "🥂", - "🥃", - "🥄", - "🥅", - "🥇", - "🥈", - "🥉", - "🥊", - "🥋", - "🥌", - "🥍", - "🥎", - "🥏", - "🥐", - "🥑", - "🥒", - "🥓", - "🥔", - "🥕", - "🥖", - "🥗", - "🥘", - "🥙", - "🥚", - "🥛", - "🥜", - "🥝", - "🥞", - "🥟", - "🥠", - "🥡", - "🥢", - "🥣", - "🥤", - "🥥", - "🥦", - "🥧", - "🥨", - "🥩", - "🥪", - "🥫", - "🥬", - "🥭", - "🥮", - "🥯", - "🥰", - "🥱", - "🥳", - "🥴", - "🥵", - "🥶", - "🥺", - "🥻", - "🥼", - "🥽", - "🥾", - "🥿", - "🦀", - "🦁", - "🦂", - "🦃", - "🦄", - "🦅", - "🦆", - "🦇", - "🦈", - "🦉", - "🦊", - "🦋", - "🦌", - "🦍", - "🦎", - "🦏", - "🦐", - "🦑", - "🦒", - "🦓", - "🦔", - "🦕", - "🦖", - "🦗", - "🦘", - "🦙", - "🦚", - "🦛", - "🦜", - "🦝", - "🦞", - "🦟", - "🦠", - "🦡", - "🦢", - "🦥", - "🦦", - "🦧", - "🦨", - "🦩", - "🦪", - "🦮", - "🦯", - "🦰", - "🦱", - "🦲", - "🦳", - "🦴", - "🦵🏻", - "🦵🏼", - "🦵🏽", - "🦵🏾", - "🦵🏿", - "🦵", - "🦶🏻", - "🦶🏼", - "🦶🏽", - "🦶🏾", - "🦶🏿", - "🦶", - "🦷", - "🦸🏻‍♀️", - "🦸🏻‍♂️", - "🦸🏻", - "🦸🏼‍♀️", - "🦸🏼‍♂️", - "🦸🏼", - "🦸🏽‍♀️", - "🦸🏽‍♂️", - "🦸🏽", - "🦸🏾‍♀️", - "🦸🏾‍♂️", - "🦸🏾", - "🦸🏿‍♀️", - "🦸🏿‍♂️", - "🦸🏿", - "🦸‍♀️", - "🦸‍♂️", - "🦸", - "🦹🏻‍♀️", - "🦹🏻‍♂️", - "🦹🏻", - "🦹🏼‍♀️", - "🦹🏼‍♂️", - "🦹🏼", - "🦹🏽‍♀️", - "🦹🏽‍♂️", - "🦹🏽", - "🦹🏾‍♀️", - "🦹🏾‍♂️", - "🦹🏾", - "🦹🏿‍♀️", - "🦹🏿‍♂️", - "🦹🏿", - "🦹‍♀️", - "🦹‍♂️", - "🦹", - "🦺", - "🦻🏻", - "🦻🏼", - "🦻🏽", - "🦻🏾", - "🦻🏿", - "🦻", - "🦼", - "🦽", - "🦾", - "🦿", - "🧀", - "🧁", - "🧂", - "🧃", - "🧄", - "🧅", - "🧆", - "🧇", - "🧈", - "🧉", - "🧊", - "🧍🏻‍♀️", - "🧍🏻‍♂️", - "🧍🏻", - "🧍🏼‍♀️", - "🧍🏼‍♂️", - "🧍🏼", - "🧍🏽‍♀️", - "🧍🏽‍♂️", - "🧍🏽", - "🧍🏾‍♀️", - "🧍🏾‍♂️", - "🧍🏾", - "🧍🏿‍♀️", - "🧍🏿‍♂️", - "🧍🏿", - "🧍‍♀️", - "🧍‍♂️", - "🧍", - "🧎🏻‍♀️", - "🧎🏻‍♂️", - "🧎🏻", - "🧎🏼‍♀️", - "🧎🏼‍♂️", - "🧎🏼", - "🧎🏽‍♀️", - "🧎🏽‍♂️", - "🧎🏽", - "🧎🏾‍♀️", - "🧎🏾‍♂️", - "🧎🏾", - "🧎🏿‍♀️", - "🧎🏿‍♂️", - "🧎🏿", - "🧎‍♀️", - "🧎‍♂️", - "🧎", - "🧏🏻‍♀️", - "🧏🏻‍♂️", - "🧏🏻", - "🧏🏼‍♀️", - "🧏🏼‍♂️", - "🧏🏼", - "🧏🏽‍♀️", - "🧏🏽‍♂️", - "🧏🏽", - "🧏🏾‍♀️", - "🧏🏾‍♂️", - "🧏🏾", - "🧏🏿‍♀️", - "🧏🏿‍♂️", - "🧏🏿", - "🧏‍♀️", - "🧏‍♂️", - "🧏", - "🧐", - "🧑🏻‍🤝‍🧑🏻", - "🧑🏻", - "🧑🏼‍🤝‍🧑🏻", - "🧑🏼‍🤝‍🧑🏼", - "🧑🏼", - "🧑🏽‍🤝‍🧑🏻", - "🧑🏽‍🤝‍🧑🏼", - "🧑🏽‍🤝‍🧑🏽", - "🧑🏽", - "🧑🏾‍🤝‍🧑🏻", - "🧑🏾‍🤝‍🧑🏼", - "🧑🏾‍🤝‍🧑🏽", - "🧑🏾‍🤝‍🧑🏾", - "🧑🏾", - "🧑🏿‍🤝‍🧑🏻", - "🧑🏿‍🤝‍🧑🏼", - "🧑🏿‍🤝‍🧑🏽", - "🧑🏿‍🤝‍🧑🏾", - "🧑🏿‍🤝‍🧑🏿", - "🧑🏿", - "🧑‍🤝‍🧑", - "🧑", - "🧒🏻", - "🧒🏼", - "🧒🏽", - "🧒🏾", - "🧒🏿", - "🧒", - "🧓🏻", - "🧓🏼", - "🧓🏽", - "🧓🏾", - "🧓🏿", - "🧓", - "🧔🏻", - "🧔🏼", - "🧔🏽", - "🧔🏾", - "🧔🏿", - "🧔", - "🧕🏻", - "🧕🏼", - "🧕🏽", - "🧕🏾", - "🧕🏿", - "🧕", - "🧖🏻‍♀️", - "🧖🏻‍♂️", - "🧖🏻", - "🧖🏼‍♀️", - "🧖🏼‍♂️", - "🧖🏼", - "🧖🏽‍♀️", - "🧖🏽‍♂️", - "🧖🏽", - "🧖🏾‍♀️", - "🧖🏾‍♂️", - "🧖🏾", - "🧖🏿‍♀️", - "🧖🏿‍♂️", - "🧖🏿", - "🧖‍♀️", - "🧖‍♂️", - "🧖", - "🧗🏻‍♀️", - "🧗🏻‍♂️", - "🧗🏻", - "🧗🏼‍♀️", - "🧗🏼‍♂️", - "🧗🏼", - "🧗🏽‍♀️", - "🧗🏽‍♂️", - "🧗🏽", - "🧗🏾‍♀️", - "🧗🏾‍♂️", - "🧗🏾", - "🧗🏿‍♀️", - "🧗🏿‍♂️", - "🧗🏿", - "🧗‍♀️", - "🧗‍♂️", - "🧗", - "🧘🏻‍♀️", - "🧘🏻‍♂️", - "🧘🏻", - "🧘🏼‍♀️", - "🧘🏼‍♂️", - "🧘🏼", - "🧘🏽‍♀️", - "🧘🏽‍♂️", - "🧘🏽", - "🧘🏾‍♀️", - "🧘🏾‍♂️", - "🧘🏾", - "🧘🏿‍♀️", - "🧘🏿‍♂️", - "🧘🏿", - "🧘‍♀️", - "🧘‍♂️", - "🧘", - "🧙🏻‍♀️", - "🧙🏻‍♂️", - "🧙🏻", - "🧙🏼‍♀️", - "🧙🏼‍♂️", - "🧙🏼", - "🧙🏽‍♀️", - "🧙🏽‍♂️", - "🧙🏽", - "🧙🏾‍♀️", - "🧙🏾‍♂️", - "🧙🏾", - "🧙🏿‍♀️", - "🧙🏿‍♂️", - "🧙🏿", - "🧙‍♀️", - "🧙‍♂️", - "🧙", - "🧚🏻‍♀️", - "🧚🏻‍♂️", - "🧚🏻", - "🧚🏼‍♀️", - "🧚🏼‍♂️", - "🧚🏼", - "🧚🏽‍♀️", - "🧚🏽‍♂️", - "🧚🏽", - "🧚🏾‍♀️", - "🧚🏾‍♂️", - "🧚🏾", - "🧚🏿‍♀️", - "🧚🏿‍♂️", - "🧚🏿", - "🧚‍♀️", - "🧚‍♂️", - "🧚", - "🧛🏻‍♀️", - "🧛🏻‍♂️", - "🧛🏻", - "🧛🏼‍♀️", - "🧛🏼‍♂️", - "🧛🏼", - "🧛🏽‍♀️", - "🧛🏽‍♂️", - "🧛🏽", - "🧛🏾‍♀️", - "🧛🏾‍♂️", - "🧛🏾", - "🧛🏿‍♀️", - "🧛🏿‍♂️", - "🧛🏿", - "🧛‍♀️", - "🧛‍♂️", - "🧛", - "🧜🏻‍♀️", - "🧜🏻‍♂️", - "🧜🏻", - "🧜🏼‍♀️", - "🧜🏼‍♂️", - "🧜🏼", - "🧜🏽‍♀️", - "🧜🏽‍♂️", - "🧜🏽", - "🧜🏾‍♀️", - "🧜🏾‍♂️", - "🧜🏾", - "🧜🏿‍♀️", - "🧜🏿‍♂️", - "🧜🏿", - "🧜‍♀️", - "🧜‍♂️", - "🧜", - "🧝🏻‍♀️", - "🧝🏻‍♂️", - "🧝🏻", - "🧝🏼‍♀️", - "🧝🏼‍♂️", - "🧝🏼", - "🧝🏽‍♀️", - "🧝🏽‍♂️", - "🧝🏽", - "🧝🏾‍♀️", - "🧝🏾‍♂️", - "🧝🏾", - "🧝🏿‍♀️", - "🧝🏿‍♂️", - "🧝🏿", - "🧝‍♀️", - "🧝‍♂️", - "🧝", - "🧞‍♀️", - "🧞‍♂️", - "🧞", - "🧟‍♀️", - "🧟‍♂️", - "🧟", - "🧠", - "🧡", - "🧢", - "🧣", - "🧤", - "🧥", - "🧦", - "🧧", - "🧨", - "🧩", - "🧪", - "🧫", - "🧬", - "🧭", - "🧮", - "🧯", - "🧰", - "🧱", - "🧲", - "🧳", - "🧴", - "🧵", - "🧶", - "🧷", - "🧸", - "🧹", - "🧺", - "🧻", - "🧼", - "🧽", - "🧾", - "🧿", - "🩰", - "🩱", - "🩲", - "🩳", - "🩸", - "🩹", - "🩺", - "🪀", - "🪁", - "🪂", - "🪐", - "🪑", - "🪒", - "🪓", - "🪔", - "🪕", - "‼️", - "⁉️", - "™️", - "ℹ️", - "↔️", - "↕️", - "↖️", - "↗️", - "↘️", - "↙️", - "↩️", - "↪️", - "#⃣", - "⌚️", - "⌛️", - "⌨️", - "⏏️", - "⏩", - "⏪", - "⏫", - "⏬", - "⏭️", - "⏮️", - "⏯️", - "⏰", - "⏱️", - "⏲️", - "⏳", - "⏸️", - "⏹️", - "⏺️", - "Ⓜ️", - "▪️", - "▫️", - "▶️", - "◀️", - "◻️", - "◼️", - "◽️", - "◾️", - "☀️", - "☁️", - "☂️", - "☃️", - "☄️", - "☎️", - "☑️", - "☔️", - "☕️", - "☘️", - "☝🏻", - "☝🏼", - "☝🏽", - "☝🏾", - "☝🏿", - "☝️", - "☠️", - "☢️", - "☣️", - "☦️", - "☪️", - "☮️", - "☯️", - "☸️", - "☹️", - "☺️", - "♀️", - "♂️", - "♈️", - "♉️", - "♊️", - "♋️", - "♌️", - "♍️", - "♎️", - "♏️", - "♐️", - "♑️", - "♒️", - "♓️", - "♟️", - "♠️", - "♣️", - "♥️", - "♦️", - "♨️", - "♻️", - "♾", - "♿️", - "⚒️", - "⚓️", - "⚔️", - "⚕️", - "⚖️", - "⚗️", - "⚙️", - "⚛️", - "⚜️", - "⚠️", - "⚡️", - "⚪️", - "⚫️", - "⚰️", - "⚱️", - "⚽️", - "⚾️", - "⛄️", - "⛅️", - "⛈️", - "⛎", - "⛏️", - "⛑️", - "⛓️", - "⛔️", - "⛩️", - "⛪️", - "⛰️", - "⛱️", - "⛲️", - "⛳️", - "⛴️", - "⛵️", - "⛷🏻", - "⛷🏼", - "⛷🏽", - "⛷🏾", - "⛷🏿", - "⛷️", - "⛸️", - "⛹🏻‍♀️", - "⛹🏻‍♂️", - "⛹🏻", - "⛹🏼‍♀️", - "⛹🏼‍♂️", - "⛹🏼", - "⛹🏽‍♀️", - "⛹🏽‍♂️", - "⛹🏽", - "⛹🏾‍♀️", - "⛹🏾‍♂️", - "⛹🏾", - "⛹🏿‍♀️", - "⛹🏿‍♂️", - "⛹🏿", - "⛹️‍♀️", - "⛹️‍♂️", - "⛹️", - "⛺️", - "⛽️", - "✂️", - "✅", - "✈️", - "✉️", - "✊🏻", - "✊🏼", - "✊🏽", - "✊🏾", - "✊🏿", - "✊", - "✋🏻", - "✋🏼", - "✋🏽", - "✋🏾", - "✋🏿", - "✋", - "✌🏻", - "✌🏼", - "✌🏽", - "✌🏾", - "✌🏿", - "✌️", - "✍🏻", - "✍🏼", - "✍🏽", - "✍🏾", - "✍🏿", - "✍️", - "✏️", - "✒️", - "✔️", - "✖️", - "✝️", - "✡️", - "✨", - "✳️", - "✴️", - "❄️", - "❇️", - "❌", - "❎", - "❓", - "❔", - "❕", - "❗️", - "❣️", - "❤️", - "➕", - "➖", - "➗", - "➡️", - "➰", - "➿", - "⤴️", - "⤵️", - "*⃣", - "⬅️", - "⬆️", - "⬇️", - "⬛️", - "⬜️", - "⭐️", - "⭕️", - "0⃣", - "〰️", - "〽️", - "1⃣", - "2⃣", - "㊗️", - "㊙️", - "3⃣", - "4⃣", - "5⃣", - "6⃣", - "7⃣", - "8⃣", - "9⃣", - "©️", - "®️", - "" -]; - -const emojiRegex = /[\uD800-\uDFFF]./; -const emojiList = emojisList.filter((emoji) => emojiRegex.test(emoji)); -const emojiCache = {}; - -function encodeStringToEmoji(content, length) { - if (emojiCache[content]) { - return emojiCache[content]; - } - - length = length || 1; - - const emojis = []; - - do { - if (!emojiList.length) { - throw new Error('Ran out of emoji'); - } - - const index = Math.floor(Math.random() * emojiList.length); - - emojis.push(emojiList[index]); - emojiList.splice(index, 1); - } while (--length > 0); - - const emojiEncoding = emojis.join(''); - - emojiCache[content] = emojiEncoding; - - return emojiEncoding; -} - -function interpolateName$1(loaderContext, name, options) { - let filename; - - const hasQuery = - loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1; - - if (typeof name === 'function') { - filename = name( - loaderContext.resourcePath, - hasQuery ? loaderContext.resourceQuery : undefined - ); - } else { - filename = name || '[hash].[ext]'; - } - - const context = options.context; - const content = options.content; - const regExp = options.regExp; - - let ext = 'bin'; - let basename = 'file'; - let directory = ''; - let folder = ''; - let query = ''; - - if (loaderContext.resourcePath) { - const parsed = path__default.parse(loaderContext.resourcePath); - let resourcePath = loaderContext.resourcePath; - - if (parsed.ext) { - ext = parsed.ext.substr(1); - } - - if (parsed.dir) { - basename = parsed.name; - resourcePath = parsed.dir + path__default.sep; - } - - if (typeof context !== 'undefined') { - directory = path__default - .relative(context, resourcePath + '_') - .replace(/\\/g, '/') - .replace(/\.\.(\/)?/g, '_$1'); - directory = directory.substr(0, directory.length - 1); - } else { - directory = resourcePath.replace(/\\/g, '/').replace(/\.\.(\/)?/g, '_$1'); - } - - if (directory.length === 1) { - directory = ''; - } else if (directory.length > 1) { - folder = path__default.basename(directory); - } - } - - if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) { - query = loaderContext.resourceQuery; - - const hashIdx = query.indexOf('#'); - - if (hashIdx >= 0) { - query = query.substr(0, hashIdx); - } - } - - let url = filename; - - if (content) { - // Match hash template - url = url - // `hash` and `contenthash` are same in `loader-utils` context - // let's keep `hash` for backward compatibility - .replace( - /\[(?:([^:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\]/gi, - (all, hashType, digestType, maxLength) => - getHashDigest_1$1(content, hashType, digestType, parseInt(maxLength, 10)) - ) - .replace(/\[emoji(?::(\d+))?\]/gi, (all, length) => - encodeStringToEmoji(content, parseInt(length, 10)) - ); - } - - url = url - .replace(/\[ext\]/gi, () => ext) - .replace(/\[name\]/gi, () => basename) - .replace(/\[path\]/gi, () => directory) - .replace(/\[folder\]/gi, () => folder) - .replace(/\[query\]/gi, () => query); - - if (regExp && loaderContext.resourcePath) { - const match = loaderContext.resourcePath.match(new RegExp(regExp)); - - match && - match.forEach((matched, i) => { - url = url.replace(new RegExp('\\[' + i + '\\]', 'ig'), matched); - }); - } - - if ( - typeof loaderContext.options === 'object' && - typeof loaderContext.options.customInterpolateName === 'function' - ) { - url = loaderContext.options.customInterpolateName.call( - loaderContext, - url, - name, - options - ); - } - - return url; -} - -var interpolateName_1$1 = interpolateName$1; - -var getOptions_1 = getOptions_1$1; -var parseQuery_1 = parseQuery_1$1; -var stringifyRequest_1 = stringifyRequest_1$1; -var getRemainingRequest_1 = getRemainingRequest_1$1; -var getCurrentRequest_1 = getCurrentRequest_1$1; -var isUrlRequest_1 = isUrlRequest_1$1; -var urlToRequest_1 = urlToRequest_1$1; -var parseString_1 = parseString_1$1; -var getHashDigest_1 = getHashDigest_1$1; -var interpolateName_1 = interpolateName_1$1; - -var lib$1 = { - getOptions: getOptions_1, - parseQuery: parseQuery_1, - stringifyRequest: stringifyRequest_1, - getRemainingRequest: getRemainingRequest_1, - getCurrentRequest: getCurrentRequest_1, - isUrlRequest: isUrlRequest_1, - urlToRequest: urlToRequest_1, - parseString: parseString_1, - getHashDigest: getHashDigest_1, - interpolateName: interpolateName_1 -}; - -var interpolateName = lib$1.interpolateName; - - -/** - * @param {string} pattern - * @param {object} options - * @param {string} options.context - * @param {string} options.hashPrefix - * @return {function} - */ -var genericNames = function createGenerator(pattern, options) { - options = options || {}; - var context = - options && typeof options.context === "string" - ? options.context - : process.cwd(); - var hashPrefix = - options && typeof options.hashPrefix === "string" ? options.hashPrefix : ""; - - /** - * @param {string} localName Usually a class name - * @param {string} filepath Absolute path - * @return {string} - */ - return function generate(localName, filepath) { - var name = pattern.replace(/\[local\]/gi, localName); - var loaderContext = { - resourcePath: filepath - }; - - var loaderOptions = { - content: - hashPrefix + - path__default.relative(context, filepath).replace(/\\/g, "/") + - "+" + - localName, - context: context - }; - - var genericName = interpolateName(loaderContext, name, loaderOptions); - return genericName - .replace(new RegExp("[^a-zA-Z0-9\\-_\u00A0-\uFFFF]", "g"), "-") - .replace(/^((-?[0-9])|--)/, "_$1"); - }; -}; - -var replaceAll_1 = replaceAll; -var matchConstName = /[$#]?[\w-\.]+/g; - -function replaceAll(replacements, text) { - var matches = void 0; - while (matches = matchConstName.exec(text)) { - var replacement = replacements[matches[0]]; - if (replacement) { - text = text.slice(0, matches.index) + replacement + text.slice(matchConstName.lastIndex); - matchConstName.lastIndex -= matches[0].length - replacement.length; - } - } - return text; -} - -var _default$4 = function (css, translations) { - css.walkDecls(function (decl) { - return decl.value = replaceAll(translations, decl.value); - }); - css.walkAtRules('media', function (atRule) { - return atRule.params = replaceAll(translations, atRule.params); - }); -}; - -var lib = /*#__PURE__*/Object.defineProperty({ - replaceAll: replaceAll_1, - default: _default$4 -}, '__esModule', {value: true}); - -var _icssReplaceSymbols2 = _interopRequireDefault$3(lib); - -function _interopRequireDefault$3(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// Copied from https://github.com/css-modules/css-modules-loader-core - -const importRegexp = /^:import\((.+)\)$/; -class Parser { - constructor(pathFetcher, trace) { - this.pathFetcher = pathFetcher; - this.plugin = this.plugin.bind(this); - this.exportTokens = {}; - this.translations = {}; - this.trace = trace; - } - - plugin() { - const parser = this; - return { - postcssPlugin: "css-modules-parser", - OnceExit(css) { - return Promise.all(parser.fetchAllImports(css)).then(() => parser.linkImportedSymbols(css)).then(() => parser.extractExports(css)); - } - }; - } - - fetchAllImports(css) { - let imports = []; - css.each(node => { - if (node.type == "rule" && node.selector.match(importRegexp)) { - imports.push(this.fetchImport(node, css.source.input.from, imports.length)); - } - }); - return imports; - } - - linkImportedSymbols(css) { - (0, _icssReplaceSymbols2.default)(css, this.translations); - } - - extractExports(css) { - css.each(node => { - if (node.type == "rule" && node.selector == ":export") this.handleExport(node); - }); - } - - handleExport(exportNode) { - exportNode.each(decl => { - if (decl.type == "decl") { - Object.keys(this.translations).forEach(translation => { - decl.value = decl.value.replace(translation, this.translations[translation]); - }); - this.exportTokens[decl.prop] = decl.value; - } - }); - exportNode.remove(); - } - - fetchImport(importNode, relativeTo, depNr) { - let file = importNode.selector.match(importRegexp)[1], - depTrace = this.trace + String.fromCharCode(depNr); - return this.pathFetcher(file, relativeTo, depTrace).then(exports => { - importNode.each(decl => { - if (decl.type == "decl") { - this.translations[decl.prop] = exports[decl.value]; - } - }); - importNode.remove(); - }, err => console.log(err)); - } -} -var _default$3 = Parser; - -var parser$1 = /*#__PURE__*/Object.defineProperty({ - default: _default$3 -}, '__esModule', {value: true}); - -var _postcss2$1 = _interopRequireDefault$2(_postcss__default); - - - -var _fs2 = _interopRequireDefault$2(fs__default); - - - -var _path2 = _interopRequireDefault$2(path__default); - - - -var _parser2$1 = _interopRequireDefault$2(parser$1); - -function _interopRequireDefault$2(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// Copied from https://github.com/css-modules/css-modules-loader-core - -class Core { - constructor(plugins) { - this.plugins = plugins || Core.defaultPlugins; - } - - load(sourceString, sourcePath, trace, pathFetcher) { - let parser = new _parser2$1.default(pathFetcher, trace); - - return (0, _postcss2$1.default)(this.plugins.concat([parser.plugin()])).process(sourceString, { from: "/" + sourcePath }).then(result => { - return { - injectableSource: result.css, - exportTokens: parser.exportTokens - }; - }); - } -} - -// Sorts dependencies in the following way: -// AAA comes before AA and A -// AB comes after AA and before A -// All Bs come after all As -// This ensures that the files are always returned in the following order: -// - In the order they were required, except -// - After all their dependencies -const traceKeySorter = (a, b) => { - if (a.length < b.length) { - return a < b.substring(0, a.length) ? -1 : 1; - } else if (a.length > b.length) { - return a.substring(0, b.length) <= b ? -1 : 1; - } else { - return a < b ? -1 : 1; - } -}; - -class FileSystemLoader { - constructor(root, plugins) { - this.root = root; - this.sources = {}; - this.traces = {}; - this.importNr = 0; - this.core = new Core(plugins); - this.tokensByFile = {}; - } - - fetch(_newPath, relativeTo, _trace) { - let newPath = _newPath.replace(/^["']|["']$/g, ""), - trace = _trace || String.fromCharCode(this.importNr++); - return new Promise((resolve, reject) => { - let relativeDir = _path2.default.dirname(relativeTo), - rootRelativePath = _path2.default.resolve(relativeDir, newPath), - fileRelativePath = _path2.default.resolve(_path2.default.join(this.root, relativeDir), newPath); - - // if the path is not relative or absolute, try to resolve it in node_modules - if (newPath[0] !== "." && newPath[0] !== "/") { - try { - fileRelativePath = require.resolve(newPath); - } catch (e) { - // noop - } - } - - const tokens = this.tokensByFile[fileRelativePath]; - if (tokens) { - return resolve(tokens); - } - - _fs2.default.readFile(fileRelativePath, "utf-8", (err, source) => { - if (err) reject(err); - this.core.load(source, rootRelativePath, trace, this.fetch.bind(this)).then(({ injectableSource, exportTokens }) => { - this.sources[fileRelativePath] = injectableSource; - this.traces[trace] = fileRelativePath; - this.tokensByFile[fileRelativePath] = exportTokens; - resolve(exportTokens); - }, reject); - }); - }); - } - - get finalSource() { - const traces = this.traces; - const sources = this.sources; - let written = new Set(); - - return Object.keys(traces).sort(traceKeySorter).map(key => { - const filename = traces[key]; - if (written.has(filename)) { - return null; - } - written.add(filename); - - return sources[filename]; - }).join(""); - } -} -var _default$2 = FileSystemLoader; - -var loader = /*#__PURE__*/Object.defineProperty({ - default: _default$2 -}, '__esModule', {value: true}); - -function hash(str) { - var hash = 5381, - i = str.length; - - while(i) { - hash = (hash * 33) ^ str.charCodeAt(--i); - } - - /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed - * integers. Since we want the results to be always positive, convert the - * signed int to an unsigned by doing an unsigned bitshift. */ - return hash >>> 0; -} - -var stringHash = hash; - -var _default$1 = generateScopedName; - - - -var _stringHash2 = _interopRequireDefault$1(stringHash); - -function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function generateScopedName(name, filename, css) { - const i = css.indexOf(`.${name}`); - const lineNumber = css.substr(0, i).split(/[\r\n]/).length; - const hash = (0, _stringHash2.default)(css).toString(36).substr(0, 5); - - return `_${name}_${hash}_${lineNumber}`; -} - -var generateScopedName_1 = /*#__PURE__*/Object.defineProperty({ - default: _default$1 -}, '__esModule', {value: true}); - -var _default = saveJSON; - - - -function saveJSON(cssFile, json) { - return new Promise((resolve, reject) => { - (0, fs__default.writeFile)(`${cssFile}.json`, JSON.stringify(json), e => e ? reject(e) : resolve(json)); - }); -} - -var saveJSON_1 = /*#__PURE__*/Object.defineProperty({ - default: _default -}, '__esModule', {value: true}); - -var indexesOf = function (ary, item) { - var i = -1, indexes = []; - while((i = ary.indexOf(item, i + 1)) !== -1) - indexes.push(i); - return indexes -}; - -function unique_pred(list, compare) { - var ptr = 1 - , len = list.length - , a=list[0], b=list[0]; - for(var i=1; i> 10 | 0xd800, high & 0x3ff | 0xdc00); - }); -} - -module.exports = exports.default; -}); - -var getProp_1 = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = getProp; - -function getProp(obj) { - for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - props[_key - 1] = arguments[_key]; - } - - while (props.length > 0) { - var prop = props.shift(); - - if (!obj[prop]) { - return undefined; - } - - obj = obj[prop]; - } - - return obj; -} - -module.exports = exports.default; -}); - -var ensureObject_1 = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = ensureObject; - -function ensureObject(obj) { - for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - props[_key - 1] = arguments[_key]; - } - - while (props.length > 0) { - var prop = props.shift(); - - if (!obj[prop]) { - obj[prop] = {}; - } - - obj = obj[prop]; - } -} - -module.exports = exports.default; -}); - -var stripComments_1 = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = stripComments; - -function stripComments(str) { - var s = ""; - var commentStart = str.indexOf("/*"); - var lastEnd = 0; - - while (commentStart >= 0) { - s = s + str.slice(lastEnd, commentStart); - var commentEnd = str.indexOf("*/", commentStart + 2); - - if (commentEnd < 0) { - return s; - } - - lastEnd = commentEnd + 2; - commentStart = str.indexOf("/*", lastEnd); - } - - s = s + str.slice(lastEnd); - return s; -} - -module.exports = exports.default; -}); - -var util = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.stripComments = exports.ensureObject = exports.getProp = exports.unesc = void 0; - -var _unesc = _interopRequireDefault(unesc_1); - -exports.unesc = _unesc.default; - -var _getProp = _interopRequireDefault(getProp_1); - -exports.getProp = _getProp.default; - -var _ensureObject = _interopRequireDefault(ensureObject_1); - -exports.ensureObject = _ensureObject.default; - -var _stripComments = _interopRequireDefault(stripComments_1); - -exports.stripComments = _stripComments.default; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -}); - -var node$1 = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - - - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var cloneNode = function cloneNode(obj, parent) { - if (typeof obj !== 'object' || obj === null) { - return obj; - } - - var cloned = new obj.constructor(); - - for (var i in obj) { - if (!obj.hasOwnProperty(i)) { - continue; - } - - var value = obj[i]; - var type = typeof value; - - if (i === 'parent' && type === 'object') { - if (parent) { - cloned[i] = parent; - } - } else if (value instanceof Array) { - cloned[i] = value.map(function (j) { - return cloneNode(j, cloned); - }); - } else { - cloned[i] = cloneNode(value, cloned); - } - } - - return cloned; -}; - -var Node = -/*#__PURE__*/ -function () { - function Node(opts) { - if (opts === void 0) { - opts = {}; - } - - Object.assign(this, opts); - this.spaces = this.spaces || {}; - this.spaces.before = this.spaces.before || ''; - this.spaces.after = this.spaces.after || ''; - } - - var _proto = Node.prototype; - - _proto.remove = function remove() { - if (this.parent) { - this.parent.removeChild(this); - } - - this.parent = undefined; - return this; - }; - - _proto.replaceWith = function replaceWith() { - if (this.parent) { - for (var index in arguments) { - this.parent.insertBefore(this, arguments[index]); - } - - this.remove(); - } - - return this; - }; - - _proto.next = function next() { - return this.parent.at(this.parent.index(this) + 1); - }; - - _proto.prev = function prev() { - return this.parent.at(this.parent.index(this) - 1); - }; - - _proto.clone = function clone(overrides) { - if (overrides === void 0) { - overrides = {}; - } - - var cloned = cloneNode(this); - - for (var name in overrides) { - cloned[name] = overrides[name]; - } - - return cloned; - } - /** - * Some non-standard syntax doesn't follow normal escaping rules for css. - * This allows non standard syntax to be appended to an existing property - * by specifying the escaped value. By specifying the escaped value, - * illegal characters are allowed to be directly inserted into css output. - * @param {string} name the property to set - * @param {any} value the unescaped value of the property - * @param {string} valueEscaped optional. the escaped value of the property. - */ - ; - - _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) { - if (!this.raws) { - this.raws = {}; - } - - var originalValue = this[name]; - var originalEscaped = this.raws[name]; - this[name] = originalValue + value; // this may trigger a setter that updates raws, so it has to be set first. - - if (originalEscaped || valueEscaped !== value) { - this.raws[name] = (originalEscaped || originalValue) + valueEscaped; - } else { - delete this.raws[name]; // delete any escaped value that was created by the setter. - } - } - /** - * Some non-standard syntax doesn't follow normal escaping rules for css. - * This allows the escaped value to be specified directly, allowing illegal - * characters to be directly inserted into css output. - * @param {string} name the property to set - * @param {any} value the unescaped value of the property - * @param {string} valueEscaped the escaped value of the property. - */ - ; - - _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) { - if (!this.raws) { - this.raws = {}; - } - - this[name] = value; // this may trigger a setter that updates raws, so it has to be set first. - - this.raws[name] = valueEscaped; - } - /** - * When you want a value to passed through to CSS directly. This method - * deletes the corresponding raw value causing the stringifier to fallback - * to the unescaped value. - * @param {string} name the property to set. - * @param {any} value The value that is both escaped and unescaped. - */ - ; - - _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) { - this[name] = value; // this may trigger a setter that updates raws, so it has to be set first. - - if (this.raws) { - delete this.raws[name]; - } - } - /** - * - * @param {number} line The number (starting with 1) - * @param {number} column The column number (starting with 1) - */ - ; - - _proto.isAtPosition = function isAtPosition(line, column) { - if (this.source && this.source.start && this.source.end) { - if (this.source.start.line > line) { - return false; - } - - if (this.source.end.line < line) { - return false; - } - - if (this.source.start.line === line && this.source.start.column > column) { - return false; - } - - if (this.source.end.line === line && this.source.end.column < column) { - return false; - } - - return true; - } - - return undefined; - }; - - _proto.stringifyProperty = function stringifyProperty(name) { - return this.raws && this.raws[name] || this[name]; - }; - - _proto.valueToString = function valueToString() { - return String(this.stringifyProperty("value")); - }; - - _proto.toString = function toString() { - return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join(''); - }; - - _createClass(Node, [{ - key: "rawSpaceBefore", - get: function get() { - var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before; - - if (rawSpace === undefined) { - rawSpace = this.spaces && this.spaces.before; - } - - return rawSpace || ""; - }, - set: function set(raw) { - (0, util.ensureObject)(this, "raws", "spaces"); - this.raws.spaces.before = raw; - } - }, { - key: "rawSpaceAfter", - get: function get() { - var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after; - - if (rawSpace === undefined) { - rawSpace = this.spaces.after; - } - - return rawSpace || ""; - }, - set: function set(raw) { - (0, util.ensureObject)(this, "raws", "spaces"); - this.raws.spaces.after = raw; - } - }]); - - return Node; -}(); - -exports.default = Node; -module.exports = exports.default; -}); - -var types = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.UNIVERSAL = exports.ATTRIBUTE = exports.CLASS = exports.COMBINATOR = exports.COMMENT = exports.ID = exports.NESTING = exports.PSEUDO = exports.ROOT = exports.SELECTOR = exports.STRING = exports.TAG = void 0; -var TAG = 'tag'; -exports.TAG = TAG; -var STRING = 'string'; -exports.STRING = STRING; -var SELECTOR = 'selector'; -exports.SELECTOR = SELECTOR; -var ROOT = 'root'; -exports.ROOT = ROOT; -var PSEUDO = 'pseudo'; -exports.PSEUDO = PSEUDO; -var NESTING = 'nesting'; -exports.NESTING = NESTING; -var ID = 'id'; -exports.ID = ID; -var COMMENT = 'comment'; -exports.COMMENT = COMMENT; -var COMBINATOR = 'combinator'; -exports.COMBINATOR = COMBINATOR; -var CLASS = 'class'; -exports.CLASS = CLASS; -var ATTRIBUTE = 'attribute'; -exports.ATTRIBUTE = ATTRIBUTE; -var UNIVERSAL = 'universal'; -exports.UNIVERSAL = UNIVERSAL; -}); - -var container = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _node = _interopRequireDefault(node$1); - -var types$1 = _interopRequireWildcard(types); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var Container = -/*#__PURE__*/ -function (_Node) { - _inheritsLoose(Container, _Node); - - function Container(opts) { - var _this; - - _this = _Node.call(this, opts) || this; - - if (!_this.nodes) { - _this.nodes = []; - } - - return _this; - } - - var _proto = Container.prototype; - - _proto.append = function append(selector) { - selector.parent = this; - this.nodes.push(selector); - return this; - }; - - _proto.prepend = function prepend(selector) { - selector.parent = this; - this.nodes.unshift(selector); - return this; - }; - - _proto.at = function at(index) { - return this.nodes[index]; - }; - - _proto.index = function index(child) { - if (typeof child === 'number') { - return child; - } - - return this.nodes.indexOf(child); - }; - - _proto.removeChild = function removeChild(child) { - child = this.index(child); - this.at(child).parent = undefined; - this.nodes.splice(child, 1); - var index; - - for (var id in this.indexes) { - index = this.indexes[id]; - - if (index >= child) { - this.indexes[id] = index - 1; - } - } - - return this; - }; - - _proto.removeAll = function removeAll() { - for (var _iterator = this.nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { - var _ref; - - if (_isArray) { - if (_i >= _iterator.length) break; - _ref = _iterator[_i++]; - } else { - _i = _iterator.next(); - if (_i.done) break; - _ref = _i.value; - } - - var node = _ref; - node.parent = undefined; - } - - this.nodes = []; - return this; - }; - - _proto.empty = function empty() { - return this.removeAll(); - }; - - _proto.insertAfter = function insertAfter(oldNode, newNode) { - newNode.parent = this; - var oldIndex = this.index(oldNode); - this.nodes.splice(oldIndex + 1, 0, newNode); - newNode.parent = this; - var index; - - for (var id in this.indexes) { - index = this.indexes[id]; - - if (oldIndex <= index) { - this.indexes[id] = index + 1; - } - } - - return this; - }; - - _proto.insertBefore = function insertBefore(oldNode, newNode) { - newNode.parent = this; - var oldIndex = this.index(oldNode); - this.nodes.splice(oldIndex, 0, newNode); - newNode.parent = this; - var index; - - for (var id in this.indexes) { - index = this.indexes[id]; - - if (index <= oldIndex) { - this.indexes[id] = index + 1; - } - } - - return this; - }; - - _proto._findChildAtPosition = function _findChildAtPosition(line, col) { - var found = undefined; - this.each(function (node) { - if (node.atPosition) { - var foundChild = node.atPosition(line, col); - - if (foundChild) { - found = foundChild; - return false; - } - } else if (node.isAtPosition(line, col)) { - found = node; - return false; - } - }); - return found; - } - /** - * Return the most specific node at the line and column number given. - * The source location is based on the original parsed location, locations aren't - * updated as selector nodes are mutated. - * - * Note that this location is relative to the location of the first character - * of the selector, and not the location of the selector in the overall document - * when used in conjunction with postcss. - * - * If not found, returns undefined. - * @param {number} line The line number of the node to find. (1-based index) - * @param {number} col The column number of the node to find. (1-based index) - */ - ; - - _proto.atPosition = function atPosition(line, col) { - if (this.isAtPosition(line, col)) { - return this._findChildAtPosition(line, col) || this; - } else { - return undefined; - } - }; - - _proto._inferEndPosition = function _inferEndPosition() { - if (this.last && this.last.source && this.last.source.end) { - this.source = this.source || {}; - this.source.end = this.source.end || {}; - Object.assign(this.source.end, this.last.source.end); - } - }; - - _proto.each = function each(callback) { - if (!this.lastEach) { - this.lastEach = 0; - } - - if (!this.indexes) { - this.indexes = {}; - } - - this.lastEach++; - var id = this.lastEach; - this.indexes[id] = 0; - - if (!this.length) { - return undefined; - } - - var index, result; - - while (this.indexes[id] < this.length) { - index = this.indexes[id]; - result = callback(this.at(index), index); - - if (result === false) { - break; - } - - this.indexes[id] += 1; - } - - delete this.indexes[id]; - - if (result === false) { - return false; - } - }; - - _proto.walk = function walk(callback) { - return this.each(function (node, i) { - var result = callback(node, i); - - if (result !== false && node.length) { - result = node.walk(callback); - } - - if (result === false) { - return false; - } - }); - }; - - _proto.walkAttributes = function walkAttributes(callback) { - var _this2 = this; - - return this.walk(function (selector) { - if (selector.type === types$1.ATTRIBUTE) { - return callback.call(_this2, selector); - } - }); - }; - - _proto.walkClasses = function walkClasses(callback) { - var _this3 = this; - - return this.walk(function (selector) { - if (selector.type === types$1.CLASS) { - return callback.call(_this3, selector); - } - }); - }; - - _proto.walkCombinators = function walkCombinators(callback) { - var _this4 = this; - - return this.walk(function (selector) { - if (selector.type === types$1.COMBINATOR) { - return callback.call(_this4, selector); - } - }); - }; - - _proto.walkComments = function walkComments(callback) { - var _this5 = this; - - return this.walk(function (selector) { - if (selector.type === types$1.COMMENT) { - return callback.call(_this5, selector); - } - }); - }; - - _proto.walkIds = function walkIds(callback) { - var _this6 = this; - - return this.walk(function (selector) { - if (selector.type === types$1.ID) { - return callback.call(_this6, selector); - } - }); - }; - - _proto.walkNesting = function walkNesting(callback) { - var _this7 = this; - - return this.walk(function (selector) { - if (selector.type === types$1.NESTING) { - return callback.call(_this7, selector); - } - }); - }; - - _proto.walkPseudos = function walkPseudos(callback) { - var _this8 = this; - - return this.walk(function (selector) { - if (selector.type === types$1.PSEUDO) { - return callback.call(_this8, selector); - } - }); - }; - - _proto.walkTags = function walkTags(callback) { - var _this9 = this; - - return this.walk(function (selector) { - if (selector.type === types$1.TAG) { - return callback.call(_this9, selector); - } - }); - }; - - _proto.walkUniversals = function walkUniversals(callback) { - var _this10 = this; - - return this.walk(function (selector) { - if (selector.type === types$1.UNIVERSAL) { - return callback.call(_this10, selector); - } - }); - }; - - _proto.split = function split(callback) { - var _this11 = this; - - var current = []; - return this.reduce(function (memo, node, index) { - var split = callback.call(_this11, node); - current.push(node); - - if (split) { - memo.push(current); - current = []; - } else if (index === _this11.length - 1) { - memo.push(current); - } - - return memo; - }, []); - }; - - _proto.map = function map(callback) { - return this.nodes.map(callback); - }; - - _proto.reduce = function reduce(callback, memo) { - return this.nodes.reduce(callback, memo); - }; - - _proto.every = function every(callback) { - return this.nodes.every(callback); - }; - - _proto.some = function some(callback) { - return this.nodes.some(callback); - }; - - _proto.filter = function filter(callback) { - return this.nodes.filter(callback); - }; - - _proto.sort = function sort(callback) { - return this.nodes.sort(callback); - }; - - _proto.toString = function toString() { - return this.map(String).join(''); - }; - - _createClass(Container, [{ - key: "first", - get: function get() { - return this.at(0); - } - }, { - key: "last", - get: function get() { - return this.at(this.length - 1); - } - }, { - key: "length", - get: function get() { - return this.nodes.length; - } - }]); - - return Container; -}(_node.default); - -exports.default = Container; -module.exports = exports.default; -}); - -var root = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _container = _interopRequireDefault(container); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var Root = -/*#__PURE__*/ -function (_Container) { - _inheritsLoose(Root, _Container); - - function Root(opts) { - var _this; - - _this = _Container.call(this, opts) || this; - _this.type = types.ROOT; - return _this; - } - - var _proto = Root.prototype; - - _proto.toString = function toString() { - var str = this.reduce(function (memo, selector) { - memo.push(String(selector)); - return memo; - }, []).join(','); - return this.trailingComma ? str + ',' : str; - }; - - _proto.error = function error(message, options) { - if (this._error) { - return this._error(message, options); - } else { - return new Error(message); - } - }; - - _createClass(Root, [{ - key: "errorGenerator", - set: function set(handler) { - this._error = handler; - } - }]); - - return Root; -}(_container.default); - -exports.default = Root; -module.exports = exports.default; -}); - -var selector = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _container = _interopRequireDefault(container); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var Selector = -/*#__PURE__*/ -function (_Container) { - _inheritsLoose(Selector, _Container); - - function Selector(opts) { - var _this; - - _this = _Container.call(this, opts) || this; - _this.type = types.SELECTOR; - return _this; - } - - return Selector; -}(_container.default); - -exports.default = Selector; -module.exports = exports.default; -}); - -/*! https://mths.be/cssesc v3.0.0 by @mathias */ - -var object = {}; -var hasOwnProperty$1 = object.hasOwnProperty; -var merge = function merge(options, defaults) { - if (!options) { - return defaults; - } - var result = {}; - for (var key in defaults) { - // `if (defaults.hasOwnProperty(key) { … }` is not needed here, since - // only recognized option names are used. - result[key] = hasOwnProperty$1.call(options, key) ? options[key] : defaults[key]; - } - return result; -}; - -var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/; -var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/; -var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g; - -// https://mathiasbynens.be/notes/css-escapes#css -var cssesc = function cssesc(string, options) { - options = merge(options, cssesc.options); - if (options.quotes != 'single' && options.quotes != 'double') { - options.quotes = 'single'; - } - var quote = options.quotes == 'double' ? '"' : '\''; - var isIdentifier = options.isIdentifier; - - var firstChar = string.charAt(0); - var output = ''; - var counter = 0; - var length = string.length; - while (counter < length) { - var character = string.charAt(counter++); - var codePoint = character.charCodeAt(); - var value = void 0; - // If it’s not a printable ASCII character… - if (codePoint < 0x20 || codePoint > 0x7E) { - if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) { - // It’s a high surrogate, and there is a next character. - var extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { - // next character is low surrogate - codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000; - } else { - // It’s an unmatched surrogate; only append this code unit, in case - // the next code unit is the high surrogate of a surrogate pair. - counter--; - } - } - value = '\\' + codePoint.toString(16).toUpperCase() + ' '; - } else { - if (options.escapeEverything) { - if (regexAnySingleEscape.test(character)) { - value = '\\' + character; - } else { - value = '\\' + codePoint.toString(16).toUpperCase() + ' '; - } - } else if (/[\t\n\f\r\x0B]/.test(character)) { - value = '\\' + codePoint.toString(16).toUpperCase() + ' '; - } else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) { - value = '\\' + character; - } else { - value = character; - } - } - output += value; - } - - if (isIdentifier) { - if (/^-[-\d]/.test(output)) { - output = '\\-' + output.slice(1); - } else if (/\d/.test(firstChar)) { - output = '\\3' + firstChar + ' ' + output.slice(1); - } - } - - // Remove spaces after `\HEX` escapes that are not followed by a hex digit, - // since they’re redundant. Note that this is only possible if the escape - // sequence isn’t preceded by an odd number of backslashes. - output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) { - if ($1 && $1.length % 2) { - // It’s not safe to remove the space, so don’t. - return $0; - } - // Strip the space. - return ($1 || '') + $2; - }); - - if (!isIdentifier && options.wrap) { - return quote + output + quote; - } - return output; -}; - -// Expose default options (so they can be overridden globally). -cssesc.options = { - 'escapeEverything': false, - 'isIdentifier': false, - 'quotes': 'single', - 'wrap': false -}; - -cssesc.version = '3.0.0'; - -var cssesc_1 = cssesc; - -var className = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _cssesc = _interopRequireDefault(cssesc_1); - - - -var _node = _interopRequireDefault(node$1); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var ClassName = -/*#__PURE__*/ -function (_Node) { - _inheritsLoose(ClassName, _Node); - - function ClassName(opts) { - var _this; - - _this = _Node.call(this, opts) || this; - _this.type = types.CLASS; - _this._constructed = true; - return _this; - } - - var _proto = ClassName.prototype; - - _proto.valueToString = function valueToString() { - return '.' + _Node.prototype.valueToString.call(this); - }; - - _createClass(ClassName, [{ - key: "value", - set: function set(v) { - if (this._constructed) { - var escaped = (0, _cssesc.default)(v, { - isIdentifier: true - }); - - if (escaped !== v) { - (0, util.ensureObject)(this, "raws"); - this.raws.value = escaped; - } else if (this.raws) { - delete this.raws.value; - } - } - - this._value = v; - }, - get: function get() { - return this._value; - } - }]); - - return ClassName; -}(_node.default); - -exports.default = ClassName; -module.exports = exports.default; -}); - -var comment = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _node = _interopRequireDefault(node$1); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var Comment = -/*#__PURE__*/ -function (_Node) { - _inheritsLoose(Comment, _Node); - - function Comment(opts) { - var _this; - - _this = _Node.call(this, opts) || this; - _this.type = types.COMMENT; - return _this; - } - - return Comment; -}(_node.default); - -exports.default = Comment; -module.exports = exports.default; -}); - -var id = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _node = _interopRequireDefault(node$1); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var ID = -/*#__PURE__*/ -function (_Node) { - _inheritsLoose(ID, _Node); - - function ID(opts) { - var _this; - - _this = _Node.call(this, opts) || this; - _this.type = types.ID; - return _this; - } - - var _proto = ID.prototype; - - _proto.valueToString = function valueToString() { - return '#' + _Node.prototype.valueToString.call(this); - }; - - return ID; -}(_node.default); - -exports.default = ID; -module.exports = exports.default; -}); - -var namespace = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _cssesc = _interopRequireDefault(cssesc_1); - - - -var _node = _interopRequireDefault(node$1); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var Namespace = -/*#__PURE__*/ -function (_Node) { - _inheritsLoose(Namespace, _Node); - - function Namespace() { - return _Node.apply(this, arguments) || this; - } - - var _proto = Namespace.prototype; - - _proto.qualifiedName = function qualifiedName(value) { - if (this.namespace) { - return this.namespaceString + "|" + value; - } else { - return value; - } - }; - - _proto.valueToString = function valueToString() { - return this.qualifiedName(_Node.prototype.valueToString.call(this)); - }; - - _createClass(Namespace, [{ - key: "namespace", - get: function get() { - return this._namespace; - }, - set: function set(namespace) { - if (namespace === true || namespace === "*" || namespace === "&") { - this._namespace = namespace; - - if (this.raws) { - delete this.raws.namespace; - } - - return; - } - - var escaped = (0, _cssesc.default)(namespace, { - isIdentifier: true - }); - this._namespace = namespace; - - if (escaped !== namespace) { - (0, util.ensureObject)(this, "raws"); - this.raws.namespace = escaped; - } else if (this.raws) { - delete this.raws.namespace; - } - } - }, { - key: "ns", - get: function get() { - return this._namespace; - }, - set: function set(namespace) { - this.namespace = namespace; - } - }, { - key: "namespaceString", - get: function get() { - if (this.namespace) { - var ns = this.stringifyProperty("namespace"); - - if (ns === true) { - return ''; - } else { - return ns; - } - } else { - return ''; - } - } - }]); - - return Namespace; -}(_node.default); - -exports.default = Namespace; -module.exports = exports.default; -}); - -var tag = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _namespace = _interopRequireDefault(namespace); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var Tag = -/*#__PURE__*/ -function (_Namespace) { - _inheritsLoose(Tag, _Namespace); - - function Tag(opts) { - var _this; - - _this = _Namespace.call(this, opts) || this; - _this.type = types.TAG; - return _this; - } - - return Tag; -}(_namespace.default); - -exports.default = Tag; -module.exports = exports.default; -}); - -var string = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _node = _interopRequireDefault(node$1); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var String = -/*#__PURE__*/ -function (_Node) { - _inheritsLoose(String, _Node); - - function String(opts) { - var _this; - - _this = _Node.call(this, opts) || this; - _this.type = types.STRING; - return _this; - } - - return String; -}(_node.default); - -exports.default = String; -module.exports = exports.default; -}); - -var pseudo = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _container = _interopRequireDefault(container); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var Pseudo = -/*#__PURE__*/ -function (_Container) { - _inheritsLoose(Pseudo, _Container); - - function Pseudo(opts) { - var _this; - - _this = _Container.call(this, opts) || this; - _this.type = types.PSEUDO; - return _this; - } - - var _proto = Pseudo.prototype; - - _proto.toString = function toString() { - var params = this.length ? '(' + this.map(String).join(',') + ')' : ''; - return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join(''); - }; - - return Pseudo; -}(_container.default); - -exports.default = Pseudo; -module.exports = exports.default; -}); - -/** - * For Node.js, simply re-export the core `util.deprecate` function. - */ - -var node = util__default.deprecate; - -var attribute = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.unescapeValue = unescapeValue; -exports.default = void 0; - -var _cssesc = _interopRequireDefault(cssesc_1); - -var _unesc = _interopRequireDefault(unesc_1); - -var _namespace = _interopRequireDefault(namespace); - - - -var _CSSESC_QUOTE_OPTIONS; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - - - -var WRAPPED_IN_QUOTES = /^('|")(.*)\1$/; -var warnOfDeprecatedValueAssignment = node(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead."); -var warnOfDeprecatedQuotedAssignment = node(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead."); -var warnOfDeprecatedConstructor = node(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now."); - -function unescapeValue(value) { - var deprecatedUsage = false; - var quoteMark = null; - var unescaped = value; - var m = unescaped.match(WRAPPED_IN_QUOTES); - - if (m) { - quoteMark = m[1]; - unescaped = m[2]; - } - - unescaped = (0, _unesc.default)(unescaped); - - if (unescaped !== value) { - deprecatedUsage = true; - } - - return { - deprecatedUsage: deprecatedUsage, - unescaped: unescaped, - quoteMark: quoteMark - }; -} - -function handleDeprecatedContructorOpts(opts) { - if (opts.quoteMark !== undefined) { - return opts; - } - - if (opts.value === undefined) { - return opts; - } - - warnOfDeprecatedConstructor(); - - var _unescapeValue = unescapeValue(opts.value), - quoteMark = _unescapeValue.quoteMark, - unescaped = _unescapeValue.unescaped; - - if (!opts.raws) { - opts.raws = {}; - } - - if (opts.raws.value === undefined) { - opts.raws.value = opts.value; - } - - opts.value = unescaped; - opts.quoteMark = quoteMark; - return opts; -} - -var Attribute = -/*#__PURE__*/ -function (_Namespace) { - _inheritsLoose(Attribute, _Namespace); - - function Attribute(opts) { - var _this; - - if (opts === void 0) { - opts = {}; - } - - _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this; - _this.type = types.ATTRIBUTE; - _this.raws = _this.raws || {}; - Object.defineProperty(_this.raws, 'unquoted', { - get: node(function () { - return _this.value; - }, "attr.raws.unquoted is deprecated. Call attr.value instead."), - set: node(function () { - return _this.value; - }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.") - }); - _this._constructed = true; - return _this; - } - /** - * Returns the Attribute's value quoted such that it would be legal to use - * in the value of a css file. The original value's quotation setting - * used for stringification is left unchanged. See `setValue(value, options)` - * if you want to control the quote settings of a new value for the attribute. - * - * You can also change the quotation used for the current value by setting quoteMark. - * - * Options: - * * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this - * option is not set, the original value for quoteMark will be used. If - * indeterminate, a double quote is used. The legal values are: - * * `null` - the value will be unquoted and characters will be escaped as necessary. - * * `'` - the value will be quoted with a single quote and single quotes are escaped. - * * `"` - the value will be quoted with a double quote and double quotes are escaped. - * * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark - * over the quoteMark option value. - * * smart {boolean} - if true, will select a quote mark based on the value - * and the other options specified here. See the `smartQuoteMark()` - * method. - **/ - - - var _proto = Attribute.prototype; - - _proto.getQuotedValue = function getQuotedValue(options) { - if (options === void 0) { - options = {}; - } - - var quoteMark = this._determineQuoteMark(options); - - var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark]; - var escaped = (0, _cssesc.default)(this._value, cssescopts); - return escaped; - }; - - _proto._determineQuoteMark = function _determineQuoteMark(options) { - return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options); - } - /** - * Set the unescaped value with the specified quotation options. The value - * provided must not include any wrapping quote marks -- those quotes will - * be interpreted as part of the value and escaped accordingly. - */ - ; - - _proto.setValue = function setValue(value, options) { - if (options === void 0) { - options = {}; - } - - this._value = value; - this._quoteMark = this._determineQuoteMark(options); - - this._syncRawValue(); - } - /** - * Intelligently select a quoteMark value based on the value's contents. If - * the value is a legal CSS ident, it will not be quoted. Otherwise a quote - * mark will be picked that minimizes the number of escapes. - * - * If there's no clear winner, the quote mark from these options is used, - * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is - * true). If the quoteMark is unspecified, a double quote is used. - * - * @param options This takes the quoteMark and preferCurrentQuoteMark options - * from the quoteValue method. - */ - ; - - _proto.smartQuoteMark = function smartQuoteMark(options) { - var v = this.value; - var numSingleQuotes = v.replace(/[^']/g, '').length; - var numDoubleQuotes = v.replace(/[^"]/g, '').length; - - if (numSingleQuotes + numDoubleQuotes === 0) { - var escaped = (0, _cssesc.default)(v, { - isIdentifier: true - }); - - if (escaped === v) { - return Attribute.NO_QUOTE; - } else { - var pref = this.preferredQuoteMark(options); - - if (pref === Attribute.NO_QUOTE) { - // pick a quote mark that isn't none and see if it's smaller - var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE; - var opts = CSSESC_QUOTE_OPTIONS[quote]; - var quoteValue = (0, _cssesc.default)(v, opts); - - if (quoteValue.length < escaped.length) { - return quote; - } - } - - return pref; - } - } else if (numDoubleQuotes === numSingleQuotes) { - return this.preferredQuoteMark(options); - } else if (numDoubleQuotes < numSingleQuotes) { - return Attribute.DOUBLE_QUOTE; - } else { - return Attribute.SINGLE_QUOTE; - } - } - /** - * Selects the preferred quote mark based on the options and the current quote mark value. - * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)` - * instead. - */ - ; - - _proto.preferredQuoteMark = function preferredQuoteMark(options) { - var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark; - - if (quoteMark === undefined) { - quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark; - } - - if (quoteMark === undefined) { - quoteMark = Attribute.DOUBLE_QUOTE; - } - - return quoteMark; - }; - - _proto._syncRawValue = function _syncRawValue() { - var rawValue = (0, _cssesc.default)(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]); - - if (rawValue === this._value) { - if (this.raws) { - delete this.raws.value; - } - } else { - this.raws.value = rawValue; - } - }; - - _proto._handleEscapes = function _handleEscapes(prop, value) { - if (this._constructed) { - var escaped = (0, _cssesc.default)(value, { - isIdentifier: true - }); - - if (escaped !== value) { - this.raws[prop] = escaped; - } else { - delete this.raws[prop]; - } - } - }; - - _proto._spacesFor = function _spacesFor(name) { - var attrSpaces = { - before: '', - after: '' - }; - var spaces = this.spaces[name] || {}; - var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {}; - return Object.assign(attrSpaces, spaces, rawSpaces); - }; - - _proto._stringFor = function _stringFor(name, spaceName, concat) { - if (spaceName === void 0) { - spaceName = name; - } - - if (concat === void 0) { - concat = defaultAttrConcat; - } - - var attrSpaces = this._spacesFor(spaceName); - - return concat(this.stringifyProperty(name), attrSpaces); - } - /** - * returns the offset of the attribute part specified relative to the - * start of the node of the output string. - * - * * "ns" - alias for "namespace" - * * "namespace" - the namespace if it exists. - * * "attribute" - the attribute name - * * "attributeNS" - the start of the attribute or its namespace - * * "operator" - the match operator of the attribute - * * "value" - The value (string or identifier) - * * "insensitive" - the case insensitivity flag; - * @param part One of the possible values inside an attribute. - * @returns -1 if the name is invalid or the value doesn't exist in this attribute. - */ - ; - - _proto.offsetOf = function offsetOf(name) { - var count = 1; - - var attributeSpaces = this._spacesFor("attribute"); - - count += attributeSpaces.before.length; - - if (name === "namespace" || name === "ns") { - return this.namespace ? count : -1; - } - - if (name === "attributeNS") { - return count; - } - - count += this.namespaceString.length; - - if (this.namespace) { - count += 1; - } - - if (name === "attribute") { - return count; - } - - count += this.stringifyProperty("attribute").length; - count += attributeSpaces.after.length; - - var operatorSpaces = this._spacesFor("operator"); - - count += operatorSpaces.before.length; - var operator = this.stringifyProperty("operator"); - - if (name === "operator") { - return operator ? count : -1; - } - - count += operator.length; - count += operatorSpaces.after.length; - - var valueSpaces = this._spacesFor("value"); - - count += valueSpaces.before.length; - var value = this.stringifyProperty("value"); - - if (name === "value") { - return value ? count : -1; - } - - count += value.length; - count += valueSpaces.after.length; - - var insensitiveSpaces = this._spacesFor("insensitive"); - - count += insensitiveSpaces.before.length; - - if (name === "insensitive") { - return this.insensitive ? count : -1; - } - - return -1; - }; - - _proto.toString = function toString() { - var _this2 = this; - - var selector = [this.rawSpaceBefore, '[']; - selector.push(this._stringFor('qualifiedAttribute', 'attribute')); - - if (this.operator && (this.value || this.value === '')) { - selector.push(this._stringFor('operator')); - selector.push(this._stringFor('value')); - selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) { - if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) { - attrSpaces.before = " "; - } - - return defaultAttrConcat(attrValue, attrSpaces); - })); - } - - selector.push(']'); - selector.push(this.rawSpaceAfter); - return selector.join(''); - }; - - _createClass(Attribute, [{ - key: "quoted", - get: function get() { - var qm = this.quoteMark; - return qm === "'" || qm === '"'; - }, - set: function set(value) { - warnOfDeprecatedQuotedAssignment(); - } - /** - * returns a single (`'`) or double (`"`) quote character if the value is quoted. - * returns `null` if the value is not quoted. - * returns `undefined` if the quotation state is unknown (this can happen when - * the attribute is constructed without specifying a quote mark.) - */ - - }, { - key: "quoteMark", - get: function get() { - return this._quoteMark; - } - /** - * Set the quote mark to be used by this attribute's value. - * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute - * value is updated accordingly. - * - * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted. - */ - , - set: function set(quoteMark) { - if (!this._constructed) { - this._quoteMark = quoteMark; - return; - } - - if (this._quoteMark !== quoteMark) { - this._quoteMark = quoteMark; - - this._syncRawValue(); - } - } - }, { - key: "qualifiedAttribute", - get: function get() { - return this.qualifiedName(this.raws.attribute || this.attribute); - } - }, { - key: "insensitiveFlag", - get: function get() { - return this.insensitive ? 'i' : ''; - } - }, { - key: "value", - get: function get() { - return this._value; - } - /** - * Before 3.0, the value had to be set to an escaped value including any wrapped - * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value - * is unescaped during parsing and any quote marks are removed. - * - * Because the ambiguity of this semantic change, if you set `attr.value = newValue`, - * a deprecation warning is raised when the new value contains any characters that would - * require escaping (including if it contains wrapped quotes). - * - * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe - * how the new value is quoted. - */ - , - set: function set(v) { - if (this._constructed) { - var _unescapeValue2 = unescapeValue(v), - deprecatedUsage = _unescapeValue2.deprecatedUsage, - unescaped = _unescapeValue2.unescaped, - quoteMark = _unescapeValue2.quoteMark; - - if (deprecatedUsage) { - warnOfDeprecatedValueAssignment(); - } - - if (unescaped === this._value && quoteMark === this._quoteMark) { - return; - } - - this._value = unescaped; - this._quoteMark = quoteMark; - - this._syncRawValue(); - } else { - this._value = v; - } - } - }, { - key: "attribute", - get: function get() { - return this._attribute; - }, - set: function set(name) { - this._handleEscapes("attribute", name); - - this._attribute = name; - } - }]); - - return Attribute; -}(_namespace.default); - -exports.default = Attribute; -Attribute.NO_QUOTE = null; -Attribute.SINGLE_QUOTE = "'"; -Attribute.DOUBLE_QUOTE = '"'; -var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = { - "'": { - quotes: 'single', - wrap: true - }, - '"': { - quotes: 'double', - wrap: true - } -}, _CSSESC_QUOTE_OPTIONS[null] = { - isIdentifier: true -}, _CSSESC_QUOTE_OPTIONS); - -function defaultAttrConcat(attrValue, attrSpaces) { - return "" + attrSpaces.before + attrValue + attrSpaces.after; -} -}); - -var universal = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _namespace = _interopRequireDefault(namespace); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var Universal = -/*#__PURE__*/ -function (_Namespace) { - _inheritsLoose(Universal, _Namespace); - - function Universal(opts) { - var _this; - - _this = _Namespace.call(this, opts) || this; - _this.type = types.UNIVERSAL; - _this.value = '*'; - return _this; - } - - return Universal; -}(_namespace.default); - -exports.default = Universal; -module.exports = exports.default; -}); - -var combinator = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _node = _interopRequireDefault(node$1); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var Combinator = -/*#__PURE__*/ -function (_Node) { - _inheritsLoose(Combinator, _Node); - - function Combinator(opts) { - var _this; - - _this = _Node.call(this, opts) || this; - _this.type = types.COMBINATOR; - return _this; - } - - return Combinator; -}(_node.default); - -exports.default = Combinator; -module.exports = exports.default; -}); - -var nesting = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _node = _interopRequireDefault(node$1); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var Nesting = -/*#__PURE__*/ -function (_Node) { - _inheritsLoose(Nesting, _Node); - - function Nesting(opts) { - var _this; - - _this = _Node.call(this, opts) || this; - _this.type = types.NESTING; - _this.value = '&'; - return _this; - } - - return Nesting; -}(_node.default); - -exports.default = Nesting; -module.exports = exports.default; -}); - -var sortAscending_1 = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = sortAscending; - -function sortAscending(list) { - return list.sort(function (a, b) { - return a - b; - }); -} -module.exports = exports.default; -}); - -var tokenTypes = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.combinator = exports.word = exports.comment = exports.str = exports.tab = exports.newline = exports.feed = exports.cr = exports.backslash = exports.bang = exports.slash = exports.doubleQuote = exports.singleQuote = exports.space = exports.greaterThan = exports.pipe = exports.equals = exports.plus = exports.caret = exports.tilde = exports.dollar = exports.closeSquare = exports.openSquare = exports.closeParenthesis = exports.openParenthesis = exports.semicolon = exports.colon = exports.comma = exports.at = exports.asterisk = exports.ampersand = void 0; -var ampersand = 38; // `&`.charCodeAt(0); - -exports.ampersand = ampersand; -var asterisk = 42; // `*`.charCodeAt(0); - -exports.asterisk = asterisk; -var at = 64; // `@`.charCodeAt(0); - -exports.at = at; -var comma = 44; // `,`.charCodeAt(0); - -exports.comma = comma; -var colon = 58; // `:`.charCodeAt(0); - -exports.colon = colon; -var semicolon = 59; // `;`.charCodeAt(0); - -exports.semicolon = semicolon; -var openParenthesis = 40; // `(`.charCodeAt(0); - -exports.openParenthesis = openParenthesis; -var closeParenthesis = 41; // `)`.charCodeAt(0); - -exports.closeParenthesis = closeParenthesis; -var openSquare = 91; // `[`.charCodeAt(0); - -exports.openSquare = openSquare; -var closeSquare = 93; // `]`.charCodeAt(0); - -exports.closeSquare = closeSquare; -var dollar = 36; // `$`.charCodeAt(0); - -exports.dollar = dollar; -var tilde = 126; // `~`.charCodeAt(0); - -exports.tilde = tilde; -var caret = 94; // `^`.charCodeAt(0); - -exports.caret = caret; -var plus = 43; // `+`.charCodeAt(0); - -exports.plus = plus; -var equals = 61; // `=`.charCodeAt(0); - -exports.equals = equals; -var pipe = 124; // `|`.charCodeAt(0); - -exports.pipe = pipe; -var greaterThan = 62; // `>`.charCodeAt(0); - -exports.greaterThan = greaterThan; -var space = 32; // ` `.charCodeAt(0); - -exports.space = space; -var singleQuote = 39; // `'`.charCodeAt(0); - -exports.singleQuote = singleQuote; -var doubleQuote = 34; // `"`.charCodeAt(0); - -exports.doubleQuote = doubleQuote; -var slash = 47; // `/`.charCodeAt(0); - -exports.slash = slash; -var bang = 33; // `!`.charCodeAt(0); - -exports.bang = bang; -var backslash = 92; // '\\'.charCodeAt(0); - -exports.backslash = backslash; -var cr = 13; // '\r'.charCodeAt(0); - -exports.cr = cr; -var feed = 12; // '\f'.charCodeAt(0); - -exports.feed = feed; -var newline = 10; // '\n'.charCodeAt(0); - -exports.newline = newline; -var tab = 9; // '\t'.charCodeAt(0); -// Expose aliases primarily for readability. - -exports.tab = tab; -var str = singleQuote; // No good single character representation! - -exports.str = str; -var comment = -1; -exports.comment = comment; -var word = -2; -exports.word = word; -var combinator = -3; -exports.combinator = combinator; -}); - -var tokenize_1 = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = tokenize; -exports.FIELDS = void 0; - -var t = _interopRequireWildcard(tokenTypes); - -var _unescapable, _wordDelimiters; - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable); -var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters); -var hex = {}; -var hexChars = "0123456789abcdefABCDEF"; - -for (var i = 0; i < hexChars.length; i++) { - hex[hexChars.charCodeAt(i)] = true; -} -/** - * Returns the last index of the bar css word - * @param {string} css The string in which the word begins - * @param {number} start The index into the string where word's first letter occurs - */ - - -function consumeWord(css, start) { - var next = start; - var code; - - do { - code = css.charCodeAt(next); - - if (wordDelimiters[code]) { - return next - 1; - } else if (code === t.backslash) { - next = consumeEscape(css, next) + 1; - } else { - // All other characters are part of the word - next++; - } - } while (next < css.length); - - return next - 1; -} -/** - * Returns the last index of the escape sequence - * @param {string} css The string in which the sequence begins - * @param {number} start The index into the string where escape character (`\`) occurs. - */ - - -function consumeEscape(css, start) { - var next = start; - var code = css.charCodeAt(next + 1); - - if (unescapable[code]) ; else if (hex[code]) { - var hexDigits = 0; // consume up to 6 hex chars - - do { - next++; - hexDigits++; - code = css.charCodeAt(next + 1); - } while (hex[code] && hexDigits < 6); // if fewer than 6 hex chars, a trailing space ends the escape - - - if (hexDigits < 6 && code === t.space) { - next++; - } - } else { - // the next char is part of the current word - next++; - } - - return next; -} - -var FIELDS = { - TYPE: 0, - START_LINE: 1, - START_COL: 2, - END_LINE: 3, - END_COL: 4, - START_POS: 5, - END_POS: 6 -}; -exports.FIELDS = FIELDS; - -function tokenize(input) { - var tokens = []; - var css = input.css.valueOf(); - var _css = css, - length = _css.length; - var offset = -1; - var line = 1; - var start = 0; - var end = 0; - var code, content, endColumn, endLine, escaped, escapePos, last, lines, next, nextLine, nextOffset, quote, tokenType; - - function unclosed(what, fix) { - if (input.safe) { - // fyi: this is never set to true. - css += fix; - next = css.length - 1; - } else { - throw input.error('Unclosed ' + what, line, start - offset, start); - } - } - - while (start < length) { - code = css.charCodeAt(start); - - if (code === t.newline) { - offset = start; - line += 1; - } - - switch (code) { - case t.space: - case t.tab: - case t.newline: - case t.cr: - case t.feed: - next = start; - - do { - next += 1; - code = css.charCodeAt(next); - - if (code === t.newline) { - offset = next; - line += 1; - } - } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed); - - tokenType = t.space; - endLine = line; - endColumn = next - offset - 1; - end = next; - break; - - case t.plus: - case t.greaterThan: - case t.tilde: - case t.pipe: - next = start; - - do { - next += 1; - code = css.charCodeAt(next); - } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe); - - tokenType = t.combinator; - endLine = line; - endColumn = start - offset; - end = next; - break; - // Consume these characters as single tokens. - - case t.asterisk: - case t.ampersand: - case t.bang: - case t.comma: - case t.equals: - case t.dollar: - case t.caret: - case t.openSquare: - case t.closeSquare: - case t.colon: - case t.semicolon: - case t.openParenthesis: - case t.closeParenthesis: - next = start; - tokenType = code; - endLine = line; - endColumn = start - offset; - end = next + 1; - break; - - case t.singleQuote: - case t.doubleQuote: - quote = code === t.singleQuote ? "'" : '"'; - next = start; - - do { - escaped = false; - next = css.indexOf(quote, next + 1); - - if (next === -1) { - unclosed('quote', quote); - } - - escapePos = next; - - while (css.charCodeAt(escapePos - 1) === t.backslash) { - escapePos -= 1; - escaped = !escaped; - } - } while (escaped); - - tokenType = t.str; - endLine = line; - endColumn = start - offset; - end = next + 1; - break; - - default: - if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) { - next = css.indexOf('*/', start + 2) + 1; - - if (next === 0) { - unclosed('comment', '*/'); - } - - content = css.slice(start, next + 1); - lines = content.split('\n'); - last = lines.length - 1; - - if (last > 0) { - nextLine = line + last; - nextOffset = next - lines[last].length; - } else { - nextLine = line; - nextOffset = offset; - } - - tokenType = t.comment; - line = nextLine; - endLine = nextLine; - endColumn = next - nextOffset; - } else if (code === t.slash) { - next = start; - tokenType = code; - endLine = line; - endColumn = start - offset; - end = next + 1; - } else { - next = consumeWord(css, start); - tokenType = t.word; - endLine = line; - endColumn = next - offset; - } - - end = next + 1; - break; - } // Ensure that the token structure remains consistent - - - tokens.push([tokenType, // [0] Token type - line, // [1] Starting line - start - offset, // [2] Starting column - endLine, // [3] Ending line - endColumn, // [4] Ending column - start, // [5] Start position / Source index - end]); // Reset offset for the next token - - if (nextOffset) { - offset = nextOffset; - nextOffset = null; - } - - start = end; - } - - return tokens; -} -}); - -var parser = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _indexesOf = _interopRequireDefault(indexesOf); - -var _uniq = _interopRequireDefault(uniq); - -var _root = _interopRequireDefault(root); - -var _selector = _interopRequireDefault(selector); - -var _className = _interopRequireDefault(className); - -var _comment = _interopRequireDefault(comment); - -var _id = _interopRequireDefault(id); - -var _tag = _interopRequireDefault(tag); - -var _string = _interopRequireDefault(string); - -var _pseudo = _interopRequireDefault(pseudo); - -var _attribute = _interopRequireWildcard(attribute); - -var _universal = _interopRequireDefault(universal); - -var _combinator = _interopRequireDefault(combinator); - -var _nesting = _interopRequireDefault(nesting); - -var _sortAscending = _interopRequireDefault(sortAscending_1); - -var _tokenize = _interopRequireWildcard(tokenize_1); - -var tokens = _interopRequireWildcard(tokenTypes); - -var types$1 = _interopRequireWildcard(types); - - - -var _WHITESPACE_TOKENS, _Object$assign; - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS); -var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign)); - -function tokenStart(token) { - return { - line: token[_tokenize.FIELDS.START_LINE], - column: token[_tokenize.FIELDS.START_COL] - }; -} - -function tokenEnd(token) { - return { - line: token[_tokenize.FIELDS.END_LINE], - column: token[_tokenize.FIELDS.END_COL] - }; -} - -function getSource(startLine, startColumn, endLine, endColumn) { - return { - start: { - line: startLine, - column: startColumn - }, - end: { - line: endLine, - column: endColumn - } - }; -} - -function getTokenSource(token) { - return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]); -} - -function getTokenSourceSpan(startToken, endToken) { - if (!startToken) { - return undefined; - } - - return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]); -} - -function unescapeProp(node, prop) { - var value = node[prop]; - - if (typeof value !== "string") { - return; - } - - if (value.indexOf("\\") !== -1) { - (0, util.ensureObject)(node, 'raws'); - node[prop] = (0, util.unesc)(value); - - if (node.raws[prop] === undefined) { - node.raws[prop] = value; - } - } - - return node; -} - -var Parser = -/*#__PURE__*/ -function () { - function Parser(rule, options) { - if (options === void 0) { - options = {}; - } - - this.rule = rule; - this.options = Object.assign({ - lossy: false, - safe: false - }, options); - this.position = 0; - this.css = typeof this.rule === 'string' ? this.rule : this.rule.selector; - this.tokens = (0, _tokenize.default)({ - css: this.css, - error: this._errorGenerator(), - safe: this.options.safe - }); - var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]); - this.root = new _root.default({ - source: rootSource - }); - this.root.errorGenerator = this._errorGenerator(); - var selector = new _selector.default({ - source: { - start: { - line: 1, - column: 1 - } - } - }); - this.root.append(selector); - this.current = selector; - this.loop(); - } - - var _proto = Parser.prototype; - - _proto._errorGenerator = function _errorGenerator() { - var _this = this; - - return function (message, errorOptions) { - if (typeof _this.rule === 'string') { - return new Error(message); - } - - return _this.rule.error(message, errorOptions); - }; - }; - - _proto.attribute = function attribute() { - var attr = []; - var startingToken = this.currToken; - this.position++; - - while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) { - attr.push(this.currToken); - this.position++; - } - - if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) { - return this.expected('closing square bracket', this.currToken[_tokenize.FIELDS.START_POS]); - } - - var len = attr.length; - var node = { - source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]), - sourceIndex: startingToken[_tokenize.FIELDS.START_POS] - }; - - if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) { - return this.expected('attribute', attr[0][_tokenize.FIELDS.START_POS]); - } - - var pos = 0; - var spaceBefore = ''; - var commentBefore = ''; - var lastAdded = null; - var spaceAfterMeaningfulToken = false; - - while (pos < len) { - var token = attr[pos]; - var content = this.content(token); - var next = attr[pos + 1]; - - switch (token[_tokenize.FIELDS.TYPE]) { - case tokens.space: - // if ( - // len === 1 || - // pos === 0 && this.content(next) === '|' - // ) { - // return this.expected('attribute', token[TOKEN.START_POS], content); - // } - spaceAfterMeaningfulToken = true; - - if (this.options.lossy) { - break; - } - - if (lastAdded) { - (0, util.ensureObject)(node, 'spaces', lastAdded); - var prevContent = node.spaces[lastAdded].after || ''; - node.spaces[lastAdded].after = prevContent + content; - var existingComment = (0, util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || null; - - if (existingComment) { - node.raws.spaces[lastAdded].after = existingComment + content; - } - } else { - spaceBefore = spaceBefore + content; - commentBefore = commentBefore + content; - } - - break; - - case tokens.asterisk: - if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { - node.operator = content; - lastAdded = 'operator'; - } else if ((!node.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) { - if (spaceBefore) { - (0, util.ensureObject)(node, 'spaces', 'attribute'); - node.spaces.attribute.before = spaceBefore; - spaceBefore = ''; - } - - if (commentBefore) { - (0, util.ensureObject)(node, 'raws', 'spaces', 'attribute'); - node.raws.spaces.attribute.before = spaceBefore; - commentBefore = ''; - } - - node.namespace = (node.namespace || "") + content; - var rawValue = (0, util.getProp)(node, 'raws', 'namespace') || null; - - if (rawValue) { - node.raws.namespace += content; - } - - lastAdded = 'namespace'; - } - - spaceAfterMeaningfulToken = false; - break; - - case tokens.dollar: - if (lastAdded === "value") { - var oldRawValue = (0, util.getProp)(node, 'raws', 'value'); - node.value += "$"; - - if (oldRawValue) { - node.raws.value = oldRawValue + "$"; - } - - break; - } - - // Falls through - - case tokens.caret: - if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { - node.operator = content; - lastAdded = 'operator'; - } - - spaceAfterMeaningfulToken = false; - break; - - case tokens.combinator: - if (content === '~' && next[_tokenize.FIELDS.TYPE] === tokens.equals) { - node.operator = content; - lastAdded = 'operator'; - } - - if (content !== '|') { - spaceAfterMeaningfulToken = false; - break; - } - - if (next[_tokenize.FIELDS.TYPE] === tokens.equals) { - node.operator = content; - lastAdded = 'operator'; - } else if (!node.namespace && !node.attribute) { - node.namespace = true; - } - - spaceAfterMeaningfulToken = false; - break; - - case tokens.word: - if (next && this.content(next) === '|' && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals && // this look-ahead probably fails with comment nodes involved. - !node.operator && !node.namespace) { - node.namespace = content; - lastAdded = 'namespace'; - } else if (!node.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) { - if (spaceBefore) { - (0, util.ensureObject)(node, 'spaces', 'attribute'); - node.spaces.attribute.before = spaceBefore; - spaceBefore = ''; - } - - if (commentBefore) { - (0, util.ensureObject)(node, 'raws', 'spaces', 'attribute'); - node.raws.spaces.attribute.before = commentBefore; - commentBefore = ''; - } - - node.attribute = (node.attribute || "") + content; - - var _rawValue = (0, util.getProp)(node, 'raws', 'attribute') || null; - - if (_rawValue) { - node.raws.attribute += content; - } - - lastAdded = 'attribute'; - } else if (!node.value && node.value !== "" || lastAdded === "value" && !spaceAfterMeaningfulToken) { - var _unescaped = (0, util.unesc)(content); - - var _oldRawValue = (0, util.getProp)(node, 'raws', 'value') || ''; - - var oldValue = node.value || ''; - node.value = oldValue + _unescaped; - node.quoteMark = null; - - if (_unescaped !== content || _oldRawValue) { - (0, util.ensureObject)(node, 'raws'); - node.raws.value = (_oldRawValue || oldValue) + content; - } - - lastAdded = 'value'; - } else { - var insensitive = content === 'i' || content === "I"; - - if ((node.value || node.value === '') && (node.quoteMark || spaceAfterMeaningfulToken)) { - node.insensitive = insensitive; - - if (!insensitive || content === "I") { - (0, util.ensureObject)(node, 'raws'); - node.raws.insensitiveFlag = content; - } - - lastAdded = 'insensitive'; - - if (spaceBefore) { - (0, util.ensureObject)(node, 'spaces', 'insensitive'); - node.spaces.insensitive.before = spaceBefore; - spaceBefore = ''; - } - - if (commentBefore) { - (0, util.ensureObject)(node, 'raws', 'spaces', 'insensitive'); - node.raws.spaces.insensitive.before = commentBefore; - commentBefore = ''; - } - } else if (node.value || node.value === '') { - lastAdded = 'value'; - node.value += content; - - if (node.raws.value) { - node.raws.value += content; - } - } - } - - spaceAfterMeaningfulToken = false; - break; - - case tokens.str: - if (!node.attribute || !node.operator) { - return this.error("Expected an attribute followed by an operator preceding the string.", { - index: token[_tokenize.FIELDS.START_POS] - }); - } - - var _unescapeValue = (0, _attribute.unescapeValue)(content), - unescaped = _unescapeValue.unescaped, - quoteMark = _unescapeValue.quoteMark; - - node.value = unescaped; - node.quoteMark = quoteMark; - lastAdded = 'value'; - (0, util.ensureObject)(node, 'raws'); - node.raws.value = content; - spaceAfterMeaningfulToken = false; - break; - - case tokens.equals: - if (!node.attribute) { - return this.expected('attribute', token[_tokenize.FIELDS.START_POS], content); - } - - if (node.value) { - return this.error('Unexpected "=" found; an operator was already defined.', { - index: token[_tokenize.FIELDS.START_POS] - }); - } - - node.operator = node.operator ? node.operator + content : content; - lastAdded = 'operator'; - spaceAfterMeaningfulToken = false; - break; - - case tokens.comment: - if (lastAdded) { - if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === 'insensitive') { - var lastComment = (0, util.getProp)(node, 'spaces', lastAdded, 'after') || ''; - var rawLastComment = (0, util.getProp)(node, 'raws', 'spaces', lastAdded, 'after') || lastComment; - (0, util.ensureObject)(node, 'raws', 'spaces', lastAdded); - node.raws.spaces[lastAdded].after = rawLastComment + content; - } else { - var lastValue = node[lastAdded] || ''; - var rawLastValue = (0, util.getProp)(node, 'raws', lastAdded) || lastValue; - (0, util.ensureObject)(node, 'raws'); - node.raws[lastAdded] = rawLastValue + content; - } - } else { - commentBefore = commentBefore + content; - } - - break; - - default: - return this.error("Unexpected \"" + content + "\" found.", { - index: token[_tokenize.FIELDS.START_POS] - }); - } - - pos++; - } - - unescapeProp(node, "attribute"); - unescapeProp(node, "namespace"); - this.newNode(new _attribute.default(node)); - this.position++; - } - /** - * return a node containing meaningless garbage up to (but not including) the specified token position. - * if the token position is negative, all remaining tokens are consumed. - * - * This returns an array containing a single string node if all whitespace, - * otherwise an array of comment nodes with space before and after. - * - * These tokens are not added to the current selector, the caller can add them or use them to amend - * a previous node's space metadata. - * - * In lossy mode, this returns only comments. - */ - ; - - _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) { - if (stopPosition < 0) { - stopPosition = this.tokens.length; - } - - var startPosition = this.position; - var nodes = []; - var space = ""; - var lastComment = undefined; - - do { - if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) { - if (!this.options.lossy) { - space += this.content(); - } - } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) { - var spaces = {}; - - if (space) { - spaces.before = space; - space = ""; - } - - lastComment = new _comment.default({ - value: this.content(), - source: getTokenSource(this.currToken), - sourceIndex: this.currToken[_tokenize.FIELDS.START_POS], - spaces: spaces - }); - nodes.push(lastComment); - } - } while (++this.position < stopPosition); - - if (space) { - if (lastComment) { - lastComment.spaces.after = space; - } else if (!this.options.lossy) { - var firstToken = this.tokens[startPosition]; - var lastToken = this.tokens[this.position - 1]; - nodes.push(new _string.default({ - value: '', - source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]), - sourceIndex: firstToken[_tokenize.FIELDS.START_POS], - spaces: { - before: space, - after: '' - } - })); - } - } - - return nodes; - } - /** - * - * @param {*} nodes - */ - ; - - _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) { - var _this2 = this; - - if (requiredSpace === void 0) { - requiredSpace = false; - } - - var space = ""; - var rawSpace = ""; - nodes.forEach(function (n) { - var spaceBefore = _this2.lossySpace(n.spaces.before, requiredSpace); - - var rawSpaceBefore = _this2.lossySpace(n.rawSpaceBefore, requiredSpace); - - space += spaceBefore + _this2.lossySpace(n.spaces.after, requiredSpace && spaceBefore.length === 0); - rawSpace += spaceBefore + n.value + _this2.lossySpace(n.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0); - }); - - if (rawSpace === space) { - rawSpace = undefined; - } - - var result = { - space: space, - rawSpace: rawSpace - }; - return result; - }; - - _proto.isNamedCombinator = function isNamedCombinator(position) { - if (position === void 0) { - position = this.position; - } - - return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash; - }; - - _proto.namedCombinator = function namedCombinator() { - if (this.isNamedCombinator()) { - var nameRaw = this.content(this.tokens[this.position + 1]); - var name = (0, util.unesc)(nameRaw).toLowerCase(); - var raws = {}; - - if (name !== nameRaw) { - raws.value = "/" + nameRaw + "/"; - } - - var node = new _combinator.default({ - value: "/" + name + "/", - source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]), - sourceIndex: this.currToken[_tokenize.FIELDS.START_POS], - raws: raws - }); - this.position = this.position + 3; - return node; - } else { - this.unexpected(); - } - }; - - _proto.combinator = function combinator() { - var _this3 = this; - - if (this.content() === '|') { - return this.namespace(); - } // We need to decide between a space that's a descendant combinator and meaningless whitespace at the end of a selector. - - - var nextSigTokenPos = this.locateNextMeaningfulToken(this.position); - - if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) { - var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos); - - if (nodes.length > 0) { - var last = this.current.last; - - if (last) { - var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes), - space = _this$convertWhitespa.space, - rawSpace = _this$convertWhitespa.rawSpace; - - if (rawSpace !== undefined) { - last.rawSpaceAfter += rawSpace; - } - - last.spaces.after += space; - } else { - nodes.forEach(function (n) { - return _this3.newNode(n); - }); - } - } - - return; - } - - var firstToken = this.currToken; - var spaceOrDescendantSelectorNodes = undefined; - - if (nextSigTokenPos > this.position) { - spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos); - } - - var node; - - if (this.isNamedCombinator()) { - node = this.namedCombinator(); - } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) { - node = new _combinator.default({ - value: this.content(), - source: getTokenSource(this.currToken), - sourceIndex: this.currToken[_tokenize.FIELDS.START_POS] - }); - this.position++; - } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) ; else if (!spaceOrDescendantSelectorNodes) { - this.unexpected(); - } - - if (node) { - if (spaceOrDescendantSelectorNodes) { - var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes), - _space = _this$convertWhitespa2.space, - _rawSpace = _this$convertWhitespa2.rawSpace; - - node.spaces.before = _space; - node.rawSpaceBefore = _rawSpace; - } - } else { - // descendant combinator - var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true), - _space2 = _this$convertWhitespa3.space, - _rawSpace2 = _this$convertWhitespa3.rawSpace; - - if (!_rawSpace2) { - _rawSpace2 = _space2; - } - - var spaces = {}; - var raws = { - spaces: {} - }; - - if (_space2.endsWith(' ') && _rawSpace2.endsWith(' ')) { - spaces.before = _space2.slice(0, _space2.length - 1); - raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1); - } else if (_space2.startsWith(' ') && _rawSpace2.startsWith(' ')) { - spaces.after = _space2.slice(1); - raws.spaces.after = _rawSpace2.slice(1); - } else { - raws.value = _rawSpace2; - } - - node = new _combinator.default({ - value: ' ', - source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]), - sourceIndex: firstToken[_tokenize.FIELDS.START_POS], - spaces: spaces, - raws: raws - }); - } - - if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) { - node.spaces.after = this.optionalSpace(this.content()); - this.position++; - } - - return this.newNode(node); - }; - - _proto.comma = function comma() { - if (this.position === this.tokens.length - 1) { - this.root.trailingComma = true; - this.position++; - return; - } - - this.current._inferEndPosition(); - - var selector = new _selector.default({ - source: { - start: tokenStart(this.tokens[this.position + 1]) - } - }); - this.current.parent.append(selector); - this.current = selector; - this.position++; - }; - - _proto.comment = function comment() { - var current = this.currToken; - this.newNode(new _comment.default({ - value: this.content(), - source: getTokenSource(current), - sourceIndex: current[_tokenize.FIELDS.START_POS] - })); - this.position++; - }; - - _proto.error = function error(message, opts) { - throw this.root.error(message, opts); - }; - - _proto.missingBackslash = function missingBackslash() { - return this.error('Expected a backslash preceding the semicolon.', { - index: this.currToken[_tokenize.FIELDS.START_POS] - }); - }; - - _proto.missingParenthesis = function missingParenthesis() { - return this.expected('opening parenthesis', this.currToken[_tokenize.FIELDS.START_POS]); - }; - - _proto.missingSquareBracket = function missingSquareBracket() { - return this.expected('opening square bracket', this.currToken[_tokenize.FIELDS.START_POS]); - }; - - _proto.unexpected = function unexpected() { - return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]); - }; - - _proto.namespace = function namespace() { - var before = this.prevToken && this.content(this.prevToken) || true; - - if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) { - this.position++; - return this.word(before); - } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) { - this.position++; - return this.universal(before); - } - }; - - _proto.nesting = function nesting() { - if (this.nextToken) { - var nextContent = this.content(this.nextToken); - - if (nextContent === "|") { - this.position++; - return; - } - } - - var current = this.currToken; - this.newNode(new _nesting.default({ - value: this.content(), - source: getTokenSource(current), - sourceIndex: current[_tokenize.FIELDS.START_POS] - })); - this.position++; - }; - - _proto.parentheses = function parentheses() { - var last = this.current.last; - var unbalanced = 1; - this.position++; - - if (last && last.type === types$1.PSEUDO) { - var selector = new _selector.default({ - source: { - start: tokenStart(this.tokens[this.position - 1]) - } - }); - var cache = this.current; - last.append(selector); - this.current = selector; - - while (this.position < this.tokens.length && unbalanced) { - if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { - unbalanced++; - } - - if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { - unbalanced--; - } - - if (unbalanced) { - this.parse(); - } else { - this.current.source.end = tokenEnd(this.currToken); - this.current.parent.source.end = tokenEnd(this.currToken); - this.position++; - } - } - - this.current = cache; - } else { - // I think this case should be an error. It's used to implement a basic parse of media queries - // but I don't think it's a good idea. - var parenStart = this.currToken; - var parenValue = "("; - var parenEnd; - - while (this.position < this.tokens.length && unbalanced) { - if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { - unbalanced++; - } - - if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { - unbalanced--; - } - - parenEnd = this.currToken; - parenValue += this.parseParenthesisToken(this.currToken); - this.position++; - } - - if (last) { - last.appendToPropertyAndEscape("value", parenValue, parenValue); - } else { - this.newNode(new _string.default({ - value: parenValue, - source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]), - sourceIndex: parenStart[_tokenize.FIELDS.START_POS] - })); - } - } - - if (unbalanced) { - return this.expected('closing parenthesis', this.currToken[_tokenize.FIELDS.START_POS]); - } - }; - - _proto.pseudo = function pseudo() { - var _this4 = this; - - var pseudoStr = ''; - var startingToken = this.currToken; - - while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) { - pseudoStr += this.content(); - this.position++; - } - - if (!this.currToken) { - return this.expected(['pseudo-class', 'pseudo-element'], this.position - 1); - } - - if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) { - this.splitWord(false, function (first, length) { - pseudoStr += first; - - _this4.newNode(new _pseudo.default({ - value: pseudoStr, - source: getTokenSourceSpan(startingToken, _this4.currToken), - sourceIndex: startingToken[_tokenize.FIELDS.START_POS] - })); - - if (length > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) { - _this4.error('Misplaced parenthesis.', { - index: _this4.nextToken[_tokenize.FIELDS.START_POS] - }); - } - }); - } else { - return this.expected(['pseudo-class', 'pseudo-element'], this.currToken[_tokenize.FIELDS.START_POS]); - } - }; - - _proto.space = function space() { - var content = this.content(); // Handle space before and after the selector - - if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function (node) { - return node.type === 'comment'; - })) { - this.spaces = this.optionalSpace(content); - this.position++; - } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) { - this.current.last.spaces.after = this.optionalSpace(content); - this.position++; - } else { - this.combinator(); - } - }; - - _proto.string = function string() { - var current = this.currToken; - this.newNode(new _string.default({ - value: this.content(), - source: getTokenSource(current), - sourceIndex: current[_tokenize.FIELDS.START_POS] - })); - this.position++; - }; - - _proto.universal = function universal(namespace) { - var nextToken = this.nextToken; - - if (nextToken && this.content(nextToken) === '|') { - this.position++; - return this.namespace(); - } - - var current = this.currToken; - this.newNode(new _universal.default({ - value: this.content(), - source: getTokenSource(current), - sourceIndex: current[_tokenize.FIELDS.START_POS] - }), namespace); - this.position++; - }; - - _proto.splitWord = function splitWord(namespace, firstCallback) { - var _this5 = this; - - var nextToken = this.nextToken; - var word = this.content(); - - while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) { - this.position++; - var current = this.content(); - word += current; - - if (current.lastIndexOf('\\') === current.length - 1) { - var next = this.nextToken; - - if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) { - word += this.requiredSpace(this.content(next)); - this.position++; - } - } - - nextToken = this.nextToken; - } - - var hasClass = (0, _indexesOf.default)(word, '.').filter(function (i) { - return word[i - 1] !== '\\'; - }); - var hasId = (0, _indexesOf.default)(word, '#').filter(function (i) { - return word[i - 1] !== '\\'; - }); // Eliminate Sass interpolations from the list of id indexes - - var interpolations = (0, _indexesOf.default)(word, '#{'); - - if (interpolations.length) { - hasId = hasId.filter(function (hashIndex) { - return !~interpolations.indexOf(hashIndex); - }); - } - - var indices = (0, _sortAscending.default)((0, _uniq.default)([0].concat(hasClass, hasId))); - indices.forEach(function (ind, i) { - var index = indices[i + 1] || word.length; - var value = word.slice(ind, index); - - if (i === 0 && firstCallback) { - return firstCallback.call(_this5, value, indices.length); - } - - var node; - var current = _this5.currToken; - var sourceIndex = current[_tokenize.FIELDS.START_POS] + indices[i]; - var source = getSource(current[1], current[2] + ind, current[3], current[2] + (index - 1)); - - if (~hasClass.indexOf(ind)) { - var classNameOpts = { - value: value.slice(1), - source: source, - sourceIndex: sourceIndex - }; - node = new _className.default(unescapeProp(classNameOpts, "value")); - } else if (~hasId.indexOf(ind)) { - var idOpts = { - value: value.slice(1), - source: source, - sourceIndex: sourceIndex - }; - node = new _id.default(unescapeProp(idOpts, "value")); - } else { - var tagOpts = { - value: value, - source: source, - sourceIndex: sourceIndex - }; - unescapeProp(tagOpts, "value"); - node = new _tag.default(tagOpts); - } - - _this5.newNode(node, namespace); // Ensure that the namespace is used only once - - - namespace = null; - }); - this.position++; - }; - - _proto.word = function word(namespace) { - var nextToken = this.nextToken; - - if (nextToken && this.content(nextToken) === '|') { - this.position++; - return this.namespace(); - } - - return this.splitWord(namespace); - }; - - _proto.loop = function loop() { - while (this.position < this.tokens.length) { - this.parse(true); - } - - this.current._inferEndPosition(); - - return this.root; - }; - - _proto.parse = function parse(throwOnParenthesis) { - switch (this.currToken[_tokenize.FIELDS.TYPE]) { - case tokens.space: - this.space(); - break; - - case tokens.comment: - this.comment(); - break; - - case tokens.openParenthesis: - this.parentheses(); - break; - - case tokens.closeParenthesis: - if (throwOnParenthesis) { - this.missingParenthesis(); - } - - break; - - case tokens.openSquare: - this.attribute(); - break; - - case tokens.dollar: - case tokens.caret: - case tokens.equals: - case tokens.word: - this.word(); - break; - - case tokens.colon: - this.pseudo(); - break; - - case tokens.comma: - this.comma(); - break; - - case tokens.asterisk: - this.universal(); - break; - - case tokens.ampersand: - this.nesting(); - break; - - case tokens.slash: - case tokens.combinator: - this.combinator(); - break; - - case tokens.str: - this.string(); - break; - // These cases throw; no break needed. - - case tokens.closeSquare: - this.missingSquareBracket(); - - case tokens.semicolon: - this.missingBackslash(); - - default: - this.unexpected(); - } - } - /** - * Helpers - */ - ; - - _proto.expected = function expected(description, index, found) { - if (Array.isArray(description)) { - var last = description.pop(); - description = description.join(', ') + " or " + last; - } - - var an = /^[aeiou]/.test(description[0]) ? 'an' : 'a'; - - if (!found) { - return this.error("Expected " + an + " " + description + ".", { - index: index - }); - } - - return this.error("Expected " + an + " " + description + ", found \"" + found + "\" instead.", { - index: index - }); - }; - - _proto.requiredSpace = function requiredSpace(space) { - return this.options.lossy ? ' ' : space; - }; - - _proto.optionalSpace = function optionalSpace(space) { - return this.options.lossy ? '' : space; - }; - - _proto.lossySpace = function lossySpace(space, required) { - if (this.options.lossy) { - return required ? ' ' : ''; - } else { - return space; - } - }; - - _proto.parseParenthesisToken = function parseParenthesisToken(token) { - var content = this.content(token); - - if (token[_tokenize.FIELDS.TYPE] === tokens.space) { - return this.requiredSpace(content); - } else { - return content; - } - }; - - _proto.newNode = function newNode(node, namespace) { - if (namespace) { - if (/^ +$/.test(namespace)) { - if (!this.options.lossy) { - this.spaces = (this.spaces || '') + namespace; - } - - namespace = true; - } - - node.namespace = namespace; - unescapeProp(node, "namespace"); - } - - if (this.spaces) { - node.spaces.before = this.spaces; - this.spaces = ''; - } - - return this.current.append(node); - }; - - _proto.content = function content(token) { - if (token === void 0) { - token = this.currToken; - } - - return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]); - }; - - /** - * returns the index of the next non-whitespace, non-comment token. - * returns -1 if no meaningful token is found. - */ - _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) { - if (startPosition === void 0) { - startPosition = this.position + 1; - } - - var searchPosition = startPosition; - - while (searchPosition < this.tokens.length) { - if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) { - searchPosition++; - continue; - } else { - return searchPosition; - } - } - - return -1; - }; - - _createClass(Parser, [{ - key: "currToken", - get: function get() { - return this.tokens[this.position]; - } - }, { - key: "nextToken", - get: function get() { - return this.tokens[this.position + 1]; - } - }, { - key: "prevToken", - get: function get() { - return this.tokens[this.position - 1]; - } - }]); - - return Parser; -}(); - -exports.default = Parser; -module.exports = exports.default; -}); - -var processor = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _parser = _interopRequireDefault(parser); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var Processor = -/*#__PURE__*/ -function () { - function Processor(func, options) { - this.func = func || function noop() {}; - - this.funcRes = null; - this.options = options; - } - - var _proto = Processor.prototype; - - _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule, options) { - if (options === void 0) { - options = {}; - } - - var merged = Object.assign({}, this.options, options); - - if (merged.updateSelector === false) { - return false; - } else { - return typeof rule !== "string"; - } - }; - - _proto._isLossy = function _isLossy(options) { - if (options === void 0) { - options = {}; - } - - var merged = Object.assign({}, this.options, options); - - if (merged.lossless === false) { - return true; - } else { - return false; - } - }; - - _proto._root = function _root(rule, options) { - if (options === void 0) { - options = {}; - } - - var parser = new _parser.default(rule, this._parseOptions(options)); - return parser.root; - }; - - _proto._parseOptions = function _parseOptions(options) { - return { - lossy: this._isLossy(options) - }; - }; - - _proto._run = function _run(rule, options) { - var _this = this; - - if (options === void 0) { - options = {}; - } - - return new Promise(function (resolve, reject) { - try { - var root = _this._root(rule, options); - - Promise.resolve(_this.func(root)).then(function (transform) { - var string = undefined; - - if (_this._shouldUpdateSelector(rule, options)) { - string = root.toString(); - rule.selector = string; - } - - return { - transform: transform, - root: root, - string: string - }; - }).then(resolve, reject); - } catch (e) { - reject(e); - return; - } - }); - }; - - _proto._runSync = function _runSync(rule, options) { - if (options === void 0) { - options = {}; - } - - var root = this._root(rule, options); - - var transform = this.func(root); - - if (transform && typeof transform.then === "function") { - throw new Error("Selector processor returned a promise to a synchronous call."); - } - - var string = undefined; - - if (options.updateSelector && typeof rule !== "string") { - string = root.toString(); - rule.selector = string; - } - - return { - transform: transform, - root: root, - string: string - }; - } - /** - * Process rule into a selector AST. - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {Promise} The AST of the selector after processing it. - */ - ; - - _proto.ast = function ast(rule, options) { - return this._run(rule, options).then(function (result) { - return result.root; - }); - } - /** - * Process rule into a selector AST synchronously. - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {parser.Root} The AST of the selector after processing it. - */ - ; - - _proto.astSync = function astSync(rule, options) { - return this._runSync(rule, options).root; - } - /** - * Process a selector into a transformed value asynchronously - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {Promise} The value returned by the processor. - */ - ; - - _proto.transform = function transform(rule, options) { - return this._run(rule, options).then(function (result) { - return result.transform; - }); - } - /** - * Process a selector into a transformed value synchronously. - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {any} The value returned by the processor. - */ - ; - - _proto.transformSync = function transformSync(rule, options) { - return this._runSync(rule, options).transform; - } - /** - * Process a selector into a new selector string asynchronously. - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {string} the selector after processing. - */ - ; - - _proto.process = function process(rule, options) { - return this._run(rule, options).then(function (result) { - return result.string || result.root.toString(); - }); - } - /** - * Process a selector into a new selector string synchronously. - * - * @param rule {postcss.Rule | string} The css selector to be processed - * @param options The options for processing - * @returns {string} the selector after processing. - */ - ; - - _proto.processSync = function processSync(rule, options) { - var result = this._runSync(rule, options); - - return result.string || result.root.toString(); - }; - - return Processor; -}(); - -exports.default = Processor; -module.exports = exports.default; -}); - -var constructors = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.universal = exports.tag = exports.string = exports.selector = exports.root = exports.pseudo = exports.nesting = exports.id = exports.comment = exports.combinator = exports.className = exports.attribute = void 0; - -var _attribute = _interopRequireDefault(attribute); - -var _className = _interopRequireDefault(className); - -var _combinator = _interopRequireDefault(combinator); - -var _comment = _interopRequireDefault(comment); - -var _id = _interopRequireDefault(id); - -var _nesting = _interopRequireDefault(nesting); - -var _pseudo = _interopRequireDefault(pseudo); - -var _root = _interopRequireDefault(root); - -var _selector = _interopRequireDefault(selector); - -var _string = _interopRequireDefault(string); - -var _tag = _interopRequireDefault(tag); - -var _universal = _interopRequireDefault(universal); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var attribute$1 = function attribute(opts) { - return new _attribute.default(opts); -}; - -exports.attribute = attribute$1; - -var className$1 = function className(opts) { - return new _className.default(opts); -}; - -exports.className = className$1; - -var combinator$1 = function combinator(opts) { - return new _combinator.default(opts); -}; - -exports.combinator = combinator$1; - -var comment$1 = function comment(opts) { - return new _comment.default(opts); -}; - -exports.comment = comment$1; - -var id$1 = function id(opts) { - return new _id.default(opts); -}; - -exports.id = id$1; - -var nesting$1 = function nesting(opts) { - return new _nesting.default(opts); -}; - -exports.nesting = nesting$1; - -var pseudo$1 = function pseudo(opts) { - return new _pseudo.default(opts); -}; - -exports.pseudo = pseudo$1; - -var root$1 = function root(opts) { - return new _root.default(opts); -}; - -exports.root = root$1; - -var selector$1 = function selector(opts) { - return new _selector.default(opts); -}; - -exports.selector = selector$1; - -var string$1 = function string(opts) { - return new _string.default(opts); -}; - -exports.string = string$1; - -var tag$1 = function tag(opts) { - return new _tag.default(opts); -}; - -exports.tag = tag$1; - -var universal$1 = function universal(opts) { - return new _universal.default(opts); -}; - -exports.universal = universal$1; -}); - -var guards = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.isNode = isNode; -exports.isPseudoElement = isPseudoElement; -exports.isPseudoClass = isPseudoClass; -exports.isContainer = isContainer; -exports.isNamespace = isNamespace; -exports.isUniversal = exports.isTag = exports.isString = exports.isSelector = exports.isRoot = exports.isPseudo = exports.isNesting = exports.isIdentifier = exports.isComment = exports.isCombinator = exports.isClassName = exports.isAttribute = void 0; - - - -var _IS_TYPE; - -var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[types.ATTRIBUTE] = true, _IS_TYPE[types.CLASS] = true, _IS_TYPE[types.COMBINATOR] = true, _IS_TYPE[types.COMMENT] = true, _IS_TYPE[types.ID] = true, _IS_TYPE[types.NESTING] = true, _IS_TYPE[types.PSEUDO] = true, _IS_TYPE[types.ROOT] = true, _IS_TYPE[types.SELECTOR] = true, _IS_TYPE[types.STRING] = true, _IS_TYPE[types.TAG] = true, _IS_TYPE[types.UNIVERSAL] = true, _IS_TYPE); - -function isNode(node) { - return typeof node === "object" && IS_TYPE[node.type]; -} - -function isNodeType(type, node) { - return isNode(node) && node.type === type; -} - -var isAttribute = isNodeType.bind(null, types.ATTRIBUTE); -exports.isAttribute = isAttribute; -var isClassName = isNodeType.bind(null, types.CLASS); -exports.isClassName = isClassName; -var isCombinator = isNodeType.bind(null, types.COMBINATOR); -exports.isCombinator = isCombinator; -var isComment = isNodeType.bind(null, types.COMMENT); -exports.isComment = isComment; -var isIdentifier = isNodeType.bind(null, types.ID); -exports.isIdentifier = isIdentifier; -var isNesting = isNodeType.bind(null, types.NESTING); -exports.isNesting = isNesting; -var isPseudo = isNodeType.bind(null, types.PSEUDO); -exports.isPseudo = isPseudo; -var isRoot = isNodeType.bind(null, types.ROOT); -exports.isRoot = isRoot; -var isSelector = isNodeType.bind(null, types.SELECTOR); -exports.isSelector = isSelector; -var isString = isNodeType.bind(null, types.STRING); -exports.isString = isString; -var isTag = isNodeType.bind(null, types.TAG); -exports.isTag = isTag; -var isUniversal = isNodeType.bind(null, types.UNIVERSAL); -exports.isUniversal = isUniversal; - -function isPseudoElement(node) { - return isPseudo(node) && node.value && (node.value.startsWith("::") || node.value.toLowerCase() === ":before" || node.value.toLowerCase() === ":after"); -} - -function isPseudoClass(node) { - return isPseudo(node) && !isPseudoElement(node); -} - -function isContainer(node) { - return !!(isNode(node) && node.walk); -} - -function isNamespace(node) { - return isAttribute(node) || isTag(node); -} -}); - -var selectors = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; - - - -Object.keys(types).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - exports[key] = types[key]; -}); - - - -Object.keys(constructors).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - exports[key] = constructors[key]; -}); - - - -Object.keys(guards).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - exports[key] = guards[key]; -}); -}); - -var dist = build$1.createCommonjsModule(function (module, exports) { - -exports.__esModule = true; -exports.default = void 0; - -var _processor = _interopRequireDefault(processor); - -var selectors$1 = _interopRequireWildcard(selectors); - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var parser = function parser(processor) { - return new _processor.default(processor); -}; - -Object.assign(parser, selectors$1); -delete parser.__esModule; -var _default = parser; -exports.default = _default; -module.exports = exports.default; -}); - -const matchValueName = /[$]?[\w-]+/g; - -const replaceValueSymbols = (value, replacements) => { - let matches; - - while ((matches = matchValueName.exec(value))) { - const replacement = replacements[matches[0]]; - - if (replacement) { - value = - value.slice(0, matches.index) + - replacement + - value.slice(matchValueName.lastIndex); - - matchValueName.lastIndex -= matches[0].length - replacement.length; - } - } - - return value; -}; - -var replaceValueSymbols_1 = replaceValueSymbols; - -const replaceSymbols = (css, replacements) => { - css.walk((node) => { - if (node.type === "decl" && node.value) { - node.value = replaceValueSymbols_1(node.value.toString(), replacements); - } else if (node.type === "rule" && node.selector) { - node.selector = replaceValueSymbols_1( - node.selector.toString(), - replacements - ); - } else if (node.type === "atrule" && node.params) { - node.params = replaceValueSymbols_1(node.params.toString(), replacements); - } - }); -}; - -var replaceSymbols_1 = replaceSymbols; - -const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/; -const balancedQuotes = /^("[^"]*"|'[^']*'|[^"']+)$/; - -const getDeclsObject = (rule) => { - const object = {}; - - rule.walkDecls((decl) => { - const before = decl.raws.before ? decl.raws.before.trim() : ""; - - object[before + decl.prop] = decl.value; - }); - - return object; -}; -/** - * - * @param {string} css - * @param {boolean} removeRules - * @param {'auto' | 'rule' | 'at-rule'} mode - */ -const extractICSS$1 = (css, removeRules = true, mode = "auto") => { - const icssImports = {}; - const icssExports = {}; - - function addImports(node, path) { - const unquoted = path.replace(/'|"/g, ""); - icssImports[unquoted] = Object.assign( - icssImports[unquoted] || {}, - getDeclsObject(node) - ); - - if (removeRules) { - node.remove(); - } - } - - function addExports(node) { - Object.assign(icssExports, getDeclsObject(node)); - if (removeRules) { - node.remove(); - } - } - - css.each((node) => { - if (node.type === "rule" && mode !== "at-rule") { - if (node.selector.slice(0, 7) === ":import") { - const matches = importPattern.exec(node.selector); - - if (matches) { - addImports(node, matches[1]); - } - } - - if (node.selector === ":export") { - addExports(node); - } - } - - if (node.type === "atrule" && mode !== "rule") { - if (node.name === "icss-import") { - const matches = balancedQuotes.exec(node.params); - - if (matches) { - addImports(node, matches[1]); - } - } - if (node.name === "icss-export") { - addExports(node); - } - } - }); - - return { icssImports, icssExports }; -}; - -var extractICSS_1 = extractICSS$1; - -const createImports = (imports, postcss, mode = "rule") => { - return Object.keys(imports).map((path) => { - const aliases = imports[path]; - const declarations = Object.keys(aliases).map((key) => - postcss.decl({ - prop: key, - value: aliases[key], - raws: { before: "\n " }, - }) - ); - - const hasDeclarations = declarations.length > 0; - - const rule = - mode === "rule" - ? postcss.rule({ - selector: `:import('${path}')`, - raws: { after: hasDeclarations ? "\n" : "" }, - }) - : postcss.atRule({ - name: "icss-import", - params: `'${path}'`, - raws: { after: hasDeclarations ? "\n" : "" }, - }); - - if (hasDeclarations) { - rule.append(declarations); - } - - return rule; - }); -}; - -const createExports = (exports, postcss, mode = "rule") => { - const declarations = Object.keys(exports).map((key) => - postcss.decl({ - prop: key, - value: exports[key], - raws: { before: "\n " }, - }) - ); - - if (declarations.length === 0) { - return []; - } - const rule = - mode === "rule" - ? postcss.rule({ - selector: `:export`, - raws: { after: "\n" }, - }) - : postcss.atRule({ - name: "icss-export", - raws: { after: "\n" }, - }); - - rule.append(declarations); - - return [rule]; -}; - -const createICSSRules = (imports, exports, postcss, mode) => [ - ...createImports(imports, postcss, mode), - ...createExports(exports, postcss, mode), -]; - -var createICSSRules_1 = createICSSRules; - -var src$4 = { - replaceValueSymbols: replaceValueSymbols_1, - replaceSymbols: replaceSymbols_1, - extractICSS: extractICSS_1, - createICSSRules: createICSSRules_1, -}; - -const { extractICSS } = src$4; - -const isSpacing = (node) => node.type === "combinator" && node.value === " "; - -function normalizeNodeArray(nodes) { - const array = []; - - nodes.forEach((x) => { - if (Array.isArray(x)) { - normalizeNodeArray(x).forEach((item) => { - array.push(item); - }); - } else if (x) { - array.push(x); - } - }); - - if (array.length > 0 && isSpacing(array[array.length - 1])) { - array.pop(); - } - return array; -} - -function localizeNode(rule, mode, localAliasMap) { - const transform = (node, context) => { - if (context.ignoreNextSpacing && !isSpacing(node)) { - throw new Error("Missing whitespace after " + context.ignoreNextSpacing); - } - - if (context.enforceNoSpacing && isSpacing(node)) { - throw new Error("Missing whitespace before " + context.enforceNoSpacing); - } - - let newNodes; - - switch (node.type) { - case "root": { - let resultingGlobal; - - context.hasPureGlobals = false; - - newNodes = node.nodes.map((n) => { - const nContext = { - global: context.global, - lastWasSpacing: true, - hasLocals: false, - explicit: false, - }; - - n = transform(n, nContext); - - if (typeof resultingGlobal === "undefined") { - resultingGlobal = nContext.global; - } else if (resultingGlobal !== nContext.global) { - throw new Error( - 'Inconsistent rule global/local result in rule "' + - node + - '" (multiple selectors must result in the same mode for the rule)' - ); - } - - if (!nContext.hasLocals) { - context.hasPureGlobals = true; - } - - return n; - }); - - context.global = resultingGlobal; - - node.nodes = normalizeNodeArray(newNodes); - break; - } - case "selector": { - newNodes = node.map((childNode) => transform(childNode, context)); - - node = node.clone(); - node.nodes = normalizeNodeArray(newNodes); - break; - } - case "combinator": { - if (isSpacing(node)) { - if (context.ignoreNextSpacing) { - context.ignoreNextSpacing = false; - context.lastWasSpacing = false; - context.enforceNoSpacing = false; - return null; - } - context.lastWasSpacing = true; - return node; - } - break; - } - case "pseudo": { - let childContext; - const isNested = !!node.length; - const isScoped = node.value === ":local" || node.value === ":global"; - const isImportExport = - node.value === ":import" || node.value === ":export"; - - if (isImportExport) { - context.hasLocals = true; - // :local(.foo) - } else if (isNested) { - if (isScoped) { - if (node.nodes.length === 0) { - throw new Error(`${node.value}() can't be empty`); - } - - if (context.inside) { - throw new Error( - `A ${node.value} is not allowed inside of a ${context.inside}(...)` - ); - } - - childContext = { - global: node.value === ":global", - inside: node.value, - hasLocals: false, - explicit: true, - }; - - newNodes = node - .map((childNode) => transform(childNode, childContext)) - .reduce((acc, next) => acc.concat(next.nodes), []); - - if (newNodes.length) { - const { before, after } = node.spaces; - - const first = newNodes[0]; - const last = newNodes[newNodes.length - 1]; - - first.spaces = { before, after: first.spaces.after }; - last.spaces = { before: last.spaces.before, after }; - } - - node = newNodes; - - break; - } else { - childContext = { - global: context.global, - inside: context.inside, - lastWasSpacing: true, - hasLocals: false, - explicit: context.explicit, - }; - newNodes = node.map((childNode) => - transform(childNode, childContext) - ); - - node = node.clone(); - node.nodes = normalizeNodeArray(newNodes); - - if (childContext.hasLocals) { - context.hasLocals = true; - } - } - break; - - //:local .foo .bar - } else if (isScoped) { - if (context.inside) { - throw new Error( - `A ${node.value} is not allowed inside of a ${context.inside}(...)` - ); - } - - const addBackSpacing = !!node.spaces.before; - - context.ignoreNextSpacing = context.lastWasSpacing - ? node.value - : false; - - context.enforceNoSpacing = context.lastWasSpacing - ? false - : node.value; - - context.global = node.value === ":global"; - context.explicit = true; - - // because this node has spacing that is lost when we remove it - // we make up for it by adding an extra combinator in since adding - // spacing on the parent selector doesn't work - return addBackSpacing - ? dist.combinator({ value: " " }) - : null; - } - break; - } - case "id": - case "class": { - if (!node.value) { - throw new Error("Invalid class or id selector syntax"); - } - - if (context.global) { - break; - } - - const isImportedValue = localAliasMap.has(node.value); - const isImportedWithExplicitScope = isImportedValue && context.explicit; - - if (!isImportedValue || isImportedWithExplicitScope) { - const innerNode = node.clone(); - innerNode.spaces = { before: "", after: "" }; - - node = dist.pseudo({ - value: ":local", - nodes: [innerNode], - spaces: node.spaces, - }); - - context.hasLocals = true; - } - - break; - } - } - - context.lastWasSpacing = false; - context.ignoreNextSpacing = false; - context.enforceNoSpacing = false; - - return node; - }; - - const rootContext = { - global: mode === "global", - hasPureGlobals: false, - }; - - rootContext.selector = dist((root) => { - transform(root, rootContext); - }).processSync(rule, { updateSelector: false, lossless: true }); - - return rootContext; -} - -function localizeDeclNode(node, context) { - switch (node.type) { - case "word": - if (context.localizeNextItem) { - if (!context.localAliasMap.has(node.value)) { - node.value = ":local(" + node.value + ")"; - context.localizeNextItem = false; - } - } - break; - - case "function": - if ( - context.options && - context.options.rewriteUrl && - node.value.toLowerCase() === "url" - ) { - node.nodes.map((nestedNode) => { - if (nestedNode.type !== "string" && nestedNode.type !== "word") { - return; - } - - let newUrl = context.options.rewriteUrl( - context.global, - nestedNode.value - ); - - switch (nestedNode.type) { - case "string": - if (nestedNode.quote === "'") { - newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/'/g, "\\'"); - } - - if (nestedNode.quote === '"') { - newUrl = newUrl.replace(/(\\)/g, "\\$1").replace(/"/g, '\\"'); - } - - break; - case "word": - newUrl = newUrl.replace(/("|'|\)|\\)/g, "\\$1"); - break; - } - - nestedNode.value = newUrl; - }); - } - break; - } - return node; -} - -function isWordAFunctionArgument(wordNode, functionNode) { - return functionNode - ? functionNode.nodes.some( - (functionNodeChild) => - functionNodeChild.sourceIndex === wordNode.sourceIndex - ) - : false; -} - -function localizeDeclarationValues(localize, declaration, context) { - const valueNodes = index$1.lib(declaration.value); - - valueNodes.walk((node, index, nodes) => { - const subContext = { - options: context.options, - global: context.global, - localizeNextItem: localize && !context.global, - localAliasMap: context.localAliasMap, - }; - nodes[index] = localizeDeclNode(node, subContext); - }); - - declaration.value = valueNodes.toString(); -} - -function localizeDeclaration(declaration, context) { - const isAnimation = /animation$/i.test(declaration.prop); - - if (isAnimation) { - const validIdent = /^-?[_a-z][_a-z0-9-]*$/i; - - /* - The spec defines some keywords that you can use to describe properties such as the timing - function. These are still valid animation names, so as long as there is a property that accepts - a keyword, it is given priority. Only when all the properties that can take a keyword are - exhausted can the animation name be set to the keyword. I.e. - - animation: infinite infinite; - - The animation will repeat an infinite number of times from the first argument, and will have an - animation name of infinite from the second. - */ - const animationKeywords = { - $alternate: 1, - "$alternate-reverse": 1, - $backwards: 1, - $both: 1, - $ease: 1, - "$ease-in": 1, - "$ease-in-out": 1, - "$ease-out": 1, - $forwards: 1, - $infinite: 1, - $linear: 1, - $none: Infinity, // No matter how many times you write none, it will never be an animation name - $normal: 1, - $paused: 1, - $reverse: 1, - $running: 1, - "$step-end": 1, - "$step-start": 1, - $initial: Infinity, - $inherit: Infinity, - $unset: Infinity, - }; - let parsedAnimationKeywords = {}; - let stepsFunctionNode = null; - const valueNodes = index$1.lib(declaration.value).walk((node) => { - /* If div-token appeared (represents as comma ','), a possibility of an animation-keywords should be reflesh. */ - if (node.type === "div") { - parsedAnimationKeywords = {}; - } - if (node.type === "function" && node.value.toLowerCase() === "steps") { - stepsFunctionNode = node; - } - const value = - node.type === "word" && - !isWordAFunctionArgument(node, stepsFunctionNode) - ? node.value.toLowerCase() - : null; - - let shouldParseAnimationName = false; - - if (value && validIdent.test(value)) { - if ("$" + value in animationKeywords) { - parsedAnimationKeywords["$" + value] = - "$" + value in parsedAnimationKeywords - ? parsedAnimationKeywords["$" + value] + 1 - : 0; - - shouldParseAnimationName = - parsedAnimationKeywords["$" + value] >= - animationKeywords["$" + value]; - } else { - shouldParseAnimationName = true; - } - } - - const subContext = { - options: context.options, - global: context.global, - localizeNextItem: shouldParseAnimationName && !context.global, - localAliasMap: context.localAliasMap, - }; - return localizeDeclNode(node, subContext); - }); - - declaration.value = valueNodes.toString(); - - return; - } - - const isAnimationName = /animation(-name)?$/i.test(declaration.prop); - - if (isAnimationName) { - return localizeDeclarationValues(true, declaration, context); - } - - const hasUrl = /url\(/i.test(declaration.value); - - if (hasUrl) { - return localizeDeclarationValues(false, declaration, context); - } -} - -var src$3 = (options = {}) => { - if ( - options && - options.mode && - options.mode !== "global" && - options.mode !== "local" && - options.mode !== "pure" - ) { - throw new Error( - 'options.mode must be either "global", "local" or "pure" (default "local")' - ); - } - - const pureMode = options && options.mode === "pure"; - const globalMode = options && options.mode === "global"; - - return { - postcssPlugin: "postcss-modules-local-by-default", - prepare() { - const localAliasMap = new Map(); - - return { - Once(root) { - const { icssImports } = extractICSS(root, false); - - Object.keys(icssImports).forEach((key) => { - Object.keys(icssImports[key]).forEach((prop) => { - localAliasMap.set(prop, icssImports[key][prop]); - }); - }); - - root.walkAtRules((atRule) => { - if (/keyframes$/i.test(atRule.name)) { - const globalMatch = /^\s*:global\s*\((.+)\)\s*$/.exec( - atRule.params - ); - const localMatch = /^\s*:local\s*\((.+)\)\s*$/.exec( - atRule.params - ); - - let globalKeyframes = globalMode; - - if (globalMatch) { - if (pureMode) { - throw atRule.error( - "@keyframes :global(...) is not allowed in pure mode" - ); - } - atRule.params = globalMatch[1]; - globalKeyframes = true; - } else if (localMatch) { - atRule.params = localMatch[0]; - globalKeyframes = false; - } else if (!globalMode) { - if (atRule.params && !localAliasMap.has(atRule.params)) { - atRule.params = ":local(" + atRule.params + ")"; - } - } - - atRule.walkDecls((declaration) => { - localizeDeclaration(declaration, { - localAliasMap, - options: options, - global: globalKeyframes, - }); - }); - } else if (atRule.nodes) { - atRule.nodes.forEach((declaration) => { - if (declaration.type === "decl") { - localizeDeclaration(declaration, { - localAliasMap, - options: options, - global: globalMode, - }); - } - }); - } - }); - - root.walkRules((rule) => { - if ( - rule.parent && - rule.parent.type === "atrule" && - /keyframes$/i.test(rule.parent.name) - ) { - // ignore keyframe rules - return; - } - - const context = localizeNode(rule, options.mode, localAliasMap); - - context.options = options; - context.localAliasMap = localAliasMap; - - if (pureMode && context.hasPureGlobals) { - throw rule.error( - 'Selector "' + - rule.selector + - '" is not pure ' + - "(pure selectors must contain at least one local class or id)" - ); - } - - rule.selector = context.selector; - - // Less-syntax mixins parse as rules with no nodes - if (rule.nodes) { - rule.nodes.forEach((declaration) => - localizeDeclaration(declaration, context) - ); - } - }); - }, - }; - }, - }; -}; -var postcss$3 = true; -src$3.postcss = postcss$3; - -const PERMANENT_MARKER = 2; -const TEMPORARY_MARKER = 1; - -function createError(node, graph) { - const er = new Error("Nondeterministic import's order"); - - const related = graph[node]; - const relatedNode = related.find( - (relatedNode) => graph[relatedNode].indexOf(node) > -1 - ); - - er.nodes = [node, relatedNode]; - - return er; -} - -function walkGraph(node, graph, state, result, strict) { - if (state[node] === PERMANENT_MARKER) { - return; - } - - if (state[node] === TEMPORARY_MARKER) { - if (strict) { - return createError(node, graph); - } - - return; - } - - state[node] = TEMPORARY_MARKER; - - const children = graph[node]; - const length = children.length; - - for (let i = 0; i < length; ++i) { - const error = walkGraph(children[i], graph, state, result, strict); - - if (error instanceof Error) { - return error; - } - } - - state[node] = PERMANENT_MARKER; - - result.push(node); -} - -function topologicalSort(graph, strict) { - const result = []; - const state = {}; - - const nodes = Object.keys(graph); - const length = nodes.length; - - for (let i = 0; i < length; ++i) { - const er = walkGraph(nodes[i], graph, state, result, strict); - - if (er instanceof Error) { - return er; - } - } - - return result; -} - -var topologicalSort_1 = topologicalSort; - -const matchImports$1 = /^(.+?)\s+from\s+(?:"([^"]+)"|'([^']+)'|(global))$/; -const icssImport = /^:import\((?:"([^"]+)"|'([^']+)')\)/; - -const VISITED_MARKER = 1; - -/** - * :import('G') {} - * - * Rule - * composes: ... from 'A' - * composes: ... from 'B' - - * Rule - * composes: ... from 'A' - * composes: ... from 'A' - * composes: ... from 'C' - * - * Results in: - * - * graph: { - * G: [], - * A: [], - * B: ['A'], - * C: ['A'], - * } - */ -function addImportToGraph(importId, parentId, graph, visited) { - const siblingsId = parentId + "_" + "siblings"; - const visitedId = parentId + "_" + importId; - - if (visited[visitedId] !== VISITED_MARKER) { - if (!Array.isArray(visited[siblingsId])) { - visited[siblingsId] = []; - } - - const siblings = visited[siblingsId]; - - if (Array.isArray(graph[importId])) { - graph[importId] = graph[importId].concat(siblings); - } else { - graph[importId] = siblings.slice(); - } - - visited[visitedId] = VISITED_MARKER; - - siblings.push(importId); - } -} - -var src$2 = (options = {}) => { - let importIndex = 0; - const createImportedName = - typeof options.createImportedName !== "function" - ? (importName /*, path*/) => - `i__imported_${importName.replace(/\W/g, "_")}_${importIndex++}` - : options.createImportedName; - const failOnWrongOrder = options.failOnWrongOrder; - - return { - postcssPlugin: "postcss-modules-extract-imports", - prepare() { - const graph = {}; - const visited = {}; - const existingImports = {}; - const importDecls = {}; - const imports = {}; - - return { - Once(root, postcss) { - // Check the existing imports order and save refs - root.walkRules((rule) => { - const matches = icssImport.exec(rule.selector); - - if (matches) { - const [, /*match*/ doubleQuotePath, singleQuotePath] = matches; - const importPath = doubleQuotePath || singleQuotePath; - - addImportToGraph(importPath, "root", graph, visited); - - existingImports[importPath] = rule; - } - }); - - root.walkDecls(/^composes$/, (declaration) => { - const matches = declaration.value.match(matchImports$1); - - if (!matches) { - return; - } - - let tmpSymbols; - let [ - , - /*match*/ symbols, - doubleQuotePath, - singleQuotePath, - global, - ] = matches; - - if (global) { - // Composing globals simply means changing these classes to wrap them in global(name) - tmpSymbols = symbols.split(/\s+/).map((s) => `global(${s})`); - } else { - const importPath = doubleQuotePath || singleQuotePath; - - let parent = declaration.parent; - let parentIndexes = ""; - - while (parent.type !== "root") { - parentIndexes = - parent.parent.index(parent) + "_" + parentIndexes; - parent = parent.parent; - } - - const { selector } = declaration.parent; - const parentRule = `_${parentIndexes}${selector}`; - - addImportToGraph(importPath, parentRule, graph, visited); - - importDecls[importPath] = declaration; - imports[importPath] = imports[importPath] || {}; - - tmpSymbols = symbols.split(/\s+/).map((s) => { - if (!imports[importPath][s]) { - imports[importPath][s] = createImportedName(s, importPath); - } - - return imports[importPath][s]; - }); - } - - declaration.value = tmpSymbols.join(" "); - }); - - const importsOrder = topologicalSort_1(graph, failOnWrongOrder); - - if (importsOrder instanceof Error) { - const importPath = importsOrder.nodes.find((importPath) => - // eslint-disable-next-line no-prototype-builtins - importDecls.hasOwnProperty(importPath) - ); - const decl = importDecls[importPath]; - - throw decl.error( - "Failed to resolve order of composed modules " + - importsOrder.nodes - .map((importPath) => "`" + importPath + "`") - .join(", ") + - ".", - { - plugin: "postcss-modules-extract-imports", - word: "composes", - } - ); - } - - let lastImportRule; - - importsOrder.forEach((path) => { - const importedSymbols = imports[path]; - let rule = existingImports[path]; - - if (!rule && importedSymbols) { - rule = postcss.rule({ - selector: `:import("${path}")`, - raws: { after: "\n" }, - }); - - if (lastImportRule) { - root.insertAfter(lastImportRule, rule); - } else { - root.prepend(rule); - } - } - - lastImportRule = rule; - - if (!importedSymbols) { - return; - } - - Object.keys(importedSymbols).forEach((importedSymbol) => { - rule.append( - postcss.decl({ - value: importedSymbol, - prop: importedSymbols[importedSymbol], - raws: { before: "\n " }, - }) - ); - }); - }); - }, - }; - }, - }; -}; - -var postcss$2 = true; -src$2.postcss = postcss$2; - -const hasOwnProperty = Object.prototype.hasOwnProperty; - -function getSingleLocalNamesForComposes(root) { - return root.nodes.map((node) => { - if (node.type !== "selector" || node.nodes.length !== 1) { - throw new Error( - `composition is only allowed when selector is single :local class name not in "${root}"` - ); - } - - node = node.nodes[0]; - - if ( - node.type !== "pseudo" || - node.value !== ":local" || - node.nodes.length !== 1 - ) { - throw new Error( - 'composition is only allowed when selector is single :local class name not in "' + - root + - '", "' + - node + - '" is weird' - ); - } - - node = node.first; - - if (node.type !== "selector" || node.length !== 1) { - throw new Error( - 'composition is only allowed when selector is single :local class name not in "' + - root + - '", "' + - node + - '" is weird' - ); - } - - node = node.first; - - if (node.type !== "class") { - // 'id' is not possible, because you can't compose ids - throw new Error( - 'composition is only allowed when selector is single :local class name not in "' + - root + - '", "' + - node + - '" is weird' - ); - } - - return node.value; - }); -} - -const whitespace = "[\\x20\\t\\r\\n\\f]"; -const unescapeRegExp = new RegExp( - "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", - "ig" -); - -function unescape(str) { - return str.replace(unescapeRegExp, (_, escaped, escapedWhitespace) => { - const high = "0x" + escaped - 0x10000; - - // NaN means non-codepoint - // Workaround erroneous numeric interpretation of +"0x" - return high !== high || escapedWhitespace - ? escaped - : high < 0 - ? // BMP codepoint - String.fromCharCode(high + 0x10000) - : // Supplemental Plane codepoint (surrogate pair) - String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00); - }); -} - -const plugin = (options = {}) => { - const generateScopedName = - (options && options.generateScopedName) || plugin.generateScopedName; - const generateExportEntry = - (options && options.generateExportEntry) || plugin.generateExportEntry; - const exportGlobals = options && options.exportGlobals; - - return { - postcssPlugin: "postcss-modules-scope", - Once(root, { rule }) { - const exports = Object.create(null); - - function exportScopedName(name, rawName) { - const scopedName = generateScopedName( - rawName ? rawName : name, - root.source.input.from, - root.source.input.css - ); - const exportEntry = generateExportEntry( - rawName ? rawName : name, - scopedName, - root.source.input.from, - root.source.input.css - ); - const { key, value } = exportEntry; - - exports[key] = exports[key] || []; - - if (exports[key].indexOf(value) < 0) { - exports[key].push(value); - } - - return scopedName; - } - - function localizeNode(node) { - switch (node.type) { - case "selector": - node.nodes = node.map(localizeNode); - return node; - case "class": - return dist.className({ - value: exportScopedName( - node.value, - node.raws && node.raws.value ? node.raws.value : null - ), - }); - case "id": { - return dist.id({ - value: exportScopedName( - node.value, - node.raws && node.raws.value ? node.raws.value : null - ), - }); - } - } - - throw new Error( - `${node.type} ("${node}") is not allowed in a :local block` - ); - } - - function traverseNode(node) { - switch (node.type) { - case "pseudo": - if (node.value === ":local") { - if (node.nodes.length !== 1) { - throw new Error('Unexpected comma (",") in :local block'); - } - - const selector = localizeNode(node.first); - // move the spaces that were around the psuedo selector to the first - // non-container node - selector.first.spaces = node.spaces; - - const nextNode = node.next(); - - if ( - nextNode && - nextNode.type === "combinator" && - nextNode.value === " " && - /\\[A-F0-9]{1,6}$/.test(selector.last.value) - ) { - selector.last.spaces.after = " "; - } - - node.replaceWith(selector); - - return; - } - /* falls through */ - case "root": - case "selector": { - node.each(traverseNode); - break; - } - case "id": - case "class": - if (exportGlobals) { - exports[node.value] = [node.value]; - } - break; - } - return node; - } - - // Find any :import and remember imported names - const importedNames = {}; - - root.walkRules(/^:import\(.+\)$/, (rule) => { - rule.walkDecls((decl) => { - importedNames[decl.prop] = true; - }); - }); - - // Find any :local selectors - root.walkRules((rule) => { - let parsedSelector = dist().astSync(rule); - - rule.selector = traverseNode(parsedSelector.clone()).toString(); - - rule.walkDecls(/composes|compose-with/i, (decl) => { - const localNames = getSingleLocalNamesForComposes(parsedSelector); - const classes = decl.value.split(/\s+/); - - classes.forEach((className) => { - const global = /^global\(([^)]+)\)$/.exec(className); - - if (global) { - localNames.forEach((exportedName) => { - exports[exportedName].push(global[1]); - }); - } else if (hasOwnProperty.call(importedNames, className)) { - localNames.forEach((exportedName) => { - exports[exportedName].push(className); - }); - } else if (hasOwnProperty.call(exports, className)) { - localNames.forEach((exportedName) => { - exports[className].forEach((item) => { - exports[exportedName].push(item); - }); - }); - } else { - throw decl.error( - `referenced class name "${className}" in ${decl.prop} not found` - ); - } - }); - - decl.remove(); - }); - - // Find any :local values - rule.walkDecls((decl) => { - if (!/:local\s*\((.+?)\)/.test(decl.value)) { - return; - } - - let tokens = decl.value.split(/(,|'[^']*'|"[^"]*")/); - - tokens = tokens.map((token, idx) => { - if (idx === 0 || tokens[idx - 1] === ",") { - let result = token; - - const localMatch = /:local\s*\((.+?)\)/.exec(token); - - if (localMatch) { - const input = localMatch.input; - const matchPattern = localMatch[0]; - const matchVal = localMatch[1]; - const newVal = exportScopedName(matchVal); - - result = input.replace(matchPattern, newVal); - } else { - return token; - } - - return result; - } else { - return token; - } - }); - - decl.value = tokens.join(""); - }); - }); - - // Find any :local keyframes - root.walkAtRules(/keyframes$/i, (atRule) => { - const localMatch = /^\s*:local\s*\((.+?)\)\s*$/.exec(atRule.params); - - if (!localMatch) { - return; - } - - atRule.params = exportScopedName(localMatch[1]); - }); - - // If we found any :locals, insert an :export rule - const exportedNames = Object.keys(exports); - - if (exportedNames.length > 0) { - const exportRule = rule({ selector: ":export" }); - - exportedNames.forEach((exportedName) => - exportRule.append({ - prop: exportedName, - value: exports[exportedName].join(" "), - raws: { before: "\n " }, - }) - ); - - root.append(exportRule); - } - }, - }; -}; - -plugin.postcss = true; - -plugin.generateScopedName = function (name, path) { - const sanitisedPath = path - .replace(/\.[^./\\]+$/, "") - .replace(/[\W_]+/g, "_") - .replace(/^_|_$/g, ""); - - return `_${sanitisedPath}__${name}`.trim(); -}; - -plugin.generateExportEntry = function (name, scopedName) { - return { - key: unescape(name), - value: unescape(scopedName), - }; -}; - -var src$1 = plugin; - -const matchImports = /^(.+?|\([\s\S]+?\))\s+from\s+("[^"]*"|'[^']*'|[\w-]+)$/; -const matchValueDefinition = /(?:\s+|^)([\w-]+):?(.*?)$/; -const matchImport = /^([\w-]+)(?:\s+as\s+([\w-]+))?/; - -var src = (options) => { - let importIndex = 0; - const createImportedName = - (options && options.createImportedName) || - ((importName /*, path*/) => - `i__const_${importName.replace(/\W/g, "_")}_${importIndex++}`); - - return { - postcssPlugin: "postcss-modules-values", - prepare(result) { - const importAliases = []; - const definitions = {}; - - return { - Once(root, postcss) { - root.walkAtRules(/value/i, (atRule) => { - const matches = atRule.params.match(matchImports); - - if (matches) { - let [, /*match*/ aliases, path] = matches; - - // We can use constants for path names - if (definitions[path]) { - path = definitions[path]; - } - - const imports = aliases - .replace(/^\(\s*([\s\S]+)\s*\)$/, "$1") - .split(/\s*,\s*/) - .map((alias) => { - const tokens = matchImport.exec(alias); - - if (tokens) { - const [, /*match*/ theirName, myName = theirName] = tokens; - const importedName = createImportedName(myName); - definitions[myName] = importedName; - return { theirName, importedName }; - } else { - throw new Error(`@import statement "${alias}" is invalid!`); - } - }); - - importAliases.push({ path, imports }); - - atRule.remove(); - - return; - } - - if (atRule.params.indexOf("@value") !== -1) { - result.warn("Invalid value definition: " + atRule.params); - } - - let [, key, value] = `${atRule.params}${atRule.raws.between}`.match( - matchValueDefinition - ); - - const normalizedValue = value.replace(/\/\*((?!\*\/).*?)\*\//g, ""); - - if (normalizedValue.length === 0) { - result.warn("Invalid value definition: " + atRule.params); - atRule.remove(); - - return; - } - - let isOnlySpace = /^\s+$/.test(normalizedValue); - - if (!isOnlySpace) { - value = value.trim(); - } - - // Add to the definitions, knowing that values can refer to each other - definitions[key] = src$4.replaceValueSymbols( - value, - definitions - ); - - atRule.remove(); - }); - - /* If we have no definitions, don't continue */ - if (!Object.keys(definitions).length) { - return; - } - - /* Perform replacements */ - src$4.replaceSymbols(root, definitions); - - /* We want to export anything defined by now, but don't add it to the CSS yet or it well get picked up by the replacement stuff */ - const exportDeclarations = Object.keys(definitions).map((key) => - postcss.decl({ - value: definitions[key], - prop: key, - raws: { before: "\n " }, - }) - ); - - /* Add export rules if any */ - if (exportDeclarations.length > 0) { - const exportRule = postcss.rule({ - selector: ":export", - raws: { after: "\n" }, - }); - - exportRule.append(exportDeclarations); - - root.prepend(exportRule); - } - - /* Add import rules */ - importAliases.reverse().forEach(({ path, imports }) => { - const importRule = postcss.rule({ - selector: `:import(${path})`, - raws: { after: "\n" }, - }); - - imports.forEach(({ theirName, importedName }) => { - importRule.append({ - value: theirName, - prop: importedName, - raws: { before: "\n " }, - }); - }); - - root.prepend(importRule); - }); - }, - }; - }, - }; -}; - -var postcss$1 = true; -src.postcss = postcss$1; - -var behaviours_1 = build$1.createCommonjsModule(function (module, exports) { - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.behaviours = undefined; -exports.getDefaultPlugins = getDefaultPlugins; -exports.isValidBehaviour = isValidBehaviour; - - - -var _postcssModulesLocalByDefault2 = _interopRequireDefault(src$3); - - - -var _postcssModulesExtractImports2 = _interopRequireDefault(src$2); - - - -var _postcssModulesScope2 = _interopRequireDefault(src$1); - - - -var _postcssModulesValues2 = _interopRequireDefault(src); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const behaviours = exports.behaviours = { - LOCAL: "local", - GLOBAL: "global" -}; - -function getDefaultPlugins({ - behaviour, - generateScopedName, - exportGlobals -}) { - const scope = (0, _postcssModulesScope2.default)({ generateScopedName, exportGlobals }); - - const plugins = { - [behaviours.LOCAL]: [_postcssModulesValues2.default, _postcssModulesLocalByDefault2.default, _postcssModulesExtractImports2.default, scope], - [behaviours.GLOBAL]: [_postcssModulesValues2.default, _postcssModulesExtractImports2.default, scope] - }; - - return plugins[behaviour]; -} - -function isValidBehaviour(behaviour) { - return Object.keys(behaviours).map(key => behaviours[key]).indexOf(behaviour) > -1; -} -}); - -var _postcss2 = _interopRequireDefault(_postcss__default); - - - -var _lodash2 = _interopRequireDefault(lodash_camelcase); - - - -var _genericNames2 = _interopRequireDefault(genericNames); - - - -var _parser2 = _interopRequireDefault(parser$1); - - - -var _loader2 = _interopRequireDefault(loader); - - - -var _generateScopedName2 = _interopRequireDefault(generateScopedName_1); - - - -var _saveJSON2 = _interopRequireDefault(saveJSON_1); - - - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - -const PLUGIN_NAME = "postcss-modules"; - -function getDefaultScopeBehaviour(opts) { - if (opts.scopeBehaviour && (0, behaviours_1.isValidBehaviour)(opts.scopeBehaviour)) { - return opts.scopeBehaviour; - } - - return behaviours_1.behaviours.LOCAL; -} - -function getScopedNameGenerator(opts) { - const scopedNameGenerator = opts.generateScopedName || _generateScopedName2.default; - - if (typeof scopedNameGenerator === "function") return scopedNameGenerator; - return (0, _genericNames2.default)(scopedNameGenerator, { - context: process.cwd(), - hashPrefix: opts.hashPrefix - }); -} - -function getLoader(opts, plugins) { - const root = typeof opts.root === "undefined" ? "/" : opts.root; - return typeof opts.Loader === "function" ? new opts.Loader(root, plugins) : new _loader2.default(root, plugins); -} - -function isGlobalModule(globalModules, inputFile) { - return globalModules.some(regex => inputFile.match(regex)); -} - -function getDefaultPluginsList(opts, inputFile) { - const globalModulesList = opts.globalModulePaths || null; - const exportGlobals = opts.exportGlobals || false; - const defaultBehaviour = getDefaultScopeBehaviour(opts); - const generateScopedName = getScopedNameGenerator(opts); - - if (globalModulesList && isGlobalModule(globalModulesList, inputFile)) { - return (0, behaviours_1.getDefaultPlugins)({ - behaviour: behaviours_1.behaviours.GLOBAL, - generateScopedName, - exportGlobals - }); - } - - return (0, behaviours_1.getDefaultPlugins)({ - behaviour: defaultBehaviour, - generateScopedName, - exportGlobals - }); -} - -function isOurPlugin(plugin) { - return plugin.postcssPlugin === PLUGIN_NAME; -} - -function dashesCamelCase(string) { - return string.replace(/-+(\w)/g, (_, firstLetter) => firstLetter.toUpperCase()); -} - -var build = (opts = {}) => { - return { - postcssPlugin: PLUGIN_NAME, - OnceExit(css, { result }) { - return _asyncToGenerator(function* () { - const getJSON = opts.getJSON || _saveJSON2.default; - const inputFile = css.source.input.file; - const pluginList = getDefaultPluginsList(opts, inputFile); - const resultPluginIndex = result.processor.plugins.findIndex(function (plugin) { - return isOurPlugin(plugin); - }); - if (resultPluginIndex === -1) { - throw new Error('Plugin missing from options.'); - } - const earlierPlugins = result.processor.plugins.slice(0, resultPluginIndex); - const loaderPlugins = [...earlierPlugins, ...pluginList]; - const loader = getLoader(opts, loaderPlugins); - const parser = new _parser2.default(loader.fetch.bind(loader)); - - yield (0, _postcss2.default)([...pluginList, parser.plugin()]).process(css, { - from: inputFile - }); - - const out = loader.finalSource; - if (out) css.prepend(out); - - if (opts.localsConvention) { - const isFunc = typeof opts.localsConvention === "function"; - - parser.exportTokens = Object.entries(parser.exportTokens).reduce(function (tokens, [className, value]) { - if (isFunc) { - tokens[opts.localsConvention(className, value, inputFile)] = value; - - return tokens; - } - - switch (opts.localsConvention) { - case "camelCase": - tokens[className] = value; - tokens[(0, _lodash2.default)(className)] = value; - - break; - case "camelCaseOnly": - tokens[(0, _lodash2.default)(className)] = value; - - break; - case "dashes": - tokens[className] = value; - tokens[dashesCamelCase(className)] = value; - - break; - case "dashesOnly": - tokens[dashesCamelCase(className)] = value; - - break; - } - - return tokens; - }, {}); - } - - result.messages.push({ - type: "export", - plugin: "postcss-modules", - exportTokens: parser.exportTokens - }); - - // getJSON may return a promise - return getJSON(css.source.input.file, parser.exportTokens, result.opts.to); - })(); - } - }; -}; - -var postcss = true; -build.postcss = postcss; - -var index = /*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), build, { - 'default': build, - postcss: postcss -}); - -exports.index = index; diff --git a/node_modules/vite/dist/node/cli.js b/node_modules/vite/dist/node/cli.js deleted file mode 100644 index 780539b..0000000 --- a/node_modules/vite/dist/node/cli.js +++ /dev/null @@ -1,14131 +0,0 @@ -'use strict'; - -var require$$0$1 = require('events'); -var build = require('./chunks/dep-66eb515d.js'); -var os = require('os'); -var path = require('path'); -var tty = require('tty'); -var util = require('util'); -var fs = require('fs'); -var require$$2 = require('net'); -var zlib_1 = require('zlib'); -require('url'); -require('http'); -require('stream'); -require('resolve'); -require('module'); -require('readline'); -require('crypto'); -require('esbuild'); -require('worker_threads'); -require('assert'); -require('https'); -require('tls'); -require('buffer'); -require('child_process'); -require('querystring'); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; } - -var os__default = /*#__PURE__*/_interopDefaultLegacy(os); -var path__default = /*#__PURE__*/_interopDefaultLegacy(path); -var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty); -var util__default = /*#__PURE__*/_interopDefaultLegacy(util); -var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); -var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); -var zlib_1__default = /*#__PURE__*/_interopDefaultLegacy(zlib_1); - -function toArr(any) { - return any == null ? [] : Array.isArray(any) ? any : [any]; -} - -function toVal(out, key, val, opts) { - var x, old=out[key], nxt=( - !!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val)) - : typeof val === 'boolean' ? val - : !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val)) - : (x = +val,x * 0 === 0) ? x : val - ); - out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]); -} - -function mri2 (args, opts) { - args = args || []; - opts = opts || {}; - - var k, arr, arg, name, val, out={ _:[] }; - var i=0, j=0, idx=0, len=args.length; - - const alibi = opts.alias !== void 0; - const strict = opts.unknown !== void 0; - const defaults = opts.default !== void 0; - - opts.alias = opts.alias || {}; - opts.string = toArr(opts.string); - opts.boolean = toArr(opts.boolean); - - if (alibi) { - for (k in opts.alias) { - arr = opts.alias[k] = toArr(opts.alias[k]); - for (i=0; i < arr.length; i++) { - (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1); - } - } - } - - for (i=opts.boolean.length; i-- > 0;) { - arr = opts.alias[opts.boolean[i]] || []; - for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]); - } - - for (i=opts.string.length; i-- > 0;) { - arr = opts.alias[opts.string[i]] || []; - for (j=arr.length; j-- > 0;) opts.string.push(arr[j]); - } - - if (defaults) { - for (k in opts.default) { - name = typeof opts.default[k]; - arr = opts.alias[k] = opts.alias[k] || []; - if (opts[name] !== void 0) { - opts[name].push(k); - for (i=0; i < arr.length; i++) { - opts[name].push(arr[i]); - } - } - } - } - - const keys = strict ? Object.keys(opts.alias) : []; - - for (i=0; i < len; i++) { - arg = args[i]; - - if (arg === '--') { - out._ = out._.concat(args.slice(++i)); - break; - } - - for (j=0; j < arg.length; j++) { - if (arg.charCodeAt(j) !== 45) break; // "-" - } - - if (j === 0) { - out._.push(arg); - } else if (arg.substring(j, j + 3) === 'no-') { - name = arg.substring(j + 3); - if (strict && !~keys.indexOf(name)) { - return opts.unknown(arg); - } - out[name] = false; - } else { - for (idx=j+1; idx < arg.length; idx++) { - if (arg.charCodeAt(idx) === 61) break; // "=" - } - - name = arg.substring(j, idx); - val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]); - arr = (j === 2 ? [name] : name); - - for (idx=0; idx < arr.length; idx++) { - name = arr[idx]; - if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name); - toVal(out, name, (idx + 1 < arr.length) || val, opts); - } - } - } - - if (defaults) { - for (k in opts.default) { - if (out[k] === void 0) { - out[k] = opts.default[k]; - } - } - } - - if (alibi) { - for (k in out) { - arr = opts.alias[k] || []; - while (arr.length > 0) { - out[arr.shift()] = out[k]; - } - } - } - - return out; -} - -const removeBrackets = (v) => v.replace(/[<[].+/, "").trim(); -const findAllBrackets = (v) => { - const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g; - const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g; - const res = []; - const parse = (match) => { - let variadic = false; - let value = match[1]; - if (value.startsWith("...")) { - value = value.slice(3); - variadic = true; - } - return { - required: match[0].startsWith("<"), - value, - variadic - }; - }; - let angledMatch; - while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) { - res.push(parse(angledMatch)); - } - let squareMatch; - while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) { - res.push(parse(squareMatch)); - } - return res; -}; -const getMriOptions = (options) => { - const result = {alias: {}, boolean: []}; - for (const [index, option] of options.entries()) { - if (option.names.length > 1) { - result.alias[option.names[0]] = option.names.slice(1); - } - if (option.isBoolean) { - if (option.negated) { - const hasStringTypeOption = options.some((o, i) => { - return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean"; - }); - if (!hasStringTypeOption) { - result.boolean.push(option.names[0]); - } - } else { - result.boolean.push(option.names[0]); - } - } - } - return result; -}; -const findLongest = (arr) => { - return arr.sort((a, b) => { - return a.length > b.length ? -1 : 1; - })[0]; -}; -const padRight = (str, length) => { - return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`; -}; -const camelcase = (input) => { - return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => { - return p1 + p2.toUpperCase(); - }); -}; -const setDotProp = (obj, keys, val) => { - let i = 0; - let length = keys.length; - let t = obj; - let x; - for (; i < length; ++i) { - x = t[keys[i]]; - t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : []; - } -}; -const setByType = (obj, transforms) => { - for (const key of Object.keys(transforms)) { - const transform = transforms[key]; - if (transform.shouldTransform) { - obj[key] = Array.prototype.concat.call([], obj[key]); - if (typeof transform.transformFunction === "function") { - obj[key] = obj[key].map(transform.transformFunction); - } - } - } -}; -const getFileName = (input) => { - const m = /([^\\\/]+)$/.exec(input); - return m ? m[1] : ""; -}; -const camelcaseOptionName = (name) => { - return name.split(".").map((v, i) => { - return i === 0 ? camelcase(v) : v; - }).join("."); -}; -class CACError extends Error { - constructor(message) { - super(message); - this.name = this.constructor.name; - if (typeof Error.captureStackTrace === "function") { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = new Error(message).stack; - } - } -} - -class Option { - constructor(rawName, description, config) { - this.rawName = rawName; - this.description = description; - this.config = Object.assign({}, config); - rawName = rawName.replace(/\.\*/g, ""); - this.negated = false; - this.names = removeBrackets(rawName).split(",").map((v) => { - let name = v.trim().replace(/^-{1,2}/, ""); - if (name.startsWith("no-")) { - this.negated = true; - name = name.replace(/^no-/, ""); - } - return camelcaseOptionName(name); - }).sort((a, b) => a.length > b.length ? 1 : -1); - this.name = this.names[this.names.length - 1]; - if (this.negated && this.config.default == null) { - this.config.default = true; - } - if (rawName.includes("<")) { - this.required = true; - } else if (rawName.includes("[")) { - this.required = false; - } else { - this.isBoolean = true; - } - } -} - -const processArgs = process.argv; -const platformInfo = `${process.platform}-${process.arch} node-${process.version}`; - -class Command { - constructor(rawName, description, config = {}, cli) { - this.rawName = rawName; - this.description = description; - this.config = config; - this.cli = cli; - this.options = []; - this.aliasNames = []; - this.name = removeBrackets(rawName); - this.args = findAllBrackets(rawName); - this.examples = []; - } - usage(text) { - this.usageText = text; - return this; - } - allowUnknownOptions() { - this.config.allowUnknownOptions = true; - return this; - } - ignoreOptionDefaultValue() { - this.config.ignoreOptionDefaultValue = true; - return this; - } - version(version, customFlags = "-v, --version") { - this.versionNumber = version; - this.option(customFlags, "Display version number"); - return this; - } - example(example) { - this.examples.push(example); - return this; - } - option(rawName, description, config) { - const option = new Option(rawName, description, config); - this.options.push(option); - return this; - } - alias(name) { - this.aliasNames.push(name); - return this; - } - action(callback) { - this.commandAction = callback; - return this; - } - isMatched(name) { - return this.name === name || this.aliasNames.includes(name); - } - get isDefaultCommand() { - return this.name === "" || this.aliasNames.includes("!"); - } - get isGlobalCommand() { - return this instanceof GlobalCommand; - } - hasOption(name) { - name = name.split(".")[0]; - return this.options.find((option) => { - return option.names.includes(name); - }); - } - outputHelp() { - const {name, commands} = this.cli; - const { - versionNumber, - options: globalOptions, - helpCallback - } = this.cli.globalCommand; - let sections = [ - { - body: `${name}${versionNumber ? `/${versionNumber}` : ""}` - } - ]; - sections.push({ - title: "Usage", - body: ` $ ${name} ${this.usageText || this.rawName}` - }); - const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0; - if (showCommands) { - const longestCommandName = findLongest(commands.map((command) => command.rawName)); - sections.push({ - title: "Commands", - body: commands.map((command) => { - return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`; - }).join("\n") - }); - sections.push({ - title: `For more info, run any command with the \`--help\` flag`, - body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n") - }); - } - const options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []]; - if (options.length > 0) { - const longestOptionName = findLongest(options.map((option) => option.rawName)); - sections.push({ - title: "Options", - body: options.map((option) => { - return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`; - }).join("\n") - }); - } - if (this.examples.length > 0) { - sections.push({ - title: "Examples", - body: this.examples.map((example) => { - if (typeof example === "function") { - return example(name); - } - return example; - }).join("\n") - }); - } - if (helpCallback) { - sections = helpCallback(sections) || sections; - } - console.log(sections.map((section) => { - return section.title ? `${section.title}: -${section.body}` : section.body; - }).join("\n\n")); - } - outputVersion() { - const {name} = this.cli; - const {versionNumber} = this.cli.globalCommand; - if (versionNumber) { - console.log(`${name}/${versionNumber} ${platformInfo}`); - } - } - checkRequiredArgs() { - const minimalArgsCount = this.args.filter((arg) => arg.required).length; - if (this.cli.args.length < minimalArgsCount) { - throw new CACError(`missing required args for command \`${this.rawName}\``); - } - } - checkUnknownOptions() { - const {options, globalCommand} = this.cli; - if (!this.config.allowUnknownOptions) { - for (const name of Object.keys(options)) { - if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) { - throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``); - } - } - } - } - checkOptionValue() { - const {options: parsedOptions, globalCommand} = this.cli; - const options = [...globalCommand.options, ...this.options]; - for (const option of options) { - const value = parsedOptions[option.name.split(".")[0]]; - if (option.required) { - const hasNegated = options.some((o) => o.negated && o.names.includes(option.name)); - if (value === true || value === false && !hasNegated) { - throw new CACError(`option \`${option.rawName}\` value is missing`); - } - } - } - } -} -class GlobalCommand extends Command { - constructor(cli) { - super("@@global@@", "", {}, cli); - } -} - -var __assign = Object.assign; -class CAC extends require$$0$1.EventEmitter { - constructor(name = "") { - super(); - this.name = name; - this.commands = []; - this.rawArgs = []; - this.args = []; - this.options = {}; - this.globalCommand = new GlobalCommand(this); - this.globalCommand.usage(" [options]"); - } - usage(text) { - this.globalCommand.usage(text); - return this; - } - command(rawName, description, config) { - const command = new Command(rawName, description || "", config, this); - command.globalCommand = this.globalCommand; - this.commands.push(command); - return command; - } - option(rawName, description, config) { - this.globalCommand.option(rawName, description, config); - return this; - } - help(callback) { - this.globalCommand.option("-h, --help", "Display this message"); - this.globalCommand.helpCallback = callback; - this.showHelpOnExit = true; - return this; - } - version(version, customFlags = "-v, --version") { - this.globalCommand.version(version, customFlags); - this.showVersionOnExit = true; - return this; - } - example(example) { - this.globalCommand.example(example); - return this; - } - outputHelp() { - if (this.matchedCommand) { - this.matchedCommand.outputHelp(); - } else { - this.globalCommand.outputHelp(); - } - } - outputVersion() { - this.globalCommand.outputVersion(); - } - setParsedInfo({args, options}, matchedCommand, matchedCommandName) { - this.args = args; - this.options = options; - if (matchedCommand) { - this.matchedCommand = matchedCommand; - } - if (matchedCommandName) { - this.matchedCommandName = matchedCommandName; - } - return this; - } - unsetMatchedCommand() { - this.matchedCommand = void 0; - this.matchedCommandName = void 0; - } - parse(argv = processArgs, { - run = true - } = {}) { - this.rawArgs = argv; - if (!this.name) { - this.name = argv[1] ? getFileName(argv[1]) : "cli"; - } - let shouldParse = true; - for (const command of this.commands) { - const parsed = this.mri(argv.slice(2), command); - const commandName = parsed.args[0]; - if (command.isMatched(commandName)) { - shouldParse = false; - const parsedInfo = __assign(__assign({}, parsed), { - args: parsed.args.slice(1) - }); - this.setParsedInfo(parsedInfo, command, commandName); - this.emit(`command:${commandName}`, command); - } - } - if (shouldParse) { - for (const command of this.commands) { - if (command.name === "") { - shouldParse = false; - const parsed = this.mri(argv.slice(2), command); - this.setParsedInfo(parsed, command); - this.emit(`command:!`, command); - } - } - } - if (shouldParse) { - const parsed = this.mri(argv.slice(2)); - this.setParsedInfo(parsed); - } - if (this.options.help && this.showHelpOnExit) { - this.outputHelp(); - run = false; - this.unsetMatchedCommand(); - } - if (this.options.version && this.showVersionOnExit) { - this.outputVersion(); - run = false; - this.unsetMatchedCommand(); - } - const parsedArgv = {args: this.args, options: this.options}; - if (run) { - this.runMatchedCommand(); - } - if (!this.matchedCommand && this.args[0]) { - this.emit("command:*"); - } - return parsedArgv; - } - mri(argv, command) { - const cliOptions = [ - ...this.globalCommand.options, - ...command ? command.options : [] - ]; - const mriOptions = getMriOptions(cliOptions); - let argsAfterDoubleDashes = []; - const doubleDashesIndex = argv.indexOf("--"); - if (doubleDashesIndex > -1) { - argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1); - argv = argv.slice(0, doubleDashesIndex); - } - let parsed = mri2(argv, mriOptions); - parsed = Object.keys(parsed).reduce((res, name) => { - return __assign(__assign({}, res), { - [camelcaseOptionName(name)]: parsed[name] - }); - }, {_: []}); - const args = parsed._; - const options = { - "--": argsAfterDoubleDashes - }; - const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue; - let transforms = Object.create(null); - for (const cliOption of cliOptions) { - if (!ignoreDefault && cliOption.config.default !== void 0) { - for (const name of cliOption.names) { - options[name] = cliOption.config.default; - } - } - if (Array.isArray(cliOption.config.type)) { - if (transforms[cliOption.name] === void 0) { - transforms[cliOption.name] = Object.create(null); - transforms[cliOption.name]["shouldTransform"] = true; - transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0]; - } - } - } - for (const key of Object.keys(parsed)) { - if (key !== "_") { - const keys = key.split("."); - setDotProp(options, keys, parsed[key]); - setByType(options, transforms); - } - } - return { - args, - options - }; - } - runMatchedCommand() { - const {args, options, matchedCommand: command} = this; - if (!command || !command.commandAction) - return; - command.checkUnknownOptions(); - command.checkOptionValue(); - command.checkRequiredArgs(); - const actionArgs = []; - command.args.forEach((arg, index) => { - if (arg.variadic) { - actionArgs.push(args.slice(index)); - } else { - actionArgs.push(args[index]); - } - }); - actionArgs.push(options); - return command.commandAction.apply(this, actionArgs); - } -} - -const cac = (name = "") => new CAC(name); - -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module exports. - * @public - */ - -var charset = preferredCharsets; -var preferredCharsets_1 = preferredCharsets; - -/** - * Module variables. - * @private - */ - -var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; - -/** - * Parse the Accept-Charset header. - * @private - */ - -function parseAcceptCharset(accept) { - var accepts = accept.split(','); - - for (var i = 0, j = 0; i < accepts.length; i++) { - var charset = parseCharset(accepts[i].trim(), i); - - if (charset) { - accepts[j++] = charset; - } - } - - // trim accepts - accepts.length = j; - - return accepts; -} - -/** - * Parse a charset from the Accept-Charset header. - * @private - */ - -function parseCharset(str, i) { - var match = simpleCharsetRegExp.exec(str); - if (!match) return null; - - var charset = match[1]; - var q = 1; - if (match[2]) { - var params = match[2].split(';'); - for (var j = 0; j < params.length; j++) { - var p = params[j].trim().split('='); - if (p[0] === 'q') { - q = parseFloat(p[1]); - break; - } - } - } - - return { - charset: charset, - q: q, - i: i - }; -} - -/** - * Get the priority of a charset. - * @private - */ - -function getCharsetPriority(charset, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; - - for (var i = 0; i < accepted.length; i++) { - var spec = specify$3(charset, accepted[i], index); - - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - - return priority; -} - -/** - * Get the specificity of the charset. - * @private - */ - -function specify$3(charset, spec, index) { - var s = 0; - if(spec.charset.toLowerCase() === charset.toLowerCase()){ - s |= 1; - } else if (spec.charset !== '*' ) { - return null - } - - return { - i: index, - o: spec.i, - q: spec.q, - s: s - } -} - -/** - * Get the preferred charsets from an Accept-Charset header. - * @public - */ - -function preferredCharsets(accept, provided) { - // RFC 2616 sec 14.2: no header = * - var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); - - if (!provided) { - // sorted list of all charsets - return accepts - .filter(isQuality$3) - .sort(compareSpecs$3) - .map(getFullCharset); - } - - var priorities = provided.map(function getPriority(type, index) { - return getCharsetPriority(type, accepts, index); - }); - - // sorted list of accepted charsets - return priorities.filter(isQuality$3).sort(compareSpecs$3).map(function getCharset(priority) { - return provided[priorities.indexOf(priority)]; - }); -} - -/** - * Compare two specs. - * @private - */ - -function compareSpecs$3(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} - -/** - * Get full charset string. - * @private - */ - -function getFullCharset(spec) { - return spec.charset; -} - -/** - * Check if a spec has any quality. - * @private - */ - -function isQuality$3(spec) { - return spec.q > 0; -} -charset.preferredCharsets = preferredCharsets_1; - -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module exports. - * @public - */ - -var encoding = preferredEncodings; -var preferredEncodings_1 = preferredEncodings; - -/** - * Module variables. - * @private - */ - -var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; - -/** - * Parse the Accept-Encoding header. - * @private - */ - -function parseAcceptEncoding(accept) { - var accepts = accept.split(','); - var hasIdentity = false; - var minQuality = 1; - - for (var i = 0, j = 0; i < accepts.length; i++) { - var encoding = parseEncoding(accepts[i].trim(), i); - - if (encoding) { - accepts[j++] = encoding; - hasIdentity = hasIdentity || specify$2('identity', encoding); - minQuality = Math.min(minQuality, encoding.q || 1); - } - } - - if (!hasIdentity) { - /* - * If identity doesn't explicitly appear in the accept-encoding header, - * it's added to the list of acceptable encoding with the lowest q - */ - accepts[j++] = { - encoding: 'identity', - q: minQuality, - i: i - }; - } - - // trim accepts - accepts.length = j; - - return accepts; -} - -/** - * Parse an encoding from the Accept-Encoding header. - * @private - */ - -function parseEncoding(str, i) { - var match = simpleEncodingRegExp.exec(str); - if (!match) return null; - - var encoding = match[1]; - var q = 1; - if (match[2]) { - var params = match[2].split(';'); - for (var j = 0; j < params.length; j++) { - var p = params[j].trim().split('='); - if (p[0] === 'q') { - q = parseFloat(p[1]); - break; - } - } - } - - return { - encoding: encoding, - q: q, - i: i - }; -} - -/** - * Get the priority of an encoding. - * @private - */ - -function getEncodingPriority(encoding, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; - - for (var i = 0; i < accepted.length; i++) { - var spec = specify$2(encoding, accepted[i], index); - - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - - return priority; -} - -/** - * Get the specificity of the encoding. - * @private - */ - -function specify$2(encoding, spec, index) { - var s = 0; - if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ - s |= 1; - } else if (spec.encoding !== '*' ) { - return null - } - - return { - i: index, - o: spec.i, - q: spec.q, - s: s - } -} -/** - * Get the preferred encodings from an Accept-Encoding header. - * @public - */ - -function preferredEncodings(accept, provided) { - var accepts = parseAcceptEncoding(accept || ''); - - if (!provided) { - // sorted list of all encodings - return accepts - .filter(isQuality$2) - .sort(compareSpecs$2) - .map(getFullEncoding); - } - - var priorities = provided.map(function getPriority(type, index) { - return getEncodingPriority(type, accepts, index); - }); - - // sorted list of accepted encodings - return priorities.filter(isQuality$2).sort(compareSpecs$2).map(function getEncoding(priority) { - return provided[priorities.indexOf(priority)]; - }); -} - -/** - * Compare two specs. - * @private - */ - -function compareSpecs$2(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} - -/** - * Get full encoding string. - * @private - */ - -function getFullEncoding(spec) { - return spec.encoding; -} - -/** - * Check if a spec has any quality. - * @private - */ - -function isQuality$2(spec) { - return spec.q > 0; -} -encoding.preferredEncodings = preferredEncodings_1; - -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module exports. - * @public - */ - -var language = preferredLanguages; -var preferredLanguages_1 = preferredLanguages; - -/** - * Module variables. - * @private - */ - -var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; - -/** - * Parse the Accept-Language header. - * @private - */ - -function parseAcceptLanguage(accept) { - var accepts = accept.split(','); - - for (var i = 0, j = 0; i < accepts.length; i++) { - var language = parseLanguage(accepts[i].trim(), i); - - if (language) { - accepts[j++] = language; - } - } - - // trim accepts - accepts.length = j; - - return accepts; -} - -/** - * Parse a language from the Accept-Language header. - * @private - */ - -function parseLanguage(str, i) { - var match = simpleLanguageRegExp.exec(str); - if (!match) return null; - - var prefix = match[1], - suffix = match[2], - full = prefix; - - if (suffix) full += "-" + suffix; - - var q = 1; - if (match[3]) { - var params = match[3].split(';'); - for (var j = 0; j < params.length; j++) { - var p = params[j].split('='); - if (p[0] === 'q') q = parseFloat(p[1]); - } - } - - return { - prefix: prefix, - suffix: suffix, - q: q, - i: i, - full: full - }; -} - -/** - * Get the priority of a language. - * @private - */ - -function getLanguagePriority(language, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; - - for (var i = 0; i < accepted.length; i++) { - var spec = specify$1(language, accepted[i], index); - - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - - return priority; -} - -/** - * Get the specificity of the language. - * @private - */ - -function specify$1(language, spec, index) { - var p = parseLanguage(language); - if (!p) return null; - var s = 0; - if(spec.full.toLowerCase() === p.full.toLowerCase()){ - s |= 4; - } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { - s |= 2; - } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { - s |= 1; - } else if (spec.full !== '*' ) { - return null - } - - return { - i: index, - o: spec.i, - q: spec.q, - s: s - } -} -/** - * Get the preferred languages from an Accept-Language header. - * @public - */ - -function preferredLanguages(accept, provided) { - // RFC 2616 sec 14.4: no header = * - var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); - - if (!provided) { - // sorted list of all languages - return accepts - .filter(isQuality$1) - .sort(compareSpecs$1) - .map(getFullLanguage); - } - - var priorities = provided.map(function getPriority(type, index) { - return getLanguagePriority(type, accepts, index); - }); - - // sorted list of accepted languages - return priorities.filter(isQuality$1).sort(compareSpecs$1).map(function getLanguage(priority) { - return provided[priorities.indexOf(priority)]; - }); -} - -/** - * Compare two specs. - * @private - */ - -function compareSpecs$1(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} - -/** - * Get full language string. - * @private - */ - -function getFullLanguage(spec) { - return spec.full; -} - -/** - * Check if a spec has any quality. - * @private - */ - -function isQuality$1(spec) { - return spec.q > 0; -} -language.preferredLanguages = preferredLanguages_1; - -/** - * negotiator - * Copyright(c) 2012 Isaac Z. Schlueter - * Copyright(c) 2014 Federico Romero - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module exports. - * @public - */ - -var mediaType = preferredMediaTypes; -var preferredMediaTypes_1 = preferredMediaTypes; - -/** - * Module variables. - * @private - */ - -var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; - -/** - * Parse the Accept header. - * @private - */ - -function parseAccept(accept) { - var accepts = splitMediaTypes(accept); - - for (var i = 0, j = 0; i < accepts.length; i++) { - var mediaType = parseMediaType(accepts[i].trim(), i); - - if (mediaType) { - accepts[j++] = mediaType; - } - } - - // trim accepts - accepts.length = j; - - return accepts; -} - -/** - * Parse a media type from the Accept header. - * @private - */ - -function parseMediaType(str, i) { - var match = simpleMediaTypeRegExp.exec(str); - if (!match) return null; - - var params = Object.create(null); - var q = 1; - var subtype = match[2]; - var type = match[1]; - - if (match[3]) { - var kvps = splitParameters(match[3]).map(splitKeyValuePair); - - for (var j = 0; j < kvps.length; j++) { - var pair = kvps[j]; - var key = pair[0].toLowerCase(); - var val = pair[1]; - - // get the value, unwrapping quotes - var value = val && val[0] === '"' && val[val.length - 1] === '"' - ? val.substr(1, val.length - 2) - : val; - - if (key === 'q') { - q = parseFloat(value); - break; - } - - // store parameter - params[key] = value; - } - } - - return { - type: type, - subtype: subtype, - params: params, - q: q, - i: i - }; -} - -/** - * Get the priority of a media type. - * @private - */ - -function getMediaTypePriority(type, accepted, index) { - var priority = {o: -1, q: 0, s: 0}; - - for (var i = 0; i < accepted.length; i++) { - var spec = specify(type, accepted[i], index); - - if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { - priority = spec; - } - } - - return priority; -} - -/** - * Get the specificity of the media type. - * @private - */ - -function specify(type, spec, index) { - var p = parseMediaType(type); - var s = 0; - - if (!p) { - return null; - } - - if(spec.type.toLowerCase() == p.type.toLowerCase()) { - s |= 4; - } else if(spec.type != '*') { - return null; - } - - if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { - s |= 2; - } else if(spec.subtype != '*') { - return null; - } - - var keys = Object.keys(spec.params); - if (keys.length > 0) { - if (keys.every(function (k) { - return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); - })) { - s |= 1; - } else { - return null - } - } - - return { - i: index, - o: spec.i, - q: spec.q, - s: s, - } -} - -/** - * Get the preferred media types from an Accept header. - * @public - */ - -function preferredMediaTypes(accept, provided) { - // RFC 2616 sec 14.2: no header = */* - var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); - - if (!provided) { - // sorted list of all types - return accepts - .filter(isQuality) - .sort(compareSpecs) - .map(getFullType); - } - - var priorities = provided.map(function getPriority(type, index) { - return getMediaTypePriority(type, accepts, index); - }); - - // sorted list of accepted types - return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { - return provided[priorities.indexOf(priority)]; - }); -} - -/** - * Compare two specs. - * @private - */ - -function compareSpecs(a, b) { - return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; -} - -/** - * Get full type string. - * @private - */ - -function getFullType(spec) { - return spec.type + '/' + spec.subtype; -} - -/** - * Check if a spec has any quality. - * @private - */ - -function isQuality(spec) { - return spec.q > 0; -} - -/** - * Count the number of quotes in a string. - * @private - */ - -function quoteCount(string) { - var count = 0; - var index = 0; - - while ((index = string.indexOf('"', index)) !== -1) { - count++; - index++; - } - - return count; -} - -/** - * Split a key value pair. - * @private - */ - -function splitKeyValuePair(str) { - var index = str.indexOf('='); - var key; - var val; - - if (index === -1) { - key = str; - } else { - key = str.substr(0, index); - val = str.substr(index + 1); - } - - return [key, val]; -} - -/** - * Split an Accept header into media types. - * @private - */ - -function splitMediaTypes(accept) { - var accepts = accept.split(','); - - for (var i = 1, j = 0; i < accepts.length; i++) { - if (quoteCount(accepts[j]) % 2 == 0) { - accepts[++j] = accepts[i]; - } else { - accepts[j] += ',' + accepts[i]; - } - } - - // trim accepts - accepts.length = j + 1; - - return accepts; -} - -/** - * Split a string of parameters. - * @private - */ - -function splitParameters(str) { - var parameters = str.split(';'); - - for (var i = 1, j = 0; i < parameters.length; i++) { - if (quoteCount(parameters[j]) % 2 == 0) { - parameters[++j] = parameters[i]; - } else { - parameters[j] += ';' + parameters[i]; - } - } - - // trim parameters - parameters.length = j + 1; - - for (var i = 0; i < parameters.length; i++) { - parameters[i] = parameters[i].trim(); - } - - return parameters; -} -mediaType.preferredMediaTypes = preferredMediaTypes_1; - -/*! - * negotiator - * Copyright(c) 2012 Federico Romero - * Copyright(c) 2012-2014 Isaac Z. Schlueter - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Cached loaded submodules. - * @private - */ - -var modules = Object.create(null); - -/** - * Module exports. - * @public - */ - -var negotiator = Negotiator; -var Negotiator_1 = Negotiator; - -/** - * Create a Negotiator instance from a request. - * @param {object} request - * @public - */ - -function Negotiator(request) { - if (!(this instanceof Negotiator)) { - return new Negotiator(request); - } - - this.request = request; -} - -Negotiator.prototype.charset = function charset(available) { - var set = this.charsets(available); - return set && set[0]; -}; - -Negotiator.prototype.charsets = function charsets(available) { - var preferredCharsets = loadModule('charset').preferredCharsets; - return preferredCharsets(this.request.headers['accept-charset'], available); -}; - -Negotiator.prototype.encoding = function encoding(available) { - var set = this.encodings(available); - return set && set[0]; -}; - -Negotiator.prototype.encodings = function encodings(available) { - var preferredEncodings = loadModule('encoding').preferredEncodings; - return preferredEncodings(this.request.headers['accept-encoding'], available); -}; - -Negotiator.prototype.language = function language(available) { - var set = this.languages(available); - return set && set[0]; -}; - -Negotiator.prototype.languages = function languages(available) { - var preferredLanguages = loadModule('language').preferredLanguages; - return preferredLanguages(this.request.headers['accept-language'], available); -}; - -Negotiator.prototype.mediaType = function mediaType(available) { - var set = this.mediaTypes(available); - return set && set[0]; -}; - -Negotiator.prototype.mediaTypes = function mediaTypes(available) { - var preferredMediaTypes = loadModule('mediaType').preferredMediaTypes; - return preferredMediaTypes(this.request.headers.accept, available); -}; - -// Backwards compatibility -Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; -Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; -Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; -Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; -Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; -Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; -Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; -Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; - -/** - * Load the given module. - * @private - */ - -function loadModule(moduleName) { - var module = modules[moduleName]; - - if (module !== undefined) { - return module; - } - - // This uses a switch for static require analysis - switch (moduleName) { - case 'charset': - module = charset; - break; - case 'encoding': - module = encoding; - break; - case 'language': - module = language; - break; - case 'mediaType': - module = mediaType; - break; - default: - throw new Error('Cannot find module \'' + moduleName + '\''); - } - - // Store to prevent invoking require() - modules[moduleName] = module; - - return module; -} -negotiator.Negotiator = Negotiator_1; - -var require$$0 = { - "application/1d-interleaved-parityfec": { - source: "iana" -}, - "application/3gpdash-qoe-report+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/3gpp-ims+xml": { - source: "iana", - compressible: true -}, - "application/a2l": { - source: "iana" -}, - "application/activemessage": { - source: "iana" -}, - "application/activity+json": { - source: "iana", - compressible: true -}, - "application/alto-costmap+json": { - source: "iana", - compressible: true -}, - "application/alto-costmapfilter+json": { - source: "iana", - compressible: true -}, - "application/alto-directory+json": { - source: "iana", - compressible: true -}, - "application/alto-endpointcost+json": { - source: "iana", - compressible: true -}, - "application/alto-endpointcostparams+json": { - source: "iana", - compressible: true -}, - "application/alto-endpointprop+json": { - source: "iana", - compressible: true -}, - "application/alto-endpointpropparams+json": { - source: "iana", - compressible: true -}, - "application/alto-error+json": { - source: "iana", - compressible: true -}, - "application/alto-networkmap+json": { - source: "iana", - compressible: true -}, - "application/alto-networkmapfilter+json": { - source: "iana", - compressible: true -}, - "application/alto-updatestreamcontrol+json": { - source: "iana", - compressible: true -}, - "application/alto-updatestreamparams+json": { - source: "iana", - compressible: true -}, - "application/aml": { - source: "iana" -}, - "application/andrew-inset": { - source: "iana", - extensions: [ - "ez" - ] -}, - "application/applefile": { - source: "iana" -}, - "application/applixware": { - source: "apache", - extensions: [ - "aw" - ] -}, - "application/atf": { - source: "iana" -}, - "application/atfx": { - source: "iana" -}, - "application/atom+xml": { - source: "iana", - compressible: true, - extensions: [ - "atom" - ] -}, - "application/atomcat+xml": { - source: "iana", - compressible: true, - extensions: [ - "atomcat" - ] -}, - "application/atomdeleted+xml": { - source: "iana", - compressible: true, - extensions: [ - "atomdeleted" - ] -}, - "application/atomicmail": { - source: "iana" -}, - "application/atomsvc+xml": { - source: "iana", - compressible: true, - extensions: [ - "atomsvc" - ] -}, - "application/atsc-dwd+xml": { - source: "iana", - compressible: true, - extensions: [ - "dwd" - ] -}, - "application/atsc-dynamic-event-message": { - source: "iana" -}, - "application/atsc-held+xml": { - source: "iana", - compressible: true, - extensions: [ - "held" - ] -}, - "application/atsc-rdt+json": { - source: "iana", - compressible: true -}, - "application/atsc-rsat+xml": { - source: "iana", - compressible: true, - extensions: [ - "rsat" - ] -}, - "application/atxml": { - source: "iana" -}, - "application/auth-policy+xml": { - source: "iana", - compressible: true -}, - "application/bacnet-xdd+zip": { - source: "iana", - compressible: false -}, - "application/batch-smtp": { - source: "iana" -}, - "application/bdoc": { - compressible: false, - extensions: [ - "bdoc" - ] -}, - "application/beep+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/calendar+json": { - source: "iana", - compressible: true -}, - "application/calendar+xml": { - source: "iana", - compressible: true, - extensions: [ - "xcs" - ] -}, - "application/call-completion": { - source: "iana" -}, - "application/cals-1840": { - source: "iana" -}, - "application/captive+json": { - source: "iana", - compressible: true -}, - "application/cbor": { - source: "iana" -}, - "application/cbor-seq": { - source: "iana" -}, - "application/cccex": { - source: "iana" -}, - "application/ccmp+xml": { - source: "iana", - compressible: true -}, - "application/ccxml+xml": { - source: "iana", - compressible: true, - extensions: [ - "ccxml" - ] -}, - "application/cdfx+xml": { - source: "iana", - compressible: true, - extensions: [ - "cdfx" - ] -}, - "application/cdmi-capability": { - source: "iana", - extensions: [ - "cdmia" - ] -}, - "application/cdmi-container": { - source: "iana", - extensions: [ - "cdmic" - ] -}, - "application/cdmi-domain": { - source: "iana", - extensions: [ - "cdmid" - ] -}, - "application/cdmi-object": { - source: "iana", - extensions: [ - "cdmio" - ] -}, - "application/cdmi-queue": { - source: "iana", - extensions: [ - "cdmiq" - ] -}, - "application/cdni": { - source: "iana" -}, - "application/cea": { - source: "iana" -}, - "application/cea-2018+xml": { - source: "iana", - compressible: true -}, - "application/cellml+xml": { - source: "iana", - compressible: true -}, - "application/cfw": { - source: "iana" -}, - "application/clr": { - source: "iana" -}, - "application/clue+xml": { - source: "iana", - compressible: true -}, - "application/clue_info+xml": { - source: "iana", - compressible: true -}, - "application/cms": { - source: "iana" -}, - "application/cnrp+xml": { - source: "iana", - compressible: true -}, - "application/coap-group+json": { - source: "iana", - compressible: true -}, - "application/coap-payload": { - source: "iana" -}, - "application/commonground": { - source: "iana" -}, - "application/conference-info+xml": { - source: "iana", - compressible: true -}, - "application/cose": { - source: "iana" -}, - "application/cose-key": { - source: "iana" -}, - "application/cose-key-set": { - source: "iana" -}, - "application/cpl+xml": { - source: "iana", - compressible: true -}, - "application/csrattrs": { - source: "iana" -}, - "application/csta+xml": { - source: "iana", - compressible: true -}, - "application/cstadata+xml": { - source: "iana", - compressible: true -}, - "application/csvm+json": { - source: "iana", - compressible: true -}, - "application/cu-seeme": { - source: "apache", - extensions: [ - "cu" - ] -}, - "application/cwt": { - source: "iana" -}, - "application/cybercash": { - source: "iana" -}, - "application/dart": { - compressible: true -}, - "application/dash+xml": { - source: "iana", - compressible: true, - extensions: [ - "mpd" - ] -}, - "application/dashdelta": { - source: "iana" -}, - "application/davmount+xml": { - source: "iana", - compressible: true, - extensions: [ - "davmount" - ] -}, - "application/dca-rft": { - source: "iana" -}, - "application/dcd": { - source: "iana" -}, - "application/dec-dx": { - source: "iana" -}, - "application/dialog-info+xml": { - source: "iana", - compressible: true -}, - "application/dicom": { - source: "iana" -}, - "application/dicom+json": { - source: "iana", - compressible: true -}, - "application/dicom+xml": { - source: "iana", - compressible: true -}, - "application/dii": { - source: "iana" -}, - "application/dit": { - source: "iana" -}, - "application/dns": { - source: "iana" -}, - "application/dns+json": { - source: "iana", - compressible: true -}, - "application/dns-message": { - source: "iana" -}, - "application/docbook+xml": { - source: "apache", - compressible: true, - extensions: [ - "dbk" - ] -}, - "application/dots+cbor": { - source: "iana" -}, - "application/dskpp+xml": { - source: "iana", - compressible: true -}, - "application/dssc+der": { - source: "iana", - extensions: [ - "dssc" - ] -}, - "application/dssc+xml": { - source: "iana", - compressible: true, - extensions: [ - "xdssc" - ] -}, - "application/dvcs": { - source: "iana" -}, - "application/ecmascript": { - source: "iana", - compressible: true, - extensions: [ - "ecma", - "es" - ] -}, - "application/edi-consent": { - source: "iana" -}, - "application/edi-x12": { - source: "iana", - compressible: false -}, - "application/edifact": { - source: "iana", - compressible: false -}, - "application/efi": { - source: "iana" -}, - "application/elm+json": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/elm+xml": { - source: "iana", - compressible: true -}, - "application/emergencycalldata.cap+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/emergencycalldata.comment+xml": { - source: "iana", - compressible: true -}, - "application/emergencycalldata.control+xml": { - source: "iana", - compressible: true -}, - "application/emergencycalldata.deviceinfo+xml": { - source: "iana", - compressible: true -}, - "application/emergencycalldata.ecall.msd": { - source: "iana" -}, - "application/emergencycalldata.providerinfo+xml": { - source: "iana", - compressible: true -}, - "application/emergencycalldata.serviceinfo+xml": { - source: "iana", - compressible: true -}, - "application/emergencycalldata.subscriberinfo+xml": { - source: "iana", - compressible: true -}, - "application/emergencycalldata.veds+xml": { - source: "iana", - compressible: true -}, - "application/emma+xml": { - source: "iana", - compressible: true, - extensions: [ - "emma" - ] -}, - "application/emotionml+xml": { - source: "iana", - compressible: true, - extensions: [ - "emotionml" - ] -}, - "application/encaprtp": { - source: "iana" -}, - "application/epp+xml": { - source: "iana", - compressible: true -}, - "application/epub+zip": { - source: "iana", - compressible: false, - extensions: [ - "epub" - ] -}, - "application/eshop": { - source: "iana" -}, - "application/exi": { - source: "iana", - extensions: [ - "exi" - ] -}, - "application/expect-ct-report+json": { - source: "iana", - compressible: true -}, - "application/fastinfoset": { - source: "iana" -}, - "application/fastsoap": { - source: "iana" -}, - "application/fdt+xml": { - source: "iana", - compressible: true, - extensions: [ - "fdt" - ] -}, - "application/fhir+json": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/fhir+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/fido.trusted-apps+json": { - compressible: true -}, - "application/fits": { - source: "iana" -}, - "application/flexfec": { - source: "iana" -}, - "application/font-sfnt": { - source: "iana" -}, - "application/font-tdpfr": { - source: "iana", - extensions: [ - "pfr" - ] -}, - "application/font-woff": { - source: "iana", - compressible: false -}, - "application/framework-attributes+xml": { - source: "iana", - compressible: true -}, - "application/geo+json": { - source: "iana", - compressible: true, - extensions: [ - "geojson" - ] -}, - "application/geo+json-seq": { - source: "iana" -}, - "application/geopackage+sqlite3": { - source: "iana" -}, - "application/geoxacml+xml": { - source: "iana", - compressible: true -}, - "application/gltf-buffer": { - source: "iana" -}, - "application/gml+xml": { - source: "iana", - compressible: true, - extensions: [ - "gml" - ] -}, - "application/gpx+xml": { - source: "apache", - compressible: true, - extensions: [ - "gpx" - ] -}, - "application/gxf": { - source: "apache", - extensions: [ - "gxf" - ] -}, - "application/gzip": { - source: "iana", - compressible: false, - extensions: [ - "gz" - ] -}, - "application/h224": { - source: "iana" -}, - "application/held+xml": { - source: "iana", - compressible: true -}, - "application/hjson": { - extensions: [ - "hjson" - ] -}, - "application/http": { - source: "iana" -}, - "application/hyperstudio": { - source: "iana", - extensions: [ - "stk" - ] -}, - "application/ibe-key-request+xml": { - source: "iana", - compressible: true -}, - "application/ibe-pkg-reply+xml": { - source: "iana", - compressible: true -}, - "application/ibe-pp-data": { - source: "iana" -}, - "application/iges": { - source: "iana" -}, - "application/im-iscomposing+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/index": { - source: "iana" -}, - "application/index.cmd": { - source: "iana" -}, - "application/index.obj": { - source: "iana" -}, - "application/index.response": { - source: "iana" -}, - "application/index.vnd": { - source: "iana" -}, - "application/inkml+xml": { - source: "iana", - compressible: true, - extensions: [ - "ink", - "inkml" - ] -}, - "application/iotp": { - source: "iana" -}, - "application/ipfix": { - source: "iana", - extensions: [ - "ipfix" - ] -}, - "application/ipp": { - source: "iana" -}, - "application/isup": { - source: "iana" -}, - "application/its+xml": { - source: "iana", - compressible: true, - extensions: [ - "its" - ] -}, - "application/java-archive": { - source: "apache", - compressible: false, - extensions: [ - "jar", - "war", - "ear" - ] -}, - "application/java-serialized-object": { - source: "apache", - compressible: false, - extensions: [ - "ser" - ] -}, - "application/java-vm": { - source: "apache", - compressible: false, - extensions: [ - "class" - ] -}, - "application/javascript": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: [ - "js", - "mjs" - ] -}, - "application/jf2feed+json": { - source: "iana", - compressible: true -}, - "application/jose": { - source: "iana" -}, - "application/jose+json": { - source: "iana", - compressible: true -}, - "application/jrd+json": { - source: "iana", - compressible: true -}, - "application/jscalendar+json": { - source: "iana", - compressible: true -}, - "application/json": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: [ - "json", - "map" - ] -}, - "application/json-patch+json": { - source: "iana", - compressible: true -}, - "application/json-seq": { - source: "iana" -}, - "application/json5": { - extensions: [ - "json5" - ] -}, - "application/jsonml+json": { - source: "apache", - compressible: true, - extensions: [ - "jsonml" - ] -}, - "application/jwk+json": { - source: "iana", - compressible: true -}, - "application/jwk-set+json": { - source: "iana", - compressible: true -}, - "application/jwt": { - source: "iana" -}, - "application/kpml-request+xml": { - source: "iana", - compressible: true -}, - "application/kpml-response+xml": { - source: "iana", - compressible: true -}, - "application/ld+json": { - source: "iana", - compressible: true, - extensions: [ - "jsonld" - ] -}, - "application/lgr+xml": { - source: "iana", - compressible: true, - extensions: [ - "lgr" - ] -}, - "application/link-format": { - source: "iana" -}, - "application/load-control+xml": { - source: "iana", - compressible: true -}, - "application/lost+xml": { - source: "iana", - compressible: true, - extensions: [ - "lostxml" - ] -}, - "application/lostsync+xml": { - source: "iana", - compressible: true -}, - "application/lpf+zip": { - source: "iana", - compressible: false -}, - "application/lxf": { - source: "iana" -}, - "application/mac-binhex40": { - source: "iana", - extensions: [ - "hqx" - ] -}, - "application/mac-compactpro": { - source: "apache", - extensions: [ - "cpt" - ] -}, - "application/macwriteii": { - source: "iana" -}, - "application/mads+xml": { - source: "iana", - compressible: true, - extensions: [ - "mads" - ] -}, - "application/manifest+json": { - charset: "UTF-8", - compressible: true, - extensions: [ - "webmanifest" - ] -}, - "application/marc": { - source: "iana", - extensions: [ - "mrc" - ] -}, - "application/marcxml+xml": { - source: "iana", - compressible: true, - extensions: [ - "mrcx" - ] -}, - "application/mathematica": { - source: "iana", - extensions: [ - "ma", - "nb", - "mb" - ] -}, - "application/mathml+xml": { - source: "iana", - compressible: true, - extensions: [ - "mathml" - ] -}, - "application/mathml-content+xml": { - source: "iana", - compressible: true -}, - "application/mathml-presentation+xml": { - source: "iana", - compressible: true -}, - "application/mbms-associated-procedure-description+xml": { - source: "iana", - compressible: true -}, - "application/mbms-deregister+xml": { - source: "iana", - compressible: true -}, - "application/mbms-envelope+xml": { - source: "iana", - compressible: true -}, - "application/mbms-msk+xml": { - source: "iana", - compressible: true -}, - "application/mbms-msk-response+xml": { - source: "iana", - compressible: true -}, - "application/mbms-protection-description+xml": { - source: "iana", - compressible: true -}, - "application/mbms-reception-report+xml": { - source: "iana", - compressible: true -}, - "application/mbms-register+xml": { - source: "iana", - compressible: true -}, - "application/mbms-register-response+xml": { - source: "iana", - compressible: true -}, - "application/mbms-schedule+xml": { - source: "iana", - compressible: true -}, - "application/mbms-user-service-description+xml": { - source: "iana", - compressible: true -}, - "application/mbox": { - source: "iana", - extensions: [ - "mbox" - ] -}, - "application/media-policy-dataset+xml": { - source: "iana", - compressible: true -}, - "application/media_control+xml": { - source: "iana", - compressible: true -}, - "application/mediaservercontrol+xml": { - source: "iana", - compressible: true, - extensions: [ - "mscml" - ] -}, - "application/merge-patch+json": { - source: "iana", - compressible: true -}, - "application/metalink+xml": { - source: "apache", - compressible: true, - extensions: [ - "metalink" - ] -}, - "application/metalink4+xml": { - source: "iana", - compressible: true, - extensions: [ - "meta4" - ] -}, - "application/mets+xml": { - source: "iana", - compressible: true, - extensions: [ - "mets" - ] -}, - "application/mf4": { - source: "iana" -}, - "application/mikey": { - source: "iana" -}, - "application/mipc": { - source: "iana" -}, - "application/mmt-aei+xml": { - source: "iana", - compressible: true, - extensions: [ - "maei" - ] -}, - "application/mmt-usd+xml": { - source: "iana", - compressible: true, - extensions: [ - "musd" - ] -}, - "application/mods+xml": { - source: "iana", - compressible: true, - extensions: [ - "mods" - ] -}, - "application/moss-keys": { - source: "iana" -}, - "application/moss-signature": { - source: "iana" -}, - "application/mosskey-data": { - source: "iana" -}, - "application/mosskey-request": { - source: "iana" -}, - "application/mp21": { - source: "iana", - extensions: [ - "m21", - "mp21" - ] -}, - "application/mp4": { - source: "iana", - extensions: [ - "mp4s", - "m4p" - ] -}, - "application/mpeg4-generic": { - source: "iana" -}, - "application/mpeg4-iod": { - source: "iana" -}, - "application/mpeg4-iod-xmt": { - source: "iana" -}, - "application/mrb-consumer+xml": { - source: "iana", - compressible: true, - extensions: [ - "xdf" - ] -}, - "application/mrb-publish+xml": { - source: "iana", - compressible: true, - extensions: [ - "xdf" - ] -}, - "application/msc-ivr+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/msc-mixer+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/msword": { - source: "iana", - compressible: false, - extensions: [ - "doc", - "dot" - ] -}, - "application/mud+json": { - source: "iana", - compressible: true -}, - "application/multipart-core": { - source: "iana" -}, - "application/mxf": { - source: "iana", - extensions: [ - "mxf" - ] -}, - "application/n-quads": { - source: "iana", - extensions: [ - "nq" - ] -}, - "application/n-triples": { - source: "iana", - extensions: [ - "nt" - ] -}, - "application/nasdata": { - source: "iana" -}, - "application/news-checkgroups": { - source: "iana", - charset: "US-ASCII" -}, - "application/news-groupinfo": { - source: "iana", - charset: "US-ASCII" -}, - "application/news-transmission": { - source: "iana" -}, - "application/nlsml+xml": { - source: "iana", - compressible: true -}, - "application/node": { - source: "iana", - extensions: [ - "cjs" - ] -}, - "application/nss": { - source: "iana" -}, - "application/ocsp-request": { - source: "iana" -}, - "application/ocsp-response": { - source: "iana" -}, - "application/octet-stream": { - source: "iana", - compressible: false, - extensions: [ - "bin", - "dms", - "lrf", - "mar", - "so", - "dist", - "distz", - "pkg", - "bpk", - "dump", - "elc", - "deploy", - "exe", - "dll", - "deb", - "dmg", - "iso", - "img", - "msi", - "msp", - "msm", - "buffer" - ] -}, - "application/oda": { - source: "iana", - extensions: [ - "oda" - ] -}, - "application/odm+xml": { - source: "iana", - compressible: true -}, - "application/odx": { - source: "iana" -}, - "application/oebps-package+xml": { - source: "iana", - compressible: true, - extensions: [ - "opf" - ] -}, - "application/ogg": { - source: "iana", - compressible: false, - extensions: [ - "ogx" - ] -}, - "application/omdoc+xml": { - source: "apache", - compressible: true, - extensions: [ - "omdoc" - ] -}, - "application/onenote": { - source: "apache", - extensions: [ - "onetoc", - "onetoc2", - "onetmp", - "onepkg" - ] -}, - "application/opc-nodeset+xml": { - source: "iana", - compressible: true -}, - "application/oscore": { - source: "iana" -}, - "application/oxps": { - source: "iana", - extensions: [ - "oxps" - ] -}, - "application/p2p-overlay+xml": { - source: "iana", - compressible: true, - extensions: [ - "relo" - ] -}, - "application/parityfec": { - source: "iana" -}, - "application/passport": { - source: "iana" -}, - "application/patch-ops-error+xml": { - source: "iana", - compressible: true, - extensions: [ - "xer" - ] -}, - "application/pdf": { - source: "iana", - compressible: false, - extensions: [ - "pdf" - ] -}, - "application/pdx": { - source: "iana" -}, - "application/pem-certificate-chain": { - source: "iana" -}, - "application/pgp-encrypted": { - source: "iana", - compressible: false, - extensions: [ - "pgp" - ] -}, - "application/pgp-keys": { - source: "iana" -}, - "application/pgp-signature": { - source: "iana", - extensions: [ - "asc", - "sig" - ] -}, - "application/pics-rules": { - source: "apache", - extensions: [ - "prf" - ] -}, - "application/pidf+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/pidf-diff+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/pkcs10": { - source: "iana", - extensions: [ - "p10" - ] -}, - "application/pkcs12": { - source: "iana" -}, - "application/pkcs7-mime": { - source: "iana", - extensions: [ - "p7m", - "p7c" - ] -}, - "application/pkcs7-signature": { - source: "iana", - extensions: [ - "p7s" - ] -}, - "application/pkcs8": { - source: "iana", - extensions: [ - "p8" - ] -}, - "application/pkcs8-encrypted": { - source: "iana" -}, - "application/pkix-attr-cert": { - source: "iana", - extensions: [ - "ac" - ] -}, - "application/pkix-cert": { - source: "iana", - extensions: [ - "cer" - ] -}, - "application/pkix-crl": { - source: "iana", - extensions: [ - "crl" - ] -}, - "application/pkix-pkipath": { - source: "iana", - extensions: [ - "pkipath" - ] -}, - "application/pkixcmp": { - source: "iana", - extensions: [ - "pki" - ] -}, - "application/pls+xml": { - source: "iana", - compressible: true, - extensions: [ - "pls" - ] -}, - "application/poc-settings+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/postscript": { - source: "iana", - compressible: true, - extensions: [ - "ai", - "eps", - "ps" - ] -}, - "application/ppsp-tracker+json": { - source: "iana", - compressible: true -}, - "application/problem+json": { - source: "iana", - compressible: true -}, - "application/problem+xml": { - source: "iana", - compressible: true -}, - "application/provenance+xml": { - source: "iana", - compressible: true, - extensions: [ - "provx" - ] -}, - "application/prs.alvestrand.titrax-sheet": { - source: "iana" -}, - "application/prs.cww": { - source: "iana", - extensions: [ - "cww" - ] -}, - "application/prs.cyn": { - source: "iana", - charset: "7-BIT" -}, - "application/prs.hpub+zip": { - source: "iana", - compressible: false -}, - "application/prs.nprend": { - source: "iana" -}, - "application/prs.plucker": { - source: "iana" -}, - "application/prs.rdf-xml-crypt": { - source: "iana" -}, - "application/prs.xsf+xml": { - source: "iana", - compressible: true -}, - "application/pskc+xml": { - source: "iana", - compressible: true, - extensions: [ - "pskcxml" - ] -}, - "application/pvd+json": { - source: "iana", - compressible: true -}, - "application/qsig": { - source: "iana" -}, - "application/raml+yaml": { - compressible: true, - extensions: [ - "raml" - ] -}, - "application/raptorfec": { - source: "iana" -}, - "application/rdap+json": { - source: "iana", - compressible: true -}, - "application/rdf+xml": { - source: "iana", - compressible: true, - extensions: [ - "rdf", - "owl" - ] -}, - "application/reginfo+xml": { - source: "iana", - compressible: true, - extensions: [ - "rif" - ] -}, - "application/relax-ng-compact-syntax": { - source: "iana", - extensions: [ - "rnc" - ] -}, - "application/remote-printing": { - source: "iana" -}, - "application/reputon+json": { - source: "iana", - compressible: true -}, - "application/resource-lists+xml": { - source: "iana", - compressible: true, - extensions: [ - "rl" - ] -}, - "application/resource-lists-diff+xml": { - source: "iana", - compressible: true, - extensions: [ - "rld" - ] -}, - "application/rfc+xml": { - source: "iana", - compressible: true -}, - "application/riscos": { - source: "iana" -}, - "application/rlmi+xml": { - source: "iana", - compressible: true -}, - "application/rls-services+xml": { - source: "iana", - compressible: true, - extensions: [ - "rs" - ] -}, - "application/route-apd+xml": { - source: "iana", - compressible: true, - extensions: [ - "rapd" - ] -}, - "application/route-s-tsid+xml": { - source: "iana", - compressible: true, - extensions: [ - "sls" - ] -}, - "application/route-usd+xml": { - source: "iana", - compressible: true, - extensions: [ - "rusd" - ] -}, - "application/rpki-ghostbusters": { - source: "iana", - extensions: [ - "gbr" - ] -}, - "application/rpki-manifest": { - source: "iana", - extensions: [ - "mft" - ] -}, - "application/rpki-publication": { - source: "iana" -}, - "application/rpki-roa": { - source: "iana", - extensions: [ - "roa" - ] -}, - "application/rpki-updown": { - source: "iana" -}, - "application/rsd+xml": { - source: "apache", - compressible: true, - extensions: [ - "rsd" - ] -}, - "application/rss+xml": { - source: "apache", - compressible: true, - extensions: [ - "rss" - ] -}, - "application/rtf": { - source: "iana", - compressible: true, - extensions: [ - "rtf" - ] -}, - "application/rtploopback": { - source: "iana" -}, - "application/rtx": { - source: "iana" -}, - "application/samlassertion+xml": { - source: "iana", - compressible: true -}, - "application/samlmetadata+xml": { - source: "iana", - compressible: true -}, - "application/sarif+json": { - source: "iana", - compressible: true -}, - "application/sbe": { - source: "iana" -}, - "application/sbml+xml": { - source: "iana", - compressible: true, - extensions: [ - "sbml" - ] -}, - "application/scaip+xml": { - source: "iana", - compressible: true -}, - "application/scim+json": { - source: "iana", - compressible: true -}, - "application/scvp-cv-request": { - source: "iana", - extensions: [ - "scq" - ] -}, - "application/scvp-cv-response": { - source: "iana", - extensions: [ - "scs" - ] -}, - "application/scvp-vp-request": { - source: "iana", - extensions: [ - "spq" - ] -}, - "application/scvp-vp-response": { - source: "iana", - extensions: [ - "spp" - ] -}, - "application/sdp": { - source: "iana", - extensions: [ - "sdp" - ] -}, - "application/secevent+jwt": { - source: "iana" -}, - "application/senml+cbor": { - source: "iana" -}, - "application/senml+json": { - source: "iana", - compressible: true -}, - "application/senml+xml": { - source: "iana", - compressible: true, - extensions: [ - "senmlx" - ] -}, - "application/senml-etch+cbor": { - source: "iana" -}, - "application/senml-etch+json": { - source: "iana", - compressible: true -}, - "application/senml-exi": { - source: "iana" -}, - "application/sensml+cbor": { - source: "iana" -}, - "application/sensml+json": { - source: "iana", - compressible: true -}, - "application/sensml+xml": { - source: "iana", - compressible: true, - extensions: [ - "sensmlx" - ] -}, - "application/sensml-exi": { - source: "iana" -}, - "application/sep+xml": { - source: "iana", - compressible: true -}, - "application/sep-exi": { - source: "iana" -}, - "application/session-info": { - source: "iana" -}, - "application/set-payment": { - source: "iana" -}, - "application/set-payment-initiation": { - source: "iana", - extensions: [ - "setpay" - ] -}, - "application/set-registration": { - source: "iana" -}, - "application/set-registration-initiation": { - source: "iana", - extensions: [ - "setreg" - ] -}, - "application/sgml": { - source: "iana" -}, - "application/sgml-open-catalog": { - source: "iana" -}, - "application/shf+xml": { - source: "iana", - compressible: true, - extensions: [ - "shf" - ] -}, - "application/sieve": { - source: "iana", - extensions: [ - "siv", - "sieve" - ] -}, - "application/simple-filter+xml": { - source: "iana", - compressible: true -}, - "application/simple-message-summary": { - source: "iana" -}, - "application/simplesymbolcontainer": { - source: "iana" -}, - "application/sipc": { - source: "iana" -}, - "application/slate": { - source: "iana" -}, - "application/smil": { - source: "iana" -}, - "application/smil+xml": { - source: "iana", - compressible: true, - extensions: [ - "smi", - "smil" - ] -}, - "application/smpte336m": { - source: "iana" -}, - "application/soap+fastinfoset": { - source: "iana" -}, - "application/soap+xml": { - source: "iana", - compressible: true -}, - "application/sparql-query": { - source: "iana", - extensions: [ - "rq" - ] -}, - "application/sparql-results+xml": { - source: "iana", - compressible: true, - extensions: [ - "srx" - ] -}, - "application/spirits-event+xml": { - source: "iana", - compressible: true -}, - "application/sql": { - source: "iana" -}, - "application/srgs": { - source: "iana", - extensions: [ - "gram" - ] -}, - "application/srgs+xml": { - source: "iana", - compressible: true, - extensions: [ - "grxml" - ] -}, - "application/sru+xml": { - source: "iana", - compressible: true, - extensions: [ - "sru" - ] -}, - "application/ssdl+xml": { - source: "apache", - compressible: true, - extensions: [ - "ssdl" - ] -}, - "application/ssml+xml": { - source: "iana", - compressible: true, - extensions: [ - "ssml" - ] -}, - "application/stix+json": { - source: "iana", - compressible: true -}, - "application/swid+xml": { - source: "iana", - compressible: true, - extensions: [ - "swidtag" - ] -}, - "application/tamp-apex-update": { - source: "iana" -}, - "application/tamp-apex-update-confirm": { - source: "iana" -}, - "application/tamp-community-update": { - source: "iana" -}, - "application/tamp-community-update-confirm": { - source: "iana" -}, - "application/tamp-error": { - source: "iana" -}, - "application/tamp-sequence-adjust": { - source: "iana" -}, - "application/tamp-sequence-adjust-confirm": { - source: "iana" -}, - "application/tamp-status-query": { - source: "iana" -}, - "application/tamp-status-response": { - source: "iana" -}, - "application/tamp-update": { - source: "iana" -}, - "application/tamp-update-confirm": { - source: "iana" -}, - "application/tar": { - compressible: true -}, - "application/taxii+json": { - source: "iana", - compressible: true -}, - "application/td+json": { - source: "iana", - compressible: true -}, - "application/tei+xml": { - source: "iana", - compressible: true, - extensions: [ - "tei", - "teicorpus" - ] -}, - "application/tetra_isi": { - source: "iana" -}, - "application/thraud+xml": { - source: "iana", - compressible: true, - extensions: [ - "tfi" - ] -}, - "application/timestamp-query": { - source: "iana" -}, - "application/timestamp-reply": { - source: "iana" -}, - "application/timestamped-data": { - source: "iana", - extensions: [ - "tsd" - ] -}, - "application/tlsrpt+gzip": { - source: "iana" -}, - "application/tlsrpt+json": { - source: "iana", - compressible: true -}, - "application/tnauthlist": { - source: "iana" -}, - "application/toml": { - compressible: true, - extensions: [ - "toml" - ] -}, - "application/trickle-ice-sdpfrag": { - source: "iana" -}, - "application/trig": { - source: "iana" -}, - "application/ttml+xml": { - source: "iana", - compressible: true, - extensions: [ - "ttml" - ] -}, - "application/tve-trigger": { - source: "iana" -}, - "application/tzif": { - source: "iana" -}, - "application/tzif-leap": { - source: "iana" -}, - "application/ubjson": { - compressible: false, - extensions: [ - "ubj" - ] -}, - "application/ulpfec": { - source: "iana" -}, - "application/urc-grpsheet+xml": { - source: "iana", - compressible: true -}, - "application/urc-ressheet+xml": { - source: "iana", - compressible: true, - extensions: [ - "rsheet" - ] -}, - "application/urc-targetdesc+xml": { - source: "iana", - compressible: true, - extensions: [ - "td" - ] -}, - "application/urc-uisocketdesc+xml": { - source: "iana", - compressible: true -}, - "application/vcard+json": { - source: "iana", - compressible: true -}, - "application/vcard+xml": { - source: "iana", - compressible: true -}, - "application/vemmi": { - source: "iana" -}, - "application/vividence.scriptfile": { - source: "apache" -}, - "application/vnd.1000minds.decision-model+xml": { - source: "iana", - compressible: true, - extensions: [ - "1km" - ] -}, - "application/vnd.3gpp-prose+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp-prose-pc3ch+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp-v2x-local-service-information": { - source: "iana" -}, - "application/vnd.3gpp.access-transfer-events+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.bsf+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.gmop+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.interworking-data": { - source: "iana" -}, - "application/vnd.3gpp.mc-signalling-ear": { - source: "iana" -}, - "application/vnd.3gpp.mcdata-affiliation-command+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcdata-info+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcdata-payload": { - source: "iana" -}, - "application/vnd.3gpp.mcdata-service-config+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcdata-signalling": { - source: "iana" -}, - "application/vnd.3gpp.mcdata-ue-config+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcdata-user-profile+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcptt-affiliation-command+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcptt-floor-request+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcptt-info+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcptt-location-info+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcptt-service-config+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcptt-signed+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcptt-ue-config+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcptt-ue-init-config+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcptt-user-profile+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcvideo-affiliation-command+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcvideo-affiliation-info+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcvideo-info+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcvideo-location-info+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcvideo-service-config+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcvideo-transmission-request+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcvideo-ue-config+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mcvideo-user-profile+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.mid-call+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.pic-bw-large": { - source: "iana", - extensions: [ - "plb" - ] -}, - "application/vnd.3gpp.pic-bw-small": { - source: "iana", - extensions: [ - "psb" - ] -}, - "application/vnd.3gpp.pic-bw-var": { - source: "iana", - extensions: [ - "pvb" - ] -}, - "application/vnd.3gpp.sms": { - source: "iana" -}, - "application/vnd.3gpp.sms+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.srvcc-ext+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.srvcc-info+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.state-and-event-info+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp.ussd+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp2.bcmcsinfo+xml": { - source: "iana", - compressible: true -}, - "application/vnd.3gpp2.sms": { - source: "iana" -}, - "application/vnd.3gpp2.tcap": { - source: "iana", - extensions: [ - "tcap" - ] -}, - "application/vnd.3lightssoftware.imagescal": { - source: "iana" -}, - "application/vnd.3m.post-it-notes": { - source: "iana", - extensions: [ - "pwn" - ] -}, - "application/vnd.accpac.simply.aso": { - source: "iana", - extensions: [ - "aso" - ] -}, - "application/vnd.accpac.simply.imp": { - source: "iana", - extensions: [ - "imp" - ] -}, - "application/vnd.acucobol": { - source: "iana", - extensions: [ - "acu" - ] -}, - "application/vnd.acucorp": { - source: "iana", - extensions: [ - "atc", - "acutc" - ] -}, - "application/vnd.adobe.air-application-installer-package+zip": { - source: "apache", - compressible: false, - extensions: [ - "air" - ] -}, - "application/vnd.adobe.flash.movie": { - source: "iana" -}, - "application/vnd.adobe.formscentral.fcdt": { - source: "iana", - extensions: [ - "fcdt" - ] -}, - "application/vnd.adobe.fxp": { - source: "iana", - extensions: [ - "fxp", - "fxpl" - ] -}, - "application/vnd.adobe.partial-upload": { - source: "iana" -}, - "application/vnd.adobe.xdp+xml": { - source: "iana", - compressible: true, - extensions: [ - "xdp" - ] -}, - "application/vnd.adobe.xfdf": { - source: "iana", - extensions: [ - "xfdf" - ] -}, - "application/vnd.aether.imp": { - source: "iana" -}, - "application/vnd.afpc.afplinedata": { - source: "iana" -}, - "application/vnd.afpc.afplinedata-pagedef": { - source: "iana" -}, - "application/vnd.afpc.cmoca-cmresource": { - source: "iana" -}, - "application/vnd.afpc.foca-charset": { - source: "iana" -}, - "application/vnd.afpc.foca-codedfont": { - source: "iana" -}, - "application/vnd.afpc.foca-codepage": { - source: "iana" -}, - "application/vnd.afpc.modca": { - source: "iana" -}, - "application/vnd.afpc.modca-cmtable": { - source: "iana" -}, - "application/vnd.afpc.modca-formdef": { - source: "iana" -}, - "application/vnd.afpc.modca-mediummap": { - source: "iana" -}, - "application/vnd.afpc.modca-objectcontainer": { - source: "iana" -}, - "application/vnd.afpc.modca-overlay": { - source: "iana" -}, - "application/vnd.afpc.modca-pagesegment": { - source: "iana" -}, - "application/vnd.ah-barcode": { - source: "iana" -}, - "application/vnd.ahead.space": { - source: "iana", - extensions: [ - "ahead" - ] -}, - "application/vnd.airzip.filesecure.azf": { - source: "iana", - extensions: [ - "azf" - ] -}, - "application/vnd.airzip.filesecure.azs": { - source: "iana", - extensions: [ - "azs" - ] -}, - "application/vnd.amadeus+json": { - source: "iana", - compressible: true -}, - "application/vnd.amazon.ebook": { - source: "apache", - extensions: [ - "azw" - ] -}, - "application/vnd.amazon.mobi8-ebook": { - source: "iana" -}, - "application/vnd.americandynamics.acc": { - source: "iana", - extensions: [ - "acc" - ] -}, - "application/vnd.amiga.ami": { - source: "iana", - extensions: [ - "ami" - ] -}, - "application/vnd.amundsen.maze+xml": { - source: "iana", - compressible: true -}, - "application/vnd.android.ota": { - source: "iana" -}, - "application/vnd.android.package-archive": { - source: "apache", - compressible: false, - extensions: [ - "apk" - ] -}, - "application/vnd.anki": { - source: "iana" -}, - "application/vnd.anser-web-certificate-issue-initiation": { - source: "iana", - extensions: [ - "cii" - ] -}, - "application/vnd.anser-web-funds-transfer-initiation": { - source: "apache", - extensions: [ - "fti" - ] -}, - "application/vnd.antix.game-component": { - source: "iana", - extensions: [ - "atx" - ] -}, - "application/vnd.apache.thrift.binary": { - source: "iana" -}, - "application/vnd.apache.thrift.compact": { - source: "iana" -}, - "application/vnd.apache.thrift.json": { - source: "iana" -}, - "application/vnd.api+json": { - source: "iana", - compressible: true -}, - "application/vnd.aplextor.warrp+json": { - source: "iana", - compressible: true -}, - "application/vnd.apothekende.reservation+json": { - source: "iana", - compressible: true -}, - "application/vnd.apple.installer+xml": { - source: "iana", - compressible: true, - extensions: [ - "mpkg" - ] -}, - "application/vnd.apple.keynote": { - source: "iana", - extensions: [ - "key" - ] -}, - "application/vnd.apple.mpegurl": { - source: "iana", - extensions: [ - "m3u8" - ] -}, - "application/vnd.apple.numbers": { - source: "iana", - extensions: [ - "numbers" - ] -}, - "application/vnd.apple.pages": { - source: "iana", - extensions: [ - "pages" - ] -}, - "application/vnd.apple.pkpass": { - compressible: false, - extensions: [ - "pkpass" - ] -}, - "application/vnd.arastra.swi": { - source: "iana" -}, - "application/vnd.aristanetworks.swi": { - source: "iana", - extensions: [ - "swi" - ] -}, - "application/vnd.artisan+json": { - source: "iana", - compressible: true -}, - "application/vnd.artsquare": { - source: "iana" -}, - "application/vnd.astraea-software.iota": { - source: "iana", - extensions: [ - "iota" - ] -}, - "application/vnd.audiograph": { - source: "iana", - extensions: [ - "aep" - ] -}, - "application/vnd.autopackage": { - source: "iana" -}, - "application/vnd.avalon+json": { - source: "iana", - compressible: true -}, - "application/vnd.avistar+xml": { - source: "iana", - compressible: true -}, - "application/vnd.balsamiq.bmml+xml": { - source: "iana", - compressible: true, - extensions: [ - "bmml" - ] -}, - "application/vnd.balsamiq.bmpr": { - source: "iana" -}, - "application/vnd.banana-accounting": { - source: "iana" -}, - "application/vnd.bbf.usp.error": { - source: "iana" -}, - "application/vnd.bbf.usp.msg": { - source: "iana" -}, - "application/vnd.bbf.usp.msg+json": { - source: "iana", - compressible: true -}, - "application/vnd.bekitzur-stech+json": { - source: "iana", - compressible: true -}, - "application/vnd.bint.med-content": { - source: "iana" -}, - "application/vnd.biopax.rdf+xml": { - source: "iana", - compressible: true -}, - "application/vnd.blink-idb-value-wrapper": { - source: "iana" -}, - "application/vnd.blueice.multipass": { - source: "iana", - extensions: [ - "mpm" - ] -}, - "application/vnd.bluetooth.ep.oob": { - source: "iana" -}, - "application/vnd.bluetooth.le.oob": { - source: "iana" -}, - "application/vnd.bmi": { - source: "iana", - extensions: [ - "bmi" - ] -}, - "application/vnd.bpf": { - source: "iana" -}, - "application/vnd.bpf3": { - source: "iana" -}, - "application/vnd.businessobjects": { - source: "iana", - extensions: [ - "rep" - ] -}, - "application/vnd.byu.uapi+json": { - source: "iana", - compressible: true -}, - "application/vnd.cab-jscript": { - source: "iana" -}, - "application/vnd.canon-cpdl": { - source: "iana" -}, - "application/vnd.canon-lips": { - source: "iana" -}, - "application/vnd.capasystems-pg+json": { - source: "iana", - compressible: true -}, - "application/vnd.cendio.thinlinc.clientconf": { - source: "iana" -}, - "application/vnd.century-systems.tcp_stream": { - source: "iana" -}, - "application/vnd.chemdraw+xml": { - source: "iana", - compressible: true, - extensions: [ - "cdxml" - ] -}, - "application/vnd.chess-pgn": { - source: "iana" -}, - "application/vnd.chipnuts.karaoke-mmd": { - source: "iana", - extensions: [ - "mmd" - ] -}, - "application/vnd.ciedi": { - source: "iana" -}, - "application/vnd.cinderella": { - source: "iana", - extensions: [ - "cdy" - ] -}, - "application/vnd.cirpack.isdn-ext": { - source: "iana" -}, - "application/vnd.citationstyles.style+xml": { - source: "iana", - compressible: true, - extensions: [ - "csl" - ] -}, - "application/vnd.claymore": { - source: "iana", - extensions: [ - "cla" - ] -}, - "application/vnd.cloanto.rp9": { - source: "iana", - extensions: [ - "rp9" - ] -}, - "application/vnd.clonk.c4group": { - source: "iana", - extensions: [ - "c4g", - "c4d", - "c4f", - "c4p", - "c4u" - ] -}, - "application/vnd.cluetrust.cartomobile-config": { - source: "iana", - extensions: [ - "c11amc" - ] -}, - "application/vnd.cluetrust.cartomobile-config-pkg": { - source: "iana", - extensions: [ - "c11amz" - ] -}, - "application/vnd.coffeescript": { - source: "iana" -}, - "application/vnd.collabio.xodocuments.document": { - source: "iana" -}, - "application/vnd.collabio.xodocuments.document-template": { - source: "iana" -}, - "application/vnd.collabio.xodocuments.presentation": { - source: "iana" -}, - "application/vnd.collabio.xodocuments.presentation-template": { - source: "iana" -}, - "application/vnd.collabio.xodocuments.spreadsheet": { - source: "iana" -}, - "application/vnd.collabio.xodocuments.spreadsheet-template": { - source: "iana" -}, - "application/vnd.collection+json": { - source: "iana", - compressible: true -}, - "application/vnd.collection.doc+json": { - source: "iana", - compressible: true -}, - "application/vnd.collection.next+json": { - source: "iana", - compressible: true -}, - "application/vnd.comicbook+zip": { - source: "iana", - compressible: false -}, - "application/vnd.comicbook-rar": { - source: "iana" -}, - "application/vnd.commerce-battelle": { - source: "iana" -}, - "application/vnd.commonspace": { - source: "iana", - extensions: [ - "csp" - ] -}, - "application/vnd.contact.cmsg": { - source: "iana", - extensions: [ - "cdbcmsg" - ] -}, - "application/vnd.coreos.ignition+json": { - source: "iana", - compressible: true -}, - "application/vnd.cosmocaller": { - source: "iana", - extensions: [ - "cmc" - ] -}, - "application/vnd.crick.clicker": { - source: "iana", - extensions: [ - "clkx" - ] -}, - "application/vnd.crick.clicker.keyboard": { - source: "iana", - extensions: [ - "clkk" - ] -}, - "application/vnd.crick.clicker.palette": { - source: "iana", - extensions: [ - "clkp" - ] -}, - "application/vnd.crick.clicker.template": { - source: "iana", - extensions: [ - "clkt" - ] -}, - "application/vnd.crick.clicker.wordbank": { - source: "iana", - extensions: [ - "clkw" - ] -}, - "application/vnd.criticaltools.wbs+xml": { - source: "iana", - compressible: true, - extensions: [ - "wbs" - ] -}, - "application/vnd.cryptii.pipe+json": { - source: "iana", - compressible: true -}, - "application/vnd.crypto-shade-file": { - source: "iana" -}, - "application/vnd.ctc-posml": { - source: "iana", - extensions: [ - "pml" - ] -}, - "application/vnd.ctct.ws+xml": { - source: "iana", - compressible: true -}, - "application/vnd.cups-pdf": { - source: "iana" -}, - "application/vnd.cups-postscript": { - source: "iana" -}, - "application/vnd.cups-ppd": { - source: "iana", - extensions: [ - "ppd" - ] -}, - "application/vnd.cups-raster": { - source: "iana" -}, - "application/vnd.cups-raw": { - source: "iana" -}, - "application/vnd.curl": { - source: "iana" -}, - "application/vnd.curl.car": { - source: "apache", - extensions: [ - "car" - ] -}, - "application/vnd.curl.pcurl": { - source: "apache", - extensions: [ - "pcurl" - ] -}, - "application/vnd.cyan.dean.root+xml": { - source: "iana", - compressible: true -}, - "application/vnd.cybank": { - source: "iana" -}, - "application/vnd.cyclonedx+json": { - source: "iana", - compressible: true -}, - "application/vnd.cyclonedx+xml": { - source: "iana", - compressible: true -}, - "application/vnd.d2l.coursepackage1p0+zip": { - source: "iana", - compressible: false -}, - "application/vnd.d3m-dataset": { - source: "iana" -}, - "application/vnd.d3m-problem": { - source: "iana" -}, - "application/vnd.dart": { - source: "iana", - compressible: true, - extensions: [ - "dart" - ] -}, - "application/vnd.data-vision.rdz": { - source: "iana", - extensions: [ - "rdz" - ] -}, - "application/vnd.datapackage+json": { - source: "iana", - compressible: true -}, - "application/vnd.dataresource+json": { - source: "iana", - compressible: true -}, - "application/vnd.dbf": { - source: "iana", - extensions: [ - "dbf" - ] -}, - "application/vnd.debian.binary-package": { - source: "iana" -}, - "application/vnd.dece.data": { - source: "iana", - extensions: [ - "uvf", - "uvvf", - "uvd", - "uvvd" - ] -}, - "application/vnd.dece.ttml+xml": { - source: "iana", - compressible: true, - extensions: [ - "uvt", - "uvvt" - ] -}, - "application/vnd.dece.unspecified": { - source: "iana", - extensions: [ - "uvx", - "uvvx" - ] -}, - "application/vnd.dece.zip": { - source: "iana", - extensions: [ - "uvz", - "uvvz" - ] -}, - "application/vnd.denovo.fcselayout-link": { - source: "iana", - extensions: [ - "fe_launch" - ] -}, - "application/vnd.desmume.movie": { - source: "iana" -}, - "application/vnd.dir-bi.plate-dl-nosuffix": { - source: "iana" -}, - "application/vnd.dm.delegation+xml": { - source: "iana", - compressible: true -}, - "application/vnd.dna": { - source: "iana", - extensions: [ - "dna" - ] -}, - "application/vnd.document+json": { - source: "iana", - compressible: true -}, - "application/vnd.dolby.mlp": { - source: "apache", - extensions: [ - "mlp" - ] -}, - "application/vnd.dolby.mobile.1": { - source: "iana" -}, - "application/vnd.dolby.mobile.2": { - source: "iana" -}, - "application/vnd.doremir.scorecloud-binary-document": { - source: "iana" -}, - "application/vnd.dpgraph": { - source: "iana", - extensions: [ - "dpg" - ] -}, - "application/vnd.dreamfactory": { - source: "iana", - extensions: [ - "dfac" - ] -}, - "application/vnd.drive+json": { - source: "iana", - compressible: true -}, - "application/vnd.ds-keypoint": { - source: "apache", - extensions: [ - "kpxx" - ] -}, - "application/vnd.dtg.local": { - source: "iana" -}, - "application/vnd.dtg.local.flash": { - source: "iana" -}, - "application/vnd.dtg.local.html": { - source: "iana" -}, - "application/vnd.dvb.ait": { - source: "iana", - extensions: [ - "ait" - ] -}, - "application/vnd.dvb.dvbisl+xml": { - source: "iana", - compressible: true -}, - "application/vnd.dvb.dvbj": { - source: "iana" -}, - "application/vnd.dvb.esgcontainer": { - source: "iana" -}, - "application/vnd.dvb.ipdcdftnotifaccess": { - source: "iana" -}, - "application/vnd.dvb.ipdcesgaccess": { - source: "iana" -}, - "application/vnd.dvb.ipdcesgaccess2": { - source: "iana" -}, - "application/vnd.dvb.ipdcesgpdd": { - source: "iana" -}, - "application/vnd.dvb.ipdcroaming": { - source: "iana" -}, - "application/vnd.dvb.iptv.alfec-base": { - source: "iana" -}, - "application/vnd.dvb.iptv.alfec-enhancement": { - source: "iana" -}, - "application/vnd.dvb.notif-aggregate-root+xml": { - source: "iana", - compressible: true -}, - "application/vnd.dvb.notif-container+xml": { - source: "iana", - compressible: true -}, - "application/vnd.dvb.notif-generic+xml": { - source: "iana", - compressible: true -}, - "application/vnd.dvb.notif-ia-msglist+xml": { - source: "iana", - compressible: true -}, - "application/vnd.dvb.notif-ia-registration-request+xml": { - source: "iana", - compressible: true -}, - "application/vnd.dvb.notif-ia-registration-response+xml": { - source: "iana", - compressible: true -}, - "application/vnd.dvb.notif-init+xml": { - source: "iana", - compressible: true -}, - "application/vnd.dvb.pfr": { - source: "iana" -}, - "application/vnd.dvb.service": { - source: "iana", - extensions: [ - "svc" - ] -}, - "application/vnd.dxr": { - source: "iana" -}, - "application/vnd.dynageo": { - source: "iana", - extensions: [ - "geo" - ] -}, - "application/vnd.dzr": { - source: "iana" -}, - "application/vnd.easykaraoke.cdgdownload": { - source: "iana" -}, - "application/vnd.ecdis-update": { - source: "iana" -}, - "application/vnd.ecip.rlp": { - source: "iana" -}, - "application/vnd.ecowin.chart": { - source: "iana", - extensions: [ - "mag" - ] -}, - "application/vnd.ecowin.filerequest": { - source: "iana" -}, - "application/vnd.ecowin.fileupdate": { - source: "iana" -}, - "application/vnd.ecowin.series": { - source: "iana" -}, - "application/vnd.ecowin.seriesrequest": { - source: "iana" -}, - "application/vnd.ecowin.seriesupdate": { - source: "iana" -}, - "application/vnd.efi.img": { - source: "iana" -}, - "application/vnd.efi.iso": { - source: "iana" -}, - "application/vnd.emclient.accessrequest+xml": { - source: "iana", - compressible: true -}, - "application/vnd.enliven": { - source: "iana", - extensions: [ - "nml" - ] -}, - "application/vnd.enphase.envoy": { - source: "iana" -}, - "application/vnd.eprints.data+xml": { - source: "iana", - compressible: true -}, - "application/vnd.epson.esf": { - source: "iana", - extensions: [ - "esf" - ] -}, - "application/vnd.epson.msf": { - source: "iana", - extensions: [ - "msf" - ] -}, - "application/vnd.epson.quickanime": { - source: "iana", - extensions: [ - "qam" - ] -}, - "application/vnd.epson.salt": { - source: "iana", - extensions: [ - "slt" - ] -}, - "application/vnd.epson.ssf": { - source: "iana", - extensions: [ - "ssf" - ] -}, - "application/vnd.ericsson.quickcall": { - source: "iana" -}, - "application/vnd.espass-espass+zip": { - source: "iana", - compressible: false -}, - "application/vnd.eszigno3+xml": { - source: "iana", - compressible: true, - extensions: [ - "es3", - "et3" - ] -}, - "application/vnd.etsi.aoc+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.asic-e+zip": { - source: "iana", - compressible: false -}, - "application/vnd.etsi.asic-s+zip": { - source: "iana", - compressible: false -}, - "application/vnd.etsi.cug+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.iptvcommand+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.iptvdiscovery+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.iptvprofile+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.iptvsad-bc+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.iptvsad-cod+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.iptvsad-npvr+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.iptvservice+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.iptvsync+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.iptvueprofile+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.mcid+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.mheg5": { - source: "iana" -}, - "application/vnd.etsi.overload-control-policy-dataset+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.pstn+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.sci+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.simservs+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.timestamp-token": { - source: "iana" -}, - "application/vnd.etsi.tsl+xml": { - source: "iana", - compressible: true -}, - "application/vnd.etsi.tsl.der": { - source: "iana" -}, - "application/vnd.eudora.data": { - source: "iana" -}, - "application/vnd.evolv.ecig.profile": { - source: "iana" -}, - "application/vnd.evolv.ecig.settings": { - source: "iana" -}, - "application/vnd.evolv.ecig.theme": { - source: "iana" -}, - "application/vnd.exstream-empower+zip": { - source: "iana", - compressible: false -}, - "application/vnd.exstream-package": { - source: "iana" -}, - "application/vnd.ezpix-album": { - source: "iana", - extensions: [ - "ez2" - ] -}, - "application/vnd.ezpix-package": { - source: "iana", - extensions: [ - "ez3" - ] -}, - "application/vnd.f-secure.mobile": { - source: "iana" -}, - "application/vnd.fastcopy-disk-image": { - source: "iana" -}, - "application/vnd.fdf": { - source: "iana", - extensions: [ - "fdf" - ] -}, - "application/vnd.fdsn.mseed": { - source: "iana", - extensions: [ - "mseed" - ] -}, - "application/vnd.fdsn.seed": { - source: "iana", - extensions: [ - "seed", - "dataless" - ] -}, - "application/vnd.ffsns": { - source: "iana" -}, - "application/vnd.ficlab.flb+zip": { - source: "iana", - compressible: false -}, - "application/vnd.filmit.zfc": { - source: "iana" -}, - "application/vnd.fints": { - source: "iana" -}, - "application/vnd.firemonkeys.cloudcell": { - source: "iana" -}, - "application/vnd.flographit": { - source: "iana", - extensions: [ - "gph" - ] -}, - "application/vnd.fluxtime.clip": { - source: "iana", - extensions: [ - "ftc" - ] -}, - "application/vnd.font-fontforge-sfd": { - source: "iana" -}, - "application/vnd.framemaker": { - source: "iana", - extensions: [ - "fm", - "frame", - "maker", - "book" - ] -}, - "application/vnd.frogans.fnc": { - source: "iana", - extensions: [ - "fnc" - ] -}, - "application/vnd.frogans.ltf": { - source: "iana", - extensions: [ - "ltf" - ] -}, - "application/vnd.fsc.weblaunch": { - source: "iana", - extensions: [ - "fsc" - ] -}, - "application/vnd.fujitsu.oasys": { - source: "iana", - extensions: [ - "oas" - ] -}, - "application/vnd.fujitsu.oasys2": { - source: "iana", - extensions: [ - "oa2" - ] -}, - "application/vnd.fujitsu.oasys3": { - source: "iana", - extensions: [ - "oa3" - ] -}, - "application/vnd.fujitsu.oasysgp": { - source: "iana", - extensions: [ - "fg5" - ] -}, - "application/vnd.fujitsu.oasysprs": { - source: "iana", - extensions: [ - "bh2" - ] -}, - "application/vnd.fujixerox.art-ex": { - source: "iana" -}, - "application/vnd.fujixerox.art4": { - source: "iana" -}, - "application/vnd.fujixerox.ddd": { - source: "iana", - extensions: [ - "ddd" - ] -}, - "application/vnd.fujixerox.docuworks": { - source: "iana", - extensions: [ - "xdw" - ] -}, - "application/vnd.fujixerox.docuworks.binder": { - source: "iana", - extensions: [ - "xbd" - ] -}, - "application/vnd.fujixerox.docuworks.container": { - source: "iana" -}, - "application/vnd.fujixerox.hbpl": { - source: "iana" -}, - "application/vnd.fut-misnet": { - source: "iana" -}, - "application/vnd.futoin+cbor": { - source: "iana" -}, - "application/vnd.futoin+json": { - source: "iana", - compressible: true -}, - "application/vnd.fuzzysheet": { - source: "iana", - extensions: [ - "fzs" - ] -}, - "application/vnd.genomatix.tuxedo": { - source: "iana", - extensions: [ - "txd" - ] -}, - "application/vnd.gentics.grd+json": { - source: "iana", - compressible: true -}, - "application/vnd.geo+json": { - source: "iana", - compressible: true -}, - "application/vnd.geocube+xml": { - source: "iana", - compressible: true -}, - "application/vnd.geogebra.file": { - source: "iana", - extensions: [ - "ggb" - ] -}, - "application/vnd.geogebra.slides": { - source: "iana" -}, - "application/vnd.geogebra.tool": { - source: "iana", - extensions: [ - "ggt" - ] -}, - "application/vnd.geometry-explorer": { - source: "iana", - extensions: [ - "gex", - "gre" - ] -}, - "application/vnd.geonext": { - source: "iana", - extensions: [ - "gxt" - ] -}, - "application/vnd.geoplan": { - source: "iana", - extensions: [ - "g2w" - ] -}, - "application/vnd.geospace": { - source: "iana", - extensions: [ - "g3w" - ] -}, - "application/vnd.gerber": { - source: "iana" -}, - "application/vnd.globalplatform.card-content-mgt": { - source: "iana" -}, - "application/vnd.globalplatform.card-content-mgt-response": { - source: "iana" -}, - "application/vnd.gmx": { - source: "iana", - extensions: [ - "gmx" - ] -}, - "application/vnd.google-apps.document": { - compressible: false, - extensions: [ - "gdoc" - ] -}, - "application/vnd.google-apps.presentation": { - compressible: false, - extensions: [ - "gslides" - ] -}, - "application/vnd.google-apps.spreadsheet": { - compressible: false, - extensions: [ - "gsheet" - ] -}, - "application/vnd.google-earth.kml+xml": { - source: "iana", - compressible: true, - extensions: [ - "kml" - ] -}, - "application/vnd.google-earth.kmz": { - source: "iana", - compressible: false, - extensions: [ - "kmz" - ] -}, - "application/vnd.gov.sk.e-form+xml": { - source: "iana", - compressible: true -}, - "application/vnd.gov.sk.e-form+zip": { - source: "iana", - compressible: false -}, - "application/vnd.gov.sk.xmldatacontainer+xml": { - source: "iana", - compressible: true -}, - "application/vnd.grafeq": { - source: "iana", - extensions: [ - "gqf", - "gqs" - ] -}, - "application/vnd.gridmp": { - source: "iana" -}, - "application/vnd.groove-account": { - source: "iana", - extensions: [ - "gac" - ] -}, - "application/vnd.groove-help": { - source: "iana", - extensions: [ - "ghf" - ] -}, - "application/vnd.groove-identity-message": { - source: "iana", - extensions: [ - "gim" - ] -}, - "application/vnd.groove-injector": { - source: "iana", - extensions: [ - "grv" - ] -}, - "application/vnd.groove-tool-message": { - source: "iana", - extensions: [ - "gtm" - ] -}, - "application/vnd.groove-tool-template": { - source: "iana", - extensions: [ - "tpl" - ] -}, - "application/vnd.groove-vcard": { - source: "iana", - extensions: [ - "vcg" - ] -}, - "application/vnd.hal+json": { - source: "iana", - compressible: true -}, - "application/vnd.hal+xml": { - source: "iana", - compressible: true, - extensions: [ - "hal" - ] -}, - "application/vnd.handheld-entertainment+xml": { - source: "iana", - compressible: true, - extensions: [ - "zmm" - ] -}, - "application/vnd.hbci": { - source: "iana", - extensions: [ - "hbci" - ] -}, - "application/vnd.hc+json": { - source: "iana", - compressible: true -}, - "application/vnd.hcl-bireports": { - source: "iana" -}, - "application/vnd.hdt": { - source: "iana" -}, - "application/vnd.heroku+json": { - source: "iana", - compressible: true -}, - "application/vnd.hhe.lesson-player": { - source: "iana", - extensions: [ - "les" - ] -}, - "application/vnd.hp-hpgl": { - source: "iana", - extensions: [ - "hpgl" - ] -}, - "application/vnd.hp-hpid": { - source: "iana", - extensions: [ - "hpid" - ] -}, - "application/vnd.hp-hps": { - source: "iana", - extensions: [ - "hps" - ] -}, - "application/vnd.hp-jlyt": { - source: "iana", - extensions: [ - "jlt" - ] -}, - "application/vnd.hp-pcl": { - source: "iana", - extensions: [ - "pcl" - ] -}, - "application/vnd.hp-pclxl": { - source: "iana", - extensions: [ - "pclxl" - ] -}, - "application/vnd.httphone": { - source: "iana" -}, - "application/vnd.hydrostatix.sof-data": { - source: "iana", - extensions: [ - "sfd-hdstx" - ] -}, - "application/vnd.hyper+json": { - source: "iana", - compressible: true -}, - "application/vnd.hyper-item+json": { - source: "iana", - compressible: true -}, - "application/vnd.hyperdrive+json": { - source: "iana", - compressible: true -}, - "application/vnd.hzn-3d-crossword": { - source: "iana" -}, - "application/vnd.ibm.afplinedata": { - source: "iana" -}, - "application/vnd.ibm.electronic-media": { - source: "iana" -}, - "application/vnd.ibm.minipay": { - source: "iana", - extensions: [ - "mpy" - ] -}, - "application/vnd.ibm.modcap": { - source: "iana", - extensions: [ - "afp", - "listafp", - "list3820" - ] -}, - "application/vnd.ibm.rights-management": { - source: "iana", - extensions: [ - "irm" - ] -}, - "application/vnd.ibm.secure-container": { - source: "iana", - extensions: [ - "sc" - ] -}, - "application/vnd.iccprofile": { - source: "iana", - extensions: [ - "icc", - "icm" - ] -}, - "application/vnd.ieee.1905": { - source: "iana" -}, - "application/vnd.igloader": { - source: "iana", - extensions: [ - "igl" - ] -}, - "application/vnd.imagemeter.folder+zip": { - source: "iana", - compressible: false -}, - "application/vnd.imagemeter.image+zip": { - source: "iana", - compressible: false -}, - "application/vnd.immervision-ivp": { - source: "iana", - extensions: [ - "ivp" - ] -}, - "application/vnd.immervision-ivu": { - source: "iana", - extensions: [ - "ivu" - ] -}, - "application/vnd.ims.imsccv1p1": { - source: "iana" -}, - "application/vnd.ims.imsccv1p2": { - source: "iana" -}, - "application/vnd.ims.imsccv1p3": { - source: "iana" -}, - "application/vnd.ims.lis.v2.result+json": { - source: "iana", - compressible: true -}, - "application/vnd.ims.lti.v2.toolconsumerprofile+json": { - source: "iana", - compressible: true -}, - "application/vnd.ims.lti.v2.toolproxy+json": { - source: "iana", - compressible: true -}, - "application/vnd.ims.lti.v2.toolproxy.id+json": { - source: "iana", - compressible: true -}, - "application/vnd.ims.lti.v2.toolsettings+json": { - source: "iana", - compressible: true -}, - "application/vnd.ims.lti.v2.toolsettings.simple+json": { - source: "iana", - compressible: true -}, - "application/vnd.informedcontrol.rms+xml": { - source: "iana", - compressible: true -}, - "application/vnd.informix-visionary": { - source: "iana" -}, - "application/vnd.infotech.project": { - source: "iana" -}, - "application/vnd.infotech.project+xml": { - source: "iana", - compressible: true -}, - "application/vnd.innopath.wamp.notification": { - source: "iana" -}, - "application/vnd.insors.igm": { - source: "iana", - extensions: [ - "igm" - ] -}, - "application/vnd.intercon.formnet": { - source: "iana", - extensions: [ - "xpw", - "xpx" - ] -}, - "application/vnd.intergeo": { - source: "iana", - extensions: [ - "i2g" - ] -}, - "application/vnd.intertrust.digibox": { - source: "iana" -}, - "application/vnd.intertrust.nncp": { - source: "iana" -}, - "application/vnd.intu.qbo": { - source: "iana", - extensions: [ - "qbo" - ] -}, - "application/vnd.intu.qfx": { - source: "iana", - extensions: [ - "qfx" - ] -}, - "application/vnd.iptc.g2.catalogitem+xml": { - source: "iana", - compressible: true -}, - "application/vnd.iptc.g2.conceptitem+xml": { - source: "iana", - compressible: true -}, - "application/vnd.iptc.g2.knowledgeitem+xml": { - source: "iana", - compressible: true -}, - "application/vnd.iptc.g2.newsitem+xml": { - source: "iana", - compressible: true -}, - "application/vnd.iptc.g2.newsmessage+xml": { - source: "iana", - compressible: true -}, - "application/vnd.iptc.g2.packageitem+xml": { - source: "iana", - compressible: true -}, - "application/vnd.iptc.g2.planningitem+xml": { - source: "iana", - compressible: true -}, - "application/vnd.ipunplugged.rcprofile": { - source: "iana", - extensions: [ - "rcprofile" - ] -}, - "application/vnd.irepository.package+xml": { - source: "iana", - compressible: true, - extensions: [ - "irp" - ] -}, - "application/vnd.is-xpr": { - source: "iana", - extensions: [ - "xpr" - ] -}, - "application/vnd.isac.fcs": { - source: "iana", - extensions: [ - "fcs" - ] -}, - "application/vnd.iso11783-10+zip": { - source: "iana", - compressible: false -}, - "application/vnd.jam": { - source: "iana", - extensions: [ - "jam" - ] -}, - "application/vnd.japannet-directory-service": { - source: "iana" -}, - "application/vnd.japannet-jpnstore-wakeup": { - source: "iana" -}, - "application/vnd.japannet-payment-wakeup": { - source: "iana" -}, - "application/vnd.japannet-registration": { - source: "iana" -}, - "application/vnd.japannet-registration-wakeup": { - source: "iana" -}, - "application/vnd.japannet-setstore-wakeup": { - source: "iana" -}, - "application/vnd.japannet-verification": { - source: "iana" -}, - "application/vnd.japannet-verification-wakeup": { - source: "iana" -}, - "application/vnd.jcp.javame.midlet-rms": { - source: "iana", - extensions: [ - "rms" - ] -}, - "application/vnd.jisp": { - source: "iana", - extensions: [ - "jisp" - ] -}, - "application/vnd.joost.joda-archive": { - source: "iana", - extensions: [ - "joda" - ] -}, - "application/vnd.jsk.isdn-ngn": { - source: "iana" -}, - "application/vnd.kahootz": { - source: "iana", - extensions: [ - "ktz", - "ktr" - ] -}, - "application/vnd.kde.karbon": { - source: "iana", - extensions: [ - "karbon" - ] -}, - "application/vnd.kde.kchart": { - source: "iana", - extensions: [ - "chrt" - ] -}, - "application/vnd.kde.kformula": { - source: "iana", - extensions: [ - "kfo" - ] -}, - "application/vnd.kde.kivio": { - source: "iana", - extensions: [ - "flw" - ] -}, - "application/vnd.kde.kontour": { - source: "iana", - extensions: [ - "kon" - ] -}, - "application/vnd.kde.kpresenter": { - source: "iana", - extensions: [ - "kpr", - "kpt" - ] -}, - "application/vnd.kde.kspread": { - source: "iana", - extensions: [ - "ksp" - ] -}, - "application/vnd.kde.kword": { - source: "iana", - extensions: [ - "kwd", - "kwt" - ] -}, - "application/vnd.kenameaapp": { - source: "iana", - extensions: [ - "htke" - ] -}, - "application/vnd.kidspiration": { - source: "iana", - extensions: [ - "kia" - ] -}, - "application/vnd.kinar": { - source: "iana", - extensions: [ - "kne", - "knp" - ] -}, - "application/vnd.koan": { - source: "iana", - extensions: [ - "skp", - "skd", - "skt", - "skm" - ] -}, - "application/vnd.kodak-descriptor": { - source: "iana", - extensions: [ - "sse" - ] -}, - "application/vnd.las": { - source: "iana" -}, - "application/vnd.las.las+json": { - source: "iana", - compressible: true -}, - "application/vnd.las.las+xml": { - source: "iana", - compressible: true, - extensions: [ - "lasxml" - ] -}, - "application/vnd.laszip": { - source: "iana" -}, - "application/vnd.leap+json": { - source: "iana", - compressible: true -}, - "application/vnd.liberty-request+xml": { - source: "iana", - compressible: true -}, - "application/vnd.llamagraphics.life-balance.desktop": { - source: "iana", - extensions: [ - "lbd" - ] -}, - "application/vnd.llamagraphics.life-balance.exchange+xml": { - source: "iana", - compressible: true, - extensions: [ - "lbe" - ] -}, - "application/vnd.logipipe.circuit+zip": { - source: "iana", - compressible: false -}, - "application/vnd.loom": { - source: "iana" -}, - "application/vnd.lotus-1-2-3": { - source: "iana", - extensions: [ - "123" - ] -}, - "application/vnd.lotus-approach": { - source: "iana", - extensions: [ - "apr" - ] -}, - "application/vnd.lotus-freelance": { - source: "iana", - extensions: [ - "pre" - ] -}, - "application/vnd.lotus-notes": { - source: "iana", - extensions: [ - "nsf" - ] -}, - "application/vnd.lotus-organizer": { - source: "iana", - extensions: [ - "org" - ] -}, - "application/vnd.lotus-screencam": { - source: "iana", - extensions: [ - "scm" - ] -}, - "application/vnd.lotus-wordpro": { - source: "iana", - extensions: [ - "lwp" - ] -}, - "application/vnd.macports.portpkg": { - source: "iana", - extensions: [ - "portpkg" - ] -}, - "application/vnd.mapbox-vector-tile": { - source: "iana" -}, - "application/vnd.marlin.drm.actiontoken+xml": { - source: "iana", - compressible: true -}, - "application/vnd.marlin.drm.conftoken+xml": { - source: "iana", - compressible: true -}, - "application/vnd.marlin.drm.license+xml": { - source: "iana", - compressible: true -}, - "application/vnd.marlin.drm.mdcf": { - source: "iana" -}, - "application/vnd.mason+json": { - source: "iana", - compressible: true -}, - "application/vnd.maxmind.maxmind-db": { - source: "iana" -}, - "application/vnd.mcd": { - source: "iana", - extensions: [ - "mcd" - ] -}, - "application/vnd.medcalcdata": { - source: "iana", - extensions: [ - "mc1" - ] -}, - "application/vnd.mediastation.cdkey": { - source: "iana", - extensions: [ - "cdkey" - ] -}, - "application/vnd.meridian-slingshot": { - source: "iana" -}, - "application/vnd.mfer": { - source: "iana", - extensions: [ - "mwf" - ] -}, - "application/vnd.mfmp": { - source: "iana", - extensions: [ - "mfm" - ] -}, - "application/vnd.micro+json": { - source: "iana", - compressible: true -}, - "application/vnd.micrografx.flo": { - source: "iana", - extensions: [ - "flo" - ] -}, - "application/vnd.micrografx.igx": { - source: "iana", - extensions: [ - "igx" - ] -}, - "application/vnd.microsoft.portable-executable": { - source: "iana" -}, - "application/vnd.microsoft.windows.thumbnail-cache": { - source: "iana" -}, - "application/vnd.miele+json": { - source: "iana", - compressible: true -}, - "application/vnd.mif": { - source: "iana", - extensions: [ - "mif" - ] -}, - "application/vnd.minisoft-hp3000-save": { - source: "iana" -}, - "application/vnd.mitsubishi.misty-guard.trustweb": { - source: "iana" -}, - "application/vnd.mobius.daf": { - source: "iana", - extensions: [ - "daf" - ] -}, - "application/vnd.mobius.dis": { - source: "iana", - extensions: [ - "dis" - ] -}, - "application/vnd.mobius.mbk": { - source: "iana", - extensions: [ - "mbk" - ] -}, - "application/vnd.mobius.mqy": { - source: "iana", - extensions: [ - "mqy" - ] -}, - "application/vnd.mobius.msl": { - source: "iana", - extensions: [ - "msl" - ] -}, - "application/vnd.mobius.plc": { - source: "iana", - extensions: [ - "plc" - ] -}, - "application/vnd.mobius.txf": { - source: "iana", - extensions: [ - "txf" - ] -}, - "application/vnd.mophun.application": { - source: "iana", - extensions: [ - "mpn" - ] -}, - "application/vnd.mophun.certificate": { - source: "iana", - extensions: [ - "mpc" - ] -}, - "application/vnd.motorola.flexsuite": { - source: "iana" -}, - "application/vnd.motorola.flexsuite.adsi": { - source: "iana" -}, - "application/vnd.motorola.flexsuite.fis": { - source: "iana" -}, - "application/vnd.motorola.flexsuite.gotap": { - source: "iana" -}, - "application/vnd.motorola.flexsuite.kmr": { - source: "iana" -}, - "application/vnd.motorola.flexsuite.ttc": { - source: "iana" -}, - "application/vnd.motorola.flexsuite.wem": { - source: "iana" -}, - "application/vnd.motorola.iprm": { - source: "iana" -}, - "application/vnd.mozilla.xul+xml": { - source: "iana", - compressible: true, - extensions: [ - "xul" - ] -}, - "application/vnd.ms-3mfdocument": { - source: "iana" -}, - "application/vnd.ms-artgalry": { - source: "iana", - extensions: [ - "cil" - ] -}, - "application/vnd.ms-asf": { - source: "iana" -}, - "application/vnd.ms-cab-compressed": { - source: "iana", - extensions: [ - "cab" - ] -}, - "application/vnd.ms-color.iccprofile": { - source: "apache" -}, - "application/vnd.ms-excel": { - source: "iana", - compressible: false, - extensions: [ - "xls", - "xlm", - "xla", - "xlc", - "xlt", - "xlw" - ] -}, - "application/vnd.ms-excel.addin.macroenabled.12": { - source: "iana", - extensions: [ - "xlam" - ] -}, - "application/vnd.ms-excel.sheet.binary.macroenabled.12": { - source: "iana", - extensions: [ - "xlsb" - ] -}, - "application/vnd.ms-excel.sheet.macroenabled.12": { - source: "iana", - extensions: [ - "xlsm" - ] -}, - "application/vnd.ms-excel.template.macroenabled.12": { - source: "iana", - extensions: [ - "xltm" - ] -}, - "application/vnd.ms-fontobject": { - source: "iana", - compressible: true, - extensions: [ - "eot" - ] -}, - "application/vnd.ms-htmlhelp": { - source: "iana", - extensions: [ - "chm" - ] -}, - "application/vnd.ms-ims": { - source: "iana", - extensions: [ - "ims" - ] -}, - "application/vnd.ms-lrm": { - source: "iana", - extensions: [ - "lrm" - ] -}, - "application/vnd.ms-office.activex+xml": { - source: "iana", - compressible: true -}, - "application/vnd.ms-officetheme": { - source: "iana", - extensions: [ - "thmx" - ] -}, - "application/vnd.ms-opentype": { - source: "apache", - compressible: true -}, - "application/vnd.ms-outlook": { - compressible: false, - extensions: [ - "msg" - ] -}, - "application/vnd.ms-package.obfuscated-opentype": { - source: "apache" -}, - "application/vnd.ms-pki.seccat": { - source: "apache", - extensions: [ - "cat" - ] -}, - "application/vnd.ms-pki.stl": { - source: "apache", - extensions: [ - "stl" - ] -}, - "application/vnd.ms-playready.initiator+xml": { - source: "iana", - compressible: true -}, - "application/vnd.ms-powerpoint": { - source: "iana", - compressible: false, - extensions: [ - "ppt", - "pps", - "pot" - ] -}, - "application/vnd.ms-powerpoint.addin.macroenabled.12": { - source: "iana", - extensions: [ - "ppam" - ] -}, - "application/vnd.ms-powerpoint.presentation.macroenabled.12": { - source: "iana", - extensions: [ - "pptm" - ] -}, - "application/vnd.ms-powerpoint.slide.macroenabled.12": { - source: "iana", - extensions: [ - "sldm" - ] -}, - "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { - source: "iana", - extensions: [ - "ppsm" - ] -}, - "application/vnd.ms-powerpoint.template.macroenabled.12": { - source: "iana", - extensions: [ - "potm" - ] -}, - "application/vnd.ms-printdevicecapabilities+xml": { - source: "iana", - compressible: true -}, - "application/vnd.ms-printing.printticket+xml": { - source: "apache", - compressible: true -}, - "application/vnd.ms-printschematicket+xml": { - source: "iana", - compressible: true -}, - "application/vnd.ms-project": { - source: "iana", - extensions: [ - "mpp", - "mpt" - ] -}, - "application/vnd.ms-tnef": { - source: "iana" -}, - "application/vnd.ms-windows.devicepairing": { - source: "iana" -}, - "application/vnd.ms-windows.nwprinting.oob": { - source: "iana" -}, - "application/vnd.ms-windows.printerpairing": { - source: "iana" -}, - "application/vnd.ms-windows.wsd.oob": { - source: "iana" -}, - "application/vnd.ms-wmdrm.lic-chlg-req": { - source: "iana" -}, - "application/vnd.ms-wmdrm.lic-resp": { - source: "iana" -}, - "application/vnd.ms-wmdrm.meter-chlg-req": { - source: "iana" -}, - "application/vnd.ms-wmdrm.meter-resp": { - source: "iana" -}, - "application/vnd.ms-word.document.macroenabled.12": { - source: "iana", - extensions: [ - "docm" - ] -}, - "application/vnd.ms-word.template.macroenabled.12": { - source: "iana", - extensions: [ - "dotm" - ] -}, - "application/vnd.ms-works": { - source: "iana", - extensions: [ - "wps", - "wks", - "wcm", - "wdb" - ] -}, - "application/vnd.ms-wpl": { - source: "iana", - extensions: [ - "wpl" - ] -}, - "application/vnd.ms-xpsdocument": { - source: "iana", - compressible: false, - extensions: [ - "xps" - ] -}, - "application/vnd.msa-disk-image": { - source: "iana" -}, - "application/vnd.mseq": { - source: "iana", - extensions: [ - "mseq" - ] -}, - "application/vnd.msign": { - source: "iana" -}, - "application/vnd.multiad.creator": { - source: "iana" -}, - "application/vnd.multiad.creator.cif": { - source: "iana" -}, - "application/vnd.music-niff": { - source: "iana" -}, - "application/vnd.musician": { - source: "iana", - extensions: [ - "mus" - ] -}, - "application/vnd.muvee.style": { - source: "iana", - extensions: [ - "msty" - ] -}, - "application/vnd.mynfc": { - source: "iana", - extensions: [ - "taglet" - ] -}, - "application/vnd.ncd.control": { - source: "iana" -}, - "application/vnd.ncd.reference": { - source: "iana" -}, - "application/vnd.nearst.inv+json": { - source: "iana", - compressible: true -}, - "application/vnd.nervana": { - source: "iana" -}, - "application/vnd.netfpx": { - source: "iana" -}, - "application/vnd.neurolanguage.nlu": { - source: "iana", - extensions: [ - "nlu" - ] -}, - "application/vnd.nimn": { - source: "iana" -}, - "application/vnd.nintendo.nitro.rom": { - source: "iana" -}, - "application/vnd.nintendo.snes.rom": { - source: "iana" -}, - "application/vnd.nitf": { - source: "iana", - extensions: [ - "ntf", - "nitf" - ] -}, - "application/vnd.noblenet-directory": { - source: "iana", - extensions: [ - "nnd" - ] -}, - "application/vnd.noblenet-sealer": { - source: "iana", - extensions: [ - "nns" - ] -}, - "application/vnd.noblenet-web": { - source: "iana", - extensions: [ - "nnw" - ] -}, - "application/vnd.nokia.catalogs": { - source: "iana" -}, - "application/vnd.nokia.conml+wbxml": { - source: "iana" -}, - "application/vnd.nokia.conml+xml": { - source: "iana", - compressible: true -}, - "application/vnd.nokia.iptv.config+xml": { - source: "iana", - compressible: true -}, - "application/vnd.nokia.isds-radio-presets": { - source: "iana" -}, - "application/vnd.nokia.landmark+wbxml": { - source: "iana" -}, - "application/vnd.nokia.landmark+xml": { - source: "iana", - compressible: true -}, - "application/vnd.nokia.landmarkcollection+xml": { - source: "iana", - compressible: true -}, - "application/vnd.nokia.n-gage.ac+xml": { - source: "iana", - compressible: true, - extensions: [ - "ac" - ] -}, - "application/vnd.nokia.n-gage.data": { - source: "iana", - extensions: [ - "ngdat" - ] -}, - "application/vnd.nokia.n-gage.symbian.install": { - source: "iana", - extensions: [ - "n-gage" - ] -}, - "application/vnd.nokia.ncd": { - source: "iana" -}, - "application/vnd.nokia.pcd+wbxml": { - source: "iana" -}, - "application/vnd.nokia.pcd+xml": { - source: "iana", - compressible: true -}, - "application/vnd.nokia.radio-preset": { - source: "iana", - extensions: [ - "rpst" - ] -}, - "application/vnd.nokia.radio-presets": { - source: "iana", - extensions: [ - "rpss" - ] -}, - "application/vnd.novadigm.edm": { - source: "iana", - extensions: [ - "edm" - ] -}, - "application/vnd.novadigm.edx": { - source: "iana", - extensions: [ - "edx" - ] -}, - "application/vnd.novadigm.ext": { - source: "iana", - extensions: [ - "ext" - ] -}, - "application/vnd.ntt-local.content-share": { - source: "iana" -}, - "application/vnd.ntt-local.file-transfer": { - source: "iana" -}, - "application/vnd.ntt-local.ogw_remote-access": { - source: "iana" -}, - "application/vnd.ntt-local.sip-ta_remote": { - source: "iana" -}, - "application/vnd.ntt-local.sip-ta_tcp_stream": { - source: "iana" -}, - "application/vnd.oasis.opendocument.chart": { - source: "iana", - extensions: [ - "odc" - ] -}, - "application/vnd.oasis.opendocument.chart-template": { - source: "iana", - extensions: [ - "otc" - ] -}, - "application/vnd.oasis.opendocument.database": { - source: "iana", - extensions: [ - "odb" - ] -}, - "application/vnd.oasis.opendocument.formula": { - source: "iana", - extensions: [ - "odf" - ] -}, - "application/vnd.oasis.opendocument.formula-template": { - source: "iana", - extensions: [ - "odft" - ] -}, - "application/vnd.oasis.opendocument.graphics": { - source: "iana", - compressible: false, - extensions: [ - "odg" - ] -}, - "application/vnd.oasis.opendocument.graphics-template": { - source: "iana", - extensions: [ - "otg" - ] -}, - "application/vnd.oasis.opendocument.image": { - source: "iana", - extensions: [ - "odi" - ] -}, - "application/vnd.oasis.opendocument.image-template": { - source: "iana", - extensions: [ - "oti" - ] -}, - "application/vnd.oasis.opendocument.presentation": { - source: "iana", - compressible: false, - extensions: [ - "odp" - ] -}, - "application/vnd.oasis.opendocument.presentation-template": { - source: "iana", - extensions: [ - "otp" - ] -}, - "application/vnd.oasis.opendocument.spreadsheet": { - source: "iana", - compressible: false, - extensions: [ - "ods" - ] -}, - "application/vnd.oasis.opendocument.spreadsheet-template": { - source: "iana", - extensions: [ - "ots" - ] -}, - "application/vnd.oasis.opendocument.text": { - source: "iana", - compressible: false, - extensions: [ - "odt" - ] -}, - "application/vnd.oasis.opendocument.text-master": { - source: "iana", - extensions: [ - "odm" - ] -}, - "application/vnd.oasis.opendocument.text-template": { - source: "iana", - extensions: [ - "ott" - ] -}, - "application/vnd.oasis.opendocument.text-web": { - source: "iana", - extensions: [ - "oth" - ] -}, - "application/vnd.obn": { - source: "iana" -}, - "application/vnd.ocf+cbor": { - source: "iana" -}, - "application/vnd.oci.image.manifest.v1+json": { - source: "iana", - compressible: true -}, - "application/vnd.oftn.l10n+json": { - source: "iana", - compressible: true -}, - "application/vnd.oipf.contentaccessdownload+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oipf.contentaccessstreaming+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oipf.cspg-hexbinary": { - source: "iana" -}, - "application/vnd.oipf.dae.svg+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oipf.dae.xhtml+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oipf.mippvcontrolmessage+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oipf.pae.gem": { - source: "iana" -}, - "application/vnd.oipf.spdiscovery+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oipf.spdlist+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oipf.ueprofile+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oipf.userprofile+xml": { - source: "iana", - compressible: true -}, - "application/vnd.olpc-sugar": { - source: "iana", - extensions: [ - "xo" - ] -}, - "application/vnd.oma-scws-config": { - source: "iana" -}, - "application/vnd.oma-scws-http-request": { - source: "iana" -}, - "application/vnd.oma-scws-http-response": { - source: "iana" -}, - "application/vnd.oma.bcast.associated-procedure-parameter+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.bcast.drm-trigger+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.bcast.imd+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.bcast.ltkm": { - source: "iana" -}, - "application/vnd.oma.bcast.notification+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.bcast.provisioningtrigger": { - source: "iana" -}, - "application/vnd.oma.bcast.sgboot": { - source: "iana" -}, - "application/vnd.oma.bcast.sgdd+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.bcast.sgdu": { - source: "iana" -}, - "application/vnd.oma.bcast.simple-symbol-container": { - source: "iana" -}, - "application/vnd.oma.bcast.smartcard-trigger+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.bcast.sprov+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.bcast.stkm": { - source: "iana" -}, - "application/vnd.oma.cab-address-book+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.cab-feature-handler+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.cab-pcc+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.cab-subs-invite+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.cab-user-prefs+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.dcd": { - source: "iana" -}, - "application/vnd.oma.dcdc": { - source: "iana" -}, - "application/vnd.oma.dd2+xml": { - source: "iana", - compressible: true, - extensions: [ - "dd2" - ] -}, - "application/vnd.oma.drm.risd+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.group-usage-list+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.lwm2m+cbor": { - source: "iana" -}, - "application/vnd.oma.lwm2m+json": { - source: "iana", - compressible: true -}, - "application/vnd.oma.lwm2m+tlv": { - source: "iana" -}, - "application/vnd.oma.pal+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.poc.detailed-progress-report+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.poc.final-report+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.poc.groups+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.poc.invocation-descriptor+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.poc.optimized-progress-report+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.push": { - source: "iana" -}, - "application/vnd.oma.scidm.messages+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oma.xcap-directory+xml": { - source: "iana", - compressible: true -}, - "application/vnd.omads-email+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/vnd.omads-file+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/vnd.omads-folder+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/vnd.omaloc-supl-init": { - source: "iana" -}, - "application/vnd.onepager": { - source: "iana" -}, - "application/vnd.onepagertamp": { - source: "iana" -}, - "application/vnd.onepagertamx": { - source: "iana" -}, - "application/vnd.onepagertat": { - source: "iana" -}, - "application/vnd.onepagertatp": { - source: "iana" -}, - "application/vnd.onepagertatx": { - source: "iana" -}, - "application/vnd.openblox.game+xml": { - source: "iana", - compressible: true, - extensions: [ - "obgx" - ] -}, - "application/vnd.openblox.game-binary": { - source: "iana" -}, - "application/vnd.openeye.oeb": { - source: "iana" -}, - "application/vnd.openofficeorg.extension": { - source: "apache", - extensions: [ - "oxt" - ] -}, - "application/vnd.openstreetmap.data+xml": { - source: "iana", - compressible: true, - extensions: [ - "osm" - ] -}, - "application/vnd.openxmlformats-officedocument.custom-properties+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.drawing+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.extended-properties+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.presentation": { - source: "iana", - compressible: false, - extensions: [ - "pptx" - ] -}, - "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.slide": { - source: "iana", - extensions: [ - "sldx" - ] -}, - "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { - source: "iana", - extensions: [ - "ppsx" - ] -}, - "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.template": { - source: "iana", - extensions: [ - "potx" - ] -}, - "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { - source: "iana", - compressible: false, - extensions: [ - "xlsx" - ] -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { - source: "iana", - extensions: [ - "xltx" - ] -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.theme+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.themeoverride+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.vmldrawing": { - source: "iana" -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { - source: "iana", - compressible: false, - extensions: [ - "docx" - ] -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { - source: "iana", - extensions: [ - "dotx" - ] -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-package.core-properties+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { - source: "iana", - compressible: true -}, - "application/vnd.openxmlformats-package.relationships+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oracle.resource+json": { - source: "iana", - compressible: true -}, - "application/vnd.orange.indata": { - source: "iana" -}, - "application/vnd.osa.netdeploy": { - source: "iana" -}, - "application/vnd.osgeo.mapguide.package": { - source: "iana", - extensions: [ - "mgp" - ] -}, - "application/vnd.osgi.bundle": { - source: "iana" -}, - "application/vnd.osgi.dp": { - source: "iana", - extensions: [ - "dp" - ] -}, - "application/vnd.osgi.subsystem": { - source: "iana", - extensions: [ - "esa" - ] -}, - "application/vnd.otps.ct-kip+xml": { - source: "iana", - compressible: true -}, - "application/vnd.oxli.countgraph": { - source: "iana" -}, - "application/vnd.pagerduty+json": { - source: "iana", - compressible: true -}, - "application/vnd.palm": { - source: "iana", - extensions: [ - "pdb", - "pqa", - "oprc" - ] -}, - "application/vnd.panoply": { - source: "iana" -}, - "application/vnd.paos.xml": { - source: "iana" -}, - "application/vnd.patentdive": { - source: "iana" -}, - "application/vnd.patientecommsdoc": { - source: "iana" -}, - "application/vnd.pawaafile": { - source: "iana", - extensions: [ - "paw" - ] -}, - "application/vnd.pcos": { - source: "iana" -}, - "application/vnd.pg.format": { - source: "iana", - extensions: [ - "str" - ] -}, - "application/vnd.pg.osasli": { - source: "iana", - extensions: [ - "ei6" - ] -}, - "application/vnd.piaccess.application-licence": { - source: "iana" -}, - "application/vnd.picsel": { - source: "iana", - extensions: [ - "efif" - ] -}, - "application/vnd.pmi.widget": { - source: "iana", - extensions: [ - "wg" - ] -}, - "application/vnd.poc.group-advertisement+xml": { - source: "iana", - compressible: true -}, - "application/vnd.pocketlearn": { - source: "iana", - extensions: [ - "plf" - ] -}, - "application/vnd.powerbuilder6": { - source: "iana", - extensions: [ - "pbd" - ] -}, - "application/vnd.powerbuilder6-s": { - source: "iana" -}, - "application/vnd.powerbuilder7": { - source: "iana" -}, - "application/vnd.powerbuilder7-s": { - source: "iana" -}, - "application/vnd.powerbuilder75": { - source: "iana" -}, - "application/vnd.powerbuilder75-s": { - source: "iana" -}, - "application/vnd.preminet": { - source: "iana" -}, - "application/vnd.previewsystems.box": { - source: "iana", - extensions: [ - "box" - ] -}, - "application/vnd.proteus.magazine": { - source: "iana", - extensions: [ - "mgz" - ] -}, - "application/vnd.psfs": { - source: "iana" -}, - "application/vnd.publishare-delta-tree": { - source: "iana", - extensions: [ - "qps" - ] -}, - "application/vnd.pvi.ptid1": { - source: "iana", - extensions: [ - "ptid" - ] -}, - "application/vnd.pwg-multiplexed": { - source: "iana" -}, - "application/vnd.pwg-xhtml-print+xml": { - source: "iana", - compressible: true -}, - "application/vnd.qualcomm.brew-app-res": { - source: "iana" -}, - "application/vnd.quarantainenet": { - source: "iana" -}, - "application/vnd.quark.quarkxpress": { - source: "iana", - extensions: [ - "qxd", - "qxt", - "qwd", - "qwt", - "qxl", - "qxb" - ] -}, - "application/vnd.quobject-quoxdocument": { - source: "iana" -}, - "application/vnd.radisys.moml+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-audit+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-audit-conf+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-audit-conn+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-audit-dialog+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-audit-stream+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-conf+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-dialog+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-dialog-base+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-dialog-fax-detect+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-dialog-group+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-dialog-speech+xml": { - source: "iana", - compressible: true -}, - "application/vnd.radisys.msml-dialog-transform+xml": { - source: "iana", - compressible: true -}, - "application/vnd.rainstor.data": { - source: "iana" -}, - "application/vnd.rapid": { - source: "iana" -}, - "application/vnd.rar": { - source: "iana", - extensions: [ - "rar" - ] -}, - "application/vnd.realvnc.bed": { - source: "iana", - extensions: [ - "bed" - ] -}, - "application/vnd.recordare.musicxml": { - source: "iana", - extensions: [ - "mxl" - ] -}, - "application/vnd.recordare.musicxml+xml": { - source: "iana", - compressible: true, - extensions: [ - "musicxml" - ] -}, - "application/vnd.renlearn.rlprint": { - source: "iana" -}, - "application/vnd.restful+json": { - source: "iana", - compressible: true -}, - "application/vnd.rig.cryptonote": { - source: "iana", - extensions: [ - "cryptonote" - ] -}, - "application/vnd.rim.cod": { - source: "apache", - extensions: [ - "cod" - ] -}, - "application/vnd.rn-realmedia": { - source: "apache", - extensions: [ - "rm" - ] -}, - "application/vnd.rn-realmedia-vbr": { - source: "apache", - extensions: [ - "rmvb" - ] -}, - "application/vnd.route66.link66+xml": { - source: "iana", - compressible: true, - extensions: [ - "link66" - ] -}, - "application/vnd.rs-274x": { - source: "iana" -}, - "application/vnd.ruckus.download": { - source: "iana" -}, - "application/vnd.s3sms": { - source: "iana" -}, - "application/vnd.sailingtracker.track": { - source: "iana", - extensions: [ - "st" - ] -}, - "application/vnd.sar": { - source: "iana" -}, - "application/vnd.sbm.cid": { - source: "iana" -}, - "application/vnd.sbm.mid2": { - source: "iana" -}, - "application/vnd.scribus": { - source: "iana" -}, - "application/vnd.sealed.3df": { - source: "iana" -}, - "application/vnd.sealed.csf": { - source: "iana" -}, - "application/vnd.sealed.doc": { - source: "iana" -}, - "application/vnd.sealed.eml": { - source: "iana" -}, - "application/vnd.sealed.mht": { - source: "iana" -}, - "application/vnd.sealed.net": { - source: "iana" -}, - "application/vnd.sealed.ppt": { - source: "iana" -}, - "application/vnd.sealed.tiff": { - source: "iana" -}, - "application/vnd.sealed.xls": { - source: "iana" -}, - "application/vnd.sealedmedia.softseal.html": { - source: "iana" -}, - "application/vnd.sealedmedia.softseal.pdf": { - source: "iana" -}, - "application/vnd.seemail": { - source: "iana", - extensions: [ - "see" - ] -}, - "application/vnd.seis+json": { - source: "iana", - compressible: true -}, - "application/vnd.sema": { - source: "iana", - extensions: [ - "sema" - ] -}, - "application/vnd.semd": { - source: "iana", - extensions: [ - "semd" - ] -}, - "application/vnd.semf": { - source: "iana", - extensions: [ - "semf" - ] -}, - "application/vnd.shade-save-file": { - source: "iana" -}, - "application/vnd.shana.informed.formdata": { - source: "iana", - extensions: [ - "ifm" - ] -}, - "application/vnd.shana.informed.formtemplate": { - source: "iana", - extensions: [ - "itp" - ] -}, - "application/vnd.shana.informed.interchange": { - source: "iana", - extensions: [ - "iif" - ] -}, - "application/vnd.shana.informed.package": { - source: "iana", - extensions: [ - "ipk" - ] -}, - "application/vnd.shootproof+json": { - source: "iana", - compressible: true -}, - "application/vnd.shopkick+json": { - source: "iana", - compressible: true -}, - "application/vnd.shp": { - source: "iana" -}, - "application/vnd.shx": { - source: "iana" -}, - "application/vnd.sigrok.session": { - source: "iana" -}, - "application/vnd.simtech-mindmapper": { - source: "iana", - extensions: [ - "twd", - "twds" - ] -}, - "application/vnd.siren+json": { - source: "iana", - compressible: true -}, - "application/vnd.smaf": { - source: "iana", - extensions: [ - "mmf" - ] -}, - "application/vnd.smart.notebook": { - source: "iana" -}, - "application/vnd.smart.teacher": { - source: "iana", - extensions: [ - "teacher" - ] -}, - "application/vnd.snesdev-page-table": { - source: "iana" -}, - "application/vnd.software602.filler.form+xml": { - source: "iana", - compressible: true, - extensions: [ - "fo" - ] -}, - "application/vnd.software602.filler.form-xml-zip": { - source: "iana" -}, - "application/vnd.solent.sdkm+xml": { - source: "iana", - compressible: true, - extensions: [ - "sdkm", - "sdkd" - ] -}, - "application/vnd.spotfire.dxp": { - source: "iana", - extensions: [ - "dxp" - ] -}, - "application/vnd.spotfire.sfs": { - source: "iana", - extensions: [ - "sfs" - ] -}, - "application/vnd.sqlite3": { - source: "iana" -}, - "application/vnd.sss-cod": { - source: "iana" -}, - "application/vnd.sss-dtf": { - source: "iana" -}, - "application/vnd.sss-ntf": { - source: "iana" -}, - "application/vnd.stardivision.calc": { - source: "apache", - extensions: [ - "sdc" - ] -}, - "application/vnd.stardivision.draw": { - source: "apache", - extensions: [ - "sda" - ] -}, - "application/vnd.stardivision.impress": { - source: "apache", - extensions: [ - "sdd" - ] -}, - "application/vnd.stardivision.math": { - source: "apache", - extensions: [ - "smf" - ] -}, - "application/vnd.stardivision.writer": { - source: "apache", - extensions: [ - "sdw", - "vor" - ] -}, - "application/vnd.stardivision.writer-global": { - source: "apache", - extensions: [ - "sgl" - ] -}, - "application/vnd.stepmania.package": { - source: "iana", - extensions: [ - "smzip" - ] -}, - "application/vnd.stepmania.stepchart": { - source: "iana", - extensions: [ - "sm" - ] -}, - "application/vnd.street-stream": { - source: "iana" -}, - "application/vnd.sun.wadl+xml": { - source: "iana", - compressible: true, - extensions: [ - "wadl" - ] -}, - "application/vnd.sun.xml.calc": { - source: "apache", - extensions: [ - "sxc" - ] -}, - "application/vnd.sun.xml.calc.template": { - source: "apache", - extensions: [ - "stc" - ] -}, - "application/vnd.sun.xml.draw": { - source: "apache", - extensions: [ - "sxd" - ] -}, - "application/vnd.sun.xml.draw.template": { - source: "apache", - extensions: [ - "std" - ] -}, - "application/vnd.sun.xml.impress": { - source: "apache", - extensions: [ - "sxi" - ] -}, - "application/vnd.sun.xml.impress.template": { - source: "apache", - extensions: [ - "sti" - ] -}, - "application/vnd.sun.xml.math": { - source: "apache", - extensions: [ - "sxm" - ] -}, - "application/vnd.sun.xml.writer": { - source: "apache", - extensions: [ - "sxw" - ] -}, - "application/vnd.sun.xml.writer.global": { - source: "apache", - extensions: [ - "sxg" - ] -}, - "application/vnd.sun.xml.writer.template": { - source: "apache", - extensions: [ - "stw" - ] -}, - "application/vnd.sus-calendar": { - source: "iana", - extensions: [ - "sus", - "susp" - ] -}, - "application/vnd.svd": { - source: "iana", - extensions: [ - "svd" - ] -}, - "application/vnd.swiftview-ics": { - source: "iana" -}, - "application/vnd.sycle+xml": { - source: "iana", - compressible: true -}, - "application/vnd.symbian.install": { - source: "apache", - extensions: [ - "sis", - "sisx" - ] -}, - "application/vnd.syncml+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: [ - "xsm" - ] -}, - "application/vnd.syncml.dm+wbxml": { - source: "iana", - charset: "UTF-8", - extensions: [ - "bdm" - ] -}, - "application/vnd.syncml.dm+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: [ - "xdm" - ] -}, - "application/vnd.syncml.dm.notification": { - source: "iana" -}, - "application/vnd.syncml.dmddf+wbxml": { - source: "iana" -}, - "application/vnd.syncml.dmddf+xml": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: [ - "ddf" - ] -}, - "application/vnd.syncml.dmtnds+wbxml": { - source: "iana" -}, - "application/vnd.syncml.dmtnds+xml": { - source: "iana", - charset: "UTF-8", - compressible: true -}, - "application/vnd.syncml.ds.notification": { - source: "iana" -}, - "application/vnd.tableschema+json": { - source: "iana", - compressible: true -}, - "application/vnd.tao.intent-module-archive": { - source: "iana", - extensions: [ - "tao" - ] -}, - "application/vnd.tcpdump.pcap": { - source: "iana", - extensions: [ - "pcap", - "cap", - "dmp" - ] -}, - "application/vnd.think-cell.ppttc+json": { - source: "iana", - compressible: true -}, - "application/vnd.tmd.mediaflex.api+xml": { - source: "iana", - compressible: true -}, - "application/vnd.tml": { - source: "iana" -}, - "application/vnd.tmobile-livetv": { - source: "iana", - extensions: [ - "tmo" - ] -}, - "application/vnd.tri.onesource": { - source: "iana" -}, - "application/vnd.trid.tpt": { - source: "iana", - extensions: [ - "tpt" - ] -}, - "application/vnd.triscape.mxs": { - source: "iana", - extensions: [ - "mxs" - ] -}, - "application/vnd.trueapp": { - source: "iana", - extensions: [ - "tra" - ] -}, - "application/vnd.truedoc": { - source: "iana" -}, - "application/vnd.ubisoft.webplayer": { - source: "iana" -}, - "application/vnd.ufdl": { - source: "iana", - extensions: [ - "ufd", - "ufdl" - ] -}, - "application/vnd.uiq.theme": { - source: "iana", - extensions: [ - "utz" - ] -}, - "application/vnd.umajin": { - source: "iana", - extensions: [ - "umj" - ] -}, - "application/vnd.unity": { - source: "iana", - extensions: [ - "unityweb" - ] -}, - "application/vnd.uoml+xml": { - source: "iana", - compressible: true, - extensions: [ - "uoml" - ] -}, - "application/vnd.uplanet.alert": { - source: "iana" -}, - "application/vnd.uplanet.alert-wbxml": { - source: "iana" -}, - "application/vnd.uplanet.bearer-choice": { - source: "iana" -}, - "application/vnd.uplanet.bearer-choice-wbxml": { - source: "iana" -}, - "application/vnd.uplanet.cacheop": { - source: "iana" -}, - "application/vnd.uplanet.cacheop-wbxml": { - source: "iana" -}, - "application/vnd.uplanet.channel": { - source: "iana" -}, - "application/vnd.uplanet.channel-wbxml": { - source: "iana" -}, - "application/vnd.uplanet.list": { - source: "iana" -}, - "application/vnd.uplanet.list-wbxml": { - source: "iana" -}, - "application/vnd.uplanet.listcmd": { - source: "iana" -}, - "application/vnd.uplanet.listcmd-wbxml": { - source: "iana" -}, - "application/vnd.uplanet.signal": { - source: "iana" -}, - "application/vnd.uri-map": { - source: "iana" -}, - "application/vnd.valve.source.material": { - source: "iana" -}, - "application/vnd.vcx": { - source: "iana", - extensions: [ - "vcx" - ] -}, - "application/vnd.vd-study": { - source: "iana" -}, - "application/vnd.vectorworks": { - source: "iana" -}, - "application/vnd.vel+json": { - source: "iana", - compressible: true -}, - "application/vnd.verimatrix.vcas": { - source: "iana" -}, - "application/vnd.veryant.thin": { - source: "iana" -}, - "application/vnd.ves.encrypted": { - source: "iana" -}, - "application/vnd.vidsoft.vidconference": { - source: "iana" -}, - "application/vnd.visio": { - source: "iana", - extensions: [ - "vsd", - "vst", - "vss", - "vsw" - ] -}, - "application/vnd.visionary": { - source: "iana", - extensions: [ - "vis" - ] -}, - "application/vnd.vividence.scriptfile": { - source: "iana" -}, - "application/vnd.vsf": { - source: "iana", - extensions: [ - "vsf" - ] -}, - "application/vnd.wap.sic": { - source: "iana" -}, - "application/vnd.wap.slc": { - source: "iana" -}, - "application/vnd.wap.wbxml": { - source: "iana", - charset: "UTF-8", - extensions: [ - "wbxml" - ] -}, - "application/vnd.wap.wmlc": { - source: "iana", - extensions: [ - "wmlc" - ] -}, - "application/vnd.wap.wmlscriptc": { - source: "iana", - extensions: [ - "wmlsc" - ] -}, - "application/vnd.webturbo": { - source: "iana", - extensions: [ - "wtb" - ] -}, - "application/vnd.wfa.dpp": { - source: "iana" -}, - "application/vnd.wfa.p2p": { - source: "iana" -}, - "application/vnd.wfa.wsc": { - source: "iana" -}, - "application/vnd.windows.devicepairing": { - source: "iana" -}, - "application/vnd.wmc": { - source: "iana" -}, - "application/vnd.wmf.bootstrap": { - source: "iana" -}, - "application/vnd.wolfram.mathematica": { - source: "iana" -}, - "application/vnd.wolfram.mathematica.package": { - source: "iana" -}, - "application/vnd.wolfram.player": { - source: "iana", - extensions: [ - "nbp" - ] -}, - "application/vnd.wordperfect": { - source: "iana", - extensions: [ - "wpd" - ] -}, - "application/vnd.wqd": { - source: "iana", - extensions: [ - "wqd" - ] -}, - "application/vnd.wrq-hp3000-labelled": { - source: "iana" -}, - "application/vnd.wt.stf": { - source: "iana", - extensions: [ - "stf" - ] -}, - "application/vnd.wv.csp+wbxml": { - source: "iana" -}, - "application/vnd.wv.csp+xml": { - source: "iana", - compressible: true -}, - "application/vnd.wv.ssp+xml": { - source: "iana", - compressible: true -}, - "application/vnd.xacml+json": { - source: "iana", - compressible: true -}, - "application/vnd.xara": { - source: "iana", - extensions: [ - "xar" - ] -}, - "application/vnd.xfdl": { - source: "iana", - extensions: [ - "xfdl" - ] -}, - "application/vnd.xfdl.webform": { - source: "iana" -}, - "application/vnd.xmi+xml": { - source: "iana", - compressible: true -}, - "application/vnd.xmpie.cpkg": { - source: "iana" -}, - "application/vnd.xmpie.dpkg": { - source: "iana" -}, - "application/vnd.xmpie.plan": { - source: "iana" -}, - "application/vnd.xmpie.ppkg": { - source: "iana" -}, - "application/vnd.xmpie.xlim": { - source: "iana" -}, - "application/vnd.yamaha.hv-dic": { - source: "iana", - extensions: [ - "hvd" - ] -}, - "application/vnd.yamaha.hv-script": { - source: "iana", - extensions: [ - "hvs" - ] -}, - "application/vnd.yamaha.hv-voice": { - source: "iana", - extensions: [ - "hvp" - ] -}, - "application/vnd.yamaha.openscoreformat": { - source: "iana", - extensions: [ - "osf" - ] -}, - "application/vnd.yamaha.openscoreformat.osfpvg+xml": { - source: "iana", - compressible: true, - extensions: [ - "osfpvg" - ] -}, - "application/vnd.yamaha.remote-setup": { - source: "iana" -}, - "application/vnd.yamaha.smaf-audio": { - source: "iana", - extensions: [ - "saf" - ] -}, - "application/vnd.yamaha.smaf-phrase": { - source: "iana", - extensions: [ - "spf" - ] -}, - "application/vnd.yamaha.through-ngn": { - source: "iana" -}, - "application/vnd.yamaha.tunnel-udpencap": { - source: "iana" -}, - "application/vnd.yaoweme": { - source: "iana" -}, - "application/vnd.yellowriver-custom-menu": { - source: "iana", - extensions: [ - "cmp" - ] -}, - "application/vnd.youtube.yt": { - source: "iana" -}, - "application/vnd.zul": { - source: "iana", - extensions: [ - "zir", - "zirz" - ] -}, - "application/vnd.zzazz.deck+xml": { - source: "iana", - compressible: true, - extensions: [ - "zaz" - ] -}, - "application/voicexml+xml": { - source: "iana", - compressible: true, - extensions: [ - "vxml" - ] -}, - "application/voucher-cms+json": { - source: "iana", - compressible: true -}, - "application/vq-rtcpxr": { - source: "iana" -}, - "application/wasm": { - compressible: true, - extensions: [ - "wasm" - ] -}, - "application/watcherinfo+xml": { - source: "iana", - compressible: true -}, - "application/webpush-options+json": { - source: "iana", - compressible: true -}, - "application/whoispp-query": { - source: "iana" -}, - "application/whoispp-response": { - source: "iana" -}, - "application/widget": { - source: "iana", - extensions: [ - "wgt" - ] -}, - "application/winhlp": { - source: "apache", - extensions: [ - "hlp" - ] -}, - "application/wita": { - source: "iana" -}, - "application/wordperfect5.1": { - source: "iana" -}, - "application/wsdl+xml": { - source: "iana", - compressible: true, - extensions: [ - "wsdl" - ] -}, - "application/wspolicy+xml": { - source: "iana", - compressible: true, - extensions: [ - "wspolicy" - ] -}, - "application/x-7z-compressed": { - source: "apache", - compressible: false, - extensions: [ - "7z" - ] -}, - "application/x-abiword": { - source: "apache", - extensions: [ - "abw" - ] -}, - "application/x-ace-compressed": { - source: "apache", - extensions: [ - "ace" - ] -}, - "application/x-amf": { - source: "apache" -}, - "application/x-apple-diskimage": { - source: "apache", - extensions: [ - "dmg" - ] -}, - "application/x-arj": { - compressible: false, - extensions: [ - "arj" - ] -}, - "application/x-authorware-bin": { - source: "apache", - extensions: [ - "aab", - "x32", - "u32", - "vox" - ] -}, - "application/x-authorware-map": { - source: "apache", - extensions: [ - "aam" - ] -}, - "application/x-authorware-seg": { - source: "apache", - extensions: [ - "aas" - ] -}, - "application/x-bcpio": { - source: "apache", - extensions: [ - "bcpio" - ] -}, - "application/x-bdoc": { - compressible: false, - extensions: [ - "bdoc" - ] -}, - "application/x-bittorrent": { - source: "apache", - extensions: [ - "torrent" - ] -}, - "application/x-blorb": { - source: "apache", - extensions: [ - "blb", - "blorb" - ] -}, - "application/x-bzip": { - source: "apache", - compressible: false, - extensions: [ - "bz" - ] -}, - "application/x-bzip2": { - source: "apache", - compressible: false, - extensions: [ - "bz2", - "boz" - ] -}, - "application/x-cbr": { - source: "apache", - extensions: [ - "cbr", - "cba", - "cbt", - "cbz", - "cb7" - ] -}, - "application/x-cdlink": { - source: "apache", - extensions: [ - "vcd" - ] -}, - "application/x-cfs-compressed": { - source: "apache", - extensions: [ - "cfs" - ] -}, - "application/x-chat": { - source: "apache", - extensions: [ - "chat" - ] -}, - "application/x-chess-pgn": { - source: "apache", - extensions: [ - "pgn" - ] -}, - "application/x-chrome-extension": { - extensions: [ - "crx" - ] -}, - "application/x-cocoa": { - source: "nginx", - extensions: [ - "cco" - ] -}, - "application/x-compress": { - source: "apache" -}, - "application/x-conference": { - source: "apache", - extensions: [ - "nsc" - ] -}, - "application/x-cpio": { - source: "apache", - extensions: [ - "cpio" - ] -}, - "application/x-csh": { - source: "apache", - extensions: [ - "csh" - ] -}, - "application/x-deb": { - compressible: false -}, - "application/x-debian-package": { - source: "apache", - extensions: [ - "deb", - "udeb" - ] -}, - "application/x-dgc-compressed": { - source: "apache", - extensions: [ - "dgc" - ] -}, - "application/x-director": { - source: "apache", - extensions: [ - "dir", - "dcr", - "dxr", - "cst", - "cct", - "cxt", - "w3d", - "fgd", - "swa" - ] -}, - "application/x-doom": { - source: "apache", - extensions: [ - "wad" - ] -}, - "application/x-dtbncx+xml": { - source: "apache", - compressible: true, - extensions: [ - "ncx" - ] -}, - "application/x-dtbook+xml": { - source: "apache", - compressible: true, - extensions: [ - "dtb" - ] -}, - "application/x-dtbresource+xml": { - source: "apache", - compressible: true, - extensions: [ - "res" - ] -}, - "application/x-dvi": { - source: "apache", - compressible: false, - extensions: [ - "dvi" - ] -}, - "application/x-envoy": { - source: "apache", - extensions: [ - "evy" - ] -}, - "application/x-eva": { - source: "apache", - extensions: [ - "eva" - ] -}, - "application/x-font-bdf": { - source: "apache", - extensions: [ - "bdf" - ] -}, - "application/x-font-dos": { - source: "apache" -}, - "application/x-font-framemaker": { - source: "apache" -}, - "application/x-font-ghostscript": { - source: "apache", - extensions: [ - "gsf" - ] -}, - "application/x-font-libgrx": { - source: "apache" -}, - "application/x-font-linux-psf": { - source: "apache", - extensions: [ - "psf" - ] -}, - "application/x-font-pcf": { - source: "apache", - extensions: [ - "pcf" - ] -}, - "application/x-font-snf": { - source: "apache", - extensions: [ - "snf" - ] -}, - "application/x-font-speedo": { - source: "apache" -}, - "application/x-font-sunos-news": { - source: "apache" -}, - "application/x-font-type1": { - source: "apache", - extensions: [ - "pfa", - "pfb", - "pfm", - "afm" - ] -}, - "application/x-font-vfont": { - source: "apache" -}, - "application/x-freearc": { - source: "apache", - extensions: [ - "arc" - ] -}, - "application/x-futuresplash": { - source: "apache", - extensions: [ - "spl" - ] -}, - "application/x-gca-compressed": { - source: "apache", - extensions: [ - "gca" - ] -}, - "application/x-glulx": { - source: "apache", - extensions: [ - "ulx" - ] -}, - "application/x-gnumeric": { - source: "apache", - extensions: [ - "gnumeric" - ] -}, - "application/x-gramps-xml": { - source: "apache", - extensions: [ - "gramps" - ] -}, - "application/x-gtar": { - source: "apache", - extensions: [ - "gtar" - ] -}, - "application/x-gzip": { - source: "apache" -}, - "application/x-hdf": { - source: "apache", - extensions: [ - "hdf" - ] -}, - "application/x-httpd-php": { - compressible: true, - extensions: [ - "php" - ] -}, - "application/x-install-instructions": { - source: "apache", - extensions: [ - "install" - ] -}, - "application/x-iso9660-image": { - source: "apache", - extensions: [ - "iso" - ] -}, - "application/x-java-archive-diff": { - source: "nginx", - extensions: [ - "jardiff" - ] -}, - "application/x-java-jnlp-file": { - source: "apache", - compressible: false, - extensions: [ - "jnlp" - ] -}, - "application/x-javascript": { - compressible: true -}, - "application/x-keepass2": { - extensions: [ - "kdbx" - ] -}, - "application/x-latex": { - source: "apache", - compressible: false, - extensions: [ - "latex" - ] -}, - "application/x-lua-bytecode": { - extensions: [ - "luac" - ] -}, - "application/x-lzh-compressed": { - source: "apache", - extensions: [ - "lzh", - "lha" - ] -}, - "application/x-makeself": { - source: "nginx", - extensions: [ - "run" - ] -}, - "application/x-mie": { - source: "apache", - extensions: [ - "mie" - ] -}, - "application/x-mobipocket-ebook": { - source: "apache", - extensions: [ - "prc", - "mobi" - ] -}, - "application/x-mpegurl": { - compressible: false -}, - "application/x-ms-application": { - source: "apache", - extensions: [ - "application" - ] -}, - "application/x-ms-shortcut": { - source: "apache", - extensions: [ - "lnk" - ] -}, - "application/x-ms-wmd": { - source: "apache", - extensions: [ - "wmd" - ] -}, - "application/x-ms-wmz": { - source: "apache", - extensions: [ - "wmz" - ] -}, - "application/x-ms-xbap": { - source: "apache", - extensions: [ - "xbap" - ] -}, - "application/x-msaccess": { - source: "apache", - extensions: [ - "mdb" - ] -}, - "application/x-msbinder": { - source: "apache", - extensions: [ - "obd" - ] -}, - "application/x-mscardfile": { - source: "apache", - extensions: [ - "crd" - ] -}, - "application/x-msclip": { - source: "apache", - extensions: [ - "clp" - ] -}, - "application/x-msdos-program": { - extensions: [ - "exe" - ] -}, - "application/x-msdownload": { - source: "apache", - extensions: [ - "exe", - "dll", - "com", - "bat", - "msi" - ] -}, - "application/x-msmediaview": { - source: "apache", - extensions: [ - "mvb", - "m13", - "m14" - ] -}, - "application/x-msmetafile": { - source: "apache", - extensions: [ - "wmf", - "wmz", - "emf", - "emz" - ] -}, - "application/x-msmoney": { - source: "apache", - extensions: [ - "mny" - ] -}, - "application/x-mspublisher": { - source: "apache", - extensions: [ - "pub" - ] -}, - "application/x-msschedule": { - source: "apache", - extensions: [ - "scd" - ] -}, - "application/x-msterminal": { - source: "apache", - extensions: [ - "trm" - ] -}, - "application/x-mswrite": { - source: "apache", - extensions: [ - "wri" - ] -}, - "application/x-netcdf": { - source: "apache", - extensions: [ - "nc", - "cdf" - ] -}, - "application/x-ns-proxy-autoconfig": { - compressible: true, - extensions: [ - "pac" - ] -}, - "application/x-nzb": { - source: "apache", - extensions: [ - "nzb" - ] -}, - "application/x-perl": { - source: "nginx", - extensions: [ - "pl", - "pm" - ] -}, - "application/x-pilot": { - source: "nginx", - extensions: [ - "prc", - "pdb" - ] -}, - "application/x-pkcs12": { - source: "apache", - compressible: false, - extensions: [ - "p12", - "pfx" - ] -}, - "application/x-pkcs7-certificates": { - source: "apache", - extensions: [ - "p7b", - "spc" - ] -}, - "application/x-pkcs7-certreqresp": { - source: "apache", - extensions: [ - "p7r" - ] -}, - "application/x-pki-message": { - source: "iana" -}, - "application/x-rar-compressed": { - source: "apache", - compressible: false, - extensions: [ - "rar" - ] -}, - "application/x-redhat-package-manager": { - source: "nginx", - extensions: [ - "rpm" - ] -}, - "application/x-research-info-systems": { - source: "apache", - extensions: [ - "ris" - ] -}, - "application/x-sea": { - source: "nginx", - extensions: [ - "sea" - ] -}, - "application/x-sh": { - source: "apache", - compressible: true, - extensions: [ - "sh" - ] -}, - "application/x-shar": { - source: "apache", - extensions: [ - "shar" - ] -}, - "application/x-shockwave-flash": { - source: "apache", - compressible: false, - extensions: [ - "swf" - ] -}, - "application/x-silverlight-app": { - source: "apache", - extensions: [ - "xap" - ] -}, - "application/x-sql": { - source: "apache", - extensions: [ - "sql" - ] -}, - "application/x-stuffit": { - source: "apache", - compressible: false, - extensions: [ - "sit" - ] -}, - "application/x-stuffitx": { - source: "apache", - extensions: [ - "sitx" - ] -}, - "application/x-subrip": { - source: "apache", - extensions: [ - "srt" - ] -}, - "application/x-sv4cpio": { - source: "apache", - extensions: [ - "sv4cpio" - ] -}, - "application/x-sv4crc": { - source: "apache", - extensions: [ - "sv4crc" - ] -}, - "application/x-t3vm-image": { - source: "apache", - extensions: [ - "t3" - ] -}, - "application/x-tads": { - source: "apache", - extensions: [ - "gam" - ] -}, - "application/x-tar": { - source: "apache", - compressible: true, - extensions: [ - "tar" - ] -}, - "application/x-tcl": { - source: "apache", - extensions: [ - "tcl", - "tk" - ] -}, - "application/x-tex": { - source: "apache", - extensions: [ - "tex" - ] -}, - "application/x-tex-tfm": { - source: "apache", - extensions: [ - "tfm" - ] -}, - "application/x-texinfo": { - source: "apache", - extensions: [ - "texinfo", - "texi" - ] -}, - "application/x-tgif": { - source: "apache", - extensions: [ - "obj" - ] -}, - "application/x-ustar": { - source: "apache", - extensions: [ - "ustar" - ] -}, - "application/x-virtualbox-hdd": { - compressible: true, - extensions: [ - "hdd" - ] -}, - "application/x-virtualbox-ova": { - compressible: true, - extensions: [ - "ova" - ] -}, - "application/x-virtualbox-ovf": { - compressible: true, - extensions: [ - "ovf" - ] -}, - "application/x-virtualbox-vbox": { - compressible: true, - extensions: [ - "vbox" - ] -}, - "application/x-virtualbox-vbox-extpack": { - compressible: false, - extensions: [ - "vbox-extpack" - ] -}, - "application/x-virtualbox-vdi": { - compressible: true, - extensions: [ - "vdi" - ] -}, - "application/x-virtualbox-vhd": { - compressible: true, - extensions: [ - "vhd" - ] -}, - "application/x-virtualbox-vmdk": { - compressible: true, - extensions: [ - "vmdk" - ] -}, - "application/x-wais-source": { - source: "apache", - extensions: [ - "src" - ] -}, - "application/x-web-app-manifest+json": { - compressible: true, - extensions: [ - "webapp" - ] -}, - "application/x-www-form-urlencoded": { - source: "iana", - compressible: true -}, - "application/x-x509-ca-cert": { - source: "iana", - extensions: [ - "der", - "crt", - "pem" - ] -}, - "application/x-x509-ca-ra-cert": { - source: "iana" -}, - "application/x-x509-next-ca-cert": { - source: "iana" -}, - "application/x-xfig": { - source: "apache", - extensions: [ - "fig" - ] -}, - "application/x-xliff+xml": { - source: "apache", - compressible: true, - extensions: [ - "xlf" - ] -}, - "application/x-xpinstall": { - source: "apache", - compressible: false, - extensions: [ - "xpi" - ] -}, - "application/x-xz": { - source: "apache", - extensions: [ - "xz" - ] -}, - "application/x-zmachine": { - source: "apache", - extensions: [ - "z1", - "z2", - "z3", - "z4", - "z5", - "z6", - "z7", - "z8" - ] -}, - "application/x400-bp": { - source: "iana" -}, - "application/xacml+xml": { - source: "iana", - compressible: true -}, - "application/xaml+xml": { - source: "apache", - compressible: true, - extensions: [ - "xaml" - ] -}, - "application/xcap-att+xml": { - source: "iana", - compressible: true, - extensions: [ - "xav" - ] -}, - "application/xcap-caps+xml": { - source: "iana", - compressible: true, - extensions: [ - "xca" - ] -}, - "application/xcap-diff+xml": { - source: "iana", - compressible: true, - extensions: [ - "xdf" - ] -}, - "application/xcap-el+xml": { - source: "iana", - compressible: true, - extensions: [ - "xel" - ] -}, - "application/xcap-error+xml": { - source: "iana", - compressible: true, - extensions: [ - "xer" - ] -}, - "application/xcap-ns+xml": { - source: "iana", - compressible: true, - extensions: [ - "xns" - ] -}, - "application/xcon-conference-info+xml": { - source: "iana", - compressible: true -}, - "application/xcon-conference-info-diff+xml": { - source: "iana", - compressible: true -}, - "application/xenc+xml": { - source: "iana", - compressible: true, - extensions: [ - "xenc" - ] -}, - "application/xhtml+xml": { - source: "iana", - compressible: true, - extensions: [ - "xhtml", - "xht" - ] -}, - "application/xhtml-voice+xml": { - source: "apache", - compressible: true -}, - "application/xliff+xml": { - source: "iana", - compressible: true, - extensions: [ - "xlf" - ] -}, - "application/xml": { - source: "iana", - compressible: true, - extensions: [ - "xml", - "xsl", - "xsd", - "rng" - ] -}, - "application/xml-dtd": { - source: "iana", - compressible: true, - extensions: [ - "dtd" - ] -}, - "application/xml-external-parsed-entity": { - source: "iana" -}, - "application/xml-patch+xml": { - source: "iana", - compressible: true -}, - "application/xmpp+xml": { - source: "iana", - compressible: true -}, - "application/xop+xml": { - source: "iana", - compressible: true, - extensions: [ - "xop" - ] -}, - "application/xproc+xml": { - source: "apache", - compressible: true, - extensions: [ - "xpl" - ] -}, - "application/xslt+xml": { - source: "iana", - compressible: true, - extensions: [ - "xsl", - "xslt" - ] -}, - "application/xspf+xml": { - source: "apache", - compressible: true, - extensions: [ - "xspf" - ] -}, - "application/xv+xml": { - source: "iana", - compressible: true, - extensions: [ - "mxml", - "xhvml", - "xvml", - "xvm" - ] -}, - "application/yang": { - source: "iana", - extensions: [ - "yang" - ] -}, - "application/yang-data+json": { - source: "iana", - compressible: true -}, - "application/yang-data+xml": { - source: "iana", - compressible: true -}, - "application/yang-patch+json": { - source: "iana", - compressible: true -}, - "application/yang-patch+xml": { - source: "iana", - compressible: true -}, - "application/yin+xml": { - source: "iana", - compressible: true, - extensions: [ - "yin" - ] -}, - "application/zip": { - source: "iana", - compressible: false, - extensions: [ - "zip" - ] -}, - "application/zlib": { - source: "iana" -}, - "application/zstd": { - source: "iana" -}, - "audio/1d-interleaved-parityfec": { - source: "iana" -}, - "audio/32kadpcm": { - source: "iana" -}, - "audio/3gpp": { - source: "iana", - compressible: false, - extensions: [ - "3gpp" - ] -}, - "audio/3gpp2": { - source: "iana" -}, - "audio/aac": { - source: "iana" -}, - "audio/ac3": { - source: "iana" -}, - "audio/adpcm": { - source: "apache", - extensions: [ - "adp" - ] -}, - "audio/amr": { - source: "iana", - extensions: [ - "amr" - ] -}, - "audio/amr-wb": { - source: "iana" -}, - "audio/amr-wb+": { - source: "iana" -}, - "audio/aptx": { - source: "iana" -}, - "audio/asc": { - source: "iana" -}, - "audio/atrac-advanced-lossless": { - source: "iana" -}, - "audio/atrac-x": { - source: "iana" -}, - "audio/atrac3": { - source: "iana" -}, - "audio/basic": { - source: "iana", - compressible: false, - extensions: [ - "au", - "snd" - ] -}, - "audio/bv16": { - source: "iana" -}, - "audio/bv32": { - source: "iana" -}, - "audio/clearmode": { - source: "iana" -}, - "audio/cn": { - source: "iana" -}, - "audio/dat12": { - source: "iana" -}, - "audio/dls": { - source: "iana" -}, - "audio/dsr-es201108": { - source: "iana" -}, - "audio/dsr-es202050": { - source: "iana" -}, - "audio/dsr-es202211": { - source: "iana" -}, - "audio/dsr-es202212": { - source: "iana" -}, - "audio/dv": { - source: "iana" -}, - "audio/dvi4": { - source: "iana" -}, - "audio/eac3": { - source: "iana" -}, - "audio/encaprtp": { - source: "iana" -}, - "audio/evrc": { - source: "iana" -}, - "audio/evrc-qcp": { - source: "iana" -}, - "audio/evrc0": { - source: "iana" -}, - "audio/evrc1": { - source: "iana" -}, - "audio/evrcb": { - source: "iana" -}, - "audio/evrcb0": { - source: "iana" -}, - "audio/evrcb1": { - source: "iana" -}, - "audio/evrcnw": { - source: "iana" -}, - "audio/evrcnw0": { - source: "iana" -}, - "audio/evrcnw1": { - source: "iana" -}, - "audio/evrcwb": { - source: "iana" -}, - "audio/evrcwb0": { - source: "iana" -}, - "audio/evrcwb1": { - source: "iana" -}, - "audio/evs": { - source: "iana" -}, - "audio/flexfec": { - source: "iana" -}, - "audio/fwdred": { - source: "iana" -}, - "audio/g711-0": { - source: "iana" -}, - "audio/g719": { - source: "iana" -}, - "audio/g722": { - source: "iana" -}, - "audio/g7221": { - source: "iana" -}, - "audio/g723": { - source: "iana" -}, - "audio/g726-16": { - source: "iana" -}, - "audio/g726-24": { - source: "iana" -}, - "audio/g726-32": { - source: "iana" -}, - "audio/g726-40": { - source: "iana" -}, - "audio/g728": { - source: "iana" -}, - "audio/g729": { - source: "iana" -}, - "audio/g7291": { - source: "iana" -}, - "audio/g729d": { - source: "iana" -}, - "audio/g729e": { - source: "iana" -}, - "audio/gsm": { - source: "iana" -}, - "audio/gsm-efr": { - source: "iana" -}, - "audio/gsm-hr-08": { - source: "iana" -}, - "audio/ilbc": { - source: "iana" -}, - "audio/ip-mr_v2.5": { - source: "iana" -}, - "audio/isac": { - source: "apache" -}, - "audio/l16": { - source: "iana" -}, - "audio/l20": { - source: "iana" -}, - "audio/l24": { - source: "iana", - compressible: false -}, - "audio/l8": { - source: "iana" -}, - "audio/lpc": { - source: "iana" -}, - "audio/melp": { - source: "iana" -}, - "audio/melp1200": { - source: "iana" -}, - "audio/melp2400": { - source: "iana" -}, - "audio/melp600": { - source: "iana" -}, - "audio/mhas": { - source: "iana" -}, - "audio/midi": { - source: "apache", - extensions: [ - "mid", - "midi", - "kar", - "rmi" - ] -}, - "audio/mobile-xmf": { - source: "iana", - extensions: [ - "mxmf" - ] -}, - "audio/mp3": { - compressible: false, - extensions: [ - "mp3" - ] -}, - "audio/mp4": { - source: "iana", - compressible: false, - extensions: [ - "m4a", - "mp4a" - ] -}, - "audio/mp4a-latm": { - source: "iana" -}, - "audio/mpa": { - source: "iana" -}, - "audio/mpa-robust": { - source: "iana" -}, - "audio/mpeg": { - source: "iana", - compressible: false, - extensions: [ - "mpga", - "mp2", - "mp2a", - "mp3", - "m2a", - "m3a" - ] -}, - "audio/mpeg4-generic": { - source: "iana" -}, - "audio/musepack": { - source: "apache" -}, - "audio/ogg": { - source: "iana", - compressible: false, - extensions: [ - "oga", - "ogg", - "spx", - "opus" - ] -}, - "audio/opus": { - source: "iana" -}, - "audio/parityfec": { - source: "iana" -}, - "audio/pcma": { - source: "iana" -}, - "audio/pcma-wb": { - source: "iana" -}, - "audio/pcmu": { - source: "iana" -}, - "audio/pcmu-wb": { - source: "iana" -}, - "audio/prs.sid": { - source: "iana" -}, - "audio/qcelp": { - source: "iana" -}, - "audio/raptorfec": { - source: "iana" -}, - "audio/red": { - source: "iana" -}, - "audio/rtp-enc-aescm128": { - source: "iana" -}, - "audio/rtp-midi": { - source: "iana" -}, - "audio/rtploopback": { - source: "iana" -}, - "audio/rtx": { - source: "iana" -}, - "audio/s3m": { - source: "apache", - extensions: [ - "s3m" - ] -}, - "audio/scip": { - source: "iana" -}, - "audio/silk": { - source: "apache", - extensions: [ - "sil" - ] -}, - "audio/smv": { - source: "iana" -}, - "audio/smv-qcp": { - source: "iana" -}, - "audio/smv0": { - source: "iana" -}, - "audio/sofa": { - source: "iana" -}, - "audio/sp-midi": { - source: "iana" -}, - "audio/speex": { - source: "iana" -}, - "audio/t140c": { - source: "iana" -}, - "audio/t38": { - source: "iana" -}, - "audio/telephone-event": { - source: "iana" -}, - "audio/tetra_acelp": { - source: "iana" -}, - "audio/tetra_acelp_bb": { - source: "iana" -}, - "audio/tone": { - source: "iana" -}, - "audio/tsvcis": { - source: "iana" -}, - "audio/uemclip": { - source: "iana" -}, - "audio/ulpfec": { - source: "iana" -}, - "audio/usac": { - source: "iana" -}, - "audio/vdvi": { - source: "iana" -}, - "audio/vmr-wb": { - source: "iana" -}, - "audio/vnd.3gpp.iufp": { - source: "iana" -}, - "audio/vnd.4sb": { - source: "iana" -}, - "audio/vnd.audiokoz": { - source: "iana" -}, - "audio/vnd.celp": { - source: "iana" -}, - "audio/vnd.cisco.nse": { - source: "iana" -}, - "audio/vnd.cmles.radio-events": { - source: "iana" -}, - "audio/vnd.cns.anp1": { - source: "iana" -}, - "audio/vnd.cns.inf1": { - source: "iana" -}, - "audio/vnd.dece.audio": { - source: "iana", - extensions: [ - "uva", - "uvva" - ] -}, - "audio/vnd.digital-winds": { - source: "iana", - extensions: [ - "eol" - ] -}, - "audio/vnd.dlna.adts": { - source: "iana" -}, - "audio/vnd.dolby.heaac.1": { - source: "iana" -}, - "audio/vnd.dolby.heaac.2": { - source: "iana" -}, - "audio/vnd.dolby.mlp": { - source: "iana" -}, - "audio/vnd.dolby.mps": { - source: "iana" -}, - "audio/vnd.dolby.pl2": { - source: "iana" -}, - "audio/vnd.dolby.pl2x": { - source: "iana" -}, - "audio/vnd.dolby.pl2z": { - source: "iana" -}, - "audio/vnd.dolby.pulse.1": { - source: "iana" -}, - "audio/vnd.dra": { - source: "iana", - extensions: [ - "dra" - ] -}, - "audio/vnd.dts": { - source: "iana", - extensions: [ - "dts" - ] -}, - "audio/vnd.dts.hd": { - source: "iana", - extensions: [ - "dtshd" - ] -}, - "audio/vnd.dts.uhd": { - source: "iana" -}, - "audio/vnd.dvb.file": { - source: "iana" -}, - "audio/vnd.everad.plj": { - source: "iana" -}, - "audio/vnd.hns.audio": { - source: "iana" -}, - "audio/vnd.lucent.voice": { - source: "iana", - extensions: [ - "lvp" - ] -}, - "audio/vnd.ms-playready.media.pya": { - source: "iana", - extensions: [ - "pya" - ] -}, - "audio/vnd.nokia.mobile-xmf": { - source: "iana" -}, - "audio/vnd.nortel.vbk": { - source: "iana" -}, - "audio/vnd.nuera.ecelp4800": { - source: "iana", - extensions: [ - "ecelp4800" - ] -}, - "audio/vnd.nuera.ecelp7470": { - source: "iana", - extensions: [ - "ecelp7470" - ] -}, - "audio/vnd.nuera.ecelp9600": { - source: "iana", - extensions: [ - "ecelp9600" - ] -}, - "audio/vnd.octel.sbc": { - source: "iana" -}, - "audio/vnd.presonus.multitrack": { - source: "iana" -}, - "audio/vnd.qcelp": { - source: "iana" -}, - "audio/vnd.rhetorex.32kadpcm": { - source: "iana" -}, - "audio/vnd.rip": { - source: "iana", - extensions: [ - "rip" - ] -}, - "audio/vnd.rn-realaudio": { - compressible: false -}, - "audio/vnd.sealedmedia.softseal.mpeg": { - source: "iana" -}, - "audio/vnd.vmx.cvsd": { - source: "iana" -}, - "audio/vnd.wave": { - compressible: false -}, - "audio/vorbis": { - source: "iana", - compressible: false -}, - "audio/vorbis-config": { - source: "iana" -}, - "audio/wav": { - compressible: false, - extensions: [ - "wav" - ] -}, - "audio/wave": { - compressible: false, - extensions: [ - "wav" - ] -}, - "audio/webm": { - source: "apache", - compressible: false, - extensions: [ - "weba" - ] -}, - "audio/x-aac": { - source: "apache", - compressible: false, - extensions: [ - "aac" - ] -}, - "audio/x-aiff": { - source: "apache", - extensions: [ - "aif", - "aiff", - "aifc" - ] -}, - "audio/x-caf": { - source: "apache", - compressible: false, - extensions: [ - "caf" - ] -}, - "audio/x-flac": { - source: "apache", - extensions: [ - "flac" - ] -}, - "audio/x-m4a": { - source: "nginx", - extensions: [ - "m4a" - ] -}, - "audio/x-matroska": { - source: "apache", - extensions: [ - "mka" - ] -}, - "audio/x-mpegurl": { - source: "apache", - extensions: [ - "m3u" - ] -}, - "audio/x-ms-wax": { - source: "apache", - extensions: [ - "wax" - ] -}, - "audio/x-ms-wma": { - source: "apache", - extensions: [ - "wma" - ] -}, - "audio/x-pn-realaudio": { - source: "apache", - extensions: [ - "ram", - "ra" - ] -}, - "audio/x-pn-realaudio-plugin": { - source: "apache", - extensions: [ - "rmp" - ] -}, - "audio/x-realaudio": { - source: "nginx", - extensions: [ - "ra" - ] -}, - "audio/x-tta": { - source: "apache" -}, - "audio/x-wav": { - source: "apache", - extensions: [ - "wav" - ] -}, - "audio/xm": { - source: "apache", - extensions: [ - "xm" - ] -}, - "chemical/x-cdx": { - source: "apache", - extensions: [ - "cdx" - ] -}, - "chemical/x-cif": { - source: "apache", - extensions: [ - "cif" - ] -}, - "chemical/x-cmdf": { - source: "apache", - extensions: [ - "cmdf" - ] -}, - "chemical/x-cml": { - source: "apache", - extensions: [ - "cml" - ] -}, - "chemical/x-csml": { - source: "apache", - extensions: [ - "csml" - ] -}, - "chemical/x-pdb": { - source: "apache" -}, - "chemical/x-xyz": { - source: "apache", - extensions: [ - "xyz" - ] -}, - "font/collection": { - source: "iana", - extensions: [ - "ttc" - ] -}, - "font/otf": { - source: "iana", - compressible: true, - extensions: [ - "otf" - ] -}, - "font/sfnt": { - source: "iana" -}, - "font/ttf": { - source: "iana", - compressible: true, - extensions: [ - "ttf" - ] -}, - "font/woff": { - source: "iana", - extensions: [ - "woff" - ] -}, - "font/woff2": { - source: "iana", - extensions: [ - "woff2" - ] -}, - "image/aces": { - source: "iana", - extensions: [ - "exr" - ] -}, - "image/apng": { - compressible: false, - extensions: [ - "apng" - ] -}, - "image/avci": { - source: "iana" -}, - "image/avcs": { - source: "iana" -}, - "image/avif": { - source: "iana", - compressible: false, - extensions: [ - "avif" - ] -}, - "image/bmp": { - source: "iana", - compressible: true, - extensions: [ - "bmp" - ] -}, - "image/cgm": { - source: "iana", - extensions: [ - "cgm" - ] -}, - "image/dicom-rle": { - source: "iana", - extensions: [ - "drle" - ] -}, - "image/emf": { - source: "iana", - extensions: [ - "emf" - ] -}, - "image/fits": { - source: "iana", - extensions: [ - "fits" - ] -}, - "image/g3fax": { - source: "iana", - extensions: [ - "g3" - ] -}, - "image/gif": { - source: "iana", - compressible: false, - extensions: [ - "gif" - ] -}, - "image/heic": { - source: "iana", - extensions: [ - "heic" - ] -}, - "image/heic-sequence": { - source: "iana", - extensions: [ - "heics" - ] -}, - "image/heif": { - source: "iana", - extensions: [ - "heif" - ] -}, - "image/heif-sequence": { - source: "iana", - extensions: [ - "heifs" - ] -}, - "image/hej2k": { - source: "iana", - extensions: [ - "hej2" - ] -}, - "image/hsj2": { - source: "iana", - extensions: [ - "hsj2" - ] -}, - "image/ief": { - source: "iana", - extensions: [ - "ief" - ] -}, - "image/jls": { - source: "iana", - extensions: [ - "jls" - ] -}, - "image/jp2": { - source: "iana", - compressible: false, - extensions: [ - "jp2", - "jpg2" - ] -}, - "image/jpeg": { - source: "iana", - compressible: false, - extensions: [ - "jpeg", - "jpg", - "jpe" - ] -}, - "image/jph": { - source: "iana", - extensions: [ - "jph" - ] -}, - "image/jphc": { - source: "iana", - extensions: [ - "jhc" - ] -}, - "image/jpm": { - source: "iana", - compressible: false, - extensions: [ - "jpm" - ] -}, - "image/jpx": { - source: "iana", - compressible: false, - extensions: [ - "jpx", - "jpf" - ] -}, - "image/jxr": { - source: "iana", - extensions: [ - "jxr" - ] -}, - "image/jxra": { - source: "iana", - extensions: [ - "jxra" - ] -}, - "image/jxrs": { - source: "iana", - extensions: [ - "jxrs" - ] -}, - "image/jxs": { - source: "iana", - extensions: [ - "jxs" - ] -}, - "image/jxsc": { - source: "iana", - extensions: [ - "jxsc" - ] -}, - "image/jxsi": { - source: "iana", - extensions: [ - "jxsi" - ] -}, - "image/jxss": { - source: "iana", - extensions: [ - "jxss" - ] -}, - "image/ktx": { - source: "iana", - extensions: [ - "ktx" - ] -}, - "image/ktx2": { - source: "iana", - extensions: [ - "ktx2" - ] -}, - "image/naplps": { - source: "iana" -}, - "image/pjpeg": { - compressible: false -}, - "image/png": { - source: "iana", - compressible: false, - extensions: [ - "png" - ] -}, - "image/prs.btif": { - source: "iana", - extensions: [ - "btif" - ] -}, - "image/prs.pti": { - source: "iana", - extensions: [ - "pti" - ] -}, - "image/pwg-raster": { - source: "iana" -}, - "image/sgi": { - source: "apache", - extensions: [ - "sgi" - ] -}, - "image/svg+xml": { - source: "iana", - compressible: true, - extensions: [ - "svg", - "svgz" - ] -}, - "image/t38": { - source: "iana", - extensions: [ - "t38" - ] -}, - "image/tiff": { - source: "iana", - compressible: false, - extensions: [ - "tif", - "tiff" - ] -}, - "image/tiff-fx": { - source: "iana", - extensions: [ - "tfx" - ] -}, - "image/vnd.adobe.photoshop": { - source: "iana", - compressible: true, - extensions: [ - "psd" - ] -}, - "image/vnd.airzip.accelerator.azv": { - source: "iana", - extensions: [ - "azv" - ] -}, - "image/vnd.cns.inf2": { - source: "iana" -}, - "image/vnd.dece.graphic": { - source: "iana", - extensions: [ - "uvi", - "uvvi", - "uvg", - "uvvg" - ] -}, - "image/vnd.djvu": { - source: "iana", - extensions: [ - "djvu", - "djv" - ] -}, - "image/vnd.dvb.subtitle": { - source: "iana", - extensions: [ - "sub" - ] -}, - "image/vnd.dwg": { - source: "iana", - extensions: [ - "dwg" - ] -}, - "image/vnd.dxf": { - source: "iana", - extensions: [ - "dxf" - ] -}, - "image/vnd.fastbidsheet": { - source: "iana", - extensions: [ - "fbs" - ] -}, - "image/vnd.fpx": { - source: "iana", - extensions: [ - "fpx" - ] -}, - "image/vnd.fst": { - source: "iana", - extensions: [ - "fst" - ] -}, - "image/vnd.fujixerox.edmics-mmr": { - source: "iana", - extensions: [ - "mmr" - ] -}, - "image/vnd.fujixerox.edmics-rlc": { - source: "iana", - extensions: [ - "rlc" - ] -}, - "image/vnd.globalgraphics.pgb": { - source: "iana" -}, - "image/vnd.microsoft.icon": { - source: "iana", - extensions: [ - "ico" - ] -}, - "image/vnd.mix": { - source: "iana" -}, - "image/vnd.mozilla.apng": { - source: "iana" -}, - "image/vnd.ms-dds": { - extensions: [ - "dds" - ] -}, - "image/vnd.ms-modi": { - source: "iana", - extensions: [ - "mdi" - ] -}, - "image/vnd.ms-photo": { - source: "apache", - extensions: [ - "wdp" - ] -}, - "image/vnd.net-fpx": { - source: "iana", - extensions: [ - "npx" - ] -}, - "image/vnd.pco.b16": { - source: "iana", - extensions: [ - "b16" - ] -}, - "image/vnd.radiance": { - source: "iana" -}, - "image/vnd.sealed.png": { - source: "iana" -}, - "image/vnd.sealedmedia.softseal.gif": { - source: "iana" -}, - "image/vnd.sealedmedia.softseal.jpg": { - source: "iana" -}, - "image/vnd.svf": { - source: "iana" -}, - "image/vnd.tencent.tap": { - source: "iana", - extensions: [ - "tap" - ] -}, - "image/vnd.valve.source.texture": { - source: "iana", - extensions: [ - "vtf" - ] -}, - "image/vnd.wap.wbmp": { - source: "iana", - extensions: [ - "wbmp" - ] -}, - "image/vnd.xiff": { - source: "iana", - extensions: [ - "xif" - ] -}, - "image/vnd.zbrush.pcx": { - source: "iana", - extensions: [ - "pcx" - ] -}, - "image/webp": { - source: "apache", - extensions: [ - "webp" - ] -}, - "image/wmf": { - source: "iana", - extensions: [ - "wmf" - ] -}, - "image/x-3ds": { - source: "apache", - extensions: [ - "3ds" - ] -}, - "image/x-cmu-raster": { - source: "apache", - extensions: [ - "ras" - ] -}, - "image/x-cmx": { - source: "apache", - extensions: [ - "cmx" - ] -}, - "image/x-freehand": { - source: "apache", - extensions: [ - "fh", - "fhc", - "fh4", - "fh5", - "fh7" - ] -}, - "image/x-icon": { - source: "apache", - compressible: true, - extensions: [ - "ico" - ] -}, - "image/x-jng": { - source: "nginx", - extensions: [ - "jng" - ] -}, - "image/x-mrsid-image": { - source: "apache", - extensions: [ - "sid" - ] -}, - "image/x-ms-bmp": { - source: "nginx", - compressible: true, - extensions: [ - "bmp" - ] -}, - "image/x-pcx": { - source: "apache", - extensions: [ - "pcx" - ] -}, - "image/x-pict": { - source: "apache", - extensions: [ - "pic", - "pct" - ] -}, - "image/x-portable-anymap": { - source: "apache", - extensions: [ - "pnm" - ] -}, - "image/x-portable-bitmap": { - source: "apache", - extensions: [ - "pbm" - ] -}, - "image/x-portable-graymap": { - source: "apache", - extensions: [ - "pgm" - ] -}, - "image/x-portable-pixmap": { - source: "apache", - extensions: [ - "ppm" - ] -}, - "image/x-rgb": { - source: "apache", - extensions: [ - "rgb" - ] -}, - "image/x-tga": { - source: "apache", - extensions: [ - "tga" - ] -}, - "image/x-xbitmap": { - source: "apache", - extensions: [ - "xbm" - ] -}, - "image/x-xcf": { - compressible: false -}, - "image/x-xpixmap": { - source: "apache", - extensions: [ - "xpm" - ] -}, - "image/x-xwindowdump": { - source: "apache", - extensions: [ - "xwd" - ] -}, - "message/cpim": { - source: "iana" -}, - "message/delivery-status": { - source: "iana" -}, - "message/disposition-notification": { - source: "iana", - extensions: [ - "disposition-notification" - ] -}, - "message/external-body": { - source: "iana" -}, - "message/feedback-report": { - source: "iana" -}, - "message/global": { - source: "iana", - extensions: [ - "u8msg" - ] -}, - "message/global-delivery-status": { - source: "iana", - extensions: [ - "u8dsn" - ] -}, - "message/global-disposition-notification": { - source: "iana", - extensions: [ - "u8mdn" - ] -}, - "message/global-headers": { - source: "iana", - extensions: [ - "u8hdr" - ] -}, - "message/http": { - source: "iana", - compressible: false -}, - "message/imdn+xml": { - source: "iana", - compressible: true -}, - "message/news": { - source: "iana" -}, - "message/partial": { - source: "iana", - compressible: false -}, - "message/rfc822": { - source: "iana", - compressible: true, - extensions: [ - "eml", - "mime" - ] -}, - "message/s-http": { - source: "iana" -}, - "message/sip": { - source: "iana" -}, - "message/sipfrag": { - source: "iana" -}, - "message/tracking-status": { - source: "iana" -}, - "message/vnd.si.simp": { - source: "iana" -}, - "message/vnd.wfa.wsc": { - source: "iana", - extensions: [ - "wsc" - ] -}, - "model/3mf": { - source: "iana", - extensions: [ - "3mf" - ] -}, - "model/e57": { - source: "iana" -}, - "model/gltf+json": { - source: "iana", - compressible: true, - extensions: [ - "gltf" - ] -}, - "model/gltf-binary": { - source: "iana", - compressible: true, - extensions: [ - "glb" - ] -}, - "model/iges": { - source: "iana", - compressible: false, - extensions: [ - "igs", - "iges" - ] -}, - "model/mesh": { - source: "iana", - compressible: false, - extensions: [ - "msh", - "mesh", - "silo" - ] -}, - "model/mtl": { - source: "iana", - extensions: [ - "mtl" - ] -}, - "model/obj": { - source: "iana", - extensions: [ - "obj" - ] -}, - "model/stl": { - source: "iana", - extensions: [ - "stl" - ] -}, - "model/vnd.collada+xml": { - source: "iana", - compressible: true, - extensions: [ - "dae" - ] -}, - "model/vnd.dwf": { - source: "iana", - extensions: [ - "dwf" - ] -}, - "model/vnd.flatland.3dml": { - source: "iana" -}, - "model/vnd.gdl": { - source: "iana", - extensions: [ - "gdl" - ] -}, - "model/vnd.gs-gdl": { - source: "apache" -}, - "model/vnd.gs.gdl": { - source: "iana" -}, - "model/vnd.gtw": { - source: "iana", - extensions: [ - "gtw" - ] -}, - "model/vnd.moml+xml": { - source: "iana", - compressible: true -}, - "model/vnd.mts": { - source: "iana", - extensions: [ - "mts" - ] -}, - "model/vnd.opengex": { - source: "iana", - extensions: [ - "ogex" - ] -}, - "model/vnd.parasolid.transmit.binary": { - source: "iana", - extensions: [ - "x_b" - ] -}, - "model/vnd.parasolid.transmit.text": { - source: "iana", - extensions: [ - "x_t" - ] -}, - "model/vnd.rosette.annotated-data-model": { - source: "iana" -}, - "model/vnd.usdz+zip": { - source: "iana", - compressible: false, - extensions: [ - "usdz" - ] -}, - "model/vnd.valve.source.compiled-map": { - source: "iana", - extensions: [ - "bsp" - ] -}, - "model/vnd.vtu": { - source: "iana", - extensions: [ - "vtu" - ] -}, - "model/vrml": { - source: "iana", - compressible: false, - extensions: [ - "wrl", - "vrml" - ] -}, - "model/x3d+binary": { - source: "apache", - compressible: false, - extensions: [ - "x3db", - "x3dbz" - ] -}, - "model/x3d+fastinfoset": { - source: "iana", - extensions: [ - "x3db" - ] -}, - "model/x3d+vrml": { - source: "apache", - compressible: false, - extensions: [ - "x3dv", - "x3dvz" - ] -}, - "model/x3d+xml": { - source: "iana", - compressible: true, - extensions: [ - "x3d", - "x3dz" - ] -}, - "model/x3d-vrml": { - source: "iana", - extensions: [ - "x3dv" - ] -}, - "multipart/alternative": { - source: "iana", - compressible: false -}, - "multipart/appledouble": { - source: "iana" -}, - "multipart/byteranges": { - source: "iana" -}, - "multipart/digest": { - source: "iana" -}, - "multipart/encrypted": { - source: "iana", - compressible: false -}, - "multipart/form-data": { - source: "iana", - compressible: false -}, - "multipart/header-set": { - source: "iana" -}, - "multipart/mixed": { - source: "iana" -}, - "multipart/multilingual": { - source: "iana" -}, - "multipart/parallel": { - source: "iana" -}, - "multipart/related": { - source: "iana", - compressible: false -}, - "multipart/report": { - source: "iana" -}, - "multipart/signed": { - source: "iana", - compressible: false -}, - "multipart/vnd.bint.med-plus": { - source: "iana" -}, - "multipart/voice-message": { - source: "iana" -}, - "multipart/x-mixed-replace": { - source: "iana" -}, - "text/1d-interleaved-parityfec": { - source: "iana" -}, - "text/cache-manifest": { - source: "iana", - compressible: true, - extensions: [ - "appcache", - "manifest" - ] -}, - "text/calendar": { - source: "iana", - extensions: [ - "ics", - "ifb" - ] -}, - "text/calender": { - compressible: true -}, - "text/cmd": { - compressible: true -}, - "text/coffeescript": { - extensions: [ - "coffee", - "litcoffee" - ] -}, - "text/cql": { - source: "iana" -}, - "text/cql-expression": { - source: "iana" -}, - "text/cql-identifier": { - source: "iana" -}, - "text/css": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: [ - "css" - ] -}, - "text/csv": { - source: "iana", - compressible: true, - extensions: [ - "csv" - ] -}, - "text/csv-schema": { - source: "iana" -}, - "text/directory": { - source: "iana" -}, - "text/dns": { - source: "iana" -}, - "text/ecmascript": { - source: "iana" -}, - "text/encaprtp": { - source: "iana" -}, - "text/enriched": { - source: "iana" -}, - "text/fhirpath": { - source: "iana" -}, - "text/flexfec": { - source: "iana" -}, - "text/fwdred": { - source: "iana" -}, - "text/gff3": { - source: "iana" -}, - "text/grammar-ref-list": { - source: "iana" -}, - "text/html": { - source: "iana", - compressible: true, - extensions: [ - "html", - "htm", - "shtml" - ] -}, - "text/jade": { - extensions: [ - "jade" - ] -}, - "text/javascript": { - source: "iana", - compressible: true -}, - "text/jcr-cnd": { - source: "iana" -}, - "text/jsx": { - compressible: true, - extensions: [ - "jsx" - ] -}, - "text/less": { - compressible: true, - extensions: [ - "less" - ] -}, - "text/markdown": { - source: "iana", - compressible: true, - extensions: [ - "markdown", - "md" - ] -}, - "text/mathml": { - source: "nginx", - extensions: [ - "mml" - ] -}, - "text/mdx": { - compressible: true, - extensions: [ - "mdx" - ] -}, - "text/mizar": { - source: "iana" -}, - "text/n3": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: [ - "n3" - ] -}, - "text/parameters": { - source: "iana", - charset: "UTF-8" -}, - "text/parityfec": { - source: "iana" -}, - "text/plain": { - source: "iana", - compressible: true, - extensions: [ - "txt", - "text", - "conf", - "def", - "list", - "log", - "in", - "ini" - ] -}, - "text/provenance-notation": { - source: "iana", - charset: "UTF-8" -}, - "text/prs.fallenstein.rst": { - source: "iana" -}, - "text/prs.lines.tag": { - source: "iana", - extensions: [ - "dsc" - ] -}, - "text/prs.prop.logic": { - source: "iana" -}, - "text/raptorfec": { - source: "iana" -}, - "text/red": { - source: "iana" -}, - "text/rfc822-headers": { - source: "iana" -}, - "text/richtext": { - source: "iana", - compressible: true, - extensions: [ - "rtx" - ] -}, - "text/rtf": { - source: "iana", - compressible: true, - extensions: [ - "rtf" - ] -}, - "text/rtp-enc-aescm128": { - source: "iana" -}, - "text/rtploopback": { - source: "iana" -}, - "text/rtx": { - source: "iana" -}, - "text/sgml": { - source: "iana", - extensions: [ - "sgml", - "sgm" - ] -}, - "text/shaclc": { - source: "iana" -}, - "text/shex": { - extensions: [ - "shex" - ] -}, - "text/slim": { - extensions: [ - "slim", - "slm" - ] -}, - "text/spdx": { - source: "iana", - extensions: [ - "spdx" - ] -}, - "text/strings": { - source: "iana" -}, - "text/stylus": { - extensions: [ - "stylus", - "styl" - ] -}, - "text/t140": { - source: "iana" -}, - "text/tab-separated-values": { - source: "iana", - compressible: true, - extensions: [ - "tsv" - ] -}, - "text/troff": { - source: "iana", - extensions: [ - "t", - "tr", - "roff", - "man", - "me", - "ms" - ] -}, - "text/turtle": { - source: "iana", - charset: "UTF-8", - extensions: [ - "ttl" - ] -}, - "text/ulpfec": { - source: "iana" -}, - "text/uri-list": { - source: "iana", - compressible: true, - extensions: [ - "uri", - "uris", - "urls" - ] -}, - "text/vcard": { - source: "iana", - compressible: true, - extensions: [ - "vcard" - ] -}, - "text/vnd.a": { - source: "iana" -}, - "text/vnd.abc": { - source: "iana" -}, - "text/vnd.ascii-art": { - source: "iana" -}, - "text/vnd.curl": { - source: "iana", - extensions: [ - "curl" - ] -}, - "text/vnd.curl.dcurl": { - source: "apache", - extensions: [ - "dcurl" - ] -}, - "text/vnd.curl.mcurl": { - source: "apache", - extensions: [ - "mcurl" - ] -}, - "text/vnd.curl.scurl": { - source: "apache", - extensions: [ - "scurl" - ] -}, - "text/vnd.debian.copyright": { - source: "iana", - charset: "UTF-8" -}, - "text/vnd.dmclientscript": { - source: "iana" -}, - "text/vnd.dvb.subtitle": { - source: "iana", - extensions: [ - "sub" - ] -}, - "text/vnd.esmertec.theme-descriptor": { - source: "iana", - charset: "UTF-8" -}, - "text/vnd.ficlab.flt": { - source: "iana" -}, - "text/vnd.fly": { - source: "iana", - extensions: [ - "fly" - ] -}, - "text/vnd.fmi.flexstor": { - source: "iana", - extensions: [ - "flx" - ] -}, - "text/vnd.gml": { - source: "iana" -}, - "text/vnd.graphviz": { - source: "iana", - extensions: [ - "gv" - ] -}, - "text/vnd.hans": { - source: "iana" -}, - "text/vnd.hgl": { - source: "iana" -}, - "text/vnd.in3d.3dml": { - source: "iana", - extensions: [ - "3dml" - ] -}, - "text/vnd.in3d.spot": { - source: "iana", - extensions: [ - "spot" - ] -}, - "text/vnd.iptc.newsml": { - source: "iana" -}, - "text/vnd.iptc.nitf": { - source: "iana" -}, - "text/vnd.latex-z": { - source: "iana" -}, - "text/vnd.motorola.reflex": { - source: "iana" -}, - "text/vnd.ms-mediapackage": { - source: "iana" -}, - "text/vnd.net2phone.commcenter.command": { - source: "iana" -}, - "text/vnd.radisys.msml-basic-layout": { - source: "iana" -}, - "text/vnd.senx.warpscript": { - source: "iana" -}, - "text/vnd.si.uricatalogue": { - source: "iana" -}, - "text/vnd.sosi": { - source: "iana" -}, - "text/vnd.sun.j2me.app-descriptor": { - source: "iana", - charset: "UTF-8", - extensions: [ - "jad" - ] -}, - "text/vnd.trolltech.linguist": { - source: "iana", - charset: "UTF-8" -}, - "text/vnd.wap.si": { - source: "iana" -}, - "text/vnd.wap.sl": { - source: "iana" -}, - "text/vnd.wap.wml": { - source: "iana", - extensions: [ - "wml" - ] -}, - "text/vnd.wap.wmlscript": { - source: "iana", - extensions: [ - "wmls" - ] -}, - "text/vtt": { - source: "iana", - charset: "UTF-8", - compressible: true, - extensions: [ - "vtt" - ] -}, - "text/x-asm": { - source: "apache", - extensions: [ - "s", - "asm" - ] -}, - "text/x-c": { - source: "apache", - extensions: [ - "c", - "cc", - "cxx", - "cpp", - "h", - "hh", - "dic" - ] -}, - "text/x-component": { - source: "nginx", - extensions: [ - "htc" - ] -}, - "text/x-fortran": { - source: "apache", - extensions: [ - "f", - "for", - "f77", - "f90" - ] -}, - "text/x-gwt-rpc": { - compressible: true -}, - "text/x-handlebars-template": { - extensions: [ - "hbs" - ] -}, - "text/x-java-source": { - source: "apache", - extensions: [ - "java" - ] -}, - "text/x-jquery-tmpl": { - compressible: true -}, - "text/x-lua": { - extensions: [ - "lua" - ] -}, - "text/x-markdown": { - compressible: true, - extensions: [ - "mkd" - ] -}, - "text/x-nfo": { - source: "apache", - extensions: [ - "nfo" - ] -}, - "text/x-opml": { - source: "apache", - extensions: [ - "opml" - ] -}, - "text/x-org": { - compressible: true, - extensions: [ - "org" - ] -}, - "text/x-pascal": { - source: "apache", - extensions: [ - "p", - "pas" - ] -}, - "text/x-processing": { - compressible: true, - extensions: [ - "pde" - ] -}, - "text/x-sass": { - extensions: [ - "sass" - ] -}, - "text/x-scss": { - extensions: [ - "scss" - ] -}, - "text/x-setext": { - source: "apache", - extensions: [ - "etx" - ] -}, - "text/x-sfv": { - source: "apache", - extensions: [ - "sfv" - ] -}, - "text/x-suse-ymp": { - compressible: true, - extensions: [ - "ymp" - ] -}, - "text/x-uuencode": { - source: "apache", - extensions: [ - "uu" - ] -}, - "text/x-vcalendar": { - source: "apache", - extensions: [ - "vcs" - ] -}, - "text/x-vcard": { - source: "apache", - extensions: [ - "vcf" - ] -}, - "text/xml": { - source: "iana", - compressible: true, - extensions: [ - "xml" - ] -}, - "text/xml-external-parsed-entity": { - source: "iana" -}, - "text/yaml": { - extensions: [ - "yaml", - "yml" - ] -}, - "video/1d-interleaved-parityfec": { - source: "iana" -}, - "video/3gpp": { - source: "iana", - extensions: [ - "3gp", - "3gpp" - ] -}, - "video/3gpp-tt": { - source: "iana" -}, - "video/3gpp2": { - source: "iana", - extensions: [ - "3g2" - ] -}, - "video/av1": { - source: "iana" -}, - "video/bmpeg": { - source: "iana" -}, - "video/bt656": { - source: "iana" -}, - "video/celb": { - source: "iana" -}, - "video/dv": { - source: "iana" -}, - "video/encaprtp": { - source: "iana" -}, - "video/flexfec": { - source: "iana" -}, - "video/h261": { - source: "iana", - extensions: [ - "h261" - ] -}, - "video/h263": { - source: "iana", - extensions: [ - "h263" - ] -}, - "video/h263-1998": { - source: "iana" -}, - "video/h263-2000": { - source: "iana" -}, - "video/h264": { - source: "iana", - extensions: [ - "h264" - ] -}, - "video/h264-rcdo": { - source: "iana" -}, - "video/h264-svc": { - source: "iana" -}, - "video/h265": { - source: "iana" -}, - "video/iso.segment": { - source: "iana", - extensions: [ - "m4s" - ] -}, - "video/jpeg": { - source: "iana", - extensions: [ - "jpgv" - ] -}, - "video/jpeg2000": { - source: "iana" -}, - "video/jpm": { - source: "apache", - extensions: [ - "jpm", - "jpgm" - ] -}, - "video/mj2": { - source: "iana", - extensions: [ - "mj2", - "mjp2" - ] -}, - "video/mp1s": { - source: "iana" -}, - "video/mp2p": { - source: "iana" -}, - "video/mp2t": { - source: "iana", - extensions: [ - "ts" - ] -}, - "video/mp4": { - source: "iana", - compressible: false, - extensions: [ - "mp4", - "mp4v", - "mpg4" - ] -}, - "video/mp4v-es": { - source: "iana" -}, - "video/mpeg": { - source: "iana", - compressible: false, - extensions: [ - "mpeg", - "mpg", - "mpe", - "m1v", - "m2v" - ] -}, - "video/mpeg4-generic": { - source: "iana" -}, - "video/mpv": { - source: "iana" -}, - "video/nv": { - source: "iana" -}, - "video/ogg": { - source: "iana", - compressible: false, - extensions: [ - "ogv" - ] -}, - "video/parityfec": { - source: "iana" -}, - "video/pointer": { - source: "iana" -}, - "video/quicktime": { - source: "iana", - compressible: false, - extensions: [ - "qt", - "mov" - ] -}, - "video/raptorfec": { - source: "iana" -}, - "video/raw": { - source: "iana" -}, - "video/rtp-enc-aescm128": { - source: "iana" -}, - "video/rtploopback": { - source: "iana" -}, - "video/rtx": { - source: "iana" -}, - "video/scip": { - source: "iana" -}, - "video/smpte291": { - source: "iana" -}, - "video/smpte292m": { - source: "iana" -}, - "video/ulpfec": { - source: "iana" -}, - "video/vc1": { - source: "iana" -}, - "video/vc2": { - source: "iana" -}, - "video/vnd.cctv": { - source: "iana" -}, - "video/vnd.dece.hd": { - source: "iana", - extensions: [ - "uvh", - "uvvh" - ] -}, - "video/vnd.dece.mobile": { - source: "iana", - extensions: [ - "uvm", - "uvvm" - ] -}, - "video/vnd.dece.mp4": { - source: "iana" -}, - "video/vnd.dece.pd": { - source: "iana", - extensions: [ - "uvp", - "uvvp" - ] -}, - "video/vnd.dece.sd": { - source: "iana", - extensions: [ - "uvs", - "uvvs" - ] -}, - "video/vnd.dece.video": { - source: "iana", - extensions: [ - "uvv", - "uvvv" - ] -}, - "video/vnd.directv.mpeg": { - source: "iana" -}, - "video/vnd.directv.mpeg-tts": { - source: "iana" -}, - "video/vnd.dlna.mpeg-tts": { - source: "iana" -}, - "video/vnd.dvb.file": { - source: "iana", - extensions: [ - "dvb" - ] -}, - "video/vnd.fvt": { - source: "iana", - extensions: [ - "fvt" - ] -}, - "video/vnd.hns.video": { - source: "iana" -}, - "video/vnd.iptvforum.1dparityfec-1010": { - source: "iana" -}, - "video/vnd.iptvforum.1dparityfec-2005": { - source: "iana" -}, - "video/vnd.iptvforum.2dparityfec-1010": { - source: "iana" -}, - "video/vnd.iptvforum.2dparityfec-2005": { - source: "iana" -}, - "video/vnd.iptvforum.ttsavc": { - source: "iana" -}, - "video/vnd.iptvforum.ttsmpeg2": { - source: "iana" -}, - "video/vnd.motorola.video": { - source: "iana" -}, - "video/vnd.motorola.videop": { - source: "iana" -}, - "video/vnd.mpegurl": { - source: "iana", - extensions: [ - "mxu", - "m4u" - ] -}, - "video/vnd.ms-playready.media.pyv": { - source: "iana", - extensions: [ - "pyv" - ] -}, - "video/vnd.nokia.interleaved-multimedia": { - source: "iana" -}, - "video/vnd.nokia.mp4vr": { - source: "iana" -}, - "video/vnd.nokia.videovoip": { - source: "iana" -}, - "video/vnd.objectvideo": { - source: "iana" -}, - "video/vnd.radgamettools.bink": { - source: "iana" -}, - "video/vnd.radgamettools.smacker": { - source: "iana" -}, - "video/vnd.sealed.mpeg1": { - source: "iana" -}, - "video/vnd.sealed.mpeg4": { - source: "iana" -}, - "video/vnd.sealed.swf": { - source: "iana" -}, - "video/vnd.sealedmedia.softseal.mov": { - source: "iana" -}, - "video/vnd.uvvu.mp4": { - source: "iana", - extensions: [ - "uvu", - "uvvu" - ] -}, - "video/vnd.vivo": { - source: "iana", - extensions: [ - "viv" - ] -}, - "video/vnd.youtube.yt": { - source: "iana" -}, - "video/vp8": { - source: "iana" -}, - "video/webm": { - source: "apache", - compressible: false, - extensions: [ - "webm" - ] -}, - "video/x-f4v": { - source: "apache", - extensions: [ - "f4v" - ] -}, - "video/x-fli": { - source: "apache", - extensions: [ - "fli" - ] -}, - "video/x-flv": { - source: "apache", - compressible: false, - extensions: [ - "flv" - ] -}, - "video/x-m4v": { - source: "apache", - extensions: [ - "m4v" - ] -}, - "video/x-matroska": { - source: "apache", - compressible: false, - extensions: [ - "mkv", - "mk3d", - "mks" - ] -}, - "video/x-mng": { - source: "apache", - extensions: [ - "mng" - ] -}, - "video/x-ms-asf": { - source: "apache", - extensions: [ - "asf", - "asx" - ] -}, - "video/x-ms-vob": { - source: "apache", - extensions: [ - "vob" - ] -}, - "video/x-ms-wm": { - source: "apache", - extensions: [ - "wm" - ] -}, - "video/x-ms-wmv": { - source: "apache", - compressible: false, - extensions: [ - "wmv" - ] -}, - "video/x-ms-wmx": { - source: "apache", - extensions: [ - "wmx" - ] -}, - "video/x-ms-wvx": { - source: "apache", - extensions: [ - "wvx" - ] -}, - "video/x-msvideo": { - source: "apache", - extensions: [ - "avi" - ] -}, - "video/x-sgi-movie": { - source: "apache", - extensions: [ - "movie" - ] -}, - "video/x-smv": { - source: "apache", - extensions: [ - "smv" - ] -}, - "x-conference/x-cooltalk": { - source: "apache", - extensions: [ - "ice" - ] -}, - "x-shader/x-fragment": { - compressible: true -}, - "x-shader/x-vertex": { - compressible: true -} -}; - -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ - -/** - * Module exports. - */ - -var mimeDb = require$$0; - -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -var mimeTypes = build.createCommonjsModule(function (module, exports) { - -/** - * Module dependencies. - * @private - */ - - -var extname = path__default.extname; - -/** - * Module variables. - * @private - */ - -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; -var TEXT_TYPE_REGEXP = /^text\//i; - -/** - * Module exports. - * @public - */ - -exports.charset = charset; -exports.charsets = { lookup: charset }; -exports.contentType = contentType; -exports.extension = extension; -exports.extensions = Object.create(null); -exports.lookup = lookup; -exports.types = Object.create(null); - -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types); - -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ - -function charset (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type); - var mime = match && mimeDb[match[1].toLowerCase()]; - - if (mime && mime.charset) { - return mime.charset - } - - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } - - return false -} - -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ - -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false - } - - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str; - - if (!mime) { - return false - } - - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime); - if (charset) mime += '; charset=' + charset.toLowerCase(); - } - - return mime -} - -/** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ - -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } - - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type); - - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()]; - - if (!exts || !exts.length) { - return false - } - - return exts[0] -} - -/** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} - */ - -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } - - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1); - - if (!extension) { - return false - } - - return exports.types[extension] || false -} - -/** - * Populate the extensions and types maps. - * @private - */ - -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana']; - - Object.keys(mimeDb).forEach(function forEachMimeType (type) { - var mime = mimeDb[type]; - var exts = mime.extensions; - - if (!exts || !exts.length) { - return - } - - // mime -> extensions - extensions[type] = exts; - - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i]; - - if (types[extension]) { - var from = preference.indexOf(mimeDb[types[extension]].source); - var to = preference.indexOf(mime.source); - - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } - - // set the extension -> mime - types[extension] = type; - } - }); -} -}); - -/*! - * accepts - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module dependencies. - * @private - */ - - - - -/** - * Module exports. - * @public - */ - -var accepts = Accepts; - -/** - * Create a new Accepts object for the given req. - * - * @param {object} req - * @public - */ - -function Accepts (req) { - if (!(this instanceof Accepts)) { - return new Accepts(req) - } - - this.headers = req.headers; - this.negotiator = new negotiator(req); -} - -/** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json" or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * this.types('html'); - * // => "html" - * - * // Accept: text/*, application/json - * this.types('html'); - * // => "html" - * this.types('text/html'); - * // => "text/html" - * this.types('json', 'text'); - * // => "json" - * this.types('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * this.types('image/png'); - * this.types('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * this.types(['html', 'json']); - * this.types('html', 'json'); - * // => "json" - * - * @param {String|Array} types... - * @return {String|Array|Boolean} - * @public - */ - -Accepts.prototype.type = -Accepts.prototype.types = function (types_) { - var types = types_; - - // support flattened arguments - if (types && !Array.isArray(types)) { - types = new Array(arguments.length); - for (var i = 0; i < types.length; i++) { - types[i] = arguments[i]; - } - } - - // no types, return all requested types - if (!types || types.length === 0) { - return this.negotiator.mediaTypes() - } - - // no accept header, return first given type - if (!this.headers.accept) { - return types[0] - } - - var mimes = types.map(extToMime); - var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)); - var first = accepts[0]; - - return first - ? types[mimes.indexOf(first)] - : false -}; - -/** - * Return accepted encodings or best fit based on `encodings`. - * - * Given `Accept-Encoding: gzip, deflate` - * an array sorted by quality is returned: - * - * ['gzip', 'deflate'] - * - * @param {String|Array} encodings... - * @return {String|Array} - * @public - */ - -Accepts.prototype.encoding = -Accepts.prototype.encodings = function (encodings_) { - var encodings = encodings_; - - // support flattened arguments - if (encodings && !Array.isArray(encodings)) { - encodings = new Array(arguments.length); - for (var i = 0; i < encodings.length; i++) { - encodings[i] = arguments[i]; - } - } - - // no encodings, return all requested encodings - if (!encodings || encodings.length === 0) { - return this.negotiator.encodings() - } - - return this.negotiator.encodings(encodings)[0] || false -}; - -/** - * Return accepted charsets or best fit based on `charsets`. - * - * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` - * an array sorted by quality is returned: - * - * ['utf-8', 'utf-7', 'iso-8859-1'] - * - * @param {String|Array} charsets... - * @return {String|Array} - * @public - */ - -Accepts.prototype.charset = -Accepts.prototype.charsets = function (charsets_) { - var charsets = charsets_; - - // support flattened arguments - if (charsets && !Array.isArray(charsets)) { - charsets = new Array(arguments.length); - for (var i = 0; i < charsets.length; i++) { - charsets[i] = arguments[i]; - } - } - - // no charsets, return all requested charsets - if (!charsets || charsets.length === 0) { - return this.negotiator.charsets() - } - - return this.negotiator.charsets(charsets)[0] || false -}; - -/** - * Return accepted languages or best fit based on `langs`. - * - * Given `Accept-Language: en;q=0.8, es, pt` - * an array sorted by quality is returned: - * - * ['es', 'pt', 'en'] - * - * @param {String|Array} langs... - * @return {Array|String} - * @public - */ - -Accepts.prototype.lang = -Accepts.prototype.langs = -Accepts.prototype.language = -Accepts.prototype.languages = function (languages_) { - var languages = languages_; - - // support flattened arguments - if (languages && !Array.isArray(languages)) { - languages = new Array(arguments.length); - for (var i = 0; i < languages.length; i++) { - languages[i] = arguments[i]; - } - } - - // no languages, return all requested languages - if (!languages || languages.length === 0) { - return this.negotiator.languages() - } - - return this.negotiator.languages(languages)[0] || false -}; - -/** - * Convert extnames to mime. - * - * @param {String} type - * @return {String} - * @private - */ - -function extToMime (type) { - return type.indexOf('/') === -1 - ? mimeTypes.lookup(type) - : type -} - -/** - * Check if mime is valid. - * - * @param {String} type - * @return {String} - * @private - */ - -function validMime (type) { - return typeof type === 'string' -} - -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed - */ - -/** - * Module exports. - * @public - */ - -var bytes_1 = bytes; -var format_1 = format; -var parse_1 = parse$1; - -/** - * Module variables. - * @private - */ - -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; - -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; - -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: ((1 << 30) * 1024) -}; - -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i; - -/** - * Convert the given value in bytes into a string or parse to string to an integer in bytes. - * - * @param {string|number} value - * @param {{ - * case: [string], - * decimalPlaces: [number] - * fixedDecimals: [boolean] - * thousandsSeparator: [string] - * unitSeparator: [string] - * }} [options] bytes options. - * - * @returns {string|number|null} - */ - -function bytes(value, options) { - if (typeof value === 'string') { - return parse$1(value); - } - - if (typeof value === 'number') { - return format(value, options); - } - - return null; -} - -/** - * Format the given value in bytes into a string. - * - * If the value is negative, it is kept as such. If it is a float, - * it is rounded. - * - * @param {number} value - * @param {object} [options] - * @param {number} [options.decimalPlaces=2] - * @param {number} [options.fixedDecimals=false] - * @param {string} [options.thousandsSeparator=] - * @param {string} [options.unit=] - * @param {string} [options.unitSeparator=] - * - * @returns {string|null} - * @public - */ - -function format(value, options) { - if (!Number.isFinite(value)) { - return null; - } - - var mag = Math.abs(value); - var thousandsSeparator = (options && options.thousandsSeparator) || ''; - var unitSeparator = (options && options.unitSeparator) || ''; - var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = (options && options.unit) || ''; - - if (!unit || !map[unit.toLowerCase()]) { - if (mag >= map.tb) { - unit = 'TB'; - } else if (mag >= map.gb) { - unit = 'GB'; - } else if (mag >= map.mb) { - unit = 'MB'; - } else if (mag >= map.kb) { - unit = 'KB'; - } else { - unit = 'B'; - } - } - - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); - - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); - } - - if (thousandsSeparator) { - str = str.replace(formatThousandsRegExp, thousandsSeparator); - } - - return str + unitSeparator + unit; -} - -/** - * Parse the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {number|string} val - * - * @returns {number|null} - * @public - */ - -function parse$1(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; - } - - if (typeof val !== 'string') { - return null; - } - - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; - - if (!results) { - // Nothing could be extracted from the given string - floatValue = parseInt(val, 10); - unit = 'b'; - } else { - // Retrieve the value and the unit - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); - } - - return Math.floor(map[unit] * floatValue); -} -bytes_1.format = format_1; -bytes_1.parse = parse_1; - -/*! - * compressible - * Copyright(c) 2013 Jonathan Ong - * Copyright(c) 2014 Jeremiah Senkpiel - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module dependencies. - * @private - */ - - - -/** - * Module variables. - * @private - */ - -var COMPRESSIBLE_TYPE_REGEXP = /^text\/|\+(?:json|text|xml)$/i; -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; - -/** - * Module exports. - * @public - */ - -var compressible_1 = compressible; - -/** - * Checks if a type is compressible. - * - * @param {string} type - * @return {Boolean} compressible - * @public - */ - -function compressible (type) { - if (!type || typeof type !== 'string') { - return false - } - - // strip parameters - var match = EXTRACT_TYPE_REGEXP.exec(type); - var mime = match && match[1].toLowerCase(); - var data = mimeDb[mime]; - - // return database information - if (data && data.compressible !== undefined) { - return data.compressible - } - - // fallback to regexp or unknown - return COMPRESSIBLE_TYPE_REGEXP.test(mime) || undefined -} - -/** - * Helpers. - */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -var ms = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} - -var debug$1 = build.createCommonjsModule(function (module, exports) { -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = ms; - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; - -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - -exports.formatters = {}; - -/** - * Previous log timestamp. - */ - -var prevTime; - -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - -function selectColor(namespace) { - var hash = 0, i; - - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return exports.colors[Math.abs(hash) % exports.colors.length]; -} - -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - return debug; -} - -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } -} - -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} - -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} -}); - -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -var browser = build.createCommonjsModule(function (module, exports) { -exports = module.exports = debug$1; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } - - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} -}); - -/** - * Module dependencies. - */ - -var node = build.createCommonjsModule(function (module, exports) { -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = debug$1; -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); - - obj[prop] = val; - return obj; -}, {}); - -/** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log - */ - -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - -if (1 !== fd && 2 !== fd) { - util__default.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')(); -} - -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty__default.isatty(fd); -} - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util__default.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; - -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ - -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util__default.inspect(v, this.inspectOpts); -}; - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; - - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; - } -} - -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ - -function log() { - return stream.write(util__default.format.apply(util__default, arguments) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Copied from `node/src/node.js`. - * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. - */ - -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); - - // Note stream._type is used for test-module-load-list.js - - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty__default.WriteStream(fd); - stream._type = 'tty'; - - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - case 'FILE': - var fs = fs__default; - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; - - case 'PIPE': - case 'TCP': - var net = require$$2__default; - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); - - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; - - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } - - // For supporting legacy API we put the FD here. - stream.fd = fd; - - stream._isStdio = true; - - return stream; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init (debug) { - debug.inspectOpts = {}; - - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ - -exports.enable(load()); -}); - -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ - -var src = build.createCommonjsModule(function (module) { -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = browser; -} else { - module.exports = node; -} -}); - -/*! - * on-headers - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module exports. - * @public - */ - -var onHeaders_1 = onHeaders; - -/** - * Create a replacement writeHead method. - * - * @param {function} prevWriteHead - * @param {function} listener - * @private - */ - -function createWriteHead (prevWriteHead, listener) { - var fired = false; - - // return function with core name and argument list - return function writeHead (statusCode) { - // set headers from arguments - var args = setWriteHeadHeaders.apply(this, arguments); - - // fire listener - if (!fired) { - fired = true; - listener.call(this); - - // pass-along an updated status code - if (typeof args[0] === 'number' && this.statusCode !== args[0]) { - args[0] = this.statusCode; - args.length = 1; - } - } - - return prevWriteHead.apply(this, args) - } -} - -/** - * Execute a listener when a response is about to write headers. - * - * @param {object} res - * @return {function} listener - * @public - */ - -function onHeaders (res, listener) { - if (!res) { - throw new TypeError('argument res is required') - } - - if (typeof listener !== 'function') { - throw new TypeError('argument listener must be a function') - } - - res.writeHead = createWriteHead(res.writeHead, listener); -} - -/** - * Set headers contained in array on the response object. - * - * @param {object} res - * @param {array} headers - * @private - */ - -function setHeadersFromArray (res, headers) { - for (var i = 0; i < headers.length; i++) { - res.setHeader(headers[i][0], headers[i][1]); - } -} - -/** - * Set headers contained in object on the response object. - * - * @param {object} res - * @param {object} headers - * @private - */ - -function setHeadersFromObject (res, headers) { - var keys = Object.keys(headers); - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - if (k) res.setHeader(k, headers[k]); - } -} - -/** - * Set headers and other properties on the response object. - * - * @param {number} statusCode - * @private - */ - -function setWriteHeadHeaders (statusCode) { - var length = arguments.length; - var headerIndex = length > 1 && typeof arguments[1] === 'string' - ? 2 - : 1; - - var headers = length >= headerIndex + 1 - ? arguments[headerIndex] - : undefined; - - this.statusCode = statusCode; - - if (Array.isArray(headers)) { - // handle array case - setHeadersFromArray(this, headers); - } else if (headers) { - // handle object case - setHeadersFromObject(this, headers); - } - - // copy leading arguments - var args = new Array(Math.min(length, headerIndex)); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - return args -} - -/*! - * compression - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module dependencies. - * @private - */ - - -var Buffer = build.safeBuffer.Buffer; - - -var debug = src('compression'); - - - - -/** - * Module exports. - */ - -var compression_1 = compression; -var filter = shouldCompress; - -/** - * Module variables. - * @private - */ - -var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/; - -/** - * Compress response data with gzip / deflate. - * - * @param {Object} [options] - * @return {Function} middleware - * @public - */ - -function compression (options) { - var opts = options || {}; - - // options - var filter = opts.filter || shouldCompress; - var threshold = bytes_1.parse(opts.threshold); - - if (threshold == null) { - threshold = 1024; - } - - return function compression (req, res, next) { - var ended = false; - var length; - var listeners = []; - var stream; - - var _end = res.end; - var _on = res.on; - var _write = res.write; - - // flush - res.flush = function flush () { - if (stream) { - stream.flush(); - } - }; - - // proxy - - res.write = function write (chunk, encoding) { - if (ended) { - return false - } - - if (!this._header) { - this._implicitHeader(); - } - - return stream - ? stream.write(toBuffer(chunk, encoding)) - : _write.call(this, chunk, encoding) - }; - - res.end = function end (chunk, encoding) { - if (ended) { - return false - } - - if (!this._header) { - // estimate the length - if (!this.getHeader('Content-Length')) { - length = chunkLength(chunk, encoding); - } - - this._implicitHeader(); - } - - if (!stream) { - return _end.call(this, chunk, encoding) - } - - // mark ended - ended = true; - - // write Buffer for Node.js 0.8 - return chunk - ? stream.end(toBuffer(chunk, encoding)) - : stream.end() - }; - - res.on = function on (type, listener) { - if (!listeners || type !== 'drain') { - return _on.call(this, type, listener) - } - - if (stream) { - return stream.on(type, listener) - } - - // buffer listeners for future stream - listeners.push([type, listener]); - - return this - }; - - function nocompress (msg) { - debug('no compression: %s', msg); - addListeners(res, _on, listeners); - listeners = null; - } - - onHeaders_1(res, function onResponseHeaders () { - // determine if request is filtered - if (!filter(req, res)) { - nocompress('filtered'); - return - } - - // determine if the entity should be transformed - if (!shouldTransform(req, res)) { - nocompress('no transform'); - return - } - - // vary - build.vary_1(res, 'Accept-Encoding'); - - // content-length below threshold - if (Number(res.getHeader('Content-Length')) < threshold || length < threshold) { - nocompress('size below threshold'); - return - } - - var encoding = res.getHeader('Content-Encoding') || 'identity'; - - // already encoded - if (encoding !== 'identity') { - nocompress('already encoded'); - return - } - - // head - if (req.method === 'HEAD') { - nocompress('HEAD request'); - return - } - - // compression method - var accept = accepts(req); - var method = accept.encoding(['gzip', 'deflate', 'identity']); - - // we really don't prefer deflate - if (method === 'deflate' && accept.encoding(['gzip'])) { - method = accept.encoding(['gzip', 'identity']); - } - - // negotiation failed - if (!method || method === 'identity') { - nocompress('not acceptable'); - return - } - - // compression stream - debug('%s compression', method); - stream = method === 'gzip' - ? zlib_1__default.createGzip(opts) - : zlib_1__default.createDeflate(opts); - - // add buffered listeners to stream - addListeners(stream, stream.on, listeners); - - // header fields - res.setHeader('Content-Encoding', method); - res.removeHeader('Content-Length'); - - // compression - stream.on('data', function onStreamData (chunk) { - if (_write.call(res, chunk) === false) { - stream.pause(); - } - }); - - stream.on('end', function onStreamEnd () { - _end.call(res); - }); - - _on.call(res, 'drain', function onResponseDrain () { - stream.resume(); - }); - }); - - next(); - } -} - -/** - * Add bufferred listeners to stream - * @private - */ - -function addListeners (stream, on, listeners) { - for (var i = 0; i < listeners.length; i++) { - on.apply(stream, listeners[i]); - } -} - -/** - * Get the length of a given chunk - */ - -function chunkLength (chunk, encoding) { - if (!chunk) { - return 0 - } - - return !Buffer.isBuffer(chunk) - ? Buffer.byteLength(chunk, encoding) - : chunk.length -} - -/** - * Default filter function. - * @private - */ - -function shouldCompress (req, res) { - var type = res.getHeader('Content-Type'); - - if (type === undefined || !compressible_1(type)) { - debug('%s not compressible', type); - return false - } - - return true -} - -/** - * Determine if the entity should be transformed. - * @private - */ - -function shouldTransform (req, res) { - var cacheControl = res.getHeader('Cache-Control'); - - // Don't compress for Cache-Control: no-transform - // https://tools.ietf.org/html/rfc7234#section-5.2.2.4 - return !cacheControl || - !cacheControlNoTransformRegExp.test(cacheControl) -} - -/** - * Coerce arguments to Buffer - * @private - */ - -function toBuffer (chunk, encoding) { - return !Buffer.isBuffer(chunk) - ? Buffer.from(chunk, encoding) - : chunk -} -compression_1.filter = filter; - -async function preview(config, port = 5000) { - const app = build.connect(); - const httpServer = await build.resolveHttpServer(config.server, app); - // cors - const { cors } = config.server; - if (cors !== false) { - app.use(build.lib(typeof cors === 'boolean' ? {} : cors)); - } - // proxy - if (config.server.proxy) { - app.use(build.proxyMiddleware(httpServer, config)); - } - app.use(compression_1()); - const distDir = path__default.resolve(config.root, config.build.outDir); - app.use(config.base, build.sirv(distDir, { - etag: true, - single: true - })); - const options = config.server || {}; - const hostname = options.host || 'localhost'; - const protocol = options.https ? 'https' : 'http'; - const logger = config.logger; - const base = config.base; - httpServer.listen(port, () => { - logger.info(build.source.cyan(`\n vite v${require('vite/package.json').version}`) + - build.source.green(` build preview server running at:\n`)); - const interfaces = os__default.networkInterfaces(); - Object.keys(interfaces).forEach((key) => (interfaces[key] || []) - .filter((details) => details.family === 'IPv4') - .map((detail) => { - return { - type: detail.address.includes('127.0.0.1') - ? 'Local: ' - : 'Network: ', - host: detail.address.replace('127.0.0.1', hostname) - }; - }) - .forEach(({ type, host }) => { - const url = `${protocol}://${host}:${build.source.bold(port)}${base}`; - logger.info(` > ${type} ${build.source.cyan(url)}`); - })); - if (options.open) { - const path = typeof options.open === 'string' ? options.open : base; - build.openBrowser(`${protocol}://${hostname}:${port}${path}`, true, logger); - } - }); -} - -const cli = cac('vite'); -/** - * removing global flags before passing as command specific sub-configs - */ -function cleanOptions(options) { - const ret = { ...options }; - delete ret['--']; - delete ret.debug; - delete ret.d; - delete ret.filter; - delete ret.f; - delete ret.config; - delete ret.c; - delete ret.root; - delete ret.base; - delete ret.r; - delete ret.mode; - delete ret.m; - delete ret.logLevel; - delete ret.l; - delete ret.clearScreen; - return ret; -} -cli - .option('-c, --config ', `[string] use specified config file`) - .option('-r, --root ', `[string] use specified root directory`) - .option('--base ', `[string] public base path (default: /)`) - .option('-l, --logLevel ', `[string] silent | error | warn | all`) - .option('--clearScreen', `[boolean] allow/disable clear screen when logging`) - .option('-d, --debug [feat]', `[string | boolean] show debug logs`) - .option('-f, --filter ', `[string] filter debug logs`); -// dev -cli - .command('[root]') // default command - .alias('serve') - .option('--host ', `[string] specify hostname`) - .option('--port ', `[number] specify port`) - .option('--https', `[boolean] use TLS + HTTP/2`) - .option('--open [path]', `[boolean | string] open browser on startup`) - .option('--cors', `[boolean] enable CORS`) - .option('--strictPort', `[boolean] exit if specified port is already in use`) - .option('-m, --mode ', `[string] set env mode`) - .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`) - .action(async (root, options) => { - // output structure is preserved even after bundling so require() - // is ok here - const { createServer } = await Promise.resolve().then(function () { return require('./chunks/dep-66eb515d.js'); }).then(function (n) { return n.index$1; }); - try { - const server = await createServer({ - root, - base: options.base, - mode: options.mode, - configFile: options.config, - logLevel: options.logLevel, - clearScreen: options.clearScreen, - server: cleanOptions(options) - }); - await server.listen(); - } - catch (e) { - build.createLogger(options.logLevel).error(build.source.red(`error when starting dev server:\n${e.stack}`)); - process.exit(1); - } -}); -// build -cli - .command('build [root]') - .option('--target ', `[string] transpile target (default: 'modules')`) - .option('--outDir ', `[string] output directory (default: dist)`) - .option('--assetsDir ', `[string] directory under outDir to place assets in (default: _assets)`) - .option('--assetsInlineLimit ', `[number] static asset base64 inline threshold in bytes (default: 4096)`) - .option('--ssr [entry]', `[string] build specified entry for server-side rendering`) - .option('--sourcemap', `[boolean] output source maps for build (default: false)`) - .option('--minify [minifier]', `[boolean | "terser" | "esbuild"] enable/disable minification, ` + - `or specify minifier to use (default: terser)`) - .option('--manifest', `[boolean] emit build manifest json`) - .option('--ssrManifest', `[boolean] emit ssr manifest json`) - .option('--emptyOutDir', `[boolean] force empty outDir when it's outside of root`) - .option('-m, --mode ', `[string] set env mode`) - .action(async (root, options) => { - const { build: build$1 } = await Promise.resolve().then(function () { return require('./chunks/dep-66eb515d.js'); }).then(function (n) { return n.build$1; }); - const buildOptions = cleanOptions(options); - try { - await build$1({ - root, - base: options.base, - mode: options.mode, - configFile: options.config, - logLevel: options.logLevel, - clearScreen: options.clearScreen, - build: buildOptions - }); - } - catch (e) { - build.createLogger(options.logLevel).error(build.source.red(`error during build:\n${e.stack}`)); - process.exit(1); - } -}); -// optimize -cli - .command('optimize [root]') - .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`) - .action(async (root, options) => { - const { optimizeDeps } = await Promise.resolve().then(function () { return require('./chunks/dep-66eb515d.js'); }).then(function (n) { return n.index; }); - try { - const config = await build.resolveConfig({ - root, - base: options.base, - configFile: options.config, - logLevel: options.logLevel - }, 'build', 'development'); - await optimizeDeps(config, options.force, true); - } - catch (e) { - build.createLogger(options.logLevel).error(build.source.red(`error when optimizing deps:\n${e.stack}`)); - process.exit(1); - } -}); -cli - .command('preview [root]') - .option('--port ', `[number] specify port`) - .option('--open [path]', `[boolean | string] open browser on startup`) - .action(async (root, options) => { - try { - const config = await build.resolveConfig({ - root, - base: options.base, - configFile: options.config, - logLevel: options.logLevel, - server: { - open: options.open - } - }, 'serve', 'development'); - await preview(config, options.port); - } - catch (e) { - build.createLogger(options.logLevel).error(build.source.red(`error when starting preview server:\n${e.stack}`)); - process.exit(1); - } -}); -cli.help(); -cli.version(require('../../package.json').version); -cli.parse(); diff --git a/node_modules/vite/dist/node/index.d.ts b/node_modules/vite/dist/node/index.d.ts deleted file mode 100644 index 31043db..0000000 --- a/node_modules/vite/dist/node/index.d.ts +++ /dev/null @@ -1,2422 +0,0 @@ -/// -import { ChangeEvent } from 'rollup'; -import { CustomPluginOptions } from 'rollup'; -import * as events from 'events'; -import * as fs from 'fs'; -import * as http from 'http'; -import * as https from 'https'; -import { IncomingMessage } from 'http'; -import { InputOptions } from 'rollup'; -import { LoadResult } from 'rollup'; -import * as net from 'net'; -import { OutputBundle } from 'rollup'; -import { OutputChunk } from 'rollup'; -import { PartialResolvedId } from 'rollup'; -import { Plugin as Plugin_2 } from 'rollup'; -import { PluginContext } from 'rollup'; -import { PluginHooks } from 'rollup'; -import * as Postcss from 'postcss'; -import { RequestOptions } from 'http'; -import { RequestOptions as RequestOptions_2 } from 'https'; -import { ResolveIdResult } from 'rollup'; -import { RollupOptions } from 'rollup'; -import { RollupOutput } from 'rollup'; -import { Server } from 'http'; -import { ServerResponse } from 'http'; -import { SourceDescription } from 'rollup'; -import { SourceMap } from 'rollup'; -import * as stream from 'stream'; -import { TransformOptions as TransformOptions_2 } from 'esbuild'; -import { TransformPluginContext } from 'rollup'; -import { TransformResult as TransformResult_2 } from 'rollup'; -import { TransformResult as TransformResult_3 } from 'esbuild'; -import * as url from 'url'; - -export declare interface Alias { - find: string | RegExp - replacement: string - /** - * Instructs the plugin to use an alternative resolving algorithm, - * rather than the Rollup's resolver. - * @default null - */ - customResolver?: ResolverFunction | ResolverObject | null -} - -/** - * Specifies an `Object`, or an `Array` of `Object`, - * which defines aliases used to replace values in `import` or `require` statements. - * With either format, the order of the entries is important, - * in that the first defined rules are applied first. - * - * This is passed to \@rollup/plugin-alias as the "entries" field - * https://github.com/rollup/plugins/tree/master/packages/alias#entries - */ -export declare type AliasOptions = readonly Alias[] | { [find: string]: string } - -/** - * Bundles the app for production. - * Returns a Promise containing the build result. - */ -export declare function build(inlineConfig?: InlineConfig): Promise; - -export declare interface BuildOptions { - /** - * Base public path when served in production. - * @deprecated `base` is now a root-level config option. - */ - base?: string; - /** - * Compatibility transform target. The transform is performed with esbuild - * and the lowest supported target is es2015/es6. Note this only handles - * syntax transformation and does not cover polyfills (except for dynamic - * import) - * - * Default: 'modules' - Similar to `@babel/preset-env`'s targets.esmodules, - * transpile targeting browsers that natively support es module imports. Also - * injects a light-weight dynamic import polyfill. - * https://caniuse.com/es6-module - * - * Another special value is 'esnext' - which only performs minimal transpiling - * (for minification compat) and assumes native dynamic imports support. - * - * For custom targets, see https://esbuild.github.io/api/#target and - * https://esbuild.github.io/content-types/#javascript for more details. - */ - target?: 'modules' | TransformOptions_2['target'] | false; - /** - * Whether to inject dynamic import polyfill. Defaults to `true`, unless - * `target` is `'esnext'`. - * Note: does not apply to library mode. - */ - polyfillDynamicImport?: boolean; - /** - * Directory relative from `root` where build output will be placed. If the - * directory exists, it will be removed before the build. - * @default 'dist' - */ - outDir?: string; - /** - * Directory relative from `outDir` where the built js/css/image assets will - * be placed. - * @default 'assets' - */ - assetsDir?: string; - /** - * Static asset files smaller than this number (in bytes) will be inlined as - * base64 strings. Default limit is `4096` (4kb). Set to `0` to disable. - * @default 4096 - */ - assetsInlineLimit?: number; - /** - * Whether to code-split CSS. When enabled, CSS in async chunks will be - * inlined as strings in the chunk and inserted via dynamically created - * style tags when the chunk is loaded. - * @default true - */ - cssCodeSplit?: boolean; - /** - * Whether to generate sourcemap - * @default false - */ - sourcemap?: boolean | 'inline'; - /** - * Set to `false` to disable minification, or specify the minifier to use. - * Available options are 'terser' or 'esbuild'. - * @default 'terser' - */ - minify?: boolean | 'terser' | 'esbuild'; - /** - * Options for terser - * https://terser.org/docs/api-reference#minify-options - */ - terserOptions?: Terser.MinifyOptions; - /** - * Options for clean-css - * https://github.com/jakubpawlowicz/clean-css#constructor-options - */ - cleanCssOptions?: CleanCSS.Options; - /** - * Will be merged with internal rollup options. - * https://rollupjs.org/guide/en/#big-list-of-options - */ - rollupOptions?: RollupOptions; - /** - * Options to pass on to `@rollup/plugin-commonjs` - */ - commonjsOptions?: RollupCommonJSOptions; - /** - * Whether to write bundle to disk - * @default true - */ - write?: boolean; - /** - * Empty outDir on write. - * @default true when outDir is a sub directory of project root - */ - emptyOutDir?: boolean | null; - /** - * Whether to emit a manifest.json under assets dir to map hash-less filenames - * to their hashed versions. Useful when you want to generate your own HTML - * instead of using the one generated by Vite. - * - * Example: - * - * ```json - * { - * "main.js": { - * "file": "main.68fe3fad.js", - * "css": "main.e6b63442.css", - * "imports": [...], - * "dynamicImports": [...] - * } - * } - * ``` - * @default false - */ - manifest?: boolean; - /** - * Build in library mode. The value should be the global name of the lib in - * UMD mode. This will produce esm + cjs + umd bundle formats with default - * configurations that are suitable for distributing libraries. - */ - lib?: LibraryOptions | false; - /** - * Produce SSR oriented build. Note this requires specifying SSR entry via - * `rollupOptions.input`. - */ - ssr?: boolean | string; - /** - * Generate SSR manifest for determining style links and asset preload - * directives in production. - */ - ssrManifest?: boolean; - /** - * Set to false to disable brotli compressed size reporting for build. - * Can slightly improve build speed. - */ - brotliSize?: boolean; - /** - * Adjust chunk size warning limit (in kbs). - * @default 500 - */ - chunkSizeWarningLimit?: number; -} - -export declare namespace CleanCSS { - /** - * Shared options passed when initializing a new instance of CleanCSS that returns either a promise or output - */ - export interface OptionsBase { - /** - * Controls compatibility mode used; defaults to ie10+ using `'*'`. - * Compatibility hash exposes the following properties: `colors`, `properties`, `selectors`, and `units` - */ - compatibility?: '*' | 'ie9' | 'ie8' | 'ie7' | CompatibilityOptions - - /** - * Controls a function for handling remote requests; Defaults to the build in `loadRemoteResource` function - */ - fetch?: ( - uri: string, - inlineRequest: RequestOptions | RequestOptions_2, - inlineTimeout: number, - done: (message: string | number, body: string) => void - ) => void - - /** - * Controls output CSS formatting; defaults to `false`. - * Format hash exposes the following properties: `breaks`, `breakWith`, `indentBy`, `indentWith`, `spaces`, and `wrapAt`. - */ - format?: 'beautify' | 'keep-breaks' | FormatOptions | false - - /** - * inline option whitelists which @import rules will be processed. Defaults to `'local'` - * Accepts the following values: - * 'local': enables local inlining; - * 'remote': enables remote inlining; - * 'none': disables all inlining; - * 'all': enables all inlining, same as ['local', 'remote']; - * '[uri]': enables remote inlining from the specified uri; - * '![url]': disables remote inlining from the specified uri; - */ - inline?: ReadonlyArray | false - - /** - * Controls extra options for inlining remote @import rules - */ - inlineRequest?: RequestOptions | RequestOptions_2 - - /** - * Controls number of milliseconds after which inlining a remote @import fails; defaults to `5000`; - */ - inlineTimeout?: number - - /** - * Controls optimization level used; defaults to `1`. - * Level hash exposes `1`, and `2`. - */ - level?: 0 | 1 | 2 | OptimizationsOptions - - /** - * Controls URL rebasing; defaults to `true`; - */ - rebase?: boolean - - /** - * controls a directory to which all URLs are rebased, most likely the directory under which the output file - * will live; defaults to the current directory; - */ - rebaseTo?: string - - /** - * Controls whether an output source map is built; defaults to `false` - */ - sourceMap?: boolean - - /** - * Controls embedding sources inside a source map's `sourcesContent` field; defaults to `false` - */ - sourceMapInlineSources?: boolean - } - - /** - * Fine grained configuration for compatibility option - */ - export interface CompatibilityOptions { - /** - * A hash of compatibility options related to color - */ - colors?: { - /** - * Controls `rgba()` / `hsla()` color support; defaults to `true` - */ - opacity?: boolean - } - /** - * A hash of properties that can be set with compatibility - */ - properties?: { - /** - * Controls background-clip merging into shorthand; defaults to `true` - */ - backgroundClipMerging?: boolean - - /** - * Controls background-origin merging into shorthand; defaults to `true` - */ - backgroundOriginMerging?: boolean - - /** - * Controls background-size merging into shorthand; defaults to `true` - */ - backgroundSizeMerging?: boolean - - /** - * controls color optimizations; defaults to `true` - */ - colors?: boolean - - /** - * Controls keeping IE bang hack; defaults to `false` - */ - ieBangHack?: boolean - - /** - * Controls keeping IE `filter` / `-ms-filter`; defaults to `false` - */ - ieFilters?: boolean - - /** - * Controls keeping IE prefix hack; defaults to `false` - */ - iePrefixHack?: boolean - - /** - * Controls keeping IE suffix hack; defaults to `false` - */ - ieSuffixHack?: boolean - - /** - * Controls property merging based on understandably; defaults to `true` - */ - merging?: boolean - - /** - * Controls shortening pixel units into `pc`, `pt`, or `in` units; defaults to `false` - */ - shorterLengthUnits?: false - - /** - * Controls keeping space after closing brace - `url() no-repeat` into `url()no-repeat`; defaults to `true` - */ - spaceAfterClosingBrace?: true - - /** - * Controls keeping quoting inside `url()`; defaults to `false` - */ - urlQuotes?: boolean - - /** - * Controls removal of units `0` value; defaults to `true` - */ - zeroUnits?: boolean - } - /** - * A hash of options related to compatibility of selectors - */ - selectors?: { - /** - * Controls extra space before `nav` element; defaults to `false` - */ - adjacentSpace?: boolean - - /** - * Controls removal of IE7 selector hacks, e.g. `*+html...`; defaults to `true` - */ - ie7Hack?: boolean - - /** - * Controls a whitelist of mergeable pseudo classes; defaults to `[':active', ...]` - */ - mergeablePseudoClasses?: ReadonlyArray - - /** - * Controls a whitelist of mergeable pseudo elements; defaults to `['::after', ...]` - */ - mergeablePseudoElements: ReadonlyArray - - /** - * Controls maximum number of selectors in a single rule (since 4.1.0); defaults to `8191` - */ - mergeLimit: number - - /** - * Controls merging of rules with multiple pseudo classes / elements (since 4.1.0); defaults to `true` - */ - multiplePseudoMerging: boolean - } - /** - * A hash of options related to comparability of supported units - */ - units?: { - /** - * Controls treating `ch` as a supported unit; defaults to `true` - */ - ch?: boolean - - /** - * Controls treating `in` as a supported unit; defaults to `true` - */ - in?: boolean - - /** - * Controls treating `pc` as a supported unit; defaults to `true` - */ - pc?: boolean - - /** - * Controls treating `pt` as a supported unit; defaults to `true` - */ - pt?: boolean - - /** - * Controls treating `rem` as a supported unit; defaults to `true` - */ - rem?: boolean - - /** - * Controls treating `vh` as a supported unit; defaults to `true` - */ - vh?: boolean - - /** - * Controls treating `vm` as a supported unit; defaults to `true` - */ - vm?: boolean - - /** - * Controls treating `vmax` as a supported unit; defaults to `true` - */ - vmax?: boolean - - /** - * Controls treating `vmin` as a supported unit; defaults to `true` - */ - vmin?: boolean - } - } - - /** - * Fine grained options for configuring the CSS formatting - */ - export interface FormatOptions { - /** - * Controls where to insert breaks - */ - breaks?: { - /** - * Controls if a line break comes after an at-rule; e.g. `@charset`; defaults to `false` - */ - afterAtRule?: boolean - - /** - * Controls if a line break comes after a block begins; e.g. `@media`; defaults to `false` - */ - afterBlockBegins?: boolean - - /** - * Controls if a line break comes after a block ends, defaults to `false` - */ - afterBlockEnds?: boolean - - /** - * Controls if a line break comes after a comment; defaults to `false` - */ - afterComment?: boolean - - /** - * Controls if a line break comes after a property; defaults to `false` - */ - afterProperty?: boolean - - /** - * Controls if a line break comes after a rule begins; defaults to `false` - */ - afterRuleBegins?: boolean - - /** - * Controls if a line break comes after a rule ends; defaults to `false` - */ - afterRuleEnds?: boolean - - /** - * Controls if a line break comes before a block ends; defaults to `false` - */ - beforeBlockEnds?: boolean - - /** - * Controls if a line break comes between selectors; defaults to `false` - */ - betweenSelectors?: boolean - } - /** - * Controls the new line character, can be `'\r\n'` or `'\n'`(aliased as `'windows'` and `'unix'` - * or `'crlf'` and `'lf'`); defaults to system one, so former on Windows and latter on Unix - */ - breakWith?: string - - /** - * Controls number of characters to indent with; defaults to `0` - */ - indentBy?: number - - /** - * Controls a character to indent with, can be `'space'` or `'tab'`; defaults to `'space'` - */ - indentWith?: 'space' | 'tab' - - /** - * Controls where to insert spaces - */ - spaces?: { - /** - * Controls if spaces come around selector relations; e.g. `div > a`; defaults to `false` - */ - aroundSelectorRelation?: boolean - - /** - * Controls if a space comes before a block begins; e.g. `.block {`; defaults to `false` - */ - beforeBlockBegins?: boolean - - /** - * Controls if a space comes before a value; e.g. `width: 1rem`; defaults to `false` - */ - beforeValue?: boolean - } - /** - * Controls maximum line length; defaults to `false` - */ - wrapAt?: false | number - - /** - * Controls removing trailing semicolons in rule; defaults to `false` - means remove - */ - semicolonAfterLastProperty?: boolean - } - - /** - * Fine grained options for configuring optimizations - */ - export interface OptimizationsOptions { - 1?: { - /** - * Sets all optimizations at this level unless otherwise specified - */ - all?: boolean - - /** - * Controls `@charset` moving to the front of a stylesheet; defaults to `true` - */ - cleanupCharsets?: boolean - - /** - * Controls URL normalization; defaults to `true` - */ - normalizeUrls?: boolean - - /** - * Controls `background` property optimizations; defaults to `true` - */ - optimizeBackground?: boolean - - /** - * Controls `border-radius` property optimizations; defaults to `true` - */ - optimizeBorderRadius?: boolean - - /** - * Controls `filter` property optimizations; defaults to `true` - */ - optimizeFilter?: boolean - - /** - * Controls `font` property optimizations; defaults to `true` - */ - optimizeFont?: boolean - - /** - * Controls `font-weight` property optimizations; defaults to `true` - */ - optimizeFontWeight?: boolean - - /** - * Controls `outline` property optimizations; defaults to `true` - */ - optimizeOutline?: boolean - - /** - * Controls removing empty rules and nested blocks; defaults to `true` - */ - removeEmpty?: boolean - - /** - * Controls removing negative paddings; defaults to `true` - */ - removeNegativePaddings?: boolean - - /** - * Controls removing quotes when unnecessary; defaults to `true` - */ - removeQuotes?: boolean - - /** - * Controls removing unused whitespace; defaults to `true` - */ - removeWhitespace?: boolean - - /** - * Contols removing redundant zeros; defaults to `true` - */ - replaceMultipleZeros?: boolean - - /** - * Controls replacing time units with shorter values; defaults to `true` - */ - replaceTimeUnits?: boolean - - /** - * Controls replacing zero values with units; defaults to `true` - */ - replaceZeroUnits?: boolean - - /** - * Rounds pixel values to `N` decimal places; `false` disables rounding; defaults to `false` - */ - roundingPrecision?: boolean - - /** - * denotes selector sorting method; can be `'natural'` or `'standard'`, `'none'`, or false (the last two - * since 4.1.0); defaults to `'standard'` - */ - selectorsSortingMethod?: 'standard' | 'natural' | 'none' - - /** - * denotes a number of /*! ... * / comments preserved; defaults to `all` - */ - specialComments?: string - - /** - * Controls at-rules (e.g. `@charset`, `@import`) optimizing; defaults to `true` - */ - tidyAtRules?: boolean - - /** - * Controls block scopes (e.g. `@media`) optimizing; defaults to `true` - */ - tidyBlockScopes?: boolean - - /** - * Controls selectors optimizing; defaults to `true` - */ - tidySelectors?: boolean - - /** - * Defines a callback for fine-grained property optimization; defaults to no-op - */ - transform?: ( - propertyName: string, - propertyValue: string, - selector?: string - ) => string - } - 2?: { - /** - * Sets all optimizations at this level unless otherwise specified - */ - all?: boolean - - /** - * Controls adjacent rules merging; defaults to true - */ - mergeAdjacentRules?: boolean - - /** - * Controls merging properties into shorthands; defaults to true - */ - mergeIntoShorthands?: boolean - - /** - * Controls `@media` merging; defaults to true - */ - mergeMedia?: boolean - - /** - * Controls non-adjacent rule merging; defaults to true - */ - mergeNonAdjacentRules?: boolean - - /** - * Controls semantic merging; defaults to false - */ - mergeSemantically?: boolean - - /** - * Controls property overriding based on understandably; defaults to true - */ - overrideProperties?: boolean - - /** - * Controls removing empty rules and nested blocks; defaults to `true` - */ - removeEmpty?: boolean - - /** - * Controls non-adjacent rule reducing; defaults to true - */ - reduceNonAdjacentRules?: boolean - - /** - * Controls duplicate `@font-face` removing; defaults to true - */ - removeDuplicateFontRules?: boolean - - /** - * Controls duplicate `@media` removing; defaults to true - */ - removeDuplicateMediaBlocks?: boolean - - /** - * Controls duplicate rules removing; defaults to true - */ - removeDuplicateRules?: boolean - - /** - * Controls unused at rule removing; defaults to false (available since 4.1.0) - */ - removeUnusedAtRules?: boolean - - /** - * Controls rule restructuring; defaults to false - */ - restructureRules?: boolean - - /** - * Controls which properties won't be optimized, defaults to `[]` which means all will be optimized (since 4.1.0) - */ - skipProperties?: ReadonlyArray - } - } - - /** - * Options when returning a promise - */ - export type OptionsPromise = OptionsBase & { - /** - * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` - */ - returnPromise: true - } - - /** - * Options when returning an output - */ - export type OptionsOutput = OptionsBase & { - /** - * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` - */ - returnPromise?: false - } - - /** - * Discriminant union of both sets of options types. If you initialize without setting `returnPromise: true` - * and want to return a promise, you will need to cast to the correct options type so that TypeScript - * knows what the expected return type will be: - * `(options = options as CleanCSS.OptionsPromise).returnPromise = true` - */ - export type Options = OptionsPromise | OptionsOutput -} - -export declare interface ConfigEnv { - command: 'build' | 'serve'; - mode: string; -} - -export declare namespace Connect { - export type ServerHandle = HandleFunction | http.Server - - export class IncomingMessage extends http.IncomingMessage { - originalUrl?: http.IncomingMessage['url'] - } - - export type NextFunction = (err?: any) => void - - export type SimpleHandleFunction = ( - req: IncomingMessage, - res: http.ServerResponse - ) => void - export type NextHandleFunction = ( - req: IncomingMessage, - res: http.ServerResponse, - next: NextFunction - ) => void - export type ErrorHandleFunction = ( - err: any, - req: IncomingMessage, - res: http.ServerResponse, - next: NextFunction - ) => void - export type HandleFunction = - | SimpleHandleFunction - | NextHandleFunction - | ErrorHandleFunction - - export interface ServerStackItem { - route: string - handle: ServerHandle - } - - export interface Server extends NodeJS.EventEmitter { - (req: http.IncomingMessage, res: http.ServerResponse, next?: Function): void - - route: string - stack: ServerStackItem[] - - /** - * Utilize the given middleware `handle` to the given `route`, - * defaulting to _/_. This "route" is the mount-point for the - * middleware, when given a value other than _/_ the middleware - * is only effective when that segment is present in the request's - * pathname. - * - * For example if we were to mount a function at _/admin_, it would - * be invoked on _/admin_, and _/admin/settings_, however it would - * not be invoked for _/_, or _/posts_. - */ - use(fn: NextHandleFunction): Server - use(fn: HandleFunction): Server - use(route: string, fn: NextHandleFunction): Server - use(route: string, fn: HandleFunction): Server - - /** - * Handle server requests, punting them down - * the middleware stack. - */ - handle( - req: http.IncomingMessage, - res: http.ServerResponse, - next: Function - ): void - - /** - * Listen for connections. - * - * This method takes the same arguments - * as node's `http.Server#listen()`. - * - * HTTP and HTTPS: - * - * If you run your application both as HTTP - * and HTTPS you may wrap them individually, - * since your Connect "server" is really just - * a JavaScript `Function`. - * - * var connect = require('connect') - * , http = require('http') - * , https = require('https'); - * - * var app = connect(); - * - * http.createServer(app).listen(80); - * https.createServer(options, app).listen(443); - */ - listen( - port: number, - hostname?: string, - backlog?: number, - callback?: Function - ): http.Server - listen(port: number, hostname?: string, callback?: Function): http.Server - listen(path: string, callback?: Function): http.Server - listen(handle: any, listeningListener?: Function): http.Server - } -} - -export declare interface ConnectedPayload { - type: 'connected' -} - -/** - * https://github.com/expressjs/cors#configuration-options - */ -export declare interface CorsOptions { - origin?: CorsOrigin | ((origin: string, cb: (err: Error, origins: CorsOrigin) => void) => void); - methods?: string | string[]; - allowedHeaders?: string | string[]; - exposedHeaders?: string | string[]; - credentials?: boolean; - maxAge?: number; - preflightContinue?: boolean; - optionsSuccessStatus?: number; -} - -export declare type CorsOrigin = boolean | string | RegExp | (string | RegExp)[]; - -export declare function createLogger(level?: LogLevel, allowClearScreen?: boolean): Logger; - -export declare function createServer(inlineConfig?: InlineConfig): Promise; - -export declare interface CSSModulesOptions { - getJSON?: (cssFileName: string, json: Record, outputFileName: string) => void; - scopeBehaviour?: 'global' | 'local'; - globalModulePaths?: string[]; - generateScopedName?: string | ((name: string, filename: string, css: string) => string); - hashPrefix?: string; - /** - * default: null - */ - localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | null; -} - -export declare interface CSSOptions { - /** - * https://github.com/css-modules/postcss-modules - */ - modules?: CSSModulesOptions | false; - preprocessorOptions?: Record; - postcss?: string | (Postcss.ProcessOptions & { - plugins?: Postcss.Plugin[]; - }); -} - -export declare interface CustomPayload { - type: 'custom' - event: string - data?: any -} - -/** - * Type helper to make it easier to use vite.config.ts - * accepts a direct {@link UserConfig} object, or a function that returns it. - * The function receives a {@link ConfigEnv} object that exposes two properties: - * `command` (either `'build'` or `'serve'`), and `mode`. - */ -export declare function defineConfig(config: UserConfigExport): UserConfigExport; - -export declare interface DepOptimizationMetadata { - /** - * The main hash is determined by user config and dependency lockfiles. - * This is checked on server startup to avoid unnecessary re-bundles. - */ - hash: string; - /** - * The browser hash is determined by the main hash plus additional dependencies - * discovered at runtime. This is used to invalidate browser requests to - * optimized deps. - */ - browserHash: string; - optimized: Record; -} - -export declare interface DepOptimizationOptions { - /** - * By default, Vite will crawl your index.html to detect dependencies that - * need to be pre-bundled. If build.rollupOptions.input is specified, Vite - * will crawl those entry points instead. - * - * If neither of these fit your needs, you can specify custom entries using - * this option - the value should be a fast-glob pattern or array of patterns - * (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from - * vite project root. This will overwrite default entries inference. - */ - entries?: string | string[]; - /** - * Force optimize listed dependencies (must be resolvable import paths, - * cannot be globs). - */ - include?: string[]; - /** - * Do not optimize these dependencies (must be resolvable import paths, - * cannot be globs). - */ - exclude?: string[]; - /** - * The bundler sometimes needs to rename symbols to avoid collisions. - * Set this to `true` to keep the `name` property on functions and classes. - * https://esbuild.github.io/api/#keep-names - */ - keepNames?: boolean; -} - -export declare interface ErrorPayload { - type: 'error' - err: { - [name: string]: any - message: string - stack: string - id?: string - frame?: string - plugin?: string - pluginCode?: string - loc?: { - file?: string - line: number - column: number - } - } -} - -export declare interface ESBuildOptions extends TransformOptions_2 { - include?: string | RegExp | string[] | RegExp[]; - exclude?: string | RegExp | string[] | RegExp[]; - jsxInject?: string; -} - -export declare type ESBuildTransformResult = Omit & { - map: SourceMap; -}; - -export declare interface FSWatcher extends fs.FSWatcher { - options: WatchOptions - - /** - * Constructs a new FSWatcher instance with optional WatchOptions parameter. - */ - (options?: WatchOptions): void - - /** - * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one - * string. - */ - add(paths: string | ReadonlyArray): void - - /** - * Stop watching files, directories, or glob patterns. Takes an array of strings or just one - * string. - */ - unwatch(paths: string | ReadonlyArray): void - - /** - * Returns an object representing all the paths on the file system being watched by this - * `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless - * the `cwd` option was used), and the values are arrays of the names of the items contained in - * each directory. - */ - getWatched(): { - [directory: string]: string[] - } - - /** - * Removes all listeners from watched files. - */ - close(): Promise - - on( - event: 'add' | 'addDir' | 'change', - listener: (path: string, stats?: fs.Stats) => void - ): this - - on( - event: 'all', - listener: ( - eventName: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', - path: string, - stats?: fs.Stats - ) => void - ): this - - /** - * Error occurred - */ - on(event: 'error', listener: (error: Error) => void): this - - /** - * Exposes the native Node `fs.FSWatcher events` - */ - on( - event: 'raw', - listener: (eventName: string, path: string, details: any) => void - ): this - - /** - * Fires when the initial scan is complete - */ - on(event: 'ready', listener: () => void): this - - on(event: 'unlink' | 'unlinkDir', listener: (path: string) => void): this - - on(event: string, listener: (...args: any[]) => void): this -} - -export declare interface FullReloadPayload { - type: 'full-reload' - path?: string -} - -export declare interface HmrContext { - file: string; - timestamp: number; - modules: Array; - read: () => string | Promise; - server: ViteDevServer; -} - -export declare interface HmrOptions { - protocol?: string; - host?: string; - port?: number; - path?: string; - timeout?: number; - overlay?: boolean; - server?: Server; -} - -export declare type HMRPayload = - | ConnectedPayload - | UpdatePayload - | FullReloadPayload - | CustomPayload - | ErrorPayload - | PrunePayload - -export declare interface HtmlTagDescriptor { - tag: string; - attrs?: Record; - children?: string | HtmlTagDescriptor[]; - /** - * default: 'head-prepend' - */ - injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend'; -} - -export declare namespace HttpProxy { - export type ProxyTarget = ProxyTargetUrl | ProxyTargetDetailed - - export type ProxyTargetUrl = string | Partial - - export interface ProxyTargetDetailed { - host: string - port: number - protocol?: string - hostname?: string - socketPath?: string - key?: string - passphrase?: string - pfx?: Buffer | string - cert?: string - ca?: string - ciphers?: string - secureProtocol?: string - } - - export type ErrorCallback = ( - err: Error, - req: http.IncomingMessage, - res: http.ServerResponse, - target?: ProxyTargetUrl - ) => void - - export class Server extends events.EventEmitter { - /** - * Creates the proxy server with specified options. - * @param options - Config object passed to the proxy - */ - constructor(options?: ServerOptions) - - /** - * Used for proxying regular HTTP(S) requests - * @param req - Client request. - * @param res - Client response. - * @param options - Additionnal options. - */ - web( - req: http.IncomingMessage, - res: http.ServerResponse, - options?: ServerOptions, - callback?: ErrorCallback - ): void - - /** - * Used for proxying regular HTTP(S) requests - * @param req - Client request. - * @param socket - Client socket. - * @param head - Client head. - * @param options - Additionnal options. - */ - ws( - req: http.IncomingMessage, - socket: any, - head: any, - options?: ServerOptions, - callback?: ErrorCallback - ): void - - /** - * A function that wraps the object in a webserver, for your convenience - * @param port - Port to listen on - */ - listen(port: number): Server - - /** - * A function that closes the inner webserver and stops listening on given port - */ - close(callback?: () => void): void - - /** - * Creates the proxy server with specified options. - * @param options - Config object passed to the proxy - * @returns Proxy object with handlers for `ws` and `web` requests - */ - static createProxyServer(options?: ServerOptions): Server - - /** - * Creates the proxy server with specified options. - * @param options - Config object passed to the proxy - * @returns Proxy object with handlers for `ws` and `web` requests - */ - static createServer(options?: ServerOptions): Server - - /** - * Creates the proxy server with specified options. - * @param options - Config object passed to the proxy - * @returns Proxy object with handlers for `ws` and `web` requests - */ - static createProxy(options?: ServerOptions): Server - - addListener(event: string, listener: () => void): this - on(event: string, listener: () => void): this - on(event: 'error', listener: ErrorCallback): this - on( - event: 'start', - listener: ( - req: http.IncomingMessage, - res: http.ServerResponse, - target: ProxyTargetUrl - ) => void - ): this - on( - event: 'proxyReq', - listener: ( - proxyReq: http.ClientRequest, - req: http.IncomingMessage, - res: http.ServerResponse, - options: ServerOptions - ) => void - ): this - on( - event: 'proxyRes', - listener: ( - proxyRes: http.IncomingMessage, - req: http.IncomingMessage, - res: http.ServerResponse - ) => void - ): this - on( - event: 'proxyReqWs', - listener: ( - proxyReq: http.ClientRequest, - req: http.IncomingMessage, - socket: net.Socket, - options: ServerOptions, - head: any - ) => void - ): this - on( - event: 'econnreset', - listener: ( - err: Error, - req: http.IncomingMessage, - res: http.ServerResponse, - target: ProxyTargetUrl - ) => void - ): this - on( - event: 'end', - listener: ( - req: http.IncomingMessage, - res: http.ServerResponse, - proxyRes: http.IncomingMessage - ) => void - ): this - on( - event: 'close', - listener: ( - proxyRes: http.IncomingMessage, - proxySocket: net.Socket, - proxyHead: any - ) => void - ): this - - once(event: string, listener: () => void): this - removeListener(event: string, listener: () => void): this - removeAllListeners(event?: string): this - getMaxListeners(): number - setMaxListeners(n: number): this - listeners(event: string): Array<() => void> - emit(event: string, ...args: any[]): boolean - listenerCount(type: string): number - } - - export interface ServerOptions { - /** URL string to be parsed with the url module. */ - target?: ProxyTarget - /** URL string to be parsed with the url module. */ - forward?: ProxyTargetUrl - /** Object to be passed to http(s).request. */ - agent?: any - /** Object to be passed to https.createServer(). */ - ssl?: any - /** If you want to proxy websockets. */ - ws?: boolean - /** Adds x- forward headers. */ - xfwd?: boolean - /** Verify SSL certificate. */ - secure?: boolean - /** Explicitly specify if we are proxying to another proxy. */ - toProxy?: boolean - /** Specify whether you want to prepend the target's path to the proxy path. */ - prependPath?: boolean - /** Specify whether you want to ignore the proxy path of the incoming request. */ - ignorePath?: boolean - /** Local interface string to bind for outgoing connections. */ - localAddress?: string - /** Changes the origin of the host header to the target URL. */ - changeOrigin?: boolean - /** specify whether you want to keep letter case of response header key */ - preserveHeaderKeyCase?: boolean - /** Basic authentication i.e. 'user:password' to compute an Authorization header. */ - auth?: string - /** Rewrites the location hostname on (301 / 302 / 307 / 308) redirects, Default: null. */ - hostRewrite?: string - /** Rewrites the location host/ port on (301 / 302 / 307 / 308) redirects based on requested host/ port.Default: false. */ - autoRewrite?: boolean - /** Rewrites the location protocol on (301 / 302 / 307 / 308) redirects to 'http' or 'https'.Default: null. */ - protocolRewrite?: string - /** rewrites domain of set-cookie headers. */ - cookieDomainRewrite?: false | string | { [oldDomain: string]: string } - /** rewrites path of set-cookie headers. Default: false */ - cookiePathRewrite?: false | string | { [oldPath: string]: string } - /** object with extra headers to be added to target requests. */ - headers?: { [header: string]: string } - /** Timeout (in milliseconds) when proxy receives no response from target. Default: 120000 (2 minutes) */ - proxyTimeout?: number - /** Timeout (in milliseconds) for incoming requests */ - timeout?: number - /** Specify whether you want to follow redirects. Default: false */ - followRedirects?: boolean - /** If set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event */ - selfHandleResponse?: boolean - /** Buffer */ - buffer?: stream.Stream - } -} - -export declare type IndexHtmlTransform = IndexHtmlTransformHook | { - enforce?: 'pre' | 'post'; - transform: IndexHtmlTransformHook; -}; - -export declare interface IndexHtmlTransformContext { - /** - * public path when served - */ - path: string; - /** - * filename on disk - */ - filename: string; - server?: ViteDevServer; - bundle?: OutputBundle; - chunk?: OutputChunk; -} - -export declare type IndexHtmlTransformHook = (html: string, ctx: IndexHtmlTransformContext) => IndexHtmlTransformResult | void | Promise; - -export declare type IndexHtmlTransformResult = string | HtmlTagDescriptor[] | { - html: string; - tags: HtmlTagDescriptor[]; -}; - -export declare interface InlineConfig extends UserConfig { - configFile?: string | false; -} - -export declare interface InternalResolveOptions extends ResolveOptions { - root: string; - isBuild: boolean; - isProduction: boolean; - /** - * src code mode also attempts the following: - * - resolving /xxx as URLs - * - resolving bare imports from optimized deps - */ - asSrc?: boolean; - tryIndex?: boolean; - tryPrefix?: string; - preferRelative?: boolean; - isRequire?: boolean; -} - -export declare interface JsonOptions { - /** - * Generate a named export for every property of the JSON object - * @default true - */ - namedExports?: boolean; - /** - * Generate performant output as JSON.parse("stringified"). - * Enabling this will disable namedExports. - * @default false - */ - stringify?: boolean; -} - -export declare type LibraryFormats = 'es' | 'cjs' | 'umd' | 'iife'; - -export declare interface LibraryOptions { - entry: string; - name?: string; - formats?: LibraryFormats[]; -} - -export declare function loadConfigFromFile(configEnv: ConfigEnv, configFile?: string, configRoot?: string, logLevel?: LogLevel): Promise<{ - path: string; - config: UserConfig; -} | null>; - -export declare function loadEnv(mode: string, root: string, prefix?: string): Record; - -export declare interface Logger { - info(msg: string, options?: LogOptions): void; - warn(msg: string, options?: LogOptions): void; - error(msg: string, options?: LogOptions): void; - clearScreen(type: LogType): void; - hasWarned: boolean; -} - -export declare type LogLevel = LogType | 'silent'; - -export declare interface LogOptions { - clear?: boolean; - timestamp?: boolean; -} - -export declare type LogType = 'error' | 'warn' | 'info'; - -export declare function mergeConfig(a: Record, b: Record, isRoot?: boolean): Record; - -export declare class ModuleGraph { - urlToModuleMap: Map; - idToModuleMap: Map; - fileToModulesMap: Map>; - container: PluginContainer; - constructor(container: PluginContainer); - getModuleByUrl(rawUrl: string): Promise; - getModuleById(id: string): ModuleNode | undefined; - getModulesByFile(file: string): Set | undefined; - onFileChange(file: string): void; - invalidateModule(mod: ModuleNode, seen?: Set): void; - invalidateAll(): void; - /** - * Update the module graph based on a module's updated imports information - * If there are dependencies that no longer have any importers, they are - * returned as a Set. - */ - updateModuleInfo(mod: ModuleNode, importedModules: Set, acceptedModules: Set, isSelfAccepting: boolean): Promise | undefined>; - ensureEntryFromUrl(rawUrl: string): Promise; - createFileOnlyEntry(file: string): ModuleNode; - resolveUrl(url: string): Promise<[string, string]>; -} - -export declare class ModuleNode { - /** - * Public served url path, starts with / - */ - url: string; - /** - * Resolved file system path + query - */ - id: string | null; - file: string | null; - type: 'js' | 'css'; - importers: Set; - importedModules: Set; - acceptedHmrDeps: Set; - isSelfAccepting: boolean; - transformResult: TransformResult | null; - ssrTransformResult: TransformResult | null; - ssrModule: Record | null; - lastHMRTimestamp: number; - constructor(url: string); -} - -export declare function normalizePath(id: string): string; - -export declare function optimizeDeps(config: ResolvedConfig, force?: boolean | undefined, asCommand?: boolean, newDeps?: Record): Promise; - -export declare interface PackageData { - dir: string; - hasSideEffects: (id: string) => boolean; - resolvedImports: Record; - data: { - [field: string]: any; - version: string; - main: string; - module: string; - browser: string | Record; - exports: string | Record | string[]; - dependencies: Record; - }; -} - -/** - * Vite plugins extends the Rollup plugin interface with a few extra - * vite-specific options. A valid vite plugin is also a valid Rollup plugin. - * On the contrary, a Rollup plugin may or may NOT be a valid vite universal - * plugin, since some Rollup features do not make sense in an unbundled - * dev server context. That said, as long as a rollup plugin doesn't have strong - * coupling between its bundle phase and output phase hooks then it should - * just work (that means, most of them). - * - * By default, the plugins are run during both serve and build. When a plugin - * is applied during serve, it will only run **non output plugin hooks** (see - * rollup type definition of {@link rollup#PluginHooks}). You can think of the - * dev server as only running `const bundle = rollup.rollup()` but never calling - * `bundle.generate()`. - * - * A plugin that expects to have different behavior depending on serve/build can - * export a factory function that receives the command being run via options. - * - * If a plugin should be applied only for server or build, a function format - * config file can be used to conditional determine the plugins to use. - */ -export declare interface Plugin extends Plugin_2 { - /** - * Enforce plugin invocation tier similar to webpack loaders. - * - * Plugin invocation order: - * - alias resolution - * - `enforce: 'pre'` plugins - * - vite core plugins - * - normal plugins - * - vite build plugins - * - `enforce: 'post'` plugins - * - vite build post plugins - */ - enforce?: 'pre' | 'post'; - /** - * Apply the plugin only for serve or for build. - */ - apply?: 'serve' | 'build'; - /** - * Modify vite config before it's resolved. The hook can either mutate the - * passed-in config directly, or return a partial config object that will be - * deeply merged into existing config. - * - * Note: User plugins are resolved before running this hook so injecting other - * plugins inside the `config` hook will have no effect. - */ - config?: (config: UserConfig, env: ConfigEnv) => UserConfig | null | void; - /** - * Use this hook to read and store the final resolved vite config. - */ - configResolved?: (config: ResolvedConfig) => void; - /** - * Configure the vite server. The hook receives the {@link ViteDevServer} - * instance. This can also be used to store a reference to the server - * for use in other hooks. - * - * The hooks will be called before internal middlewares are applied. A hook - * can return a post hook that will be called after internal middlewares - * are applied. Hook can be async functions and will be called in series. - */ - configureServer?: ServerHook; - /** - * Transform index.html. - * The hook receives the following arguments: - * - * - html: string - * - ctx?: vite.ServerContext (only present during serve) - * - bundle?: rollup.OutputBundle (only present during build) - * - * It can either return a transformed string, or a list of html tag - * descriptors that will be injected into the or . - * - * By default the transform is applied **after** vite's internal html - * transform. If you need to apply the transform before vite, use an object: - * `{ enforce: 'pre', transform: hook }` - */ - transformIndexHtml?: IndexHtmlTransform; - /** - * Perform custom handling of HMR updates. - * The handler receives a context containing changed filename, timestamp, a - * list of modules affected by the file change, and the dev server instance. - * - * - The hook can return a filtered list of modules to narrow down the update. - * e.g. for a Vue SFC, we can narrow down the part to update by comparing - * the descriptors. - * - * - The hook can also return an empty array and then perform custom updates - * by sending a custom hmr payload via server.ws.send(). - * - * - If the hook doesn't return a value, the hmr update will be performed as - * normal. - */ - handleHotUpdate?(ctx: HmrContext): Array | void | Promise | void>; - /** - * extend hooks with ssr flag - */ - resolveId?(this: PluginContext, source: string, importer: string | undefined, options: { - custom?: CustomPluginOptions; - }, ssr?: boolean): Promise | ResolveIdResult; - load?(this: PluginContext, id: string, ssr?: boolean): Promise | LoadResult; - transform?(this: TransformPluginContext, code: string, id: string, ssr?: boolean): Promise | TransformResult_2; -} - -export declare interface PluginContainer { - options: InputOptions; - buildStart(options: InputOptions): Promise; - watchChange(id: string, event?: ChangeEvent): void; - resolveId(id: string, importer?: string, skip?: Set, ssr?: boolean): Promise; - transform(code: string, id: string, inMap?: SourceDescription['map'], ssr?: boolean): Promise; - load(id: string, ssr?: boolean): Promise; - close(): Promise; -} - -export declare type PluginOption = Plugin | false | null | undefined; - -export declare interface ProxyOptions extends HttpProxy.ServerOptions { - /** - * rewrite path - */ - rewrite?: (path: string) => string; - /** - * configure the proxy server (e.g. listen to events) - */ - configure?: (proxy: HttpProxy.Server, options: ProxyOptions) => void; - /** - * webpack-dev-server style bypass function - */ - bypass?: (req: http.IncomingMessage, res: http.ServerResponse, options: ProxyOptions) => void | null | undefined | false | string; -} - -export declare interface PrunePayload { - type: 'prune' - paths: string[] -} - -export declare function resolveConfig(inlineConfig: InlineConfig, command: 'build' | 'serve', defaultMode?: string): Promise; - -export declare type ResolvedBuildOptions = Required>; - -export declare type ResolvedConfig = Readonly & { - configFile: string | undefined; - inlineConfig: UserConfig; - root: string; - base: string; - publicDir: string; - command: 'build' | 'serve'; - mode: string; - isProduction: boolean; - optimizeCacheDir: string | undefined; - env: Record; - resolve: ResolveOptions & { - alias: Alias[]; - }; - plugins: readonly Plugin[]; - server: ServerOptions; - build: ResolvedBuildOptions; - assetsInclude: (file: string) => boolean; - logger: Logger; - createResolver: (options?: Partial) => ResolveFn; -}>; - -export declare type ResolveFn = (id: string, importer?: string, aliasOnly?: boolean) => Promise; - -export declare interface ResolveOptions { - mainFields?: string[]; - conditions?: string[]; - extensions?: string[]; - dedupe?: string[]; -} - -export declare function resolvePackageData(id: string, basedir: string): PackageData | undefined; - -export declare function resolvePackageEntry(id: string, { resolvedImports, dir, data }: PackageData, options: InternalResolveOptions): string | undefined; - -export declare type ResolverFunction = PluginHooks['resolveId'] - -export declare interface ResolverObject { - buildStart?: PluginHooks['buildStart'] - resolveId: ResolverFunction -} - -/** - * https://github.com/rollup/plugins/blob/master/packages/commonjs/types/index.d.ts - * - * This source code is licensed under the MIT license found in the - * LICENSE file at - * https://github.com/rollup/plugins/blob/master/LICENSE - */ -export declare interface RollupCommonJSOptions { - /** - * A minimatch pattern, or array of patterns, which specifies the files in - * the build the plugin should operate on. By default, all files with - * extension `".cjs"` or those in `extensions` are included, but you can narrow - * this list by only including specific files. These files will be analyzed - * and transpiled if either the analysis does not find ES module specific - * statements or `transformMixedEsModules` is `true`. - * @default undefined - */ - include?: string | RegExp | readonly (string | RegExp)[] - /** - * A minimatch pattern, or array of patterns, which specifies the files in - * the build the plugin should _ignore_. By default, all files with - * extensions other than those in `extensions` or `".cjs"` are ignored, but you - * can exclude additional files. See also the `include` option. - * @default undefined - */ - exclude?: string | RegExp | readonly (string | RegExp)[] - /** - * For extensionless imports, search for extensions other than .js in the - * order specified. Note that you need to make sure that non-JavaScript files - * are transpiled by another plugin first. - * @default [ '.js' ] - */ - extensions?: ReadonlyArray - /** - * If true then uses of `global` won't be dealt with by this plugin - * @default false - */ - ignoreGlobal?: boolean - /** - * If false, skips source map generation for CommonJS modules. This will improve performance. - * @default true - */ - sourceMap?: boolean - /** - * Instructs the plugin whether to enable mixed module transformations. This - * is useful in scenarios with modules that contain a mix of ES `import` - * statements and CommonJS `require` expressions. Set to `true` if `require` - * calls should be transformed to imports in mixed modules, or `false` if the - * `require` expressions should survive the transformation. The latter can be - * important if the code contains environment detection, or you are coding - * for an environment with special treatment for `require` calls such as - * ElectronJS. See also the `ignore` option. - * @default false - */ - transformMixedEsModules?: boolean - /** - * Sometimes you have to leave require statements unconverted. Pass an array - * containing the IDs or a `id => boolean` function. - * @default [] - */ - ignore?: ReadonlyArray | ((id: string) => boolean) - /** - * Controls how to render imports from external dependencies. By default, - * this plugin assumes that all external dependencies are CommonJS. This - * means they are rendered as default imports to be compatible with e.g. - * NodeJS where ES modules can only import a default export from a CommonJS - * dependency. - * - * If you set `esmExternals` to `true`, this plugins assumes that all - * external dependencies are ES modules and respect the - * `requireReturnsDefault` option. If that option is not set, they will be - * rendered as namespace imports. - * - * You can also supply an array of ids to be treated as ES modules, or a - * function that will be passed each external id to determine if it is an ES - * module. - * @default false - */ - esmExternals?: boolean | ReadonlyArray | ((id: string) => boolean) - /** - * Controls what is returned when requiring an ES module from a CommonJS file. - * When using the `esmExternals` option, this will also apply to external - * modules. By default, this plugin will render those imports as namespace - * imports i.e. - * - * ```js - * // input - * const foo = require('foo'); - * - * // output - * import * as foo from 'foo'; - * ``` - * - * However there are some situations where this may not be desired. - * For these situations, you can change Rollup's behaviour either globally or - * per module. To change it globally, set the `requireReturnsDefault` option - * to one of the following values: - * - * - `false`: This is the default, requiring an ES module returns its - * namespace. This is the only option that will also add a marker - * `__esModule: true` to the namespace to support interop patterns in - * CommonJS modules that are transpiled ES modules. - * - `"namespace"`: Like `false`, requiring an ES module returns its - * namespace, but the plugin does not add the `__esModule` marker and thus - * creates more efficient code. For external dependencies when using - * `esmExternals: true`, no additional interop code is generated. - * - `"auto"`: This is complementary to how `output.exports: "auto"` works in - * Rollup: If a module has a default export and no named exports, requiring - * that module returns the default export. In all other cases, the namespace - * is returned. For external dependencies when using `esmExternals: true`, a - * corresponding interop helper is added. - * - `"preferred"`: If a module has a default export, requiring that module - * always returns the default export, no matter whether additional named - * exports exist. This is similar to how previous versions of this plugin - * worked. Again for external dependencies when using `esmExternals: true`, - * an interop helper is added. - * - `true`: This will always try to return the default export on require - * without checking if it actually exists. This can throw at build time if - * there is no default export. This is how external dependencies are handled - * when `esmExternals` is not used. The advantage over the other options is - * that, like `false`, this does not add an interop helper for external - * dependencies, keeping the code lean. - * - * To change this for individual modules, you can supply a function for - * `requireReturnsDefault` instead. This function will then be called once for - * each required ES module or external dependency with the corresponding id - * and allows you to return different values for different modules. - * @default false - */ - requireReturnsDefault?: - | boolean - | 'auto' - | 'preferred' - | 'namespace' - | ((id: string) => boolean | 'auto' | 'preferred' | 'namespace') - /** - * Some modules contain dynamic `require` calls, or require modules that - * contain circular dependencies, which are not handled well by static - * imports. Including those modules as `dynamicRequireTargets` will simulate a - * CommonJS (NodeJS-like) environment for them with support for dynamic and - * circular dependencies. - * - * Note: In extreme cases, this feature may result in some paths being - * rendered as absolute in the final bundle. The plugin tries to avoid - * exposing paths from the local machine, but if you are `dynamicRequirePaths` - * with paths that are far away from your project's folder, that may require - * replacing strings like `"/Users/John/Desktop/foo-project/"` -\> `"/"`. - */ - dynamicRequireTargets?: string | ReadonlyArray -} - -export declare function send(req: IncomingMessage, res: ServerResponse, content: string | Buffer, type: string, etag?: string, cacheControl?: string, map?: SourceMap | null): void; - -export declare type ServerHook = (server: ViteDevServer) => (() => void) | void | Promise<(() => void) | void>; - -export declare interface ServerOptions { - host?: string; - port?: number; - /** - * Enable TLS + HTTP/2. - * Note: this downgrades to TLS only when the proxy option is also used. - */ - https?: boolean | https.ServerOptions; - /** - * Open browser window on startup - */ - open?: boolean | string; - /** - * Force dep pre-optimization regardless of whether deps have changed. - */ - force?: boolean; - /** - * Configure HMR-specific options (port, host, path & protocol) - */ - hmr?: HmrOptions | boolean; - /** - * chokidar watch options - * https://github.com/paulmillr/chokidar#api - */ - watch?: WatchOptions; - /** - * Configure custom proxy rules for the dev server. Expects an object - * of `{ key: options }` pairs. - * Uses [`http-proxy`](https://github.com/http-party/node-http-proxy). - * Full options [here](https://github.com/http-party/node-http-proxy#options). - * - * Example `vite.config.js`: - * ``` js - * module.exports = { - * proxy: { - * // string shorthand - * '/foo': 'http://localhost:4567/foo', - * // with options - * '/api': { - * target: 'http://jsonplaceholder.typicode.com', - * changeOrigin: true, - * rewrite: path => path.replace(/^\/api/, '') - * } - * } - * } - * ``` - */ - proxy?: Record; - /** - * Configure CORS for the dev server. - * Uses https://github.com/expressjs/cors. - * Set to `true` to allow all methods from any origin, or configure separately - * using an object. - */ - cors?: CorsOptions | boolean; - /** - * If enabled, vite will exit if specified port is already in use - */ - strictPort?: boolean; - /** - * Create Vite dev server to be used as a middleware in an existing server - */ - middlewareMode?: boolean; - /** - * Prepend this folder to http requests, for use when proxying vite as a subfolder - * Should start and end with the `/` character - */ - base?: string; -} - -export declare function sortUserPlugins(plugins: (Plugin | Plugin[])[] | undefined): [Plugin[], Plugin[], Plugin[]]; - -export declare interface SSROptions { - external?: string[]; - noExternal?: string[]; -} - -export declare namespace Terser { - 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 - 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 use format instead */ - output?: FormatOptions - parse?: ParseOptions - safari10?: boolean - sourceMap?: boolean | SourceMapOptions - toplevel?: boolean - } - - export interface MinifyOutput { - code?: string - map?: object | string - } - - export interface SourceMapOptions { - /** Source map object, 'inline' or source map file content */ - content?: object | string - includeSources?: boolean - filename?: string - root?: string - url?: string | 'inline' - } -} - -export declare interface TransformOptions { - ssr?: boolean; - html?: boolean; -} - -export declare interface TransformResult { - code: string; - map: SourceMap | null; - etag?: string; - deps?: string[]; -} - -export declare interface Update { - type: 'js-update' | 'css-update' - path: string - acceptedPath: string - timestamp: number -} - -export declare interface UpdatePayload { - type: 'update' - updates: Update[] -} - -export declare interface UserConfig { - /** - * Project root directory. Can be an absolute path, or a path relative from - * the location of the config file itself. - * @default process.cwd() - */ - root?: string; - /** - * Base public path when served in development or production. - * @default '/' - */ - base?: string; - /** - * Directory to serve as plain static assets. Files in this directory are - * served and copied to build dist dir as-is without transform. The value - * can be either an absolute file system path or a path relative to . - * @default 'public' - */ - publicDir?: string; - /** - * Explicitly set a mode to run in. This will override the default mode for - * each command, and can be overridden by the command line --mode option. - */ - mode?: string; - /** - * Define global variable replacements. - * Entries will be defined on `window` during dev and replaced during build. - */ - define?: Record; - /** - * Array of vite plugins to use. - */ - plugins?: (PluginOption | PluginOption[])[]; - /** - * Configure resolver - */ - resolve?: ResolveOptions & { - alias?: AliasOptions; - }; - /** - * CSS related options (preprocessors and CSS modules) - */ - css?: CSSOptions; - /** - * JSON loading options - */ - json?: JsonOptions; - /** - * Transform options to pass to esbuild. - * Or set to `false` to disable esbuild. - */ - esbuild?: ESBuildOptions | false; - /** - * Specify additional files to be treated as static assets. - */ - assetsInclude?: string | RegExp | (string | RegExp)[]; - /** - * Server specific options, e.g. host, port, https... - */ - server?: ServerOptions; - /** - * Build specific options - */ - build?: BuildOptions; - /** - * Dep optimization options - */ - optimizeDeps?: DepOptimizationOptions; - /* Excluded from this release type: ssr */ - /** - * Log level. - * Default: 'info' - */ - logLevel?: LogLevel; - /** - * Default: true - */ - clearScreen?: boolean; - /** - * Import aliases - * @deprecated use `resolve.alias` instead - */ - alias?: AliasOptions; - /** - * Force Vite to always resolve listed dependencies to the same copy (from - * project root). - * @deprecated use `resolve.dedupe` instead - */ - dedupe?: string[]; -} - -export declare type UserConfigExport = UserConfig | UserConfigFn; - -export declare type UserConfigFn = (env: ConfigEnv) => UserConfig; - -export declare interface ViteDevServer { - /** - * The resolved vite config object - */ - config: ResolvedConfig; - /** - * A connect app instance. - * - Can be used to attach custom middlewares to the dev server. - * - Can also be used as the handler function of a custom http server - * or as a middleware in any connect-style Node.js frameworks - * - * https://github.com/senchalabs/connect#use-middleware - */ - middlewares: Connect.Server; - /** - * @deprecated use `server.middlewares` instead - */ - app: Connect.Server; - /** - * native Node http server instance - * will be null in middleware mode - */ - httpServer: http.Server | null; - /** - * chokidar watcher instance - * https://github.com/paulmillr/chokidar#api - */ - watcher: FSWatcher; - /** - * web socket server with `send(payload)` method - */ - ws: WebSocketServer; - /** - * Rollup plugin container that can run plugin hooks on a given file - */ - pluginContainer: PluginContainer; - /** - * Module graph that tracks the import relationships, url to file mapping - * and hmr state. - */ - moduleGraph: ModuleGraph; - /** - * Programmatically resolve, load and transform a URL and get the result - * without going through the http request pipeline. - */ - transformRequest(url: string, options?: TransformOptions): Promise; - /** - * Apply vite built-in HTML transforms and any plugin HTML transforms. - */ - transformIndexHtml(url: string, html: string): Promise; - /** - * Util for transforming a file with esbuild. - * Can be useful for certain plugins. - */ - transformWithEsbuild(code: string, filename: string, options?: TransformOptions_2, inMap?: object): Promise; - /** - * Load a given URL as an instantiated module for SSR. - */ - ssrLoadModule(url: string): Promise>; - /** - * Fix ssr error stacktrace - */ - ssrFixStacktrace(e: Error): void; - /** - * Start the server. - */ - listen(port?: number, isRestart?: boolean): Promise; - /** - * Stop the server. - */ - close(): Promise; - /* Excluded from this release type: _optimizeDepsMetadata */ - /* Excluded from this release type: _ssrExternals */ - /* Excluded from this release type: _globImporters */ - /* Excluded from this release type: _isRunningOptimizer */ - /* Excluded from this release type: _registerMissingImport */ - /* Excluded from this release type: _pendingReload */ -} - -export declare interface WatchOptions { - /** - * Indicates whether the process should continue to run as long as files are being watched. If - * set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`, - * even if the process continues to run. - */ - persistent?: boolean - - /** - * ([anymatch](https://github.com/micromatch/anymatch)-compatible definition) Defines files/paths to - * be ignored. The whole relative or absolute path is tested, not just filename. If a function - * with two arguments is provided, it gets called twice per path - once with a single argument - * (the path), second time with two arguments (the path and the - * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path). - */ - ignored?: any - - /** - * If set to `false` then `add`/`addDir` events are also emitted for matching paths while - * instantiating the watching as chokidar discovers these file paths (before the `ready` event). - */ - ignoreInitial?: boolean - - /** - * When `false`, only the symlinks themselves will be watched for changes instead of following - * the link references and bubbling events through the link's path. - */ - followSymlinks?: boolean - - /** - * The base directory from which watch `paths` are to be derived. Paths emitted with events will - * be relative to this. - */ - cwd?: string - - /** - * If set to true then the strings passed to .watch() and .add() are treated as literal path - * names, even if they look like globs. Default: false. - */ - disableGlobbing?: boolean - - /** - * Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU - * utilization, consider setting this to `false`. It is typically necessary to **set this to - * `true` to successfully watch files over a network**, and it may be necessary to successfully - * watch files in other non-standard situations. Setting to `true` explicitly on OS X overrides - * the `useFsEvents` default. - */ - usePolling?: boolean - - /** - * Whether to use the `fsevents` watching interface if available. When set to `true` explicitly - * and `fsevents` is available this supersedes the `usePolling` setting. When set to `false` on - * OS X, `usePolling: true` becomes the default. - */ - useFsEvents?: boolean - - /** - * If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that - * may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is - * provided even in cases where it wasn't already available from the underlying watch events. - */ - alwaysStat?: boolean - - /** - * If set, limits how many levels of subdirectories will be traversed. - */ - depth?: number - - /** - * Interval of file system polling. - */ - interval?: number - - /** - * Interval of file system polling for binary files. ([see list of binary extensions](https://gi - * thub.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) - */ - binaryInterval?: number - - /** - * Indicates whether to watch files that don't have read permissions if possible. If watching - * fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed - * silently. - */ - ignorePermissionErrors?: boolean - - /** - * `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts - * that occur when using editors that use "atomic writes" instead of writing directly to the - * source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change` - * event rather than `unlink` then `add`. If the default of 100 ms does not work well for you, - * you can override it by setting `atomic` to a custom value, in milliseconds. - */ - atomic?: boolean | number - - /** - * can be set to an object in order to adjust timing params: - */ - awaitWriteFinish?: - | { - /** - * Amount of time in milliseconds for a file size to remain constant before emitting its event. - */ - stabilityThreshold?: number - - /** - * File size polling interval. - */ - pollInterval?: number - } - | boolean -} - -export declare interface WebSocketServer { - send(payload: HMRPayload): void; - close(): Promise; -} - -export { } diff --git a/node_modules/vite/dist/node/index.js b/node_modules/vite/dist/node/index.js deleted file mode 100644 index 9ebe8fb..0000000 --- a/node_modules/vite/dist/node/index.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var build = require('./chunks/dep-66eb515d.js'); -require('os'); -require('fs'); -require('path'); -require('tty'); -require('util'); -require('net'); -require('events'); -require('url'); -require('http'); -require('stream'); -require('zlib'); -require('resolve'); -require('module'); -require('readline'); -require('crypto'); -require('esbuild'); -require('worker_threads'); -require('assert'); -require('https'); -require('tls'); -require('buffer'); -require('child_process'); -require('querystring'); - - - -exports.build = build.build; -exports.createLogger = build.createLogger; -exports.createServer = build.createServer; -exports.defineConfig = build.defineConfig; -exports.loadConfigFromFile = build.loadConfigFromFile; -exports.loadEnv = build.loadEnv; -exports.mergeConfig = build.mergeConfig; -exports.normalizePath = build.normalizePath; -exports.optimizeDeps = build.optimizeDeps; -exports.resolveConfig = build.resolveConfig; -exports.resolvePackageData = build.resolvePackageData; -exports.resolvePackageEntry = build.resolvePackageEntry; -exports.send = build.send; -exports.sortUserPlugins = build.sortUserPlugins; diff --git a/node_modules/vite/dist/node/terser.js b/node_modules/vite/dist/node/terser.js deleted file mode 100644 index a0991d6..0000000 --- a/node_modules/vite/dist/node/terser.js +++ /dev/null @@ -1,35638 +0,0 @@ -'use strict'; - -var require$$0 = require('fs'); -var require$$1 = require('path'); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; } - -var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0); -var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1); - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function createCommonjsModule(fn) { - var module = { exports: {} }; - return fn(module, module.exports), module.exports; -} - -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -const intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); - -/** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ -var encode$1 = function(number) { - if (0 <= number && number < intToCharMap.length) { - return intToCharMap[number]; - } - throw new TypeError("Must be between 0 and 63: " + number); -}; - -var base64 = { - encode: encode$1 -}; - -/* -*- 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. - */ - - - -// 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; -} - -/** - * Returns the base 64 VLQ encoded value. - */ -var 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; -}; - -var base64Vlq = { - encode: encode -}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -var util = createCommonjsModule(function (module, exports) { -/* - * 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 '/..' 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; -}); - -/* -*- 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$2 { - 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$2(); - 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(); - } -} -var ArraySet_1 = ArraySet$2; - -var arraySet = { - ArraySet: ArraySet_1 -}; - -/* -*- 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 - */ - - - -/** - * 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$1 { - 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; - } -} - -var MappingList_1 = MappingList$1; - -var mappingList = { - MappingList: MappingList_1 -}; - -/* -*- 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 ArraySet$1 = arraySet.ArraySet; -const MappingList = mappingList.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$2 { - 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$1(); - this._names = new ArraySet$1(); - 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$2({ - 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$1() - : this._sources; - const newNames = new ArraySet$1(); - - // 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) ; 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) ; 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$2.prototype._version = 3; -var SourceMapGenerator_1 = SourceMapGenerator$2; - -var sourceMapGenerator = { - SourceMapGenerator: SourceMapGenerator_1 -}; - -/* -*- Mode: js; js-indent-level: 2; -*- */ - -var binarySearch = createCommonjsModule(function (module, exports) { -/* - * 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; -}; -}); - -var readWasm = createCommonjsModule(function (module) { -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$$0__default; - const path = require$$1__default; - - 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"); - }; -} -}); - -/** - * 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; - -var wasm = 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; -}; - -/* -*- 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 ArraySet = arraySet.ArraySet; - // eslint-disable-line no-unused-vars - - - -const INTERNAL = Symbol("smcInternal"); - -class SourceMapConsumer$1 { - constructor(aSourceMap, aSourceMapURL) { - // If the constructor was called by super(), just return Promise. - // Yes, this is a hack to retain the pre-existing API of the base-class - // constructor also being an async factory function. - if (aSourceMap == INTERNAL) { - return Promise.resolve(this); - } - - return _factory(aSourceMap, aSourceMapURL); - } - - static initialize(opts) { - readWasm.initialize(opts["lib/mappings.wasm"]); - } - - static fromSourceMap(aSourceMap, aSourceMapURL) { - return _factoryBSM(aSourceMap, aSourceMapURL); - } - - /** - * 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); - * ``` - */ - static with(rawSourceMap, sourceMapUrl, f) { - // Note: The `acorn` version that `webpack` currently depends on doesn't - // support `async` functions, and the nodes that we support don't all have - // `.finally`. Therefore, this is written a bit more convolutedly than it - // should really be. - - let consumer = null; - const promise = new SourceMapConsumer$1(rawSourceMap, sourceMapUrl); - return promise - .then(c => { - consumer = c; - return f(c); - }) - .then(x => { - if (consumer) { - consumer.destroy(); - } - return x; - }, e => { - if (consumer) { - consumer.destroy(); - } - throw e; - }); - } - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - _parseMappings(aStr, aSourceRoot) { - throw new Error("Subclasses must implement _parseMappings"); - } - - /** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ - eachMapping(aCallback, aContext, aOrder) { - throw new Error("Subclasses must implement eachMapping"); - } - - /** - * 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. - */ - allGeneratedPositionsFor(aArgs) { - throw new Error("Subclasses must implement allGeneratedPositionsFor"); - } - - destroy() { - throw new Error("Subclasses must implement destroy"); - } -} - -/** - * The version of the source mapping spec that we are consuming. - */ -SourceMapConsumer$1.prototype._version = 3; -SourceMapConsumer$1.GENERATED_ORDER = 1; -SourceMapConsumer$1.ORIGINAL_ORDER = 2; - -SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1; -SourceMapConsumer$1.LEAST_UPPER_BOUND = 2; - -var SourceMapConsumer_1 = SourceMapConsumer$1; - -/** - * A BasicSourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The first parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be 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 file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ -class BasicSourceMapConsumer extends SourceMapConsumer$1 { - constructor(aSourceMap, aSourceMapURL) { - return super(INTERNAL).then(that => { - let sourceMap = aSourceMap; - if (typeof aSourceMap === "string") { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - - const version = util.getArg(sourceMap, "version"); - let sources = util.getArg(sourceMap, "sources"); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - const names = util.getArg(sourceMap, "names", []); - let sourceRoot = util.getArg(sourceMap, "sourceRoot", null); - const sourcesContent = util.getArg(sourceMap, "sourcesContent", null); - const mappings = util.getArg(sourceMap, "mappings"); - const file = util.getArg(sourceMap, "file", null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != that._version) { - throw new Error("Unsupported version: " + version); - } - - if (sourceRoot) { - sourceRoot = util.normalize(sourceRoot); - } - - sources = sources - .map(String) - // Some source maps produce relative source paths like "./foo.js" instead of - // "foo.js". Normalize these first so that future comparisons will succeed. - // See bugzil.la/1090768. - .map(util.normalize) - // Always ensure that absolute sources are internally stored relative to - // the source root, if the source root is absolute. Not doing this would - // be particularly problematic when the source root is a prefix of the - // source (valid, but why??). See github issue #199 and bugzil.la/1188982. - .map(function(source) { - return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) - ? util.relative(sourceRoot, source) - : source; - }); - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - that._names = ArraySet.fromArray(names.map(String), true); - that._sources = ArraySet.fromArray(sources, true); - - that._absoluteSources = that._sources.toArray().map(function(s) { - return util.computeSourceURL(sourceRoot, s, aSourceMapURL); - }); - - that.sourceRoot = sourceRoot; - that.sourcesContent = sourcesContent; - that._mappings = mappings; - that._sourceMapURL = aSourceMapURL; - that.file = file; - - that._computedColumnSpans = false; - that._mappingsPtr = 0; - that._wasm = null; - - return wasm().then(w => { - that._wasm = w; - return that; - }); - }); - } - - /** - * Utility function to find the index of a source. Returns -1 if not - * found. - */ - _findSourceIndex(aSource) { - let relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util.relative(this.sourceRoot, relativeSource); - } - - if (this._sources.has(relativeSource)) { - return this._sources.indexOf(relativeSource); - } - - // Maybe aSource is an absolute URL as returned by |sources|. In - // this case we can't simply undo the transform. - for (let i = 0; i < this._absoluteSources.length; ++i) { - if (this._absoluteSources[i] == aSource) { - return i; - } - } - - return -1; - } - - /** - * Create a BasicSourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @param String aSourceMapURL - * The URL at which the source map can be found (optional) - * @returns BasicSourceMapConsumer - */ - static fromSourceMap(aSourceMap, aSourceMapURL) { - return new BasicSourceMapConsumer(aSourceMap.toString()); - } - - get sources() { - return this._absoluteSources.slice(); - } - - _getMappingsPtr() { - if (this._mappingsPtr === 0) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this._mappingsPtr; - } - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - _parseMappings(aStr, aSourceRoot) { - const size = aStr.length; - - const mappingsBufPtr = this._wasm.exports.allocate_mappings(size); - const mappingsBuf = new Uint8Array(this._wasm.exports.memory.buffer, mappingsBufPtr, size); - for (let i = 0; i < size; i++) { - mappingsBuf[i] = aStr.charCodeAt(i); - } - - const mappingsPtr = this._wasm.exports.parse_mappings(mappingsBufPtr); - - if (!mappingsPtr) { - const error = this._wasm.exports.get_last_error(); - let msg = `Error parsing mappings (code ${error}): `; - - // XXX: keep these error codes in sync with `fitzgen/source-map-mappings`. - switch (error) { - case 1: - msg += "the mappings contained a negative line, column, source index, or name index"; - break; - case 2: - msg += "the mappings contained a number larger than 2**32"; - break; - case 3: - msg += "reached EOF while in the middle of parsing a VLQ"; - break; - case 4: - msg += "invalid base 64 character while parsing a VLQ"; - break; - default: - msg += "unknown error code"; - break; - } - - throw new Error(msg); - } - - this._mappingsPtr = mappingsPtr; - } - - eachMapping(aCallback, aContext, aOrder) { - const context = aContext || null; - const order = aOrder || SourceMapConsumer$1.GENERATED_ORDER; - const sourceRoot = this.sourceRoot; - - this._wasm.withMappingCallback( - mapping => { - if (mapping.source !== null) { - mapping.source = this._sources.at(mapping.source); - mapping.source = util.computeSourceURL(sourceRoot, mapping.source, this._sourceMapURL); - - if (mapping.name !== null) { - mapping.name = this._names.at(mapping.name); - } - } - - aCallback.call(context, mapping); - }, - () => { - switch (order) { - case SourceMapConsumer$1.GENERATED_ORDER: - this._wasm.exports.by_generated_location(this._getMappingsPtr()); - break; - case SourceMapConsumer$1.ORIGINAL_ORDER: - this._wasm.exports.by_original_location(this._getMappingsPtr()); - break; - default: - throw new Error("Unknown order of iteration."); - } - } - ); - } - - allGeneratedPositionsFor(aArgs) { - let source = util.getArg(aArgs, "source"); - const originalLine = util.getArg(aArgs, "line"); - const originalColumn = aArgs.column || 0; - - source = this._findSourceIndex(source); - if (source < 0) { - return []; - } - - if (originalLine < 1) { - throw new Error("Line numbers must be >= 1"); - } - - if (originalColumn < 0) { - throw new Error("Column numbers must be >= 0"); - } - - const mappings = []; - - this._wasm.withMappingCallback( - m => { - let lastColumn = m.lastGeneratedColumn; - if (this._computedColumnSpans && lastColumn === null) { - lastColumn = Infinity; - } - mappings.push({ - line: m.generatedLine, - column: m.generatedColumn, - lastColumn, - }); - }, () => { - this._wasm.exports.all_generated_locations_for( - this._getMappingsPtr(), - source, - originalLine - 1, - "column" in aArgs, - originalColumn - ); - } - ); - - return mappings; - } - - destroy() { - if (this._mappingsPtr !== 0) { - this._wasm.exports.free_mappings(this._mappingsPtr); - this._mappingsPtr = 0; - } - } - - /** - * Compute the last column for each generated mapping. The last column is - * inclusive. - */ - computeColumnSpans() { - if (this._computedColumnSpans) { - return; - } - - this._wasm.exports.compute_column_spans(this._getMappingsPtr()); - this._computedColumnSpans = true; - } - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ - originalPositionFor(aArgs) { - const needle = { - generatedLine: util.getArg(aArgs, "line"), - generatedColumn: util.getArg(aArgs, "column") - }; - - if (needle.generatedLine < 1) { - throw new Error("Line numbers must be >= 1"); - } - - if (needle.generatedColumn < 0) { - throw new Error("Column numbers must be >= 0"); - } - - let bias = util.getArg(aArgs, "bias", SourceMapConsumer$1.GREATEST_LOWER_BOUND); - if (bias == null) { - bias = SourceMapConsumer$1.GREATEST_LOWER_BOUND; - } - - let mapping; - this._wasm.withMappingCallback(m => mapping = m, () => { - this._wasm.exports.original_location_for( - this._getMappingsPtr(), - needle.generatedLine - 1, - needle.generatedColumn, - bias - ); - }); - - if (mapping) { - if (mapping.generatedLine === needle.generatedLine) { - let source = util.getArg(mapping, "source", null); - if (source !== null) { - source = this._sources.at(source); - source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); - } - - let name = util.getArg(mapping, "name", null); - if (name !== null) { - name = this._names.at(name); - } - - return { - source, - line: util.getArg(mapping, "originalLine", null), - column: util.getArg(mapping, "originalColumn", null), - name - }; - } - } - - return { - source: null, - line: null, - column: null, - name: null - }; - } - - /** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ - hasContentsOfAllSources() { - if (!this.sourcesContent) { - return false; - } - return this.sourcesContent.length >= this._sources.size() && - !this.sourcesContent.some(function(sc) { return sc == null; }); - } - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ - sourceContentFor(aSource, nullOnMissing) { - if (!this.sourcesContent) { - return null; - } - - const index = this._findSourceIndex(aSource); - if (index >= 0) { - return this.sourcesContent[index]; - } - - let relativeSource = aSource; - if (this.sourceRoot != null) { - relativeSource = util.relative(this.sourceRoot, relativeSource); - } - - let url; - if (this.sourceRoot != null - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - const fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + relativeSource)) { - return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; - } - } - - // This function is used recursively from - // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we - // don't want to throw if we can't find the source - we just want to - // return null, so we provide a flag to exit gracefully. - if (nullOnMissing) { - return null; - } - - throw new Error('"' + relativeSource + '" is not in the SourceMap.'); - } - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or - * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the - * closest element that is smaller than or greater than the one we are - * searching for, respectively, if the exact element cannot be found. - * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ - generatedPositionFor(aArgs) { - let source = util.getArg(aArgs, "source"); - source = this._findSourceIndex(source); - if (source < 0) { - return { - line: null, - column: null, - lastColumn: null - }; - } - - const needle = { - source, - originalLine: util.getArg(aArgs, "line"), - originalColumn: util.getArg(aArgs, "column") - }; - - if (needle.originalLine < 1) { - throw new Error("Line numbers must be >= 1"); - } - - if (needle.originalColumn < 0) { - throw new Error("Column numbers must be >= 0"); - } - - let bias = util.getArg(aArgs, "bias", SourceMapConsumer$1.GREATEST_LOWER_BOUND); - if (bias == null) { - bias = SourceMapConsumer$1.GREATEST_LOWER_BOUND; - } - - let mapping; - this._wasm.withMappingCallback(m => mapping = m, () => { - this._wasm.exports.generated_location_for( - this._getMappingsPtr(), - needle.source, - needle.originalLine - 1, - needle.originalColumn, - bias - ); - }); - - if (mapping) { - if (mapping.source === needle.source) { - let lastColumn = mapping.lastGeneratedColumn; - if (this._computedColumnSpans && lastColumn === null) { - lastColumn = Infinity; - } - return { - line: util.getArg(mapping, "generatedLine", null), - column: util.getArg(mapping, "generatedColumn", null), - lastColumn, - }; - } - } - - return { - line: null, - column: null, - lastColumn: null - }; - } -} - -BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1; -var BasicSourceMapConsumer_1 = BasicSourceMapConsumer; - -/** - * An IndexedSourceMapConsumer instance represents a parsed source map which - * we can query for information. It differs from BasicSourceMapConsumer in - * that it takes "indexed" source maps (i.e. ones with a "sections" field) as - * input. - * - * The first parameter is a raw source map (either as a JSON string, or already - * parsed to an object). According to the spec for indexed source maps, they - * have the following attributes: - * - * - version: Which version of the source map spec this map is following. - * - file: Optional. The generated file this source map is associated with. - * - sections: A list of section definitions. - * - * Each value under the "sections" field has two fields: - * - offset: The offset into the original specified at which this section - * begins to apply, defined as an object with a "line" and "column" - * field. - * - map: A source map definition. This source map could also be indexed, - * but doesn't have to be. - * - * Instead of the "map" field, it's also possible to have a "url" field - * specifying a URL to retrieve a source map from, but that's currently - * unsupported. - * - * Here's an example source map, taken from the source map spec[0], but - * modified to omit a section which uses the "url" field. - * - * { - * version : 3, - * file: "app.js", - * sections: [{ - * offset: {line:100, column:10}, - * map: { - * version : 3, - * file: "section.js", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AAAA,E;;ABCDE;" - * } - * }], - * } - * - * The second parameter, if given, is a string whose value is the URL - * at which the source map was found. This URL is used to compute the - * sources array. - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt - */ -class IndexedSourceMapConsumer extends SourceMapConsumer$1 { - constructor(aSourceMap, aSourceMapURL) { - return super(INTERNAL).then(that => { - let sourceMap = aSourceMap; - if (typeof aSourceMap === "string") { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - - const version = util.getArg(sourceMap, "version"); - const sections = util.getArg(sourceMap, "sections"); - - if (version != that._version) { - throw new Error("Unsupported version: " + version); - } - - that._sources = new ArraySet(); - that._names = new ArraySet(); - that.__generatedMappings = null; - that.__originalMappings = null; - that.__generatedMappingsUnsorted = null; - that.__originalMappingsUnsorted = null; - - let lastOffset = { - line: -1, - column: 0 - }; - return Promise.all(sections.map(s => { - if (s.url) { - // The url field will require support for asynchronicity. - // See https://github.com/mozilla/source-map/issues/16 - throw new Error("Support for url field in sections not implemented."); - } - const offset = util.getArg(s, "offset"); - const offsetLine = util.getArg(offset, "line"); - const offsetColumn = util.getArg(offset, "column"); - - if (offsetLine < lastOffset.line || - (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { - throw new Error("Section offsets must be ordered and non-overlapping."); - } - lastOffset = offset; - - const cons = new SourceMapConsumer$1(util.getArg(s, "map"), aSourceMapURL); - return cons.then(consumer => { - return { - generatedOffset: { - // The offset fields are 0-based, but we use 1-based indices when - // encoding/decoding from VLQ. - generatedLine: offsetLine + 1, - generatedColumn: offsetColumn + 1 - }, - consumer - }; - }); - })).then(s => { - that._sections = s; - return that; - }); - }); - } - - // `__generatedMappings` and `__originalMappings` are arrays that hold the - // parsed mapping coordinates from the source map's "mappings" attribute. They - // are lazily instantiated, accessed via the `_generatedMappings` and - // `_originalMappings` getters respectively, and we only parse the mappings - // and create these arrays once queried for a source location. We jump through - // these hoops because there can be many thousands of mappings, and parsing - // them is expensive, so we only want to do it if we must. - // - // Each object in the arrays is of the form: - // - // { - // generatedLine: The line number in the generated code, - // generatedColumn: The column number in the generated code, - // source: The path to the original source file that generated this - // chunk of code, - // originalLine: The line number in the original source that - // corresponds to this chunk of generated code, - // originalColumn: The column number in the original source that - // corresponds to this chunk of generated code, - // name: The name of the original symbol which generated this chunk of - // code. - // } - // - // All properties except for `generatedLine` and `generatedColumn` can be - // `null`. - // - // `_generatedMappings` is ordered by the generated positions. - // - // `_originalMappings` is ordered by the original positions. - get _generatedMappings() { - if (!this.__generatedMappings) { - this._sortGeneratedMappings(); - } - - return this.__generatedMappings; - } - - get _originalMappings() { - if (!this.__originalMappings) { - this._sortOriginalMappings(); - } - - return this.__originalMappings; - } - - get _generatedMappingsUnsorted() { - if (!this.__generatedMappingsUnsorted) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappingsUnsorted; - } - - get _originalMappingsUnsorted() { - if (!this.__originalMappingsUnsorted) { - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappingsUnsorted; - } - - _sortGeneratedMappings() { - const mappings = this._generatedMappingsUnsorted; - mappings.sort(util.compareByGeneratedPositionsDeflated); - this.__generatedMappings = mappings; - } - - _sortOriginalMappings() { - const mappings = this._originalMappingsUnsorted; - mappings.sort(util.compareByOriginalPositions); - this.__originalMappings = mappings; - } - - /** - * The list of original sources. - */ - get sources() { - const sources = []; - for (let i = 0; i < this._sections.length; i++) { - for (let j = 0; j < this._sections[i].consumer.sources.length; j++) { - sources.push(this._sections[i].consumer.sources[j]); - } - } - return sources; - } - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. The line number - * is 1-based. - * - column: The column number in the generated source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. The - * line number is 1-based. - * - column: The column number in the original source, or null. The - * column number is 0-based. - * - name: The original identifier, or null. - */ - originalPositionFor(aArgs) { - const needle = { - generatedLine: util.getArg(aArgs, "line"), - generatedColumn: util.getArg(aArgs, "column") - }; - - // Find the section containing the generated position we're trying to map - // to an original position. - const sectionIndex = binarySearch.search(needle, this._sections, - function(aNeedle, section) { - const cmp = aNeedle.generatedLine - section.generatedOffset.generatedLine; - if (cmp) { - return cmp; - } - - return (aNeedle.generatedColumn - - section.generatedOffset.generatedColumn); - }); - const section = this._sections[sectionIndex]; - - if (!section) { - return { - source: null, - line: null, - column: null, - name: null - }; - } - - return section.consumer.originalPositionFor({ - line: needle.generatedLine - - (section.generatedOffset.generatedLine - 1), - column: needle.generatedColumn - - (section.generatedOffset.generatedLine === needle.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - bias: aArgs.bias - }); - } - - /** - * Return true if we have the source content for every source in the source - * map, false otherwise. - */ - hasContentsOfAllSources() { - return this._sections.every(function(s) { - return s.consumer.hasContentsOfAllSources(); - }); - } - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * available. - */ - sourceContentFor(aSource, nullOnMissing) { - for (let i = 0; i < this._sections.length; i++) { - const section = this._sections[i]; - - const content = section.consumer.sourceContentFor(aSource, true); - if (content) { - return content; - } - } - if (nullOnMissing) { - return null; - } - throw new Error('"' + aSource + '" is not in the SourceMap.'); - } - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. The line number - * is 1-based. - * - column: The column number in the original source. The column - * number is 0-based. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. The - * line number is 1-based. - * - column: The column number in the generated source, or null. - * The column number is 0-based. - */ - generatedPositionFor(aArgs) { - for (let i = 0; i < this._sections.length; i++) { - const section = this._sections[i]; - - // Only consider this section if the requested source is in the list of - // sources of the consumer. - if (section.consumer._findSourceIndex(util.getArg(aArgs, "source")) === -1) { - continue; - } - const generatedPosition = section.consumer.generatedPositionFor(aArgs); - if (generatedPosition) { - const ret = { - line: generatedPosition.line + - (section.generatedOffset.generatedLine - 1), - column: generatedPosition.column + - (section.generatedOffset.generatedLine === generatedPosition.line - ? section.generatedOffset.generatedColumn - 1 - : 0) - }; - return ret; - } - } - - return { - line: null, - column: null - }; - } - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - _parseMappings(aStr, aSourceRoot) { - const generatedMappings = this.__generatedMappingsUnsorted = []; - const originalMappings = this.__originalMappingsUnsorted = []; - for (let i = 0; i < this._sections.length; i++) { - const section = this._sections[i]; - - const sectionMappings = []; - section.consumer.eachMapping(m => sectionMappings.push(m)); - - for (let j = 0; j < sectionMappings.length; j++) { - const mapping = sectionMappings[j]; - - // TODO: test if null is correct here. The original code used - // `source`, which would actually have gotten used as null because - // var's get hoisted. - // See: https://github.com/mozilla/source-map/issues/333 - let source = util.computeSourceURL(section.consumer.sourceRoot, null, this._sourceMapURL); - this._sources.add(source); - source = this._sources.indexOf(source); - - let name = null; - if (mapping.name) { - this._names.add(mapping.name); - name = this._names.indexOf(mapping.name); - } - - // The mappings coming from the consumer for the section have - // generated positions relative to the start of the section, so we - // need to offset them to be relative to the start of the concatenated - // generated file. - const adjustedMapping = { - source, - generatedLine: mapping.generatedLine + - (section.generatedOffset.generatedLine - 1), - generatedColumn: mapping.generatedColumn + - (section.generatedOffset.generatedLine === mapping.generatedLine - ? section.generatedOffset.generatedColumn - 1 - : 0), - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name - }; - - generatedMappings.push(adjustedMapping); - if (typeof adjustedMapping.originalLine === "number") { - originalMappings.push(adjustedMapping); - } - } - } - } - - eachMapping(aCallback, aContext, aOrder) { - const context = aContext || null; - const order = aOrder || SourceMapConsumer$1.GENERATED_ORDER; - - let mappings; - switch (order) { - case SourceMapConsumer$1.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer$1.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - const sourceRoot = this.sourceRoot; - mappings.map(function(mapping) { - let source = null; - if (mapping.source !== null) { - source = this._sources.at(mapping.source); - source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); - } - return { - source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name === null ? null : this._names.at(mapping.name) - }; - }, this).forEach(aCallback, context); - } - - /** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ - _findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator, aBias) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError("Line must be greater than or equal to 1, got " - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError("Column must be greater than or equal to 0, got " - + aNeedle[aColumnName]); - } - - return binarySearch.search(aNeedle, aMappings, aComparator, aBias); - } - - allGeneratedPositionsFor(aArgs) { - const line = util.getArg(aArgs, "line"); - - // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping - // returns the index of the closest mapping less than the needle. By - // setting needle.originalColumn to 0, we thus find the last mapping for - // the given line, provided such a mapping exists. - const needle = { - source: util.getArg(aArgs, "source"), - originalLine: line, - originalColumn: util.getArg(aArgs, "column", 0) - }; - - needle.source = this._findSourceIndex(needle.source); - if (needle.source < 0) { - return []; - } - - if (needle.originalLine < 1) { - throw new Error("Line numbers must be >= 1"); - } - - if (needle.originalColumn < 0) { - throw new Error("Column numbers must be >= 0"); - } - - const mappings = []; - - let index = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions, - binarySearch.LEAST_UPPER_BOUND); - if (index >= 0) { - let mapping = this._originalMappings[index]; - - if (aArgs.column === undefined) { - const originalLine = mapping.originalLine; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we found. Since - // mappings are sorted, this is guaranteed to find all mappings for - // the line we found. - while (mapping && mapping.originalLine === originalLine) { - let lastColumn = mapping.lastGeneratedColumn; - if (this._computedColumnSpans && lastColumn === null) { - lastColumn = Infinity; - } - mappings.push({ - line: util.getArg(mapping, "generatedLine", null), - column: util.getArg(mapping, "generatedColumn", null), - lastColumn, - }); - - mapping = this._originalMappings[++index]; - } - } else { - const originalColumn = mapping.originalColumn; - - // Iterate until either we run out of mappings, or we run into - // a mapping for a different line than the one we were searching for. - // Since mappings are sorted, this is guaranteed to find all mappings for - // the line we are searching for. - while (mapping && - mapping.originalLine === line && - mapping.originalColumn == originalColumn) { - let lastColumn = mapping.lastGeneratedColumn; - if (this._computedColumnSpans && lastColumn === null) { - lastColumn = Infinity; - } - mappings.push({ - line: util.getArg(mapping, "generatedLine", null), - column: util.getArg(mapping, "generatedColumn", null), - lastColumn, - }); - - mapping = this._originalMappings[++index]; - } - } - } - - return mappings; - } - - destroy() { - for (let i = 0; i < this._sections.length; i++) { - this._sections[i].consumer.destroy(); - } - } -} -var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer; - -/* - * Cheat to get around inter-twingled classes. `factory()` can be at the end - * where it has access to non-hoisted classes, but it gets hoisted itself. - */ -function _factory(aSourceMap, aSourceMapURL) { - let sourceMap = aSourceMap; - if (typeof aSourceMap === "string") { - sourceMap = util.parseSourceMapInput(aSourceMap); - } - - const consumer = sourceMap.sections != null - ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) - : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); - return Promise.resolve(consumer); -} - -function _factoryBSM(aSourceMap, aSourceMapURL) { - return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); -} - -var sourceMapConsumer = { - SourceMapConsumer: SourceMapConsumer_1, - BasicSourceMapConsumer: BasicSourceMapConsumer_1, - IndexedSourceMapConsumer: IndexedSourceMapConsumer_1 -}; - -/* -*- 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$1 = sourceMapGenerator.SourceMapGenerator; - - -// 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$1 { - 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$1(); - - // 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$1(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$1(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 }; - } -} - -var SourceNode_1 = SourceNode$1; - -var sourceNode = { - SourceNode: SourceNode_1 -}; - -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -var SourceMapGenerator = sourceMapGenerator.SourceMapGenerator; -var SourceMapConsumer = sourceMapConsumer.SourceMapConsumer; -var SourceNode = sourceNode.SourceNode; - -var sourceMap = { - SourceMapGenerator: SourceMapGenerator, - SourceMapConsumer: SourceMapConsumer, - SourceNode: SourceNode -}; - -var acorn = createCommonjsModule(function (module, exports) { -(function (global, factory) { - factory(exports) ; -}(commonjsGlobal, (function (exports) { - // Reserved word lists for various dialects of the language - - var reservedWords = { - 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", - 5: "class enum extends super const export import", - 6: "enum", - strict: "implements interface let package private protected public static yield", - strictBind: "eval arguments" - }; - - // And the keywords - - var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; - - var keywords = { - 5: ecma5AndLessKeywords, - "5module": ecma5AndLessKeywords + " export import", - 6: ecma5AndLessKeywords + " const class extends export import super" - }; - - var keywordRelationalOperator = /^in(stanceof)?$/; - - // ## Character categories - - // Big ugly regular expressions that match characters in the - // whitespace, identifier, and identifier-start categories. These - // are only applied when a character is found to actually have a - // code point above 128. - // Generated by `bin/generate-identifier-regex.js`. - var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; - var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; - - var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); - var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); - - nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; - - // These are a run-length and offset encoded representation of the - // >0xffff code points that are a valid part of identifiers. The - // offset starts at 0x10000, and each pair of numbers represents an - // offset to the next range, and then a size of the range. They were - // generated by bin/generate-identifier-regex.js - - // eslint-disable-next-line comma-spacing - var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938]; - - // eslint-disable-next-line comma-spacing - var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239]; - - // This has a complexity linear to the value of the code. The - // assumption is that looking up astral identifier characters is - // rare. - function isInAstralSet(code, set) { - var pos = 0x10000; - for (var i = 0; i < set.length; i += 2) { - pos += set[i]; - if (pos > code) { return false } - pos += set[i + 1]; - if (pos >= code) { return true } - } - } - - // Test whether a given character code starts an identifier. - - function isIdentifierStart(code, astral) { - if (code < 65) { return code === 36 } - if (code < 91) { return true } - if (code < 97) { return code === 95 } - if (code < 123) { return true } - if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } - if (astral === false) { return false } - return isInAstralSet(code, astralIdentifierStartCodes) - } - - // Test whether a given character is part of an identifier. - - function isIdentifierChar(code, astral) { - if (code < 48) { return code === 36 } - if (code < 58) { return true } - if (code < 65) { return false } - if (code < 91) { return true } - if (code < 97) { return code === 95 } - if (code < 123) { return true } - if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } - if (astral === false) { return false } - return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) - } - - // ## Token types - - // The assignment of fine-grained, information-carrying type objects - // allows the tokenizer to store the information it has about a - // token in a way that is very cheap for the parser to look up. - - // All token type variables start with an underscore, to make them - // easy to recognize. - - // The `beforeExpr` property is used to disambiguate between regular - // expressions and divisions. It is set on all token types that can - // be followed by an expression (thus, a slash after them would be a - // regular expression). - // - // The `startsExpr` property is used to check if the token ends a - // `yield` expression. It is set on all token types that either can - // directly start an expression (like a quotation mark) or can - // continue an expression (like the body of a string). - // - // `isLoop` marks a keyword as starting a loop, which is important - // to know when parsing a label, in order to allow or disallow - // continue jumps to that label. - - var TokenType = function TokenType(label, conf) { - if ( conf === void 0 ) conf = {}; - - this.label = label; - this.keyword = conf.keyword; - this.beforeExpr = !!conf.beforeExpr; - this.startsExpr = !!conf.startsExpr; - this.isLoop = !!conf.isLoop; - this.isAssign = !!conf.isAssign; - this.prefix = !!conf.prefix; - this.postfix = !!conf.postfix; - this.binop = conf.binop || null; - this.updateContext = null; - }; - - function binop(name, prec) { - return new TokenType(name, {beforeExpr: true, binop: prec}) - } - var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; - - // Map keyword names to token types. - - var keywords$1 = {}; - - // Succinct definitions of keyword token types - function kw(name, options) { - if ( options === void 0 ) options = {}; - - options.keyword = name; - return keywords$1[name] = new TokenType(name, options) - } - - var types = { - num: new TokenType("num", startsExpr), - regexp: new TokenType("regexp", startsExpr), - string: new TokenType("string", startsExpr), - name: new TokenType("name", startsExpr), - eof: new TokenType("eof"), - - // Punctuation token types. - bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), - bracketR: new TokenType("]"), - braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), - braceR: new TokenType("}"), - parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), - parenR: new TokenType(")"), - comma: new TokenType(",", beforeExpr), - semi: new TokenType(";", beforeExpr), - colon: new TokenType(":", beforeExpr), - dot: new TokenType("."), - question: new TokenType("?", beforeExpr), - questionDot: new TokenType("?."), - arrow: new TokenType("=>", beforeExpr), - template: new TokenType("template"), - invalidTemplate: new TokenType("invalidTemplate"), - ellipsis: new TokenType("...", beforeExpr), - backQuote: new TokenType("`", startsExpr), - dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), - - // Operators. These carry several kinds of properties to help the - // parser use them properly (the presence of these properties is - // what categorizes them as operators). - // - // `binop`, when present, specifies that this operator is a binary - // operator, and will refer to its precedence. - // - // `prefix` and `postfix` mark the operator as a prefix or postfix - // unary operator. - // - // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as - // binary operators with a very low precedence, that should result - // in AssignmentExpression nodes. - - eq: new TokenType("=", {beforeExpr: true, isAssign: true}), - assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), - incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), - prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), - logicalOR: binop("||", 1), - logicalAND: binop("&&", 2), - bitwiseOR: binop("|", 3), - bitwiseXOR: binop("^", 4), - bitwiseAND: binop("&", 5), - equality: binop("==/!=/===/!==", 6), - relational: binop("/<=/>=", 7), - bitShift: binop("<>/>>>", 8), - plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), - modulo: binop("%", 10), - star: binop("*", 10), - slash: binop("/", 10), - starstar: new TokenType("**", {beforeExpr: true}), - coalesce: binop("??", 1), - - // Keyword token types. - _break: kw("break"), - _case: kw("case", beforeExpr), - _catch: kw("catch"), - _continue: kw("continue"), - _debugger: kw("debugger"), - _default: kw("default", beforeExpr), - _do: kw("do", {isLoop: true, beforeExpr: true}), - _else: kw("else", beforeExpr), - _finally: kw("finally"), - _for: kw("for", {isLoop: true}), - _function: kw("function", startsExpr), - _if: kw("if"), - _return: kw("return", beforeExpr), - _switch: kw("switch"), - _throw: kw("throw", beforeExpr), - _try: kw("try"), - _var: kw("var"), - _const: kw("const"), - _while: kw("while", {isLoop: true}), - _with: kw("with"), - _new: kw("new", {beforeExpr: true, startsExpr: true}), - _this: kw("this", startsExpr), - _super: kw("super", startsExpr), - _class: kw("class", startsExpr), - _extends: kw("extends", beforeExpr), - _export: kw("export"), - _import: kw("import", startsExpr), - _null: kw("null", startsExpr), - _true: kw("true", startsExpr), - _false: kw("false", startsExpr), - _in: kw("in", {beforeExpr: true, binop: 7}), - _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), - _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), - _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), - _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) - }; - - // Matches a whole line break (where CRLF is considered a single - // line break). Used to count lines. - - var lineBreak = /\r\n?|\n|\u2028|\u2029/; - var lineBreakG = new RegExp(lineBreak.source, "g"); - - function isNewLine(code, ecma2019String) { - return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) - } - - var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; - - var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; - - var ref = Object.prototype; - var hasOwnProperty = ref.hasOwnProperty; - var toString = ref.toString; - - // Checks if an object has a property. - - function has(obj, propName) { - return hasOwnProperty.call(obj, propName) - } - - var isArray = Array.isArray || (function (obj) { return ( - toString.call(obj) === "[object Array]" - ); }); - - function wordsRegexp(words) { - return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") - } - - // These are used when `options.locations` is on, for the - // `startLoc` and `endLoc` properties. - - var Position = function Position(line, col) { - this.line = line; - this.column = col; - }; - - Position.prototype.offset = function offset (n) { - return new Position(this.line, this.column + n) - }; - - var SourceLocation = function SourceLocation(p, start, end) { - this.start = start; - this.end = end; - if (p.sourceFile !== null) { this.source = p.sourceFile; } - }; - - // The `getLineInfo` function is mostly useful when the - // `locations` option is off (for performance reasons) and you - // want to find the line/column position for a given character - // offset. `input` should be the code string that the offset refers - // into. - - function getLineInfo(input, offset) { - for (var line = 1, cur = 0;;) { - lineBreakG.lastIndex = cur; - var match = lineBreakG.exec(input); - if (match && match.index < offset) { - ++line; - cur = match.index + match[0].length; - } else { - return new Position(line, offset - cur) - } - } - } - - // A second argument must be given to configure the parser process. - // These options are recognized (only `ecmaVersion` is required): - - var defaultOptions = { - // `ecmaVersion` indicates the ECMAScript version to parse. Must be - // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 - // (2019), 11 (2020), 12 (2021), or `"latest"` (the latest version - // the library supports). This influences support for strict mode, - // the set of reserved words, and support for new syntax features. - ecmaVersion: null, - // `sourceType` indicates the mode the code should be parsed in. - // Can be either `"script"` or `"module"`. This influences global - // strict mode and parsing of `import` and `export` declarations. - sourceType: "script", - // `onInsertedSemicolon` can be a callback that will be called - // when a semicolon is automatically inserted. It will be passed - // the position of the comma as an offset, and if `locations` is - // enabled, it is given the location as a `{line, column}` object - // as second argument. - onInsertedSemicolon: null, - // `onTrailingComma` is similar to `onInsertedSemicolon`, but for - // trailing commas. - onTrailingComma: null, - // By default, reserved words are only enforced if ecmaVersion >= 5. - // Set `allowReserved` to a boolean value to explicitly turn this on - // an off. When this option has the value "never", reserved words - // and keywords can also not be used as property names. - allowReserved: null, - // When enabled, a return at the top level is not considered an - // error. - allowReturnOutsideFunction: false, - // When enabled, import/export statements are not constrained to - // appearing at the top of the program, and an import.meta expression - // in a script isn't considered an error. - allowImportExportEverywhere: false, - // When enabled, await identifiers are allowed to appear at the top-level scope, - // but they are still not allowed in non-async functions. - allowAwaitOutsideFunction: false, - // When enabled, hashbang directive in the beginning of file - // is allowed and treated as a line comment. - allowHashBang: false, - // When `locations` is on, `loc` properties holding objects with - // `start` and `end` properties in `{line, column}` form (with - // line being 1-based and column 0-based) will be attached to the - // nodes. - locations: false, - // A function can be passed as `onToken` option, which will - // cause Acorn to call that function with object in the same - // format as tokens returned from `tokenizer().getToken()`. Note - // that you are not allowed to call the parser from the - // callback—that will corrupt its internal state. - onToken: null, - // A function can be passed as `onComment` option, which will - // cause Acorn to call that function with `(block, text, start, - // end)` parameters whenever a comment is skipped. `block` is a - // boolean indicating whether this is a block (`/* */`) comment, - // `text` is the content of the comment, and `start` and `end` are - // character offsets that denote the start and end of the comment. - // When the `locations` option is on, two more parameters are - // passed, the full `{line, column}` locations of the start and - // end of the comments. Note that you are not allowed to call the - // parser from the callback—that will corrupt its internal state. - onComment: null, - // Nodes have their start and end characters offsets recorded in - // `start` and `end` properties (directly on the node, rather than - // the `loc` object, which holds line/column data. To also add a - // [semi-standardized][range] `range` property holding a `[start, - // end]` array with the same numbers, set the `ranges` option to - // `true`. - // - // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 - ranges: false, - // It is possible to parse multiple files into a single AST by - // passing the tree produced by parsing the first file as - // `program` option in subsequent parses. This will add the - // toplevel forms of the parsed file to the `Program` (top) node - // of an existing parse tree. - program: null, - // When `locations` is on, you can pass this to record the source - // file in every node's `loc` object. - sourceFile: null, - // This value, if given, is stored in every node, whether - // `locations` is on or off. - directSourceFile: null, - // When enabled, parenthesized expressions are represented by - // (non-standard) ParenthesizedExpression nodes - preserveParens: false - }; - - // Interpret and default an options object - - var warnedAboutEcmaVersion = false; - - function getOptions(opts) { - var options = {}; - - for (var opt in defaultOptions) - { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } - - if (options.ecmaVersion === "latest") { - options.ecmaVersion = 1e8; - } else if (options.ecmaVersion == null) { - if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { - warnedAboutEcmaVersion = true; - console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); - } - options.ecmaVersion = 11; - } else if (options.ecmaVersion >= 2015) { - options.ecmaVersion -= 2009; - } - - if (options.allowReserved == null) - { options.allowReserved = options.ecmaVersion < 5; } - - if (isArray(options.onToken)) { - var tokens = options.onToken; - options.onToken = function (token) { return tokens.push(token); }; - } - if (isArray(options.onComment)) - { options.onComment = pushComment(options, options.onComment); } - - return options - } - - function pushComment(options, array) { - return function(block, text, start, end, startLoc, endLoc) { - var comment = { - type: block ? "Block" : "Line", - value: text, - start: start, - end: end - }; - if (options.locations) - { comment.loc = new SourceLocation(this, startLoc, endLoc); } - if (options.ranges) - { comment.range = [start, end]; } - array.push(comment); - } - } - - // Each scope gets a bitset that may contain these flags - var - SCOPE_TOP = 1, - SCOPE_FUNCTION = 2, - SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION, - SCOPE_ASYNC = 4, - SCOPE_GENERATOR = 8, - SCOPE_ARROW = 16, - SCOPE_SIMPLE_CATCH = 32, - SCOPE_SUPER = 64, - SCOPE_DIRECT_SUPER = 128; - - function functionFlags(async, generator) { - return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) - } - - // Used in checkLVal* and declareName to determine the type of a binding - var - BIND_NONE = 0, // Not a binding - BIND_VAR = 1, // Var-style binding - BIND_LEXICAL = 2, // Let- or const-style binding - BIND_FUNCTION = 3, // Function declaration - BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding - BIND_OUTSIDE = 5; // Special case for function names as bound inside the function - - var Parser = function Parser(options, input, startPos) { - this.options = options = getOptions(options); - this.sourceFile = options.sourceFile; - this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); - var reserved = ""; - if (options.allowReserved !== true) { - reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; - if (options.sourceType === "module") { reserved += " await"; } - } - this.reservedWords = wordsRegexp(reserved); - var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; - this.reservedWordsStrict = wordsRegexp(reservedStrict); - this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); - this.input = String(input); - - // Used to signal to callers of `readWord1` whether the word - // contained any escape sequences. This is needed because words with - // escape sequences must not be interpreted as keywords. - this.containsEsc = false; - - // Set up token state - - // The current position of the tokenizer in the input. - if (startPos) { - this.pos = startPos; - this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; - this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; - } else { - this.pos = this.lineStart = 0; - this.curLine = 1; - } - - // Properties of the current token: - // Its type - this.type = types.eof; - // For tokens that include more information than their type, the value - this.value = null; - // Its start and end offset - this.start = this.end = this.pos; - // And, if locations are used, the {line, column} object - // corresponding to those offsets - this.startLoc = this.endLoc = this.curPosition(); - - // Position information for the previous token - this.lastTokEndLoc = this.lastTokStartLoc = null; - this.lastTokStart = this.lastTokEnd = this.pos; - - // The context stack is used to superficially track syntactic - // context to predict whether a regular expression is allowed in a - // given position. - this.context = this.initialContext(); - this.exprAllowed = true; - - // Figure out if it's a module code. - this.inModule = options.sourceType === "module"; - this.strict = this.inModule || this.strictDirective(this.pos); - - // Used to signify the start of a potential arrow function - this.potentialArrowAt = -1; - - // Positions to delayed-check that yield/await does not exist in default parameters. - this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; - // Labels in scope. - this.labels = []; - // Thus-far undefined exports. - this.undefinedExports = Object.create(null); - - // If enabled, skip leading hashbang line. - if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") - { this.skipLineComment(2); } - - // Scope tracking for duplicate variable names (see scope.js) - this.scopeStack = []; - this.enterScope(SCOPE_TOP); - - // For RegExp validation - this.regexpState = null; - }; - - var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } }; - - Parser.prototype.parse = function parse () { - var node = this.options.program || this.startNode(); - this.nextToken(); - return this.parseTopLevel(node) - }; - - prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; - prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 }; - prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }; - prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 }; - prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; - prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; - prototypeAccessors.inNonArrowFunction.get = function () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }; - - Parser.extend = function extend () { - var plugins = [], len = arguments.length; - while ( len-- ) plugins[ len ] = arguments[ len ]; - - var cls = this; - for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } - return cls - }; - - Parser.parse = function parse (input, options) { - return new this(options, input).parse() - }; - - Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { - var parser = new this(options, input, pos); - parser.nextToken(); - return parser.parseExpression() - }; - - Parser.tokenizer = function tokenizer (input, options) { - return new this(options, input) - }; - - Object.defineProperties( Parser.prototype, prototypeAccessors ); - - var pp = Parser.prototype; - - // ## Parser utilities - - var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; - pp.strictDirective = function(start) { - for (;;) { - // Try to find string literal. - skipWhiteSpace.lastIndex = start; - start += skipWhiteSpace.exec(this.input)[0].length; - var match = literal.exec(this.input.slice(start)); - if (!match) { return false } - if ((match[1] || match[2]) === "use strict") { - skipWhiteSpace.lastIndex = start + match[0].length; - var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; - var next = this.input.charAt(end); - return next === ";" || next === "}" || - (lineBreak.test(spaceAfter[0]) && - !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) - } - start += match[0].length; - - // Skip semicolon, if any. - skipWhiteSpace.lastIndex = start; - start += skipWhiteSpace.exec(this.input)[0].length; - if (this.input[start] === ";") - { start++; } - } - }; - - // Predicate that tests whether the next token is of the given - // type, and if yes, consumes it as a side effect. - - pp.eat = function(type) { - if (this.type === type) { - this.next(); - return true - } else { - return false - } - }; - - // Tests whether parsed token is a contextual keyword. - - pp.isContextual = function(name) { - return this.type === types.name && this.value === name && !this.containsEsc - }; - - // Consumes contextual keyword if possible. - - pp.eatContextual = function(name) { - if (!this.isContextual(name)) { return false } - this.next(); - return true - }; - - // Asserts that following token is given contextual keyword. - - pp.expectContextual = function(name) { - if (!this.eatContextual(name)) { this.unexpected(); } - }; - - // Test whether a semicolon can be inserted at the current position. - - pp.canInsertSemicolon = function() { - return this.type === types.eof || - this.type === types.braceR || - lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) - }; - - pp.insertSemicolon = function() { - if (this.canInsertSemicolon()) { - if (this.options.onInsertedSemicolon) - { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } - return true - } - }; - - // Consume a semicolon, or, failing that, see if we are allowed to - // pretend that there is a semicolon at this position. - - pp.semicolon = function() { - if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } - }; - - pp.afterTrailingComma = function(tokType, notNext) { - if (this.type === tokType) { - if (this.options.onTrailingComma) - { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } - if (!notNext) - { this.next(); } - return true - } - }; - - // Expect a token of a given type. If found, consume it, otherwise, - // raise an unexpected token error. - - pp.expect = function(type) { - this.eat(type) || this.unexpected(); - }; - - // Raise an unexpected token error. - - pp.unexpected = function(pos) { - this.raise(pos != null ? pos : this.start, "Unexpected token"); - }; - - function DestructuringErrors() { - this.shorthandAssign = - this.trailingComma = - this.parenthesizedAssign = - this.parenthesizedBind = - this.doubleProto = - -1; - } - - pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { - if (!refDestructuringErrors) { return } - if (refDestructuringErrors.trailingComma > -1) - { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } - var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; - if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } - }; - - pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { - if (!refDestructuringErrors) { return false } - var shorthandAssign = refDestructuringErrors.shorthandAssign; - var doubleProto = refDestructuringErrors.doubleProto; - if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } - if (shorthandAssign >= 0) - { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } - if (doubleProto >= 0) - { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } - }; - - pp.checkYieldAwaitInDefaultParams = function() { - if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) - { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } - if (this.awaitPos) - { this.raise(this.awaitPos, "Await expression cannot be a default value"); } - }; - - pp.isSimpleAssignTarget = function(expr) { - if (expr.type === "ParenthesizedExpression") - { return this.isSimpleAssignTarget(expr.expression) } - return expr.type === "Identifier" || expr.type === "MemberExpression" - }; - - var pp$1 = Parser.prototype; - - // ### Statement parsing - - // Parse a program. Initializes the parser, reads any number of - // statements, and wraps them in a Program node. Optionally takes a - // `program` argument. If present, the statements will be appended - // to its body instead of creating a new node. - - pp$1.parseTopLevel = function(node) { - var exports = Object.create(null); - if (!node.body) { node.body = []; } - while (this.type !== types.eof) { - var stmt = this.parseStatement(null, true, exports); - node.body.push(stmt); - } - if (this.inModule) - { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) - { - var name = list[i]; - - this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); - } } - this.adaptDirectivePrologue(node.body); - this.next(); - node.sourceType = this.options.sourceType; - return this.finishNode(node, "Program") - }; - - var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; - - pp$1.isLet = function(context) { - if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); - // For ambiguous cases, determine if a LexicalDeclaration (or only a - // Statement) is allowed here. If context is not empty then only a Statement - // is allowed. However, `let [` is an explicit negative lookahead for - // ExpressionStatement, so special-case it first. - if (nextCh === 91) { return true } // '[' - if (context) { return false } - - if (nextCh === 123) { return true } // '{' - if (isIdentifierStart(nextCh, true)) { - var pos = next + 1; - while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; } - var ident = this.input.slice(next, pos); - if (!keywordRelationalOperator.test(ident)) { return true } - } - return false - }; - - // check 'async [no LineTerminator here] function' - // - 'async /*foo*/ function' is OK. - // - 'async /*\n*/ function' is invalid. - pp$1.isAsyncFunction = function() { - if (this.options.ecmaVersion < 8 || !this.isContextual("async")) - { return false } - - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length; - return !lineBreak.test(this.input.slice(this.pos, next)) && - this.input.slice(next, next + 8) === "function" && - (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) - }; - - // Parse a single statement. - // - // If expecting a statement and finding a slash operator, parse a - // regular expression literal. This is to handle cases like - // `if (foo) /blah/.exec(foo)`, where looking at the previous token - // does not help. - - pp$1.parseStatement = function(context, topLevel, exports) { - var starttype = this.type, node = this.startNode(), kind; - - if (this.isLet(context)) { - starttype = types._var; - kind = "let"; - } - - // Most types of statements are recognized by the keyword they - // start with. Many are trivial to parse, some require a bit of - // complexity. - - switch (starttype) { - case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) - case types._debugger: return this.parseDebuggerStatement(node) - case types._do: return this.parseDoStatement(node) - case types._for: return this.parseForStatement(node) - case types._function: - // Function as sole body of either an if statement or a labeled statement - // works, but not when it is part of a labeled statement that is the sole - // body of an if statement. - if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } - return this.parseFunctionStatement(node, false, !context) - case types._class: - if (context) { this.unexpected(); } - return this.parseClass(node, true) - case types._if: return this.parseIfStatement(node) - case types._return: return this.parseReturnStatement(node) - case types._switch: return this.parseSwitchStatement(node) - case types._throw: return this.parseThrowStatement(node) - case types._try: return this.parseTryStatement(node) - case types._const: case types._var: - kind = kind || this.value; - if (context && kind !== "var") { this.unexpected(); } - return this.parseVarStatement(node, kind) - case types._while: return this.parseWhileStatement(node) - case types._with: return this.parseWithStatement(node) - case types.braceL: return this.parseBlock(true, node) - case types.semi: return this.parseEmptyStatement(node) - case types._export: - case types._import: - if (this.options.ecmaVersion > 10 && starttype === types._import) { - skipWhiteSpace.lastIndex = this.pos; - var skip = skipWhiteSpace.exec(this.input); - var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); - if (nextCh === 40 || nextCh === 46) // '(' or '.' - { return this.parseExpressionStatement(node, this.parseExpression()) } - } - - if (!this.options.allowImportExportEverywhere) { - if (!topLevel) - { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } - if (!this.inModule) - { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } - } - return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports) - - // If the statement does not start with a statement keyword or a - // brace, it's an ExpressionStatement or LabeledStatement. We - // simply start parsing an expression, and afterwards, if the - // next token is a colon and the expression was a simple - // Identifier node, we switch to interpreting it as a label. - default: - if (this.isAsyncFunction()) { - if (context) { this.unexpected(); } - this.next(); - return this.parseFunctionStatement(node, true, !context) - } - - var maybeName = this.value, expr = this.parseExpression(); - if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) - { return this.parseLabeledStatement(node, maybeName, expr, context) } - else { return this.parseExpressionStatement(node, expr) } - } - }; - - pp$1.parseBreakContinueStatement = function(node, keyword) { - var isBreak = keyword === "break"; - this.next(); - if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } - else if (this.type !== types.name) { this.unexpected(); } - else { - node.label = this.parseIdent(); - this.semicolon(); - } - - // Verify that there is an actual destination to break or - // continue to. - var i = 0; - for (; i < this.labels.length; ++i) { - var lab = this.labels[i]; - if (node.label == null || lab.name === node.label.name) { - if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } - if (node.label && isBreak) { break } - } - } - if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } - return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") - }; - - pp$1.parseDebuggerStatement = function(node) { - this.next(); - this.semicolon(); - return this.finishNode(node, "DebuggerStatement") - }; - - pp$1.parseDoStatement = function(node) { - this.next(); - this.labels.push(loopLabel); - node.body = this.parseStatement("do"); - this.labels.pop(); - this.expect(types._while); - node.test = this.parseParenExpression(); - if (this.options.ecmaVersion >= 6) - { this.eat(types.semi); } - else - { this.semicolon(); } - return this.finishNode(node, "DoWhileStatement") - }; - - // Disambiguating between a `for` and a `for`/`in` or `for`/`of` - // loop is non-trivial. Basically, we have to parse the init `var` - // statement or expression, disallowing the `in` operator (see - // the second parameter to `parseExpression`), and then check - // whether the next token is `in` or `of`. When there is no init - // part (semicolon immediately after the opening parenthesis), it - // is a regular `for` loop. - - pp$1.parseForStatement = function(node) { - this.next(); - var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1; - this.labels.push(loopLabel); - this.enterScope(0); - this.expect(types.parenL); - if (this.type === types.semi) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, null) - } - var isLet = this.isLet(); - if (this.type === types._var || this.type === types._const || isLet) { - var init$1 = this.startNode(), kind = isLet ? "let" : this.value; - this.next(); - this.parseVar(init$1, true, kind); - this.finishNode(init$1, "VariableDeclaration"); - if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { - if (this.options.ecmaVersion >= 9) { - if (this.type === types._in) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - } else { node.await = awaitAt > -1; } - } - return this.parseForIn(node, init$1) - } - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, init$1) - } - var refDestructuringErrors = new DestructuringErrors; - var init = this.parseExpression(true, refDestructuringErrors); - if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { - if (this.options.ecmaVersion >= 9) { - if (this.type === types._in) { - if (awaitAt > -1) { this.unexpected(awaitAt); } - } else { node.await = awaitAt > -1; } - } - this.toAssignable(init, false, refDestructuringErrors); - this.checkLValPattern(init); - return this.parseForIn(node, init) - } else { - this.checkExpressionErrors(refDestructuringErrors, true); - } - if (awaitAt > -1) { this.unexpected(awaitAt); } - return this.parseFor(node, init) - }; - - pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { - this.next(); - return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) - }; - - pp$1.parseIfStatement = function(node) { - this.next(); - node.test = this.parseParenExpression(); - // allow function declarations in branches, but only in non-strict mode - node.consequent = this.parseStatement("if"); - node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; - return this.finishNode(node, "IfStatement") - }; - - pp$1.parseReturnStatement = function(node) { - if (!this.inFunction && !this.options.allowReturnOutsideFunction) - { this.raise(this.start, "'return' outside of function"); } - this.next(); - - // In `return` (and `break`/`continue`), the keywords with - // optional arguments, we eagerly look for a semicolon or the - // possibility to insert one. - - if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } - else { node.argument = this.parseExpression(); this.semicolon(); } - return this.finishNode(node, "ReturnStatement") - }; - - pp$1.parseSwitchStatement = function(node) { - this.next(); - node.discriminant = this.parseParenExpression(); - node.cases = []; - this.expect(types.braceL); - this.labels.push(switchLabel); - this.enterScope(0); - - // Statements under must be grouped (by label) in SwitchCase - // nodes. `cur` is used to keep the node that we are currently - // adding statements to. - - var cur; - for (var sawDefault = false; this.type !== types.braceR;) { - if (this.type === types._case || this.type === types._default) { - var isCase = this.type === types._case; - if (cur) { this.finishNode(cur, "SwitchCase"); } - node.cases.push(cur = this.startNode()); - cur.consequent = []; - this.next(); - if (isCase) { - cur.test = this.parseExpression(); - } else { - if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } - sawDefault = true; - cur.test = null; - } - this.expect(types.colon); - } else { - if (!cur) { this.unexpected(); } - cur.consequent.push(this.parseStatement(null)); - } - } - this.exitScope(); - if (cur) { this.finishNode(cur, "SwitchCase"); } - this.next(); // Closing brace - this.labels.pop(); - return this.finishNode(node, "SwitchStatement") - }; - - pp$1.parseThrowStatement = function(node) { - this.next(); - if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) - { this.raise(this.lastTokEnd, "Illegal newline after throw"); } - node.argument = this.parseExpression(); - this.semicolon(); - return this.finishNode(node, "ThrowStatement") - }; - - // Reused empty array added for node fields that are always empty. - - var empty = []; - - pp$1.parseTryStatement = function(node) { - this.next(); - node.block = this.parseBlock(); - node.handler = null; - if (this.type === types._catch) { - var clause = this.startNode(); - this.next(); - if (this.eat(types.parenL)) { - clause.param = this.parseBindingAtom(); - var simple = clause.param.type === "Identifier"; - this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); - this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); - this.expect(types.parenR); - } else { - if (this.options.ecmaVersion < 10) { this.unexpected(); } - clause.param = null; - this.enterScope(0); - } - clause.body = this.parseBlock(false); - this.exitScope(); - node.handler = this.finishNode(clause, "CatchClause"); - } - node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; - if (!node.handler && !node.finalizer) - { this.raise(node.start, "Missing catch or finally clause"); } - return this.finishNode(node, "TryStatement") - }; - - pp$1.parseVarStatement = function(node, kind) { - this.next(); - this.parseVar(node, false, kind); - this.semicolon(); - return this.finishNode(node, "VariableDeclaration") - }; - - pp$1.parseWhileStatement = function(node) { - this.next(); - node.test = this.parseParenExpression(); - this.labels.push(loopLabel); - node.body = this.parseStatement("while"); - this.labels.pop(); - return this.finishNode(node, "WhileStatement") - }; - - pp$1.parseWithStatement = function(node) { - if (this.strict) { this.raise(this.start, "'with' in strict mode"); } - this.next(); - node.object = this.parseParenExpression(); - node.body = this.parseStatement("with"); - return this.finishNode(node, "WithStatement") - }; - - pp$1.parseEmptyStatement = function(node) { - this.next(); - return this.finishNode(node, "EmptyStatement") - }; - - pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { - for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) - { - var label = list[i$1]; - - if (label.name === maybeName) - { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); - } } - var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; - for (var i = this.labels.length - 1; i >= 0; i--) { - var label$1 = this.labels[i]; - if (label$1.statementStart === node.start) { - // Update information about previous labels on this node - label$1.statementStart = this.start; - label$1.kind = kind; - } else { break } - } - this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); - node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); - this.labels.pop(); - node.label = expr; - return this.finishNode(node, "LabeledStatement") - }; - - pp$1.parseExpressionStatement = function(node, expr) { - node.expression = expr; - this.semicolon(); - return this.finishNode(node, "ExpressionStatement") - }; - - // Parse a semicolon-enclosed block of statements, handling `"use - // strict"` declarations when `allowStrict` is true (used for - // function bodies). - - pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) { - if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; - if ( node === void 0 ) node = this.startNode(); - - node.body = []; - this.expect(types.braceL); - if (createNewLexicalScope) { this.enterScope(0); } - while (this.type !== types.braceR) { - var stmt = this.parseStatement(null); - node.body.push(stmt); - } - if (exitStrict) { this.strict = false; } - this.next(); - if (createNewLexicalScope) { this.exitScope(); } - return this.finishNode(node, "BlockStatement") - }; - - // Parse a regular `for` loop. The disambiguation code in - // `parseStatement` will already have parsed the init statement or - // expression. - - pp$1.parseFor = function(node, init) { - node.init = init; - this.expect(types.semi); - node.test = this.type === types.semi ? null : this.parseExpression(); - this.expect(types.semi); - node.update = this.type === types.parenR ? null : this.parseExpression(); - this.expect(types.parenR); - node.body = this.parseStatement("for"); - this.exitScope(); - this.labels.pop(); - return this.finishNode(node, "ForStatement") - }; - - // Parse a `for`/`in` and `for`/`of` loop, which are almost - // same from parser's perspective. - - pp$1.parseForIn = function(node, init) { - var isForIn = this.type === types._in; - this.next(); - - if ( - init.type === "VariableDeclaration" && - init.declarations[0].init != null && - ( - !isForIn || - this.options.ecmaVersion < 8 || - this.strict || - init.kind !== "var" || - init.declarations[0].id.type !== "Identifier" - ) - ) { - this.raise( - init.start, - ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") - ); - } - node.left = init; - node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); - this.expect(types.parenR); - node.body = this.parseStatement("for"); - this.exitScope(); - this.labels.pop(); - return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") - }; - - // Parse a list of variable declarations. - - pp$1.parseVar = function(node, isFor, kind) { - node.declarations = []; - node.kind = kind; - for (;;) { - var decl = this.startNode(); - this.parseVarId(decl, kind); - if (this.eat(types.eq)) { - decl.init = this.parseMaybeAssign(isFor); - } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { - this.unexpected(); - } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) { - this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); - } else { - decl.init = null; - } - node.declarations.push(this.finishNode(decl, "VariableDeclarator")); - if (!this.eat(types.comma)) { break } - } - return node - }; - - pp$1.parseVarId = function(decl, kind) { - decl.id = this.parseBindingAtom(); - this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); - }; - - var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; - - // Parse a function declaration or literal (depending on the - // `statement & FUNC_STATEMENT`). - - // Remove `allowExpressionBody` for 7.0.0, as it is only called with false - pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) { - this.initFunction(node); - if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { - if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT)) - { this.unexpected(); } - node.generator = this.eat(types.star); - } - if (this.options.ecmaVersion >= 8) - { node.async = !!isAsync; } - - if (statement & FUNC_STATEMENT) { - node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); - if (node.id && !(statement & FUNC_HANGING_STATEMENT)) - // If it is a regular function declaration in sloppy mode, then it is - // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding - // mode depends on properties of the current scope (see - // treatFunctionsAsVar). - { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } - } - - var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - this.enterScope(functionFlags(node.async, node.generator)); - - if (!(statement & FUNC_STATEMENT)) - { node.id = this.type === types.name ? this.parseIdent() : null; } - - this.parseFunctionParams(node); - this.parseFunctionBody(node, allowExpressionBody, false); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") - }; - - pp$1.parseFunctionParams = function(node) { - this.expect(types.parenL); - node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); - this.checkYieldAwaitInDefaultParams(); - }; - - // Parse a class declaration or literal (depending on the - // `isStatement` parameter). - - pp$1.parseClass = function(node, isStatement) { - this.next(); - - // ecma-262 14.6 Class Definitions - // A class definition is always strict mode code. - var oldStrict = this.strict; - this.strict = true; - - this.parseClassId(node, isStatement); - this.parseClassSuper(node); - var classBody = this.startNode(); - var hadConstructor = false; - classBody.body = []; - this.expect(types.braceL); - while (this.type !== types.braceR) { - var element = this.parseClassElement(node.superClass !== null); - if (element) { - classBody.body.push(element); - if (element.type === "MethodDefinition" && element.kind === "constructor") { - if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); } - hadConstructor = true; - } - } - } - this.strict = oldStrict; - this.next(); - node.body = this.finishNode(classBody, "ClassBody"); - return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") - }; - - pp$1.parseClassElement = function(constructorAllowsSuper) { - var this$1 = this; - - if (this.eat(types.semi)) { return null } - - var method = this.startNode(); - var tryContextual = function (k, noLineBreak) { - if ( noLineBreak === void 0 ) noLineBreak = false; - - var start = this$1.start, startLoc = this$1.startLoc; - if (!this$1.eatContextual(k)) { return false } - if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true } - if (method.key) { this$1.unexpected(); } - method.computed = false; - method.key = this$1.startNodeAt(start, startLoc); - method.key.name = k; - this$1.finishNode(method.key, "Identifier"); - return false - }; - - method.kind = "method"; - method.static = tryContextual("static"); - var isGenerator = this.eat(types.star); - var isAsync = false; - if (!isGenerator) { - if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) { - isAsync = true; - isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); - } else if (tryContextual("get")) { - method.kind = "get"; - } else if (tryContextual("set")) { - method.kind = "set"; - } - } - if (!method.key) { this.parsePropertyName(method); } - var key = method.key; - var allowsDirectSuper = false; - if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || - key.type === "Literal" && key.value === "constructor")) { - if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); } - if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } - if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } - method.kind = "constructor"; - allowsDirectSuper = constructorAllowsSuper; - } else if (method.static && key.type === "Identifier" && key.name === "prototype") { - this.raise(key.start, "Classes may not have a static property named prototype"); - } - this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper); - if (method.kind === "get" && method.value.params.length !== 0) - { this.raiseRecoverable(method.value.start, "getter should have no params"); } - if (method.kind === "set" && method.value.params.length !== 1) - { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); } - if (method.kind === "set" && method.value.params[0].type === "RestElement") - { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); } - return method - }; - - pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { - method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); - return this.finishNode(method, "MethodDefinition") - }; - - pp$1.parseClassId = function(node, isStatement) { - if (this.type === types.name) { - node.id = this.parseIdent(); - if (isStatement) - { this.checkLValSimple(node.id, BIND_LEXICAL, false); } - } else { - if (isStatement === true) - { this.unexpected(); } - node.id = null; - } - }; - - pp$1.parseClassSuper = function(node) { - node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; - }; - - // Parses module export declaration. - - pp$1.parseExport = function(node, exports) { - this.next(); - // export * from '...' - if (this.eat(types.star)) { - if (this.options.ecmaVersion >= 11) { - if (this.eatContextual("as")) { - node.exported = this.parseIdent(true); - this.checkExport(exports, node.exported.name, this.lastTokStart); - } else { - node.exported = null; - } - } - this.expectContextual("from"); - if (this.type !== types.string) { this.unexpected(); } - node.source = this.parseExprAtom(); - this.semicolon(); - return this.finishNode(node, "ExportAllDeclaration") - } - if (this.eat(types._default)) { // export default ... - this.checkExport(exports, "default", this.lastTokStart); - var isAsync; - if (this.type === types._function || (isAsync = this.isAsyncFunction())) { - var fNode = this.startNode(); - this.next(); - if (isAsync) { this.next(); } - node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); - } else if (this.type === types._class) { - var cNode = this.startNode(); - node.declaration = this.parseClass(cNode, "nullableID"); - } else { - node.declaration = this.parseMaybeAssign(); - this.semicolon(); - } - return this.finishNode(node, "ExportDefaultDeclaration") - } - // export var|const|let|function|class ... - if (this.shouldParseExportStatement()) { - node.declaration = this.parseStatement(null); - if (node.declaration.type === "VariableDeclaration") - { this.checkVariableExport(exports, node.declaration.declarations); } - else - { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } - node.specifiers = []; - node.source = null; - } else { // export { x, y as z } [from '...'] - node.declaration = null; - node.specifiers = this.parseExportSpecifiers(exports); - if (this.eatContextual("from")) { - if (this.type !== types.string) { this.unexpected(); } - node.source = this.parseExprAtom(); - } else { - for (var i = 0, list = node.specifiers; i < list.length; i += 1) { - // check for keywords used as local names - var spec = list[i]; - - this.checkUnreserved(spec.local); - // check if export is defined - this.checkLocalExport(spec.local); - } - - node.source = null; - } - this.semicolon(); - } - return this.finishNode(node, "ExportNamedDeclaration") - }; - - pp$1.checkExport = function(exports, name, pos) { - if (!exports) { return } - if (has(exports, name)) - { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } - exports[name] = true; - }; - - pp$1.checkPatternExport = function(exports, pat) { - var type = pat.type; - if (type === "Identifier") - { this.checkExport(exports, pat.name, pat.start); } - else if (type === "ObjectPattern") - { for (var i = 0, list = pat.properties; i < list.length; i += 1) - { - var prop = list[i]; - - this.checkPatternExport(exports, prop); - } } - else if (type === "ArrayPattern") - { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { - var elt = list$1[i$1]; - - if (elt) { this.checkPatternExport(exports, elt); } - } } - else if (type === "Property") - { this.checkPatternExport(exports, pat.value); } - else if (type === "AssignmentPattern") - { this.checkPatternExport(exports, pat.left); } - else if (type === "RestElement") - { this.checkPatternExport(exports, pat.argument); } - else if (type === "ParenthesizedExpression") - { this.checkPatternExport(exports, pat.expression); } - }; - - pp$1.checkVariableExport = function(exports, decls) { - if (!exports) { return } - for (var i = 0, list = decls; i < list.length; i += 1) - { - var decl = list[i]; - - this.checkPatternExport(exports, decl.id); - } - }; - - pp$1.shouldParseExportStatement = function() { - return this.type.keyword === "var" || - this.type.keyword === "const" || - this.type.keyword === "class" || - this.type.keyword === "function" || - this.isLet() || - this.isAsyncFunction() - }; - - // Parses a comma-separated list of module exports. - - pp$1.parseExportSpecifiers = function(exports) { - var nodes = [], first = true; - // export { x, y as z } [from '...'] - this.expect(types.braceL); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } - - var node = this.startNode(); - node.local = this.parseIdent(true); - node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local; - this.checkExport(exports, node.exported.name, node.exported.start); - nodes.push(this.finishNode(node, "ExportSpecifier")); - } - return nodes - }; - - // Parses import declaration. - - pp$1.parseImport = function(node) { - this.next(); - // import '...' - if (this.type === types.string) { - node.specifiers = empty; - node.source = this.parseExprAtom(); - } else { - node.specifiers = this.parseImportSpecifiers(); - this.expectContextual("from"); - node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); - } - this.semicolon(); - return this.finishNode(node, "ImportDeclaration") - }; - - // Parses a comma-separated list of module imports. - - pp$1.parseImportSpecifiers = function() { - var nodes = [], first = true; - if (this.type === types.name) { - // import defaultObj, { x, y as z } from '...' - var node = this.startNode(); - node.local = this.parseIdent(); - this.checkLValSimple(node.local, BIND_LEXICAL); - nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); - if (!this.eat(types.comma)) { return nodes } - } - if (this.type === types.star) { - var node$1 = this.startNode(); - this.next(); - this.expectContextual("as"); - node$1.local = this.parseIdent(); - this.checkLValSimple(node$1.local, BIND_LEXICAL); - nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); - return nodes - } - this.expect(types.braceL); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } - - var node$2 = this.startNode(); - node$2.imported = this.parseIdent(true); - if (this.eatContextual("as")) { - node$2.local = this.parseIdent(); - } else { - this.checkUnreserved(node$2.imported); - node$2.local = node$2.imported; - } - this.checkLValSimple(node$2.local, BIND_LEXICAL); - nodes.push(this.finishNode(node$2, "ImportSpecifier")); - } - return nodes - }; - - // Set `ExpressionStatement#directive` property for directive prologues. - pp$1.adaptDirectivePrologue = function(statements) { - for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { - statements[i].directive = statements[i].expression.raw.slice(1, -1); - } - }; - pp$1.isDirectiveCandidate = function(statement) { - return ( - statement.type === "ExpressionStatement" && - statement.expression.type === "Literal" && - typeof statement.expression.value === "string" && - // Reject parenthesized strings. - (this.input[statement.start] === "\"" || this.input[statement.start] === "'") - ) - }; - - var pp$2 = Parser.prototype; - - // Convert existing expression atom to assignable pattern - // if possible. - - pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { - if (this.options.ecmaVersion >= 6 && node) { - switch (node.type) { - case "Identifier": - if (this.inAsync && node.name === "await") - { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } - break - - case "ObjectPattern": - case "ArrayPattern": - case "AssignmentPattern": - case "RestElement": - break - - case "ObjectExpression": - node.type = "ObjectPattern"; - if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - for (var i = 0, list = node.properties; i < list.length; i += 1) { - var prop = list[i]; - - this.toAssignable(prop, isBinding); - // Early error: - // AssignmentRestProperty[Yield, Await] : - // `...` DestructuringAssignmentTarget[Yield, Await] - // - // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. - if ( - prop.type === "RestElement" && - (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") - ) { - this.raise(prop.argument.start, "Unexpected token"); - } - } - break - - case "Property": - // AssignmentProperty has type === "Property" - if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } - this.toAssignable(node.value, isBinding); - break - - case "ArrayExpression": - node.type = "ArrayPattern"; - if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - this.toAssignableList(node.elements, isBinding); - break - - case "SpreadElement": - node.type = "RestElement"; - this.toAssignable(node.argument, isBinding); - if (node.argument.type === "AssignmentPattern") - { this.raise(node.argument.start, "Rest elements cannot have a default value"); } - break - - case "AssignmentExpression": - if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } - node.type = "AssignmentPattern"; - delete node.operator; - this.toAssignable(node.left, isBinding); - break - - case "ParenthesizedExpression": - this.toAssignable(node.expression, isBinding, refDestructuringErrors); - break - - case "ChainExpression": - this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); - break - - case "MemberExpression": - if (!isBinding) { break } - - default: - this.raise(node.start, "Assigning to rvalue"); - } - } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } - return node - }; - - // Convert list of expression atoms to binding list. - - pp$2.toAssignableList = function(exprList, isBinding) { - var end = exprList.length; - for (var i = 0; i < end; i++) { - var elt = exprList[i]; - if (elt) { this.toAssignable(elt, isBinding); } - } - if (end) { - var last = exprList[end - 1]; - if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") - { this.unexpected(last.argument.start); } - } - return exprList - }; - - // Parses spread element. - - pp$2.parseSpread = function(refDestructuringErrors) { - var node = this.startNode(); - this.next(); - node.argument = this.parseMaybeAssign(false, refDestructuringErrors); - return this.finishNode(node, "SpreadElement") - }; - - pp$2.parseRestBinding = function() { - var node = this.startNode(); - this.next(); - - // RestElement inside of a function parameter must be an identifier - if (this.options.ecmaVersion === 6 && this.type !== types.name) - { this.unexpected(); } - - node.argument = this.parseBindingAtom(); - - return this.finishNode(node, "RestElement") - }; - - // Parses lvalue (assignable) atom. - - pp$2.parseBindingAtom = function() { - if (this.options.ecmaVersion >= 6) { - switch (this.type) { - case types.bracketL: - var node = this.startNode(); - this.next(); - node.elements = this.parseBindingList(types.bracketR, true, true); - return this.finishNode(node, "ArrayPattern") - - case types.braceL: - return this.parseObj(true) - } - } - return this.parseIdent() - }; - - pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { - var elts = [], first = true; - while (!this.eat(close)) { - if (first) { first = false; } - else { this.expect(types.comma); } - if (allowEmpty && this.type === types.comma) { - elts.push(null); - } else if (allowTrailingComma && this.afterTrailingComma(close)) { - break - } else if (this.type === types.ellipsis) { - var rest = this.parseRestBinding(); - this.parseBindingListItem(rest); - elts.push(rest); - if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } - this.expect(close); - break - } else { - var elem = this.parseMaybeDefault(this.start, this.startLoc); - this.parseBindingListItem(elem); - elts.push(elem); - } - } - return elts - }; - - pp$2.parseBindingListItem = function(param) { - return param - }; - - // Parses assignment pattern around given atom if possible. - - pp$2.parseMaybeDefault = function(startPos, startLoc, left) { - left = left || this.parseBindingAtom(); - if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } - var node = this.startNodeAt(startPos, startLoc); - node.left = left; - node.right = this.parseMaybeAssign(); - return this.finishNode(node, "AssignmentPattern") - }; - - // The following three functions all verify that a node is an lvalue — - // something that can be bound, or assigned to. In order to do so, they perform - // a variety of checks: - // - // - Check that none of the bound/assigned-to identifiers are reserved words. - // - Record name declarations for bindings in the appropriate scope. - // - Check duplicate argument names, if checkClashes is set. - // - // If a complex binding pattern is encountered (e.g., object and array - // destructuring), the entire pattern is recursively checked. - // - // There are three versions of checkLVal*() appropriate for different - // circumstances: - // - // - checkLValSimple() shall be used if the syntactic construct supports - // nothing other than identifiers and member expressions. Parenthesized - // expressions are also correctly handled. This is generally appropriate for - // constructs for which the spec says - // - // > It is a Syntax Error if AssignmentTargetType of [the production] is not - // > simple. - // - // It is also appropriate for checking if an identifier is valid and not - // defined elsewhere, like import declarations or function/class identifiers. - // - // Examples where this is used include: - // a += …; - // import a from '…'; - // where a is the node to be checked. - // - // - checkLValPattern() shall be used if the syntactic construct supports - // anything checkLValSimple() supports, as well as object and array - // destructuring patterns. This is generally appropriate for constructs for - // which the spec says - // - // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor - // > an ArrayLiteral and AssignmentTargetType of [the production] is not - // > simple. - // - // Examples where this is used include: - // (a = …); - // const a = …; - // try { … } catch (a) { … } - // where a is the node to be checked. - // - // - checkLValInnerPattern() shall be used if the syntactic construct supports - // anything checkLValPattern() supports, as well as default assignment - // patterns, rest elements, and other constructs that may appear within an - // object or array destructuring pattern. - // - // As a special case, function parameters also use checkLValInnerPattern(), - // as they also support defaults and rest constructs. - // - // These functions deliberately support both assignment and binding constructs, - // as the logic for both is exceedingly similar. If the node is the target of - // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it - // should be set to the appropriate BIND_* constant, like BIND_VAR or - // BIND_LEXICAL. - // - // If the function is called with a non-BIND_NONE bindingType, then - // additionally a checkClashes object may be specified to allow checking for - // duplicate argument names. checkClashes is ignored if the provided construct - // is an assignment (i.e., bindingType is BIND_NONE). - - pp$2.checkLValSimple = function(expr, bindingType, checkClashes) { - if ( bindingType === void 0 ) bindingType = BIND_NONE; - - var isBind = bindingType !== BIND_NONE; - - switch (expr.type) { - case "Identifier": - if (this.strict && this.reservedWordsStrictBind.test(expr.name)) - { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } - if (isBind) { - if (bindingType === BIND_LEXICAL && expr.name === "let") - { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } - if (checkClashes) { - if (has(checkClashes, expr.name)) - { this.raiseRecoverable(expr.start, "Argument name clash"); } - checkClashes[expr.name] = true; - } - if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } - } - break - - case "ChainExpression": - this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); - break - - case "MemberExpression": - if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } - break - - case "ParenthesizedExpression": - if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } - return this.checkLValSimple(expr.expression, bindingType, checkClashes) - - default: - this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); - } - }; - - pp$2.checkLValPattern = function(expr, bindingType, checkClashes) { - if ( bindingType === void 0 ) bindingType = BIND_NONE; - - switch (expr.type) { - case "ObjectPattern": - for (var i = 0, list = expr.properties; i < list.length; i += 1) { - var prop = list[i]; - - this.checkLValInnerPattern(prop, bindingType, checkClashes); - } - break - - case "ArrayPattern": - for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { - var elem = list$1[i$1]; - - if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } - } - break - - default: - this.checkLValSimple(expr, bindingType, checkClashes); - } - }; - - pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) { - if ( bindingType === void 0 ) bindingType = BIND_NONE; - - switch (expr.type) { - case "Property": - // AssignmentProperty has type === "Property" - this.checkLValInnerPattern(expr.value, bindingType, checkClashes); - break - - case "AssignmentPattern": - this.checkLValPattern(expr.left, bindingType, checkClashes); - break - - case "RestElement": - this.checkLValPattern(expr.argument, bindingType, checkClashes); - break - - default: - this.checkLValPattern(expr, bindingType, checkClashes); - } - }; - - // A recursive descent parser operates by defining functions for all - - var pp$3 = Parser.prototype; - - // Check if property name clashes with already added. - // Object/class getters and setters are not allowed to clash — - // either with each other or with an init property — and in - // strict mode, init properties are also not allowed to be repeated. - - pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) { - if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") - { return } - if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) - { return } - var key = prop.key; - var name; - switch (key.type) { - case "Identifier": name = key.name; break - case "Literal": name = String(key.value); break - default: return - } - var kind = prop.kind; - if (this.options.ecmaVersion >= 6) { - if (name === "__proto__" && kind === "init") { - if (propHash.proto) { - if (refDestructuringErrors) { - if (refDestructuringErrors.doubleProto < 0) - { refDestructuringErrors.doubleProto = key.start; } - // Backwards-compat kludge. Can be removed in version 6.0 - } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } - } - propHash.proto = true; - } - return - } - name = "$" + name; - var other = propHash[name]; - if (other) { - var redefinition; - if (kind === "init") { - redefinition = this.strict && other.init || other.get || other.set; - } else { - redefinition = other.init || other[kind]; - } - if (redefinition) - { this.raiseRecoverable(key.start, "Redefinition of property"); } - } else { - other = propHash[name] = { - init: false, - get: false, - set: false - }; - } - other[kind] = true; - }; - - // ### Expression parsing - - // These nest, from the most general expression type at the top to - // 'atomic', nondivisible expression types at the bottom. Most of - // the functions will simply let the function(s) below them parse, - // and, *if* the syntactic construct they handle is present, wrap - // the AST node that the inner parser gave them in another node. - - // Parse a full expression. The optional arguments are used to - // forbid the `in` operator (in for loops initalization expressions) - // and provide reference for storing '=' operator inside shorthand - // property assignment in contexts where both object expression - // and object pattern might appear (so it's possible to raise - // delayed syntax error at correct position). - - pp$3.parseExpression = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseMaybeAssign(noIn, refDestructuringErrors); - if (this.type === types.comma) { - var node = this.startNodeAt(startPos, startLoc); - node.expressions = [expr]; - while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); } - return this.finishNode(node, "SequenceExpression") - } - return expr - }; - - // Parse an assignment expression. This includes applications of - // operators like `+=`. - - pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { - if (this.isContextual("yield")) { - if (this.inGenerator) { return this.parseYield(noIn) } - // The tokenizer will assume an expression is allowed after - // `yield`, but this isn't that kind of yield - else { this.exprAllowed = false; } - } - - var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1; - if (refDestructuringErrors) { - oldParenAssign = refDestructuringErrors.parenthesizedAssign; - oldTrailingComma = refDestructuringErrors.trailingComma; - refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; - } else { - refDestructuringErrors = new DestructuringErrors; - ownDestructuringErrors = true; - } - - var startPos = this.start, startLoc = this.startLoc; - if (this.type === types.parenL || this.type === types.name) - { this.potentialArrowAt = this.start; } - var left = this.parseMaybeConditional(noIn, refDestructuringErrors); - if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } - if (this.type.isAssign) { - var node = this.startNodeAt(startPos, startLoc); - node.operator = this.value; - if (this.type === types.eq) - { left = this.toAssignable(left, false, refDestructuringErrors); } - if (!ownDestructuringErrors) { - refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; - } - if (refDestructuringErrors.shorthandAssign >= left.start) - { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly - if (this.type === types.eq) - { this.checkLValPattern(left); } - else - { this.checkLValSimple(left); } - node.left = left; - this.next(); - node.right = this.parseMaybeAssign(noIn); - return this.finishNode(node, "AssignmentExpression") - } else { - if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } - } - if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } - if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } - return left - }; - - // Parse a ternary conditional (`?:`) operator. - - pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseExprOps(noIn, refDestructuringErrors); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - if (this.eat(types.question)) { - var node = this.startNodeAt(startPos, startLoc); - node.test = expr; - node.consequent = this.parseMaybeAssign(); - this.expect(types.colon); - node.alternate = this.parseMaybeAssign(noIn); - return this.finishNode(node, "ConditionalExpression") - } - return expr - }; - - // Start the precedence parser. - - pp$3.parseExprOps = function(noIn, refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseMaybeUnary(refDestructuringErrors, false); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn) - }; - - // Parse binary operators with the operator precedence parsing - // algorithm. `left` is the left-hand side of the operator. - // `minPrec` provides context that allows the function to stop and - // defer further parser to one of its callers when it encounters an - // operator that has a lower precedence than the set it is parsing. - - pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { - var prec = this.type.binop; - if (prec != null && (!noIn || this.type !== types._in)) { - if (prec > minPrec) { - var logical = this.type === types.logicalOR || this.type === types.logicalAND; - var coalesce = this.type === types.coalesce; - if (coalesce) { - // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. - // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. - prec = types.logicalAND.binop; - } - var op = this.value; - this.next(); - var startPos = this.start, startLoc = this.startLoc; - var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn); - var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); - if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) { - this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); - } - return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) - } - } - return left - }; - - pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { - var node = this.startNodeAt(startPos, startLoc); - node.left = left; - node.operator = op; - node.right = right; - return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") - }; - - // Parse unary operators, both prefix and postfix. - - pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { - var startPos = this.start, startLoc = this.startLoc, expr; - if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) { - expr = this.parseAwait(); - sawUnary = true; - } else if (this.type.prefix) { - var node = this.startNode(), update = this.type === types.incDec; - node.operator = this.value; - node.prefix = true; - this.next(); - node.argument = this.parseMaybeUnary(null, true); - this.checkExpressionErrors(refDestructuringErrors, true); - if (update) { this.checkLValSimple(node.argument); } - else if (this.strict && node.operator === "delete" && - node.argument.type === "Identifier") - { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } - else { sawUnary = true; } - expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); - } else { - expr = this.parseExprSubscripts(refDestructuringErrors); - if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } - while (this.type.postfix && !this.canInsertSemicolon()) { - var node$1 = this.startNodeAt(startPos, startLoc); - node$1.operator = this.value; - node$1.prefix = false; - node$1.argument = expr; - this.checkLValSimple(expr); - this.next(); - expr = this.finishNode(node$1, "UpdateExpression"); - } - } - - if (!sawUnary && this.eat(types.starstar)) - { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } - else - { return expr } - }; - - // Parse call, dot, and `[]`-subscript expressions. - - pp$3.parseExprSubscripts = function(refDestructuringErrors) { - var startPos = this.start, startLoc = this.startLoc; - var expr = this.parseExprAtom(refDestructuringErrors); - if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") - { return expr } - var result = this.parseSubscripts(expr, startPos, startLoc); - if (refDestructuringErrors && result.type === "MemberExpression") { - if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } - if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } - if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } - } - return result - }; - - pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { - var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && - this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && - this.potentialArrowAt === base.start; - var optionalChained = false; - - while (true) { - var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained); - - if (element.optional) { optionalChained = true; } - if (element === base || element.type === "ArrowFunctionExpression") { - if (optionalChained) { - var chainNode = this.startNodeAt(startPos, startLoc); - chainNode.expression = element; - element = this.finishNode(chainNode, "ChainExpression"); - } - return element - } - - base = element; - } - }; - - pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) { - var optionalSupported = this.options.ecmaVersion >= 11; - var optional = optionalSupported && this.eat(types.questionDot); - if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } - - var computed = this.eat(types.bracketL); - if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) { - var node = this.startNodeAt(startPos, startLoc); - node.object = base; - node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never"); - node.computed = !!computed; - if (computed) { this.expect(types.bracketR); } - if (optionalSupported) { - node.optional = optional; - } - base = this.finishNode(node, "MemberExpression"); - } else if (!noCalls && this.eat(types.parenL)) { - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); - if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) { - this.checkPatternErrors(refDestructuringErrors, false); - this.checkYieldAwaitInDefaultParams(); - if (this.awaitIdentPos > 0) - { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true) - } - this.checkExpressionErrors(refDestructuringErrors, true); - this.yieldPos = oldYieldPos || this.yieldPos; - this.awaitPos = oldAwaitPos || this.awaitPos; - this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; - var node$1 = this.startNodeAt(startPos, startLoc); - node$1.callee = base; - node$1.arguments = exprList; - if (optionalSupported) { - node$1.optional = optional; - } - base = this.finishNode(node$1, "CallExpression"); - } else if (this.type === types.backQuote) { - if (optional || optionalChained) { - this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); - } - var node$2 = this.startNodeAt(startPos, startLoc); - node$2.tag = base; - node$2.quasi = this.parseTemplate({isTagged: true}); - base = this.finishNode(node$2, "TaggedTemplateExpression"); - } - return base - }; - - // Parse an atomic expression — either a single token that is an - // expression, an expression started by a keyword like `function` or - // `new`, or an expression wrapped in punctuation like `()`, `[]`, - // or `{}`. - - pp$3.parseExprAtom = function(refDestructuringErrors) { - // If a division operator appears in an expression position, the - // tokenizer got confused, and we force it to read a regexp instead. - if (this.type === types.slash) { this.readRegexp(); } - - var node, canBeArrow = this.potentialArrowAt === this.start; - switch (this.type) { - case types._super: - if (!this.allowSuper) - { this.raise(this.start, "'super' keyword outside a method"); } - node = this.startNode(); - this.next(); - if (this.type === types.parenL && !this.allowDirectSuper) - { this.raise(node.start, "super() call outside constructor of a subclass"); } - // The `super` keyword can appear at below: - // SuperProperty: - // super [ Expression ] - // super . IdentifierName - // SuperCall: - // super ( Arguments ) - if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) - { this.unexpected(); } - return this.finishNode(node, "Super") - - case types._this: - node = this.startNode(); - this.next(); - return this.finishNode(node, "ThisExpression") - - case types.name: - var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; - var id = this.parseIdent(false); - if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) - { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } - if (canBeArrow && !this.canInsertSemicolon()) { - if (this.eat(types.arrow)) - { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } - if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) { - id = this.parseIdent(false); - if (this.canInsertSemicolon() || !this.eat(types.arrow)) - { this.unexpected(); } - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) - } - } - return id - - case types.regexp: - var value = this.value; - node = this.parseLiteral(value.value); - node.regex = {pattern: value.pattern, flags: value.flags}; - return node - - case types.num: case types.string: - return this.parseLiteral(this.value) - - case types._null: case types._true: case types._false: - node = this.startNode(); - node.value = this.type === types._null ? null : this.type === types._true; - node.raw = this.type.keyword; - this.next(); - return this.finishNode(node, "Literal") - - case types.parenL: - var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow); - if (refDestructuringErrors) { - if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) - { refDestructuringErrors.parenthesizedAssign = start; } - if (refDestructuringErrors.parenthesizedBind < 0) - { refDestructuringErrors.parenthesizedBind = start; } - } - return expr - - case types.bracketL: - node = this.startNode(); - this.next(); - node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); - return this.finishNode(node, "ArrayExpression") - - case types.braceL: - return this.parseObj(false, refDestructuringErrors) - - case types._function: - node = this.startNode(); - this.next(); - return this.parseFunction(node, 0) - - case types._class: - return this.parseClass(this.startNode(), false) - - case types._new: - return this.parseNew() - - case types.backQuote: - return this.parseTemplate() - - case types._import: - if (this.options.ecmaVersion >= 11) { - return this.parseExprImport() - } else { - return this.unexpected() - } - - default: - this.unexpected(); - } - }; - - pp$3.parseExprImport = function() { - var node = this.startNode(); - - // Consume `import` as an identifier for `import.meta`. - // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. - if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } - var meta = this.parseIdent(true); - - switch (this.type) { - case types.parenL: - return this.parseDynamicImport(node) - case types.dot: - node.meta = meta; - return this.parseImportMeta(node) - default: - this.unexpected(); - } - }; - - pp$3.parseDynamicImport = function(node) { - this.next(); // skip `(` - - // Parse node.source. - node.source = this.parseMaybeAssign(); - - // Verify ending. - if (!this.eat(types.parenR)) { - var errorPos = this.start; - if (this.eat(types.comma) && this.eat(types.parenR)) { - this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); - } else { - this.unexpected(errorPos); - } - } - - return this.finishNode(node, "ImportExpression") - }; - - pp$3.parseImportMeta = function(node) { - this.next(); // skip `.` - - var containsEsc = this.containsEsc; - node.property = this.parseIdent(true); - - if (node.property.name !== "meta") - { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } - if (containsEsc) - { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } - if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) - { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } - - return this.finishNode(node, "MetaProperty") - }; - - pp$3.parseLiteral = function(value) { - var node = this.startNode(); - node.value = value; - node.raw = this.input.slice(this.start, this.end); - if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } - this.next(); - return this.finishNode(node, "Literal") - }; - - pp$3.parseParenExpression = function() { - this.expect(types.parenL); - var val = this.parseExpression(); - this.expect(types.parenR); - return val - }; - - pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { - var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; - if (this.options.ecmaVersion >= 6) { - this.next(); - - var innerStartPos = this.start, innerStartLoc = this.startLoc; - var exprList = [], first = true, lastIsComma = false; - var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; - this.yieldPos = 0; - this.awaitPos = 0; - // Do not save awaitIdentPos to allow checking awaits nested in parameters - while (this.type !== types.parenR) { - first ? first = false : this.expect(types.comma); - if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) { - lastIsComma = true; - break - } else if (this.type === types.ellipsis) { - spreadStart = this.start; - exprList.push(this.parseParenItem(this.parseRestBinding())); - if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } - break - } else { - exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); - } - } - var innerEndPos = this.start, innerEndLoc = this.startLoc; - this.expect(types.parenR); - - if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { - this.checkPatternErrors(refDestructuringErrors, false); - this.checkYieldAwaitInDefaultParams(); - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - return this.parseParenArrowList(startPos, startLoc, exprList) - } - - if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } - if (spreadStart) { this.unexpected(spreadStart); } - this.checkExpressionErrors(refDestructuringErrors, true); - this.yieldPos = oldYieldPos || this.yieldPos; - this.awaitPos = oldAwaitPos || this.awaitPos; - - if (exprList.length > 1) { - val = this.startNodeAt(innerStartPos, innerStartLoc); - val.expressions = exprList; - this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); - } else { - val = exprList[0]; - } - } else { - val = this.parseParenExpression(); - } - - if (this.options.preserveParens) { - var par = this.startNodeAt(startPos, startLoc); - par.expression = val; - return this.finishNode(par, "ParenthesizedExpression") - } else { - return val - } - }; - - pp$3.parseParenItem = function(item) { - return item - }; - - pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { - return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) - }; - - // New's precedence is slightly tricky. It must allow its argument to - // be a `[]` or dot subscript expression, but not a call — at least, - // not without wrapping it in parentheses. Thus, it uses the noCalls - // argument to parseSubscripts to prevent it from consuming the - // argument list. - - var empty$1 = []; - - pp$3.parseNew = function() { - if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } - var node = this.startNode(); - var meta = this.parseIdent(true); - if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { - node.meta = meta; - var containsEsc = this.containsEsc; - node.property = this.parseIdent(true); - if (node.property.name !== "target") - { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } - if (containsEsc) - { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } - if (!this.inNonArrowFunction) - { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); } - return this.finishNode(node, "MetaProperty") - } - var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import; - node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); - if (isImport && node.callee.type === "ImportExpression") { - this.raise(startPos, "Cannot use new with import()"); - } - if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } - else { node.arguments = empty$1; } - return this.finishNode(node, "NewExpression") - }; - - // Parse template expression. - - pp$3.parseTemplateElement = function(ref) { - var isTagged = ref.isTagged; - - var elem = this.startNode(); - if (this.type === types.invalidTemplate) { - if (!isTagged) { - this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); - } - elem.value = { - raw: this.value, - cooked: null - }; - } else { - elem.value = { - raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), - cooked: this.value - }; - } - this.next(); - elem.tail = this.type === types.backQuote; - return this.finishNode(elem, "TemplateElement") - }; - - pp$3.parseTemplate = function(ref) { - if ( ref === void 0 ) ref = {}; - var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; - - var node = this.startNode(); - this.next(); - node.expressions = []; - var curElt = this.parseTemplateElement({isTagged: isTagged}); - node.quasis = [curElt]; - while (!curElt.tail) { - if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); } - this.expect(types.dollarBraceL); - node.expressions.push(this.parseExpression()); - this.expect(types.braceR); - node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); - } - this.next(); - return this.finishNode(node, "TemplateLiteral") - }; - - pp$3.isAsyncProp = function(prop) { - return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && - (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && - !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) - }; - - // Parse an object literal or binding pattern. - - pp$3.parseObj = function(isPattern, refDestructuringErrors) { - var node = this.startNode(), first = true, propHash = {}; - node.properties = []; - this.next(); - while (!this.eat(types.braceR)) { - if (!first) { - this.expect(types.comma); - if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break } - } else { first = false; } - - var prop = this.parseProperty(isPattern, refDestructuringErrors); - if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } - node.properties.push(prop); - } - return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") - }; - - pp$3.parseProperty = function(isPattern, refDestructuringErrors) { - var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; - if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { - if (isPattern) { - prop.argument = this.parseIdent(false); - if (this.type === types.comma) { - this.raise(this.start, "Comma is not permitted after the rest element"); - } - return this.finishNode(prop, "RestElement") - } - // To disallow parenthesized identifier via `this.toAssignable()`. - if (this.type === types.parenL && refDestructuringErrors) { - if (refDestructuringErrors.parenthesizedAssign < 0) { - refDestructuringErrors.parenthesizedAssign = this.start; - } - if (refDestructuringErrors.parenthesizedBind < 0) { - refDestructuringErrors.parenthesizedBind = this.start; - } - } - // Parse argument. - prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); - // To disallow trailing comma via `this.toAssignable()`. - if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { - refDestructuringErrors.trailingComma = this.start; - } - // Finish - return this.finishNode(prop, "SpreadElement") - } - if (this.options.ecmaVersion >= 6) { - prop.method = false; - prop.shorthand = false; - if (isPattern || refDestructuringErrors) { - startPos = this.start; - startLoc = this.startLoc; - } - if (!isPattern) - { isGenerator = this.eat(types.star); } - } - var containsEsc = this.containsEsc; - this.parsePropertyName(prop); - if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { - isAsync = true; - isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); - this.parsePropertyName(prop, refDestructuringErrors); - } else { - isAsync = false; - } - this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); - return this.finishNode(prop, "Property") - }; - - pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { - if ((isGenerator || isAsync) && this.type === types.colon) - { this.unexpected(); } - - if (this.eat(types.colon)) { - prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); - prop.kind = "init"; - } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { - if (isPattern) { this.unexpected(); } - prop.kind = "init"; - prop.method = true; - prop.value = this.parseMethod(isGenerator, isAsync); - } else if (!isPattern && !containsEsc && - this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && - (prop.key.name === "get" || prop.key.name === "set") && - (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) { - if (isGenerator || isAsync) { this.unexpected(); } - prop.kind = prop.key.name; - this.parsePropertyName(prop); - prop.value = this.parseMethod(false); - var paramCount = prop.kind === "get" ? 0 : 1; - if (prop.value.params.length !== paramCount) { - var start = prop.value.start; - if (prop.kind === "get") - { this.raiseRecoverable(start, "getter should have no params"); } - else - { this.raiseRecoverable(start, "setter should have exactly one param"); } - } else { - if (prop.kind === "set" && prop.value.params[0].type === "RestElement") - { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } - } - } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { - if (isGenerator || isAsync) { this.unexpected(); } - this.checkUnreserved(prop.key); - if (prop.key.name === "await" && !this.awaitIdentPos) - { this.awaitIdentPos = startPos; } - prop.kind = "init"; - if (isPattern) { - prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); - } else if (this.type === types.eq && refDestructuringErrors) { - if (refDestructuringErrors.shorthandAssign < 0) - { refDestructuringErrors.shorthandAssign = this.start; } - prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); - } else { - prop.value = this.copyNode(prop.key); - } - prop.shorthand = true; - } else { this.unexpected(); } - }; - - pp$3.parsePropertyName = function(prop) { - if (this.options.ecmaVersion >= 6) { - if (this.eat(types.bracketL)) { - prop.computed = true; - prop.key = this.parseMaybeAssign(); - this.expect(types.bracketR); - return prop.key - } else { - prop.computed = false; - } - } - return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") - }; - - // Initialize empty function node. - - pp$3.initFunction = function(node) { - node.id = null; - if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } - if (this.options.ecmaVersion >= 8) { node.async = false; } - }; - - // Parse object or class method. - - pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { - var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - - this.initFunction(node); - if (this.options.ecmaVersion >= 6) - { node.generator = isGenerator; } - if (this.options.ecmaVersion >= 8) - { node.async = !!isAsync; } - - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); - - this.expect(types.parenL); - node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); - this.checkYieldAwaitInDefaultParams(); - this.parseFunctionBody(node, false, true); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, "FunctionExpression") - }; - - // Parse arrow function expression with given parameters. - - pp$3.parseArrowExpression = function(node, params, isAsync) { - var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - - this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); - this.initFunction(node); - if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } - - this.yieldPos = 0; - this.awaitPos = 0; - this.awaitIdentPos = 0; - - node.params = this.toAssignableList(params, true); - this.parseFunctionBody(node, true, false); - - this.yieldPos = oldYieldPos; - this.awaitPos = oldAwaitPos; - this.awaitIdentPos = oldAwaitIdentPos; - return this.finishNode(node, "ArrowFunctionExpression") - }; - - // Parse function body and check parameters. - - pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { - var isExpression = isArrowFunction && this.type !== types.braceL; - var oldStrict = this.strict, useStrict = false; - - if (isExpression) { - node.body = this.parseMaybeAssign(); - node.expression = true; - this.checkParams(node, false); - } else { - var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); - if (!oldStrict || nonSimple) { - useStrict = this.strictDirective(this.end); - // If this is a strict mode function, verify that argument names - // are not repeated, and it does not try to bind the words `eval` - // or `arguments`. - if (useStrict && nonSimple) - { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } - } - // Start a new scope with regard to labels and the `inFunction` - // flag (restore them to their old value afterwards). - var oldLabels = this.labels; - this.labels = []; - if (useStrict) { this.strict = true; } - - // Add the params to varDeclaredNames to ensure that an error is thrown - // if a let/const declaration in the function clashes with one of the params. - this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); - // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' - if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } - node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); - node.expression = false; - this.adaptDirectivePrologue(node.body.body); - this.labels = oldLabels; - } - this.exitScope(); - }; - - pp$3.isSimpleParamList = function(params) { - for (var i = 0, list = params; i < list.length; i += 1) - { - var param = list[i]; - - if (param.type !== "Identifier") { return false - } } - return true - }; - - // Checks function params for various disallowed patterns such as using "eval" - // or "arguments" and duplicate parameters. - - pp$3.checkParams = function(node, allowDuplicates) { - var nameHash = Object.create(null); - for (var i = 0, list = node.params; i < list.length; i += 1) - { - var param = list[i]; - - this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); - } - }; - - // Parses a comma-separated list of expressions, and returns them as - // an array. `close` is the token type that ends the list, and - // `allowEmpty` can be turned on to allow subsequent commas with - // nothing in between them to be parsed as `null` (which is needed - // for array literals). - - pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { - var elts = [], first = true; - while (!this.eat(close)) { - if (!first) { - this.expect(types.comma); - if (allowTrailingComma && this.afterTrailingComma(close)) { break } - } else { first = false; } - - var elt = (void 0); - if (allowEmpty && this.type === types.comma) - { elt = null; } - else if (this.type === types.ellipsis) { - elt = this.parseSpread(refDestructuringErrors); - if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0) - { refDestructuringErrors.trailingComma = this.start; } - } else { - elt = this.parseMaybeAssign(false, refDestructuringErrors); - } - elts.push(elt); - } - return elts - }; - - pp$3.checkUnreserved = function(ref) { - var start = ref.start; - var end = ref.end; - var name = ref.name; - - if (this.inGenerator && name === "yield") - { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } - if (this.inAsync && name === "await") - { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } - if (this.keywords.test(name)) - { this.raise(start, ("Unexpected keyword '" + name + "'")); } - if (this.options.ecmaVersion < 6 && - this.input.slice(start, end).indexOf("\\") !== -1) { return } - var re = this.strict ? this.reservedWordsStrict : this.reservedWords; - if (re.test(name)) { - if (!this.inAsync && name === "await") - { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } - this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); - } - }; - - // Parse the next token as an identifier. If `liberal` is true (used - // when parsing properties), it will also convert keywords into - // identifiers. - - pp$3.parseIdent = function(liberal, isBinding) { - var node = this.startNode(); - if (this.type === types.name) { - node.name = this.value; - } else if (this.type.keyword) { - node.name = this.type.keyword; - - // To fix https://github.com/acornjs/acorn/issues/575 - // `class` and `function` keywords push new context into this.context. - // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. - // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword - if ((node.name === "class" || node.name === "function") && - (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { - this.context.pop(); - } - } else { - this.unexpected(); - } - this.next(!!liberal); - this.finishNode(node, "Identifier"); - if (!liberal) { - this.checkUnreserved(node); - if (node.name === "await" && !this.awaitIdentPos) - { this.awaitIdentPos = node.start; } - } - return node - }; - - // Parses yield expression inside generator. - - pp$3.parseYield = function(noIn) { - if (!this.yieldPos) { this.yieldPos = this.start; } - - var node = this.startNode(); - this.next(); - if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { - node.delegate = false; - node.argument = null; - } else { - node.delegate = this.eat(types.star); - node.argument = this.parseMaybeAssign(noIn); - } - return this.finishNode(node, "YieldExpression") - }; - - pp$3.parseAwait = function() { - if (!this.awaitPos) { this.awaitPos = this.start; } - - var node = this.startNode(); - this.next(); - node.argument = this.parseMaybeUnary(null, true); - return this.finishNode(node, "AwaitExpression") - }; - - var pp$4 = Parser.prototype; - - // This function is used to raise exceptions on parse errors. It - // takes an offset integer (into the current `input`) to indicate - // the location of the error, attaches the position to the end - // of the error message, and then raises a `SyntaxError` with that - // message. - - pp$4.raise = function(pos, message) { - var loc = getLineInfo(this.input, pos); - message += " (" + loc.line + ":" + loc.column + ")"; - var err = new SyntaxError(message); - err.pos = pos; err.loc = loc; err.raisedAt = this.pos; - throw err - }; - - pp$4.raiseRecoverable = pp$4.raise; - - pp$4.curPosition = function() { - if (this.options.locations) { - return new Position(this.curLine, this.pos - this.lineStart) - } - }; - - var pp$5 = Parser.prototype; - - var Scope = function Scope(flags) { - this.flags = flags; - // A list of var-declared names in the current lexical scope - this.var = []; - // A list of lexically-declared names in the current lexical scope - this.lexical = []; - // A list of lexically-declared FunctionDeclaration names in the current lexical scope - this.functions = []; - }; - - // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. - - pp$5.enterScope = function(flags) { - this.scopeStack.push(new Scope(flags)); - }; - - pp$5.exitScope = function() { - this.scopeStack.pop(); - }; - - // The spec says: - // > At the top level of a function, or script, function declarations are - // > treated like var declarations rather than like lexical declarations. - pp$5.treatFunctionsAsVarInScope = function(scope) { - return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) - }; - - pp$5.declareName = function(name, bindingType, pos) { - var redeclared = false; - if (bindingType === BIND_LEXICAL) { - var scope = this.currentScope(); - redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; - scope.lexical.push(name); - if (this.inModule && (scope.flags & SCOPE_TOP)) - { delete this.undefinedExports[name]; } - } else if (bindingType === BIND_SIMPLE_CATCH) { - var scope$1 = this.currentScope(); - scope$1.lexical.push(name); - } else if (bindingType === BIND_FUNCTION) { - var scope$2 = this.currentScope(); - if (this.treatFunctionsAsVar) - { redeclared = scope$2.lexical.indexOf(name) > -1; } - else - { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } - scope$2.functions.push(name); - } else { - for (var i = this.scopeStack.length - 1; i >= 0; --i) { - var scope$3 = this.scopeStack[i]; - if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || - !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { - redeclared = true; - break - } - scope$3.var.push(name); - if (this.inModule && (scope$3.flags & SCOPE_TOP)) - { delete this.undefinedExports[name]; } - if (scope$3.flags & SCOPE_VAR) { break } - } - } - if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } - }; - - pp$5.checkLocalExport = function(id) { - // scope.functions must be empty as Module code is always strict. - if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && - this.scopeStack[0].var.indexOf(id.name) === -1) { - this.undefinedExports[id.name] = id; - } - }; - - pp$5.currentScope = function() { - return this.scopeStack[this.scopeStack.length - 1] - }; - - pp$5.currentVarScope = function() { - for (var i = this.scopeStack.length - 1;; i--) { - var scope = this.scopeStack[i]; - if (scope.flags & SCOPE_VAR) { return scope } - } - }; - - // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. - pp$5.currentThisScope = function() { - for (var i = this.scopeStack.length - 1;; i--) { - var scope = this.scopeStack[i]; - if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } - } - }; - - var Node = function Node(parser, pos, loc) { - this.type = ""; - this.start = pos; - this.end = 0; - if (parser.options.locations) - { this.loc = new SourceLocation(parser, loc); } - if (parser.options.directSourceFile) - { this.sourceFile = parser.options.directSourceFile; } - if (parser.options.ranges) - { this.range = [pos, 0]; } - }; - - // Start an AST node, attaching a start offset. - - var pp$6 = Parser.prototype; - - pp$6.startNode = function() { - return new Node(this, this.start, this.startLoc) - }; - - pp$6.startNodeAt = function(pos, loc) { - return new Node(this, pos, loc) - }; - - // Finish an AST node, adding `type` and `end` properties. - - function finishNodeAt(node, type, pos, loc) { - node.type = type; - node.end = pos; - if (this.options.locations) - { node.loc.end = loc; } - if (this.options.ranges) - { node.range[1] = pos; } - return node - } - - pp$6.finishNode = function(node, type) { - return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) - }; - - // Finish node at given position - - pp$6.finishNodeAt = function(node, type, pos, loc) { - return finishNodeAt.call(this, node, type, pos, loc) - }; - - pp$6.copyNode = function(node) { - var newNode = new Node(this, node.start, this.startLoc); - for (var prop in node) { newNode[prop] = node[prop]; } - return newNode - }; - - // The algorithm used to determine whether a regexp can appear at a - - var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { - this.token = token; - this.isExpr = !!isExpr; - this.preserveSpace = !!preserveSpace; - this.override = override; - this.generator = !!generator; - }; - - var types$1 = { - b_stat: new TokContext("{", false), - b_expr: new TokContext("{", true), - b_tmpl: new TokContext("${", false), - p_stat: new TokContext("(", false), - p_expr: new TokContext("(", true), - q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), - f_stat: new TokContext("function", false), - f_expr: new TokContext("function", true), - f_expr_gen: new TokContext("function", true, false, null, true), - f_gen: new TokContext("function", false, false, null, true) - }; - - var pp$7 = Parser.prototype; - - pp$7.initialContext = function() { - return [types$1.b_stat] - }; - - pp$7.braceIsBlock = function(prevType) { - var parent = this.curContext(); - if (parent === types$1.f_expr || parent === types$1.f_stat) - { return true } - if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) - { return !parent.isExpr } - - // The check for `tt.name && exprAllowed` detects whether we are - // after a `yield` or `of` construct. See the `updateContext` for - // `tt.name`. - if (prevType === types._return || prevType === types.name && this.exprAllowed) - { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } - if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) - { return true } - if (prevType === types.braceL) - { return parent === types$1.b_stat } - if (prevType === types._var || prevType === types._const || prevType === types.name) - { return false } - return !this.exprAllowed - }; - - pp$7.inGeneratorContext = function() { - for (var i = this.context.length - 1; i >= 1; i--) { - var context = this.context[i]; - if (context.token === "function") - { return context.generator } - } - return false - }; - - pp$7.updateContext = function(prevType) { - var update, type = this.type; - if (type.keyword && prevType === types.dot) - { this.exprAllowed = false; } - else if (update = type.updateContext) - { update.call(this, prevType); } - else - { this.exprAllowed = type.beforeExpr; } - }; - - // Token-specific context update code - - types.parenR.updateContext = types.braceR.updateContext = function() { - if (this.context.length === 1) { - this.exprAllowed = true; - return - } - var out = this.context.pop(); - if (out === types$1.b_stat && this.curContext().token === "function") { - out = this.context.pop(); - } - this.exprAllowed = !out.isExpr; - }; - - types.braceL.updateContext = function(prevType) { - this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); - this.exprAllowed = true; - }; - - types.dollarBraceL.updateContext = function() { - this.context.push(types$1.b_tmpl); - this.exprAllowed = true; - }; - - types.parenL.updateContext = function(prevType) { - var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; - this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); - this.exprAllowed = true; - }; - - types.incDec.updateContext = function() { - // tokExprAllowed stays unchanged - }; - - types._function.updateContext = types._class.updateContext = function(prevType) { - if (prevType.beforeExpr && prevType !== types._else && - !(prevType === types.semi && this.curContext() !== types$1.p_stat) && - !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && - !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) - { this.context.push(types$1.f_expr); } - else - { this.context.push(types$1.f_stat); } - this.exprAllowed = false; - }; - - types.backQuote.updateContext = function() { - if (this.curContext() === types$1.q_tmpl) - { this.context.pop(); } - else - { this.context.push(types$1.q_tmpl); } - this.exprAllowed = false; - }; - - types.star.updateContext = function(prevType) { - if (prevType === types._function) { - var index = this.context.length - 1; - if (this.context[index] === types$1.f_expr) - { this.context[index] = types$1.f_expr_gen; } - else - { this.context[index] = types$1.f_gen; } - } - this.exprAllowed = true; - }; - - types.name.updateContext = function(prevType) { - var allowed = false; - if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { - if (this.value === "of" && !this.exprAllowed || - this.value === "yield" && this.inGeneratorContext()) - { allowed = true; } - } - this.exprAllowed = allowed; - }; - - // This file contains Unicode properties extracted from the ECMAScript - // specification. The lists are extracted like so: - // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) - - // #table-binary-unicode-properties - var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; - var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; - var ecma11BinaryProperties = ecma10BinaryProperties; - var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; - var unicodeBinaryProperties = { - 9: ecma9BinaryProperties, - 10: ecma10BinaryProperties, - 11: ecma11BinaryProperties, - 12: ecma12BinaryProperties - }; - - // #table-unicode-general-category-values - var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; - - // #table-unicode-script-values - var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; - var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; - var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; - var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; - var unicodeScriptValues = { - 9: ecma9ScriptValues, - 10: ecma10ScriptValues, - 11: ecma11ScriptValues, - 12: ecma12ScriptValues - }; - - var data = {}; - function buildUnicodeData(ecmaVersion) { - var d = data[ecmaVersion] = { - binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), - nonBinary: { - General_Category: wordsRegexp(unicodeGeneralCategoryValues), - Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) - } - }; - d.nonBinary.Script_Extensions = d.nonBinary.Script; - - d.nonBinary.gc = d.nonBinary.General_Category; - d.nonBinary.sc = d.nonBinary.Script; - d.nonBinary.scx = d.nonBinary.Script_Extensions; - } - buildUnicodeData(9); - buildUnicodeData(10); - buildUnicodeData(11); - buildUnicodeData(12); - - var pp$8 = Parser.prototype; - - var RegExpValidationState = function RegExpValidationState(parser) { - this.parser = parser; - this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : ""); - this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion]; - this.source = ""; - this.flags = ""; - this.start = 0; - this.switchU = false; - this.switchN = false; - this.pos = 0; - this.lastIntValue = 0; - this.lastStringValue = ""; - this.lastAssertionIsQuantifiable = false; - this.numCapturingParens = 0; - this.maxBackReference = 0; - this.groupNames = []; - this.backReferenceNames = []; - }; - - RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { - var unicode = flags.indexOf("u") !== -1; - this.start = start | 0; - this.source = pattern + ""; - this.flags = flags; - this.switchU = unicode && this.parser.options.ecmaVersion >= 6; - this.switchN = unicode && this.parser.options.ecmaVersion >= 9; - }; - - RegExpValidationState.prototype.raise = function raise (message) { - this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); - }; - - // If u flag is given, this returns the code point at the index (it combines a surrogate pair). - // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). - RegExpValidationState.prototype.at = function at (i, forceU) { - if ( forceU === void 0 ) forceU = false; - - var s = this.source; - var l = s.length; - if (i >= l) { - return -1 - } - var c = s.charCodeAt(i); - if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { - return c - } - var next = s.charCodeAt(i + 1); - return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c - }; - - RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { - if ( forceU === void 0 ) forceU = false; - - var s = this.source; - var l = s.length; - if (i >= l) { - return l - } - var c = s.charCodeAt(i), next; - if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || - (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { - return i + 1 - } - return i + 2 - }; - - RegExpValidationState.prototype.current = function current (forceU) { - if ( forceU === void 0 ) forceU = false; - - return this.at(this.pos, forceU) - }; - - RegExpValidationState.prototype.lookahead = function lookahead (forceU) { - if ( forceU === void 0 ) forceU = false; - - return this.at(this.nextIndex(this.pos, forceU), forceU) - }; - - RegExpValidationState.prototype.advance = function advance (forceU) { - if ( forceU === void 0 ) forceU = false; - - this.pos = this.nextIndex(this.pos, forceU); - }; - - RegExpValidationState.prototype.eat = function eat (ch, forceU) { - if ( forceU === void 0 ) forceU = false; - - if (this.current(forceU) === ch) { - this.advance(forceU); - return true - } - return false - }; - - function codePointToString(ch) { - if (ch <= 0xFFFF) { return String.fromCharCode(ch) } - ch -= 0x10000; - return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) - } - - /** - * Validate the flags part of a given RegExpLiteral. - * - * @param {RegExpValidationState} state The state to validate RegExp. - * @returns {void} - */ - pp$8.validateRegExpFlags = function(state) { - var validFlags = state.validFlags; - var flags = state.flags; - - for (var i = 0; i < flags.length; i++) { - var flag = flags.charAt(i); - if (validFlags.indexOf(flag) === -1) { - this.raise(state.start, "Invalid regular expression flag"); - } - if (flags.indexOf(flag, i + 1) > -1) { - this.raise(state.start, "Duplicate regular expression flag"); - } - } - }; - - /** - * Validate the pattern part of a given RegExpLiteral. - * - * @param {RegExpValidationState} state The state to validate RegExp. - * @returns {void} - */ - pp$8.validateRegExpPattern = function(state) { - this.regexp_pattern(state); - - // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of - // parsing contains a |GroupName|, reparse with the goal symbol - // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* - // exception if _P_ did not conform to the grammar, if any elements of _P_ - // were not matched by the parse, or if any Early Error conditions exist. - if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { - state.switchN = true; - this.regexp_pattern(state); - } - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern - pp$8.regexp_pattern = function(state) { - state.pos = 0; - state.lastIntValue = 0; - state.lastStringValue = ""; - state.lastAssertionIsQuantifiable = false; - state.numCapturingParens = 0; - state.maxBackReference = 0; - state.groupNames.length = 0; - state.backReferenceNames.length = 0; - - this.regexp_disjunction(state); - - if (state.pos !== state.source.length) { - // Make the same messages as V8. - if (state.eat(0x29 /* ) */)) { - state.raise("Unmatched ')'"); - } - if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { - state.raise("Lone quantifier brackets"); - } - } - if (state.maxBackReference > state.numCapturingParens) { - state.raise("Invalid escape"); - } - for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { - var name = list[i]; - - if (state.groupNames.indexOf(name) === -1) { - state.raise("Invalid named capture referenced"); - } - } - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction - pp$8.regexp_disjunction = function(state) { - this.regexp_alternative(state); - while (state.eat(0x7C /* | */)) { - this.regexp_alternative(state); - } - - // Make the same message as V8. - if (this.regexp_eatQuantifier(state, true)) { - state.raise("Nothing to repeat"); - } - if (state.eat(0x7B /* { */)) { - state.raise("Lone quantifier brackets"); - } - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative - pp$8.regexp_alternative = function(state) { - while (state.pos < state.source.length && this.regexp_eatTerm(state)) - { } - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term - pp$8.regexp_eatTerm = function(state) { - if (this.regexp_eatAssertion(state)) { - // Handle `QuantifiableAssertion Quantifier` alternative. - // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion - // is a QuantifiableAssertion. - if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { - // Make the same message as V8. - if (state.switchU) { - state.raise("Invalid quantifier"); - } - } - return true - } - - if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { - this.regexp_eatQuantifier(state); - return true - } - - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion - pp$8.regexp_eatAssertion = function(state) { - var start = state.pos; - state.lastAssertionIsQuantifiable = false; - - // ^, $ - if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { - return true - } - - // \b \B - if (state.eat(0x5C /* \ */)) { - if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { - return true - } - state.pos = start; - } - - // Lookahead / Lookbehind - if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { - var lookbehind = false; - if (this.options.ecmaVersion >= 9) { - lookbehind = state.eat(0x3C /* < */); - } - if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { - this.regexp_disjunction(state); - if (!state.eat(0x29 /* ) */)) { - state.raise("Unterminated group"); - } - state.lastAssertionIsQuantifiable = !lookbehind; - return true - } - } - - state.pos = start; - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier - pp$8.regexp_eatQuantifier = function(state, noError) { - if ( noError === void 0 ) noError = false; - - if (this.regexp_eatQuantifierPrefix(state, noError)) { - state.eat(0x3F /* ? */); - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix - pp$8.regexp_eatQuantifierPrefix = function(state, noError) { - return ( - state.eat(0x2A /* * */) || - state.eat(0x2B /* + */) || - state.eat(0x3F /* ? */) || - this.regexp_eatBracedQuantifier(state, noError) - ) - }; - pp$8.regexp_eatBracedQuantifier = function(state, noError) { - var start = state.pos; - if (state.eat(0x7B /* { */)) { - var min = 0, max = -1; - if (this.regexp_eatDecimalDigits(state)) { - min = state.lastIntValue; - if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { - max = state.lastIntValue; - } - if (state.eat(0x7D /* } */)) { - // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term - if (max !== -1 && max < min && !noError) { - state.raise("numbers out of order in {} quantifier"); - } - return true - } - } - if (state.switchU && !noError) { - state.raise("Incomplete quantifier"); - } - state.pos = start; - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom - pp$8.regexp_eatAtom = function(state) { - return ( - this.regexp_eatPatternCharacters(state) || - state.eat(0x2E /* . */) || - this.regexp_eatReverseSolidusAtomEscape(state) || - this.regexp_eatCharacterClass(state) || - this.regexp_eatUncapturingGroup(state) || - this.regexp_eatCapturingGroup(state) - ) - }; - pp$8.regexp_eatReverseSolidusAtomEscape = function(state) { - var start = state.pos; - if (state.eat(0x5C /* \ */)) { - if (this.regexp_eatAtomEscape(state)) { - return true - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatUncapturingGroup = function(state) { - var start = state.pos; - if (state.eat(0x28 /* ( */)) { - if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { - this.regexp_disjunction(state); - if (state.eat(0x29 /* ) */)) { - return true - } - state.raise("Unterminated group"); - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatCapturingGroup = function(state) { - if (state.eat(0x28 /* ( */)) { - if (this.options.ecmaVersion >= 9) { - this.regexp_groupSpecifier(state); - } else if (state.current() === 0x3F /* ? */) { - state.raise("Invalid group"); - } - this.regexp_disjunction(state); - if (state.eat(0x29 /* ) */)) { - state.numCapturingParens += 1; - return true - } - state.raise("Unterminated group"); - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom - pp$8.regexp_eatExtendedAtom = function(state) { - return ( - state.eat(0x2E /* . */) || - this.regexp_eatReverseSolidusAtomEscape(state) || - this.regexp_eatCharacterClass(state) || - this.regexp_eatUncapturingGroup(state) || - this.regexp_eatCapturingGroup(state) || - this.regexp_eatInvalidBracedQuantifier(state) || - this.regexp_eatExtendedPatternCharacter(state) - ) - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier - pp$8.regexp_eatInvalidBracedQuantifier = function(state) { - if (this.regexp_eatBracedQuantifier(state, true)) { - state.raise("Nothing to repeat"); - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter - pp$8.regexp_eatSyntaxCharacter = function(state) { - var ch = state.current(); - if (isSyntaxCharacter(ch)) { - state.lastIntValue = ch; - state.advance(); - return true - } - return false - }; - function isSyntaxCharacter(ch) { - return ( - ch === 0x24 /* $ */ || - ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || - ch === 0x2E /* . */ || - ch === 0x3F /* ? */ || - ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || - ch >= 0x7B /* { */ && ch <= 0x7D /* } */ - ) - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter - // But eat eager. - pp$8.regexp_eatPatternCharacters = function(state) { - var start = state.pos; - var ch = 0; - while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { - state.advance(); - } - return state.pos !== start - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter - pp$8.regexp_eatExtendedPatternCharacter = function(state) { - var ch = state.current(); - if ( - ch !== -1 && - ch !== 0x24 /* $ */ && - !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && - ch !== 0x2E /* . */ && - ch !== 0x3F /* ? */ && - ch !== 0x5B /* [ */ && - ch !== 0x5E /* ^ */ && - ch !== 0x7C /* | */ - ) { - state.advance(); - return true - } - return false - }; - - // GroupSpecifier :: - // [empty] - // `?` GroupName - pp$8.regexp_groupSpecifier = function(state) { - if (state.eat(0x3F /* ? */)) { - if (this.regexp_eatGroupName(state)) { - if (state.groupNames.indexOf(state.lastStringValue) !== -1) { - state.raise("Duplicate capture group name"); - } - state.groupNames.push(state.lastStringValue); - return - } - state.raise("Invalid group"); - } - }; - - // GroupName :: - // `<` RegExpIdentifierName `>` - // Note: this updates `state.lastStringValue` property with the eaten name. - pp$8.regexp_eatGroupName = function(state) { - state.lastStringValue = ""; - if (state.eat(0x3C /* < */)) { - if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { - return true - } - state.raise("Invalid capture group name"); - } - return false - }; - - // RegExpIdentifierName :: - // RegExpIdentifierStart - // RegExpIdentifierName RegExpIdentifierPart - // Note: this updates `state.lastStringValue` property with the eaten name. - pp$8.regexp_eatRegExpIdentifierName = function(state) { - state.lastStringValue = ""; - if (this.regexp_eatRegExpIdentifierStart(state)) { - state.lastStringValue += codePointToString(state.lastIntValue); - while (this.regexp_eatRegExpIdentifierPart(state)) { - state.lastStringValue += codePointToString(state.lastIntValue); - } - return true - } - return false - }; - - // RegExpIdentifierStart :: - // UnicodeIDStart - // `$` - // `_` - // `\` RegExpUnicodeEscapeSequence[+U] - pp$8.regexp_eatRegExpIdentifierStart = function(state) { - var start = state.pos; - var forceU = this.options.ecmaVersion >= 11; - var ch = state.current(forceU); - state.advance(forceU); - - if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { - ch = state.lastIntValue; - } - if (isRegExpIdentifierStart(ch)) { - state.lastIntValue = ch; - return true - } - - state.pos = start; - return false - }; - function isRegExpIdentifierStart(ch) { - return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ - } - - // RegExpIdentifierPart :: - // UnicodeIDContinue - // `$` - // `_` - // `\` RegExpUnicodeEscapeSequence[+U] - // - // - pp$8.regexp_eatRegExpIdentifierPart = function(state) { - var start = state.pos; - var forceU = this.options.ecmaVersion >= 11; - var ch = state.current(forceU); - state.advance(forceU); - - if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { - ch = state.lastIntValue; - } - if (isRegExpIdentifierPart(ch)) { - state.lastIntValue = ch; - return true - } - - state.pos = start; - return false - }; - function isRegExpIdentifierPart(ch) { - return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape - pp$8.regexp_eatAtomEscape = function(state) { - if ( - this.regexp_eatBackReference(state) || - this.regexp_eatCharacterClassEscape(state) || - this.regexp_eatCharacterEscape(state) || - (state.switchN && this.regexp_eatKGroupName(state)) - ) { - return true - } - if (state.switchU) { - // Make the same message as V8. - if (state.current() === 0x63 /* c */) { - state.raise("Invalid unicode escape"); - } - state.raise("Invalid escape"); - } - return false - }; - pp$8.regexp_eatBackReference = function(state) { - var start = state.pos; - if (this.regexp_eatDecimalEscape(state)) { - var n = state.lastIntValue; - if (state.switchU) { - // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape - if (n > state.maxBackReference) { - state.maxBackReference = n; - } - return true - } - if (n <= state.numCapturingParens) { - return true - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatKGroupName = function(state) { - if (state.eat(0x6B /* k */)) { - if (this.regexp_eatGroupName(state)) { - state.backReferenceNames.push(state.lastStringValue); - return true - } - state.raise("Invalid named reference"); - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape - pp$8.regexp_eatCharacterEscape = function(state) { - return ( - this.regexp_eatControlEscape(state) || - this.regexp_eatCControlLetter(state) || - this.regexp_eatZero(state) || - this.regexp_eatHexEscapeSequence(state) || - this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || - (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || - this.regexp_eatIdentityEscape(state) - ) - }; - pp$8.regexp_eatCControlLetter = function(state) { - var start = state.pos; - if (state.eat(0x63 /* c */)) { - if (this.regexp_eatControlLetter(state)) { - return true - } - state.pos = start; - } - return false - }; - pp$8.regexp_eatZero = function(state) { - if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { - state.lastIntValue = 0; - state.advance(); - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape - pp$8.regexp_eatControlEscape = function(state) { - var ch = state.current(); - if (ch === 0x74 /* t */) { - state.lastIntValue = 0x09; /* \t */ - state.advance(); - return true - } - if (ch === 0x6E /* n */) { - state.lastIntValue = 0x0A; /* \n */ - state.advance(); - return true - } - if (ch === 0x76 /* v */) { - state.lastIntValue = 0x0B; /* \v */ - state.advance(); - return true - } - if (ch === 0x66 /* f */) { - state.lastIntValue = 0x0C; /* \f */ - state.advance(); - return true - } - if (ch === 0x72 /* r */) { - state.lastIntValue = 0x0D; /* \r */ - state.advance(); - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter - pp$8.regexp_eatControlLetter = function(state) { - var ch = state.current(); - if (isControlLetter(ch)) { - state.lastIntValue = ch % 0x20; - state.advance(); - return true - } - return false - }; - function isControlLetter(ch) { - return ( - (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || - (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) - ) - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence - pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { - if ( forceU === void 0 ) forceU = false; - - var start = state.pos; - var switchU = forceU || state.switchU; - - if (state.eat(0x75 /* u */)) { - if (this.regexp_eatFixedHexDigits(state, 4)) { - var lead = state.lastIntValue; - if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { - var leadSurrogateEnd = state.pos; - if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { - var trail = state.lastIntValue; - if (trail >= 0xDC00 && trail <= 0xDFFF) { - state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; - return true - } - } - state.pos = leadSurrogateEnd; - state.lastIntValue = lead; - } - return true - } - if ( - switchU && - state.eat(0x7B /* { */) && - this.regexp_eatHexDigits(state) && - state.eat(0x7D /* } */) && - isValidUnicode(state.lastIntValue) - ) { - return true - } - if (switchU) { - state.raise("Invalid unicode escape"); - } - state.pos = start; - } - - return false - }; - function isValidUnicode(ch) { - return ch >= 0 && ch <= 0x10FFFF - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape - pp$8.regexp_eatIdentityEscape = function(state) { - if (state.switchU) { - if (this.regexp_eatSyntaxCharacter(state)) { - return true - } - if (state.eat(0x2F /* / */)) { - state.lastIntValue = 0x2F; /* / */ - return true - } - return false - } - - var ch = state.current(); - if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { - state.lastIntValue = ch; - state.advance(); - return true - } - - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape - pp$8.regexp_eatDecimalEscape = function(state) { - state.lastIntValue = 0; - var ch = state.current(); - if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { - do { - state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); - state.advance(); - } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape - pp$8.regexp_eatCharacterClassEscape = function(state) { - var ch = state.current(); - - if (isCharacterClassEscape(ch)) { - state.lastIntValue = -1; - state.advance(); - return true - } - - if ( - state.switchU && - this.options.ecmaVersion >= 9 && - (ch === 0x50 /* P */ || ch === 0x70 /* p */) - ) { - state.lastIntValue = -1; - state.advance(); - if ( - state.eat(0x7B /* { */) && - this.regexp_eatUnicodePropertyValueExpression(state) && - state.eat(0x7D /* } */) - ) { - return true - } - state.raise("Invalid property name"); - } - - return false - }; - function isCharacterClassEscape(ch) { - return ( - ch === 0x64 /* d */ || - ch === 0x44 /* D */ || - ch === 0x73 /* s */ || - ch === 0x53 /* S */ || - ch === 0x77 /* w */ || - ch === 0x57 /* W */ - ) - } - - // UnicodePropertyValueExpression :: - // UnicodePropertyName `=` UnicodePropertyValue - // LoneUnicodePropertyNameOrValue - pp$8.regexp_eatUnicodePropertyValueExpression = function(state) { - var start = state.pos; - - // UnicodePropertyName `=` UnicodePropertyValue - if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { - var name = state.lastStringValue; - if (this.regexp_eatUnicodePropertyValue(state)) { - var value = state.lastStringValue; - this.regexp_validateUnicodePropertyNameAndValue(state, name, value); - return true - } - } - state.pos = start; - - // LoneUnicodePropertyNameOrValue - if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { - var nameOrValue = state.lastStringValue; - this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); - return true - } - return false - }; - pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { - if (!has(state.unicodeProperties.nonBinary, name)) - { state.raise("Invalid property name"); } - if (!state.unicodeProperties.nonBinary[name].test(value)) - { state.raise("Invalid property value"); } - }; - pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { - if (!state.unicodeProperties.binary.test(nameOrValue)) - { state.raise("Invalid property name"); } - }; - - // UnicodePropertyName :: - // UnicodePropertyNameCharacters - pp$8.regexp_eatUnicodePropertyName = function(state) { - var ch = 0; - state.lastStringValue = ""; - while (isUnicodePropertyNameCharacter(ch = state.current())) { - state.lastStringValue += codePointToString(ch); - state.advance(); - } - return state.lastStringValue !== "" - }; - function isUnicodePropertyNameCharacter(ch) { - return isControlLetter(ch) || ch === 0x5F /* _ */ - } - - // UnicodePropertyValue :: - // UnicodePropertyValueCharacters - pp$8.regexp_eatUnicodePropertyValue = function(state) { - var ch = 0; - state.lastStringValue = ""; - while (isUnicodePropertyValueCharacter(ch = state.current())) { - state.lastStringValue += codePointToString(ch); - state.advance(); - } - return state.lastStringValue !== "" - }; - function isUnicodePropertyValueCharacter(ch) { - return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) - } - - // LoneUnicodePropertyNameOrValue :: - // UnicodePropertyValueCharacters - pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { - return this.regexp_eatUnicodePropertyValue(state) - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass - pp$8.regexp_eatCharacterClass = function(state) { - if (state.eat(0x5B /* [ */)) { - state.eat(0x5E /* ^ */); - this.regexp_classRanges(state); - if (state.eat(0x5D /* ] */)) { - return true - } - // Unreachable since it threw "unterminated regular expression" error before. - state.raise("Unterminated character class"); - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges - // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges - // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash - pp$8.regexp_classRanges = function(state) { - while (this.regexp_eatClassAtom(state)) { - var left = state.lastIntValue; - if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { - var right = state.lastIntValue; - if (state.switchU && (left === -1 || right === -1)) { - state.raise("Invalid character class"); - } - if (left !== -1 && right !== -1 && left > right) { - state.raise("Range out of order in character class"); - } - } - } - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom - // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash - pp$8.regexp_eatClassAtom = function(state) { - var start = state.pos; - - if (state.eat(0x5C /* \ */)) { - if (this.regexp_eatClassEscape(state)) { - return true - } - if (state.switchU) { - // Make the same message as V8. - var ch$1 = state.current(); - if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { - state.raise("Invalid class escape"); - } - state.raise("Invalid escape"); - } - state.pos = start; - } - - var ch = state.current(); - if (ch !== 0x5D /* ] */) { - state.lastIntValue = ch; - state.advance(); - return true - } - - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape - pp$8.regexp_eatClassEscape = function(state) { - var start = state.pos; - - if (state.eat(0x62 /* b */)) { - state.lastIntValue = 0x08; /* */ - return true - } - - if (state.switchU && state.eat(0x2D /* - */)) { - state.lastIntValue = 0x2D; /* - */ - return true - } - - if (!state.switchU && state.eat(0x63 /* c */)) { - if (this.regexp_eatClassControlLetter(state)) { - return true - } - state.pos = start; - } - - return ( - this.regexp_eatCharacterClassEscape(state) || - this.regexp_eatCharacterEscape(state) - ) - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter - pp$8.regexp_eatClassControlLetter = function(state) { - var ch = state.current(); - if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { - state.lastIntValue = ch % 0x20; - state.advance(); - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence - pp$8.regexp_eatHexEscapeSequence = function(state) { - var start = state.pos; - if (state.eat(0x78 /* x */)) { - if (this.regexp_eatFixedHexDigits(state, 2)) { - return true - } - if (state.switchU) { - state.raise("Invalid escape"); - } - state.pos = start; - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits - pp$8.regexp_eatDecimalDigits = function(state) { - var start = state.pos; - var ch = 0; - state.lastIntValue = 0; - while (isDecimalDigit(ch = state.current())) { - state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); - state.advance(); - } - return state.pos !== start - }; - function isDecimalDigit(ch) { - return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits - pp$8.regexp_eatHexDigits = function(state) { - var start = state.pos; - var ch = 0; - state.lastIntValue = 0; - while (isHexDigit(ch = state.current())) { - state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); - state.advance(); - } - return state.pos !== start - }; - function isHexDigit(ch) { - return ( - (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || - (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || - (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) - ) - } - function hexToInt(ch) { - if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { - return 10 + (ch - 0x41 /* A */) - } - if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { - return 10 + (ch - 0x61 /* a */) - } - return ch - 0x30 /* 0 */ - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence - // Allows only 0-377(octal) i.e. 0-255(decimal). - pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) { - if (this.regexp_eatOctalDigit(state)) { - var n1 = state.lastIntValue; - if (this.regexp_eatOctalDigit(state)) { - var n2 = state.lastIntValue; - if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { - state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; - } else { - state.lastIntValue = n1 * 8 + n2; - } - } else { - state.lastIntValue = n1; - } - return true - } - return false - }; - - // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit - pp$8.regexp_eatOctalDigit = function(state) { - var ch = state.current(); - if (isOctalDigit(ch)) { - state.lastIntValue = ch - 0x30; /* 0 */ - state.advance(); - return true - } - state.lastIntValue = 0; - return false - }; - function isOctalDigit(ch) { - return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ - } - - // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits - // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit - // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence - pp$8.regexp_eatFixedHexDigits = function(state, length) { - var start = state.pos; - state.lastIntValue = 0; - for (var i = 0; i < length; ++i) { - var ch = state.current(); - if (!isHexDigit(ch)) { - state.pos = start; - return false - } - state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); - state.advance(); - } - return true - }; - - // Object type used to represent tokens. Note that normally, tokens - // simply exist as properties on the parser object. This is only - // used for the onToken callback and the external tokenizer. - - var Token = function Token(p) { - this.type = p.type; - this.value = p.value; - this.start = p.start; - this.end = p.end; - if (p.options.locations) - { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } - if (p.options.ranges) - { this.range = [p.start, p.end]; } - }; - - // ## Tokenizer - - var pp$9 = Parser.prototype; - - // Move to the next token - - pp$9.next = function(ignoreEscapeSequenceInKeyword) { - if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) - { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } - if (this.options.onToken) - { this.options.onToken(new Token(this)); } - - this.lastTokEnd = this.end; - this.lastTokStart = this.start; - this.lastTokEndLoc = this.endLoc; - this.lastTokStartLoc = this.startLoc; - this.nextToken(); - }; - - pp$9.getToken = function() { - this.next(); - return new Token(this) - }; - - // If we're in an ES6 environment, make parsers iterable - if (typeof Symbol !== "undefined") - { pp$9[Symbol.iterator] = function() { - var this$1 = this; - - return { - next: function () { - var token = this$1.getToken(); - return { - done: token.type === types.eof, - value: token - } - } - } - }; } - - // Toggle strict mode. Re-reads the next number or string to please - // pedantic tests (`"use strict"; 010;` should fail). - - pp$9.curContext = function() { - return this.context[this.context.length - 1] - }; - - // Read a single token, updating the parser object's token-related - // properties. - - pp$9.nextToken = function() { - var curContext = this.curContext(); - if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } - - this.start = this.pos; - if (this.options.locations) { this.startLoc = this.curPosition(); } - if (this.pos >= this.input.length) { return this.finishToken(types.eof) } - - if (curContext.override) { return curContext.override(this) } - else { this.readToken(this.fullCharCodeAtPos()); } - }; - - pp$9.readToken = function(code) { - // Identifier or keyword. '\uXXXX' sequences are allowed in - // identifiers, so '\' also dispatches to that. - if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) - { return this.readWord() } - - return this.getTokenFromCode(code) - }; - - pp$9.fullCharCodeAtPos = function() { - var code = this.input.charCodeAt(this.pos); - if (code <= 0xd7ff || code >= 0xe000) { return code } - var next = this.input.charCodeAt(this.pos + 1); - return (code << 10) + next - 0x35fdc00 - }; - - pp$9.skipBlockComment = function() { - var startLoc = this.options.onComment && this.curPosition(); - var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); - if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } - this.pos = end + 2; - if (this.options.locations) { - lineBreakG.lastIndex = start; - var match; - while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { - ++this.curLine; - this.lineStart = match.index + match[0].length; - } - } - if (this.options.onComment) - { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, - startLoc, this.curPosition()); } - }; - - pp$9.skipLineComment = function(startSkip) { - var start = this.pos; - var startLoc = this.options.onComment && this.curPosition(); - var ch = this.input.charCodeAt(this.pos += startSkip); - while (this.pos < this.input.length && !isNewLine(ch)) { - ch = this.input.charCodeAt(++this.pos); - } - if (this.options.onComment) - { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, - startLoc, this.curPosition()); } - }; - - // Called at the start of the parse and after every token. Skips - // whitespace and comments, and. - - pp$9.skipSpace = function() { - loop: while (this.pos < this.input.length) { - var ch = this.input.charCodeAt(this.pos); - switch (ch) { - case 32: case 160: // ' ' - ++this.pos; - break - case 13: - if (this.input.charCodeAt(this.pos + 1) === 10) { - ++this.pos; - } - case 10: case 8232: case 8233: - ++this.pos; - if (this.options.locations) { - ++this.curLine; - this.lineStart = this.pos; - } - break - case 47: // '/' - switch (this.input.charCodeAt(this.pos + 1)) { - case 42: // '*' - this.skipBlockComment(); - break - case 47: - this.skipLineComment(2); - break - default: - break loop - } - break - default: - if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { - ++this.pos; - } else { - break loop - } - } - } - }; - - // Called at the end of every token. Sets `end`, `val`, and - // maintains `context` and `exprAllowed`, and skips the space after - // the token, so that the next one's `start` will point at the - // right position. - - pp$9.finishToken = function(type, val) { - this.end = this.pos; - if (this.options.locations) { this.endLoc = this.curPosition(); } - var prevType = this.type; - this.type = type; - this.value = val; - - this.updateContext(prevType); - }; - - // ### Token reading - - // This is the function that is called to fetch the next token. It - // is somewhat obscure, because it works in character codes rather - // than characters, and because operator parsing has been inlined - // into it. - // - // All in the name of speed. - // - pp$9.readToken_dot = function() { - var next = this.input.charCodeAt(this.pos + 1); - if (next >= 48 && next <= 57) { return this.readNumber(true) } - var next2 = this.input.charCodeAt(this.pos + 2); - if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' - this.pos += 3; - return this.finishToken(types.ellipsis) - } else { - ++this.pos; - return this.finishToken(types.dot) - } - }; - - pp$9.readToken_slash = function() { // '/' - var next = this.input.charCodeAt(this.pos + 1); - if (this.exprAllowed) { ++this.pos; return this.readRegexp() } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.slash, 1) - }; - - pp$9.readToken_mult_modulo_exp = function(code) { // '%*' - var next = this.input.charCodeAt(this.pos + 1); - var size = 1; - var tokentype = code === 42 ? types.star : types.modulo; - - // exponentiation operator ** and **= - if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { - ++size; - tokentype = types.starstar; - next = this.input.charCodeAt(this.pos + 2); - } - - if (next === 61) { return this.finishOp(types.assign, size + 1) } - return this.finishOp(tokentype, size) - }; - - pp$9.readToken_pipe_amp = function(code) { // '|&' - var next = this.input.charCodeAt(this.pos + 1); - if (next === code) { - if (this.options.ecmaVersion >= 12) { - var next2 = this.input.charCodeAt(this.pos + 2); - if (next2 === 61) { return this.finishOp(types.assign, 3) } - } - return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) - } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) - }; - - pp$9.readToken_caret = function() { // '^' - var next = this.input.charCodeAt(this.pos + 1); - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.bitwiseXOR, 1) - }; - - pp$9.readToken_plus_min = function(code) { // '+-' - var next = this.input.charCodeAt(this.pos + 1); - if (next === code) { - if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && - (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { - // A `-->` line comment - this.skipLineComment(3); - this.skipSpace(); - return this.nextToken() - } - return this.finishOp(types.incDec, 2) - } - if (next === 61) { return this.finishOp(types.assign, 2) } - return this.finishOp(types.plusMin, 1) - }; - - pp$9.readToken_lt_gt = function(code) { // '<>' - var next = this.input.charCodeAt(this.pos + 1); - var size = 1; - if (next === code) { - size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; - if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } - return this.finishOp(types.bitShift, size) - } - if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && - this.input.charCodeAt(this.pos + 3) === 45) { - // `") && S.newline_before) { - forward(3); - skip_line_comment("comment4"); - continue; - } - } - var ch = peek(); - if (!ch) return token("eof"); - var code = ch.charCodeAt(0); - switch (code) { - case 34: case 39: return read_string(); - case 46: return handle_dot(); - case 47: { - var tok = handle_slash(); - if (tok === next_token) continue; - return tok; - } - case 61: return handle_eq_sign(); - case 63: { - if (!is_option_chain_op()) break; // Handled below - - next(); // ? - next(); // . - - return token("punc", "?."); - } - case 96: return read_template_characters(true); - case 123: - S.brace_counter++; - break; - case 125: - S.brace_counter--; - if (S.template_braces.length > 0 - && S.template_braces[S.template_braces.length - 1] === S.brace_counter) - return read_template_characters(false); - break; - } - if (is_digit(code)) return read_num(); - if (PUNC_CHARS.has(ch)) return token("punc", next()); - if (OPERATOR_CHARS.has(ch)) return read_operator(); - if (code == 92 || is_identifier_start(ch)) return read_word(); - if (code == 35) return read_private_word(); - break; - } - parse_error("Unexpected character '" + ch + "'"); - } - - next_token.next = next; - next_token.peek = peek; - - next_token.context = function(nc) { - if (nc) S = nc; - return S; - }; - - next_token.add_directive = function(directive) { - S.directive_stack[S.directive_stack.length - 1].push(directive); - - if (S.directives[directive] === undefined) { - S.directives[directive] = 1; - } else { - S.directives[directive]++; - } - }; - - next_token.push_directives_stack = function() { - S.directive_stack.push([]); - }; - - next_token.pop_directives_stack = function() { - var directives = S.directive_stack[S.directive_stack.length - 1]; - - for (var i = 0; i < directives.length; i++) { - S.directives[directives[i]]--; - } - - S.directive_stack.pop(); - }; - - next_token.has_directive = function(directive) { - return S.directives[directive] > 0; - }; - - return next_token; - -} - -/* -----[ Parser (constants) ]----- */ - -var UNARY_PREFIX = makePredicate([ - "typeof", - "void", - "delete", - "--", - "++", - "!", - "~", - "-", - "+" -]); - -var UNARY_POSTFIX = makePredicate([ "--", "++" ]); - -var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "??=", "&&=", "||=", "/=", "*=", "**=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); - -var LOGICAL_ASSIGNMENT = makePredicate([ "??=", "&&=", "||=" ]); - -var PRECEDENCE = (function(a, ret) { - for (var i = 0; i < a.length; ++i) { - var b = a[i]; - for (var j = 0; j < b.length; ++j) { - ret[b[j]] = i + 1; - } - } - return ret; -})( - [ - ["||"], - ["??"], - ["&&"], - ["|"], - ["^"], - ["&"], - ["==", "===", "!=", "!=="], - ["<", ">", "<=", ">=", "in", "instanceof"], - [">>", "<<", ">>>"], - ["+", "-"], - ["*", "/", "%"], - ["**"] - ], - {} -); - -var ATOMIC_START_TOKEN = makePredicate([ "atom", "num", "big_int", "string", "regexp", "name" ]); - -/* -----[ Parser ]----- */ - -function parse($TEXT, options) { - // maps start tokens to count of comments found outside of their parens - // Example: /* I count */ ( /* I don't */ foo() ) - // Useful because comments_before property of call with parens outside - // contains both comments inside and outside these parens. Used to find the - // right #__PURE__ comments for an expression - const outer_comments_before_counts = new WeakMap(); - - options = defaults(options, { - bare_returns : false, - ecma : null, // Legacy - expression : false, - filename : null, - html5_comments : true, - module : false, - shebang : true, - strict : false, - toplevel : null, - }, true); - - var S = { - input : (typeof $TEXT == "string" - ? tokenizer($TEXT, options.filename, - options.html5_comments, options.shebang) - : $TEXT), - token : null, - prev : null, - peeked : null, - in_function : 0, - in_async : -1, - in_generator : -1, - in_directives : true, - in_loop : 0, - labels : [] - }; - - S.token = next(); - - function is(type, value) { - return is_token(S.token, type, value); - } - - function peek() { return S.peeked || (S.peeked = S.input()); } - - function next() { - S.prev = S.token; - - if (!S.peeked) peek(); - S.token = S.peeked; - S.peeked = null; - S.in_directives = S.in_directives && ( - S.token.type == "string" || is("punc", ";") - ); - return S.token; - } - - function prev() { - return S.prev; - } - - function croak(msg, line, col, pos) { - var ctx = S.input.context(); - js_error(msg, - ctx.filename, - line != null ? line : ctx.tokline, - col != null ? col : ctx.tokcol, - pos != null ? pos : ctx.tokpos); - } - - function token_error(token, msg) { - croak(msg, token.line, token.col); - } - - function unexpected(token) { - if (token == null) - token = S.token; - token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); - } - - function expect_token(type, val) { - if (is(type, val)) { - return next(); - } - token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); - } - - function expect(punc) { return expect_token("punc", punc); } - - function has_newline_before(token) { - return token.nlb || !token.comments_before.every((comment) => !comment.nlb); - } - - function can_insert_semicolon() { - return !options.strict - && (is("eof") || is("punc", "}") || has_newline_before(S.token)); - } - - function is_in_generator() { - return S.in_generator === S.in_function; - } - - function is_in_async() { - return S.in_async === S.in_function; - } - - function can_await() { - return ( - S.in_async === S.in_function - || S.in_function === 0 && S.input.has_directive("use strict") - ); - } - - function semicolon(optional) { - if (is("punc", ";")) next(); - else if (!optional && !can_insert_semicolon()) unexpected(); - } - - function parenthesised() { - expect("("); - var exp = expression(true); - expect(")"); - return exp; - } - - function embed_tokens(parser) { - return function _embed_tokens_wrapper(...args) { - const start = S.token; - const expr = parser(...args); - expr.start = start; - expr.end = prev(); - return expr; - }; - } - - function handle_regexp() { - if (is("operator", "/") || is("operator", "/=")) { - S.peeked = null; - S.token = S.input(S.token.value.substr(1)); // force regexp - } - } - - var statement = embed_tokens(function statement(is_export_default, is_for_body, is_if_body) { - handle_regexp(); - switch (S.token.type) { - case "string": - if (S.in_directives) { - var token = peek(); - if (!LATEST_RAW.includes("\\") - && (is_token(token, "punc", ";") - || is_token(token, "punc", "}") - || has_newline_before(token) - || is_token(token, "eof"))) { - S.input.add_directive(S.token.value); - } else { - S.in_directives = false; - } - } - var dir = S.in_directives, stat = simple_statement(); - return dir && stat.body instanceof AST_String ? new AST_Directive(stat.body) : stat; - case "template_head": - case "num": - case "big_int": - case "regexp": - case "operator": - case "atom": - return simple_statement(); - - case "name": - if (S.token.value == "async" && is_token(peek(), "keyword", "function")) { - next(); - next(); - if (is_for_body) { - croak("functions are not allowed as the body of a loop"); - } - return function_(AST_Defun, false, true, is_export_default); - } - if (S.token.value == "import" && !is_token(peek(), "punc", "(") && !is_token(peek(), "punc", ".")) { - next(); - var node = import_(); - semicolon(); - return node; - } - return is_token(peek(), "punc", ":") - ? labeled_statement() - : simple_statement(); - - case "punc": - switch (S.token.value) { - case "{": - return new AST_BlockStatement({ - start : S.token, - body : block_(), - end : prev() - }); - case "[": - case "(": - return simple_statement(); - case ";": - S.in_directives = false; - next(); - return new AST_EmptyStatement(); - default: - unexpected(); - } - - case "keyword": - switch (S.token.value) { - case "break": - next(); - return break_cont(AST_Break); - - case "continue": - next(); - return break_cont(AST_Continue); - - case "debugger": - next(); - semicolon(); - return new AST_Debugger(); - - case "do": - next(); - var body = in_loop(statement); - expect_token("keyword", "while"); - var condition = parenthesised(); - semicolon(true); - return new AST_Do({ - body : body, - condition : condition - }); - - case "while": - next(); - return new AST_While({ - condition : parenthesised(), - body : in_loop(function() { return statement(false, true); }) - }); - - case "for": - next(); - return for_(); - - case "class": - next(); - if (is_for_body) { - croak("classes are not allowed as the body of a loop"); - } - if (is_if_body) { - croak("classes are not allowed as the body of an if"); - } - return class_(AST_DefClass); - - case "function": - next(); - if (is_for_body) { - croak("functions are not allowed as the body of a loop"); - } - return function_(AST_Defun, false, false, is_export_default); - - case "if": - next(); - return if_(); - - case "return": - if (S.in_function == 0 && !options.bare_returns) - croak("'return' outside of function"); - next(); - var value = null; - if (is("punc", ";")) { - next(); - } else if (!can_insert_semicolon()) { - value = expression(true); - semicolon(); - } - return new AST_Return({ - value: value - }); - - case "switch": - next(); - return new AST_Switch({ - expression : parenthesised(), - body : in_loop(switch_body_) - }); - - case "throw": - next(); - if (has_newline_before(S.token)) - croak("Illegal newline after 'throw'"); - var value = expression(true); - semicolon(); - return new AST_Throw({ - value: value - }); - - case "try": - next(); - return try_(); - - case "var": - next(); - var node = var_(); - semicolon(); - return node; - - case "let": - next(); - var node = let_(); - semicolon(); - return node; - - case "const": - next(); - var node = const_(); - semicolon(); - return node; - - case "with": - if (S.input.has_directive("use strict")) { - croak("Strict mode may not include a with statement"); - } - next(); - return new AST_With({ - expression : parenthesised(), - body : statement() - }); - - case "export": - if (!is_token(peek(), "punc", "(")) { - next(); - var node = export_(); - if (is("punc", ";")) semicolon(); - return node; - } - } - } - unexpected(); - }); - - function labeled_statement() { - var label = as_symbol(AST_Label); - if (label.name === "await" && is_in_async()) { - token_error(S.prev, "await cannot be used as label inside async function"); - } - if (S.labels.some((l) => l.name === label.name)) { - // ECMA-262, 12.12: An ECMAScript program is considered - // syntactically incorrect if it contains a - // LabelledStatement that is enclosed by a - // LabelledStatement with the same Identifier as label. - croak("Label " + label.name + " defined twice"); - } - expect(":"); - S.labels.push(label); - var stat = statement(); - S.labels.pop(); - if (!(stat instanceof AST_IterationStatement)) { - // check for `continue` that refers to this label. - // those should be reported as syntax errors. - // https://github.com/mishoo/UglifyJS2/issues/287 - label.references.forEach(function(ref) { - if (ref instanceof AST_Continue) { - ref = ref.label.start; - croak("Continue label `" + label.name + "` refers to non-IterationStatement.", - ref.line, ref.col, ref.pos); - } - }); - } - return new AST_LabeledStatement({ body: stat, label: label }); - } - - function simple_statement(tmp) { - return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); - } - - function break_cont(type) { - var label = null, ldef; - if (!can_insert_semicolon()) { - label = as_symbol(AST_LabelRef, true); - } - if (label != null) { - ldef = S.labels.find((l) => l.name === label.name); - if (!ldef) - croak("Undefined label " + label.name); - label.thedef = ldef; - } else if (S.in_loop == 0) - croak(type.TYPE + " not inside a loop or switch"); - semicolon(); - var stat = new type({ label: label }); - if (ldef) ldef.references.push(stat); - return stat; - } - - function for_() { - var for_await_error = "`for await` invalid in this context"; - var await_tok = S.token; - if (await_tok.type == "name" && await_tok.value == "await") { - if (!can_await()) { - token_error(await_tok, for_await_error); - } - next(); - } else { - await_tok = false; - } - expect("("); - var init = null; - if (!is("punc", ";")) { - init = - is("keyword", "var") ? (next(), var_(true)) : - is("keyword", "let") ? (next(), let_(true)) : - is("keyword", "const") ? (next(), const_(true)) : - expression(true, true); - var is_in = is("operator", "in"); - var is_of = is("name", "of"); - if (await_tok && !is_of) { - token_error(await_tok, for_await_error); - } - if (is_in || is_of) { - if (init instanceof AST_Definitions) { - if (init.definitions.length > 1) - token_error(init.start, "Only one variable declaration allowed in for..in loop"); - } else if (!(is_assignable(init) || (init = to_destructuring(init)) instanceof AST_Destructuring)) { - token_error(init.start, "Invalid left-hand side in for..in loop"); - } - next(); - if (is_in) { - return for_in(init); - } else { - return for_of(init, !!await_tok); - } - } - } else if (await_tok) { - token_error(await_tok, for_await_error); - } - return regular_for(init); - } - - function regular_for(init) { - expect(";"); - var test = is("punc", ";") ? null : expression(true); - expect(";"); - var step = is("punc", ")") ? null : expression(true); - expect(")"); - return new AST_For({ - init : init, - condition : test, - step : step, - body : in_loop(function() { return statement(false, true); }) - }); - } - - function for_of(init, is_await) { - var lhs = init instanceof AST_Definitions ? init.definitions[0].name : null; - var obj = expression(true); - expect(")"); - return new AST_ForOf({ - await : is_await, - init : init, - name : lhs, - object : obj, - body : in_loop(function() { return statement(false, true); }) - }); - } - - function for_in(init) { - var obj = expression(true); - expect(")"); - return new AST_ForIn({ - init : init, - object : obj, - body : in_loop(function() { return statement(false, true); }) - }); - } - - var arrow_function = function(start, argnames, is_async) { - if (has_newline_before(S.token)) { - croak("Unexpected newline before arrow (=>)"); - } - - expect_token("arrow", "=>"); - - var body = _function_body(is("punc", "{"), false, is_async); - - var end = - body instanceof Array && body.length ? body[body.length - 1].end : - body instanceof Array ? start : - body.end; - - return new AST_Arrow({ - start : start, - end : end, - async : is_async, - argnames : argnames, - body : body - }); - }; - - var function_ = function(ctor, is_generator_property, is_async, is_export_default) { - var in_statement = ctor === AST_Defun; - var is_generator = is("operator", "*"); - if (is_generator) { - next(); - } - - var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null; - if (in_statement && !name) { - if (is_export_default) { - ctor = AST_Function; - } else { - unexpected(); - } - } - - if (name && ctor !== AST_Accessor && !(name instanceof AST_SymbolDeclaration)) - unexpected(prev()); - - var args = []; - var body = _function_body(true, is_generator || is_generator_property, is_async, name, args); - return new ctor({ - start : args.start, - end : body.end, - is_generator: is_generator, - async : is_async, - name : name, - argnames: args, - body : body - }); - }; - - function track_used_binding_identifiers(is_parameter, strict) { - var parameters = new Set(); - var duplicate = false; - var default_assignment = false; - var spread = false; - var strict_mode = !!strict; - var tracker = { - add_parameter: function(token) { - if (parameters.has(token.value)) { - if (duplicate === false) { - duplicate = token; - } - tracker.check_strict(); - } else { - parameters.add(token.value); - if (is_parameter) { - switch (token.value) { - case "arguments": - case "eval": - case "yield": - if (strict_mode) { - token_error(token, "Unexpected " + token.value + " identifier as parameter inside strict mode"); - } - break; - default: - if (RESERVED_WORDS.has(token.value)) { - unexpected(); - } - } - } - } - }, - mark_default_assignment: function(token) { - if (default_assignment === false) { - default_assignment = token; - } - }, - mark_spread: function(token) { - if (spread === false) { - spread = token; - } - }, - mark_strict_mode: function() { - strict_mode = true; - }, - is_strict: function() { - return default_assignment !== false || spread !== false || strict_mode; - }, - check_strict: function() { - if (tracker.is_strict() && duplicate !== false) { - token_error(duplicate, "Parameter " + duplicate.value + " was used already"); - } - } - }; - - return tracker; - } - - function parameters(params) { - var used_parameters = track_used_binding_identifiers(true, S.input.has_directive("use strict")); - - expect("("); - - while (!is("punc", ")")) { - var param = parameter(used_parameters); - params.push(param); - - if (!is("punc", ")")) { - expect(","); - } - - if (param instanceof AST_Expansion) { - break; - } - } - - next(); - } - - function parameter(used_parameters, symbol_type) { - var param; - var expand = false; - if (used_parameters === undefined) { - used_parameters = track_used_binding_identifiers(true, S.input.has_directive("use strict")); - } - if (is("expand", "...")) { - expand = S.token; - used_parameters.mark_spread(S.token); - next(); - } - param = binding_element(used_parameters, symbol_type); - - if (is("operator", "=") && expand === false) { - used_parameters.mark_default_assignment(S.token); - next(); - param = new AST_DefaultAssign({ - start: param.start, - left: param, - operator: "=", - right: expression(false), - end: S.token - }); - } - - if (expand !== false) { - if (!is("punc", ")")) { - unexpected(); - } - param = new AST_Expansion({ - start: expand, - expression: param, - end: expand - }); - } - used_parameters.check_strict(); - - return param; - } - - function binding_element(used_parameters, symbol_type) { - var elements = []; - var first = true; - var is_expand = false; - var expand_token; - var first_token = S.token; - if (used_parameters === undefined) { - used_parameters = track_used_binding_identifiers(false, S.input.has_directive("use strict")); - } - symbol_type = symbol_type === undefined ? AST_SymbolFunarg : symbol_type; - if (is("punc", "[")) { - next(); - while (!is("punc", "]")) { - if (first) { - first = false; - } else { - expect(","); - } - - if (is("expand", "...")) { - is_expand = true; - expand_token = S.token; - used_parameters.mark_spread(S.token); - next(); - } - if (is("punc")) { - switch (S.token.value) { - case ",": - elements.push(new AST_Hole({ - start: S.token, - end: S.token - })); - continue; - case "]": // Trailing comma after last element - break; - case "[": - case "{": - elements.push(binding_element(used_parameters, symbol_type)); - break; - default: - unexpected(); - } - } else if (is("name")) { - used_parameters.add_parameter(S.token); - elements.push(as_symbol(symbol_type)); - } else { - croak("Invalid function parameter"); - } - if (is("operator", "=") && is_expand === false) { - used_parameters.mark_default_assignment(S.token); - next(); - elements[elements.length - 1] = new AST_DefaultAssign({ - start: elements[elements.length - 1].start, - left: elements[elements.length - 1], - operator: "=", - right: expression(false), - end: S.token - }); - } - if (is_expand) { - if (!is("punc", "]")) { - croak("Rest element must be last element"); - } - elements[elements.length - 1] = new AST_Expansion({ - start: expand_token, - expression: elements[elements.length - 1], - end: expand_token - }); - } - } - expect("]"); - used_parameters.check_strict(); - return new AST_Destructuring({ - start: first_token, - names: elements, - is_array: true, - end: prev() - }); - } else if (is("punc", "{")) { - next(); - while (!is("punc", "}")) { - if (first) { - first = false; - } else { - expect(","); - } - if (is("expand", "...")) { - is_expand = true; - expand_token = S.token; - used_parameters.mark_spread(S.token); - next(); - } - if (is("name") && (is_token(peek(), "punc") || is_token(peek(), "operator")) && [",", "}", "="].includes(peek().value)) { - used_parameters.add_parameter(S.token); - var start = prev(); - var value = as_symbol(symbol_type); - if (is_expand) { - elements.push(new AST_Expansion({ - start: expand_token, - expression: value, - end: value.end, - })); - } else { - elements.push(new AST_ObjectKeyVal({ - start: start, - key: value.name, - value: value, - end: value.end, - })); - } - } else if (is("punc", "}")) { - continue; // Allow trailing hole - } else { - var property_token = S.token; - var property = as_property_name(); - if (property === null) { - unexpected(prev()); - } else if (prev().type === "name" && !is("punc", ":")) { - elements.push(new AST_ObjectKeyVal({ - start: prev(), - key: property, - value: new symbol_type({ - start: prev(), - name: property, - end: prev() - }), - end: prev() - })); - } else { - expect(":"); - elements.push(new AST_ObjectKeyVal({ - start: property_token, - quote: property_token.quote, - key: property, - value: binding_element(used_parameters, symbol_type), - end: prev() - })); - } - } - if (is_expand) { - if (!is("punc", "}")) { - croak("Rest element must be last element"); - } - } else if (is("operator", "=")) { - used_parameters.mark_default_assignment(S.token); - next(); - elements[elements.length - 1].value = new AST_DefaultAssign({ - start: elements[elements.length - 1].value.start, - left: elements[elements.length - 1].value, - operator: "=", - right: expression(false), - end: S.token - }); - } - } - expect("}"); - used_parameters.check_strict(); - return new AST_Destructuring({ - start: first_token, - names: elements, - is_array: false, - end: prev() - }); - } else if (is("name")) { - used_parameters.add_parameter(S.token); - return as_symbol(symbol_type); - } else { - croak("Invalid function parameter"); - } - } - - function params_or_seq_(allow_arrows, maybe_sequence) { - var spread_token; - var invalid_sequence; - var trailing_comma; - var a = []; - expect("("); - while (!is("punc", ")")) { - if (spread_token) unexpected(spread_token); - if (is("expand", "...")) { - spread_token = S.token; - if (maybe_sequence) invalid_sequence = S.token; - next(); - a.push(new AST_Expansion({ - start: prev(), - expression: expression(), - end: S.token, - })); - } else { - a.push(expression()); - } - if (!is("punc", ")")) { - expect(","); - if (is("punc", ")")) { - trailing_comma = prev(); - if (maybe_sequence) invalid_sequence = trailing_comma; - } - } - } - expect(")"); - if (allow_arrows && is("arrow", "=>")) { - if (spread_token && trailing_comma) unexpected(trailing_comma); - } else if (invalid_sequence) { - unexpected(invalid_sequence); - } - return a; - } - - function _function_body(block, generator, is_async, name, args) { - var loop = S.in_loop; - var labels = S.labels; - var current_generator = S.in_generator; - var current_async = S.in_async; - ++S.in_function; - if (generator) - S.in_generator = S.in_function; - if (is_async) - S.in_async = S.in_function; - if (args) parameters(args); - if (block) - S.in_directives = true; - S.in_loop = 0; - S.labels = []; - if (block) { - S.input.push_directives_stack(); - var a = block_(); - if (name) _verify_symbol(name); - if (args) args.forEach(_verify_symbol); - S.input.pop_directives_stack(); - } else { - var a = [new AST_Return({ - start: S.token, - value: expression(false), - end: S.token - })]; - } - --S.in_function; - S.in_loop = loop; - S.labels = labels; - S.in_generator = current_generator; - S.in_async = current_async; - return a; - } - - function _await_expression() { - // Previous token must be "await" and not be interpreted as an identifier - if (!can_await()) { - croak("Unexpected await expression outside async function", - S.prev.line, S.prev.col, S.prev.pos); - } - // the await expression is parsed as a unary expression in Babel - return new AST_Await({ - start: prev(), - end: S.token, - expression : maybe_unary(true), - }); - } - - function _yield_expression() { - // Previous token must be keyword yield and not be interpret as an identifier - if (!is_in_generator()) { - croak("Unexpected yield expression outside generator function", - S.prev.line, S.prev.col, S.prev.pos); - } - var start = S.token; - var star = false; - var has_expression = true; - - // Attempt to get expression or star (and then the mandatory expression) - // behind yield on the same line. - // - // If nothing follows on the same line of the yieldExpression, - // it should default to the value `undefined` for yield to return. - // In that case, the `undefined` stored as `null` in ast. - // - // Note 1: It isn't allowed for yield* to close without an expression - // Note 2: If there is a nlb between yield and star, it is interpret as - // yield * - if (can_insert_semicolon() || - (is("punc") && PUNC_AFTER_EXPRESSION.has(S.token.value))) { - has_expression = false; - - } else if (is("operator", "*")) { - star = true; - next(); - } - - return new AST_Yield({ - start : start, - is_star : star, - expression : has_expression ? expression() : null, - end : prev() - }); - } - - function if_() { - var cond = parenthesised(), body = statement(false, false, true), belse = null; - if (is("keyword", "else")) { - next(); - belse = statement(false, false, true); - } - return new AST_If({ - condition : cond, - body : body, - alternative : belse - }); - } - - function block_() { - expect("{"); - var a = []; - while (!is("punc", "}")) { - if (is("eof")) unexpected(); - a.push(statement()); - } - next(); - return a; - } - - function switch_body_() { - expect("{"); - var a = [], cur = null, branch = null, tmp; - while (!is("punc", "}")) { - if (is("eof")) unexpected(); - if (is("keyword", "case")) { - if (branch) branch.end = prev(); - cur = []; - branch = new AST_Case({ - start : (tmp = S.token, next(), tmp), - expression : expression(true), - body : cur - }); - a.push(branch); - expect(":"); - } else if (is("keyword", "default")) { - if (branch) branch.end = prev(); - cur = []; - branch = new AST_Default({ - start : (tmp = S.token, next(), expect(":"), tmp), - body : cur - }); - a.push(branch); - } else { - if (!cur) unexpected(); - cur.push(statement()); - } - } - if (branch) branch.end = prev(); - next(); - return a; - } - - function try_() { - var body = block_(), bcatch = null, bfinally = null; - if (is("keyword", "catch")) { - var start = S.token; - next(); - if (is("punc", "{")) { - var name = null; - } else { - expect("("); - var name = parameter(undefined, AST_SymbolCatch); - expect(")"); - } - bcatch = new AST_Catch({ - start : start, - argname : name, - body : block_(), - end : prev() - }); - } - if (is("keyword", "finally")) { - var start = S.token; - next(); - bfinally = new AST_Finally({ - start : start, - body : block_(), - end : prev() - }); - } - if (!bcatch && !bfinally) - croak("Missing catch/finally blocks"); - return new AST_Try({ - body : body, - bcatch : bcatch, - bfinally : bfinally - }); - } - - function vardefs(no_in, kind) { - var a = []; - var def; - for (;;) { - var sym_type = - kind === "var" ? AST_SymbolVar : - kind === "const" ? AST_SymbolConst : - kind === "let" ? AST_SymbolLet : null; - if (is("punc", "{") || is("punc", "[")) { - def = new AST_VarDef({ - start: S.token, - name: binding_element(undefined ,sym_type), - value: is("operator", "=") ? (expect_token("operator", "="), expression(false, no_in)) : null, - end: prev() - }); - } else { - def = new AST_VarDef({ - start : S.token, - name : as_symbol(sym_type), - value : is("operator", "=") - ? (next(), expression(false, no_in)) - : !no_in && kind === "const" - ? croak("Missing initializer in const declaration") : null, - end : prev() - }); - if (def.name.name == "import") croak("Unexpected token: import"); - } - a.push(def); - if (!is("punc", ",")) - break; - next(); - } - return a; - } - - var var_ = function(no_in) { - return new AST_Var({ - start : prev(), - definitions : vardefs(no_in, "var"), - end : prev() - }); - }; - - var let_ = function(no_in) { - return new AST_Let({ - start : prev(), - definitions : vardefs(no_in, "let"), - end : prev() - }); - }; - - var const_ = function(no_in) { - return new AST_Const({ - start : prev(), - definitions : vardefs(no_in, "const"), - end : prev() - }); - }; - - var new_ = function(allow_calls) { - var start = S.token; - expect_token("operator", "new"); - if (is("punc", ".")) { - next(); - expect_token("name", "target"); - return subscripts(new AST_NewTarget({ - start : start, - end : prev() - }), allow_calls); - } - var newexp = expr_atom(false), args; - if (is("punc", "(")) { - next(); - args = expr_list(")", true); - } else { - args = []; - } - var call = new AST_New({ - start : start, - expression : newexp, - args : args, - end : prev() - }); - annotate(call); - return subscripts(call, allow_calls); - }; - - function as_atom_node() { - var tok = S.token, ret; - switch (tok.type) { - case "name": - ret = _make_symbol(AST_SymbolRef); - break; - case "num": - ret = new AST_Number({ - start: tok, - end: tok, - value: tok.value, - raw: LATEST_RAW - }); - break; - case "big_int": - ret = new AST_BigInt({ start: tok, end: tok, value: tok.value }); - break; - case "string": - ret = new AST_String({ - start : tok, - end : tok, - value : tok.value, - quote : tok.quote - }); - break; - case "regexp": - const [_, source, flags] = tok.value.match(/^\/(.*)\/(\w*)$/); - - ret = new AST_RegExp({ start: tok, end: tok, value: { source, flags } }); - break; - case "atom": - switch (tok.value) { - case "false": - ret = new AST_False({ start: tok, end: tok }); - break; - case "true": - ret = new AST_True({ start: tok, end: tok }); - break; - case "null": - ret = new AST_Null({ start: tok, end: tok }); - break; - } - break; - } - next(); - return ret; - } - - function to_fun_args(ex, default_seen_above) { - var insert_default = function(ex, default_value) { - if (default_value) { - return new AST_DefaultAssign({ - start: ex.start, - left: ex, - operator: "=", - right: default_value, - end: default_value.end - }); - } - return ex; - }; - if (ex instanceof AST_Object) { - return insert_default(new AST_Destructuring({ - start: ex.start, - end: ex.end, - is_array: false, - names: ex.properties.map(prop => to_fun_args(prop)) - }), default_seen_above); - } else if (ex instanceof AST_ObjectKeyVal) { - ex.value = to_fun_args(ex.value); - return insert_default(ex, default_seen_above); - } else if (ex instanceof AST_Hole) { - return ex; - } else if (ex instanceof AST_Destructuring) { - ex.names = ex.names.map(name => to_fun_args(name)); - return insert_default(ex, default_seen_above); - } else if (ex instanceof AST_SymbolRef) { - return insert_default(new AST_SymbolFunarg({ - name: ex.name, - start: ex.start, - end: ex.end - }), default_seen_above); - } else if (ex instanceof AST_Expansion) { - ex.expression = to_fun_args(ex.expression); - return insert_default(ex, default_seen_above); - } else if (ex instanceof AST_Array) { - return insert_default(new AST_Destructuring({ - start: ex.start, - end: ex.end, - is_array: true, - names: ex.elements.map(elm => to_fun_args(elm)) - }), default_seen_above); - } else if (ex instanceof AST_Assign) { - return insert_default(to_fun_args(ex.left, ex.right), default_seen_above); - } else if (ex instanceof AST_DefaultAssign) { - ex.left = to_fun_args(ex.left); - return ex; - } else { - croak("Invalid function parameter", ex.start.line, ex.start.col); - } - } - - var expr_atom = function(allow_calls, allow_arrows) { - if (is("operator", "new")) { - return new_(allow_calls); - } - if (is("operator", "import")) { - return import_meta(); - } - var start = S.token; - var peeked; - var async = is("name", "async") - && (peeked = peek()).value != "[" - && peeked.type != "arrow" - && as_atom_node(); - if (is("punc")) { - switch (S.token.value) { - case "(": - if (async && !allow_calls) break; - var exprs = params_or_seq_(allow_arrows, !async); - if (allow_arrows && is("arrow", "=>")) { - return arrow_function(start, exprs.map(e => to_fun_args(e)), !!async); - } - var ex = async ? new AST_Call({ - expression: async, - args: exprs - }) : exprs.length == 1 ? exprs[0] : new AST_Sequence({ - expressions: exprs - }); - if (ex.start) { - const outer_comments_before = start.comments_before.length; - outer_comments_before_counts.set(start, outer_comments_before); - ex.start.comments_before.unshift(...start.comments_before); - start.comments_before = ex.start.comments_before; - if (outer_comments_before == 0 && start.comments_before.length > 0) { - var comment = start.comments_before[0]; - if (!comment.nlb) { - comment.nlb = start.nlb; - start.nlb = false; - } - } - start.comments_after = ex.start.comments_after; - } - ex.start = start; - var end = prev(); - if (ex.end) { - end.comments_before = ex.end.comments_before; - ex.end.comments_after.push(...end.comments_after); - end.comments_after = ex.end.comments_after; - } - ex.end = end; - if (ex instanceof AST_Call) annotate(ex); - return subscripts(ex, allow_calls); - case "[": - return subscripts(array_(), allow_calls); - case "{": - return subscripts(object_or_destructuring_(), allow_calls); - } - if (!async) unexpected(); - } - if (allow_arrows && is("name") && is_token(peek(), "arrow")) { - var param = new AST_SymbolFunarg({ - name: S.token.value, - start: start, - end: start, - }); - next(); - return arrow_function(start, [param], !!async); - } - if (is("keyword", "function")) { - next(); - var func = function_(AST_Function, false, !!async); - func.start = start; - func.end = prev(); - return subscripts(func, allow_calls); - } - if (async) return subscripts(async, allow_calls); - if (is("keyword", "class")) { - next(); - var cls = class_(AST_ClassExpression); - cls.start = start; - cls.end = prev(); - return subscripts(cls, allow_calls); - } - if (is("template_head")) { - return subscripts(template_string(), allow_calls); - } - if (ATOMIC_START_TOKEN.has(S.token.type)) { - return subscripts(as_atom_node(), allow_calls); - } - unexpected(); - }; - - function template_string() { - var segments = [], start = S.token; - - segments.push(new AST_TemplateSegment({ - start: S.token, - raw: LATEST_RAW, - value: S.token.value, - end: S.token - })); - - while (!LATEST_TEMPLATE_END) { - next(); - handle_regexp(); - segments.push(expression(true)); - - segments.push(new AST_TemplateSegment({ - start: S.token, - raw: LATEST_RAW, - value: S.token.value, - end: S.token - })); - } - next(); - - return new AST_TemplateString({ - start: start, - segments: segments, - end: S.token - }); - } - - function expr_list(closing, allow_trailing_comma, allow_empty) { - var first = true, a = []; - while (!is("punc", closing)) { - if (first) first = false; else expect(","); - if (allow_trailing_comma && is("punc", closing)) break; - if (is("punc", ",") && allow_empty) { - a.push(new AST_Hole({ start: S.token, end: S.token })); - } else if (is("expand", "...")) { - next(); - a.push(new AST_Expansion({start: prev(), expression: expression(),end: S.token})); - } else { - a.push(expression(false)); - } - } - next(); - return a; - } - - var array_ = embed_tokens(function() { - expect("["); - return new AST_Array({ - elements: expr_list("]", !options.strict, true) - }); - }); - - var create_accessor = embed_tokens((is_generator, is_async) => { - return function_(AST_Accessor, is_generator, is_async); - }); - - var object_or_destructuring_ = embed_tokens(function object_or_destructuring_() { - var start = S.token, first = true, a = []; - expect("{"); - while (!is("punc", "}")) { - if (first) first = false; else expect(","); - if (!options.strict && is("punc", "}")) - // allow trailing comma - break; - - start = S.token; - if (start.type == "expand") { - next(); - a.push(new AST_Expansion({ - start: start, - expression: expression(false), - end: prev(), - })); - continue; - } - - var name = as_property_name(); - var value; - - // Check property and fetch value - if (!is("punc", ":")) { - var concise = concise_method_or_getset(name, start); - if (concise) { - a.push(concise); - continue; - } - - value = new AST_SymbolRef({ - start: prev(), - name: name, - end: prev() - }); - } else if (name === null) { - unexpected(prev()); - } else { - next(); // `:` - see first condition - value = expression(false); - } - - // Check for default value and alter value accordingly if necessary - if (is("operator", "=")) { - next(); - value = new AST_Assign({ - start: start, - left: value, - operator: "=", - right: expression(false), - logical: false, - end: prev() - }); - } - - // Create property - a.push(new AST_ObjectKeyVal({ - start: start, - quote: start.quote, - key: name instanceof AST_Node ? name : "" + name, - value: value, - end: prev() - })); - } - next(); - return new AST_Object({ properties: a }); - }); - - function class_(KindOfClass) { - var start, method, class_name, extends_, a = []; - - S.input.push_directives_stack(); // Push directive stack, but not scope stack - S.input.add_directive("use strict"); - - if (S.token.type == "name" && S.token.value != "extends") { - class_name = as_symbol(KindOfClass === AST_DefClass ? AST_SymbolDefClass : AST_SymbolClass); - } - - if (KindOfClass === AST_DefClass && !class_name) { - unexpected(); - } - - if (S.token.value == "extends") { - next(); - extends_ = expression(true); - } - - expect("{"); - - while (is("punc", ";")) { next(); } // Leading semicolons are okay in class bodies. - while (!is("punc", "}")) { - start = S.token; - method = concise_method_or_getset(as_property_name(), start, true); - if (!method) { unexpected(); } - a.push(method); - while (is("punc", ";")) { next(); } - } - - S.input.pop_directives_stack(); - - next(); - - return new KindOfClass({ - start: start, - name: class_name, - extends: extends_, - properties: a, - end: prev(), - }); - } - - function concise_method_or_getset(name, start, is_class) { - var get_method_name_ast = function(name, start) { - if (typeof name === "string" || typeof name === "number") { - return new AST_SymbolMethod({ - start, - name: "" + name, - end: prev() - }); - } else if (name === null) { - unexpected(); - } - return name; - }; - const get_class_property_key_ast = (name) => { - if (typeof name === "string" || typeof name === "number") { - return new AST_SymbolClassProperty({ - start: property_token, - end: property_token, - name: "" + name - }); - } else if (name === null) { - unexpected(); - } - return name; - }; - var privatename = start.type == "privatename"; - var is_async = false; - var is_static = false; - var is_generator = false; - var property_token = start; - if (is_class && name === "static" && !is("punc", "(")) { - is_static = true; - property_token = S.token; - privatename = property_token.type == "privatename"; - name = as_property_name(); - } - if (name === "async" && !is("punc", "(") && !is("punc", ",") && !is("punc", "}") && !is("operator", "=")) { - is_async = true; - property_token = S.token; - privatename = property_token.type == "privatename"; - name = as_property_name(); - } - if (name === null) { - is_generator = true; - property_token = S.token; - privatename = property_token.type == "privatename"; - name = as_property_name(); - if (name === null) { - unexpected(); - } - } - if (is("punc", "(")) { - name = get_method_name_ast(name, start); - const AST_MethodVariant = privatename - ? AST_PrivateMethod - : AST_ConciseMethod; - var node = new AST_MethodVariant({ - start : start, - static : is_static, - is_generator: is_generator, - async : is_async, - key : name, - quote : name instanceof AST_SymbolMethod ? - property_token.quote : undefined, - value : create_accessor(is_generator, is_async), - end : prev() - }); - return node; - } - const setter_token = S.token; - if ((name === "get" || name === "set") && setter_token.type === "privatename") { - next(); - - const AST_AccessorVariant = - name === "get" - ? AST_PrivateGetter - : AST_PrivateSetter; - - return new AST_AccessorVariant({ - start, - static: is_static, - key: get_method_name_ast(setter_token.value, start), - value: create_accessor(), - end: prev(), - }); - } - - if (name == "get") { - if (!is("punc") || is("punc", "[")) { - name = get_method_name_ast(as_property_name(), start); - return new AST_ObjectGetter({ - start : start, - static: is_static, - key : name, - quote : name instanceof AST_SymbolMethod ? - setter_token.quote : undefined, - value : create_accessor(), - end : prev() - }); - } - } else if (name == "set") { - if (!is("punc") || is("punc", "[")) { - name = get_method_name_ast(as_property_name(), start); - return new AST_ObjectSetter({ - start : start, - static: is_static, - key : name, - quote : name instanceof AST_SymbolMethod ? - setter_token.quote : undefined, - value : create_accessor(), - end : prev() - }); - } - } - if (is_class) { - const key = get_class_property_key_ast(name); - const quote = key instanceof AST_SymbolClassProperty - ? property_token.quote - : undefined; - const AST_ClassPropertyVariant = privatename - ? AST_ClassPrivateProperty - : AST_ClassProperty; - if (is("operator", "=")) { - next(); - return new AST_ClassPropertyVariant({ - start, - static: is_static, - quote, - key, - value: expression(false), - end: prev() - }); - } else if ( - is("name") - || is("privatename") - || is("operator", "*") - || is("punc", ";") - || is("punc", "}") - ) { - return new AST_ClassPropertyVariant({ - start, - static: is_static, - quote, - key, - end: prev() - }); - } - } - } - - function import_() { - var start = prev(); - - var imported_name; - var imported_names; - if (is("name")) { - imported_name = as_symbol(AST_SymbolImport); - } - - if (is("punc", ",")) { - next(); - } - - imported_names = map_names(true); - - if (imported_names || imported_name) { - expect_token("name", "from"); - } - var mod_str = S.token; - if (mod_str.type !== "string") { - unexpected(); - } - next(); - return new AST_Import({ - start: start, - imported_name: imported_name, - imported_names: imported_names, - module_name: new AST_String({ - start: mod_str, - value: mod_str.value, - quote: mod_str.quote, - end: mod_str, - }), - end: S.token, - }); - } - - function import_meta() { - var start = S.token; - expect_token("operator", "import"); - expect_token("punc", "."); - expect_token("name", "meta"); - return subscripts(new AST_ImportMeta({ - start: start, - end: prev() - }), false); - } - - function map_name(is_import) { - function make_symbol(type) { - return new type({ - name: as_property_name(), - start: prev(), - end: prev() - }); - } - - var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; - var type = is_import ? AST_SymbolImport : AST_SymbolExport; - var start = S.token; - var foreign_name; - var name; - - if (is_import) { - foreign_name = make_symbol(foreign_type); - } else { - name = make_symbol(type); - } - if (is("name", "as")) { - next(); // The "as" word - if (is_import) { - name = make_symbol(type); - } else { - foreign_name = make_symbol(foreign_type); - } - } else if (is_import) { - name = new type(foreign_name); - } else { - foreign_name = new foreign_type(name); - } - - return new AST_NameMapping({ - start: start, - foreign_name: foreign_name, - name: name, - end: prev(), - }); - } - - function map_nameAsterisk(is_import, name) { - var foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign; - var type = is_import ? AST_SymbolImport : AST_SymbolExport; - var start = S.token; - var foreign_name; - var end = prev(); - - name = name || new type({ - name: "*", - start: start, - end: end, - }); - - foreign_name = new foreign_type({ - name: "*", - start: start, - end: end, - }); - - return new AST_NameMapping({ - start: start, - foreign_name: foreign_name, - name: name, - end: end, - }); - } - - function map_names(is_import) { - var names; - if (is("punc", "{")) { - next(); - names = []; - while (!is("punc", "}")) { - names.push(map_name(is_import)); - if (is("punc", ",")) { - next(); - } - } - next(); - } else if (is("operator", "*")) { - var name; - next(); - if (is_import && is("name", "as")) { - next(); // The "as" word - name = as_symbol(is_import ? AST_SymbolImport : AST_SymbolExportForeign); - } - names = [map_nameAsterisk(is_import, name)]; - } - return names; - } - - function export_() { - var start = S.token; - var is_default; - var exported_names; - - if (is("keyword", "default")) { - is_default = true; - next(); - } else if (exported_names = map_names(false)) { - if (is("name", "from")) { - next(); - - var mod_str = S.token; - if (mod_str.type !== "string") { - unexpected(); - } - next(); - - return new AST_Export({ - start: start, - is_default: is_default, - exported_names: exported_names, - module_name: new AST_String({ - start: mod_str, - value: mod_str.value, - quote: mod_str.quote, - end: mod_str, - }), - end: prev(), - }); - } else { - return new AST_Export({ - start: start, - is_default: is_default, - exported_names: exported_names, - end: prev(), - }); - } - } - - var node; - var exported_value; - var exported_definition; - if (is("punc", "{") - || is_default - && (is("keyword", "class") || is("keyword", "function")) - && is_token(peek(), "punc")) { - exported_value = expression(false); - semicolon(); - } else if ((node = statement(is_default)) instanceof AST_Definitions && is_default) { - unexpected(node.start); - } else if (node instanceof AST_Definitions || node instanceof AST_Lambda || node instanceof AST_DefClass) { - exported_definition = node; - } else if (node instanceof AST_SimpleStatement) { - exported_value = node.body; - } else { - unexpected(node.start); - } - - return new AST_Export({ - start: start, - is_default: is_default, - exported_value: exported_value, - exported_definition: exported_definition, - end: prev(), - }); - } - - function as_property_name() { - var tmp = S.token; - switch (tmp.type) { - case "punc": - if (tmp.value === "[") { - next(); - var ex = expression(false); - expect("]"); - return ex; - } else unexpected(tmp); - case "operator": - if (tmp.value === "*") { - next(); - return null; - } - if (!["delete", "in", "instanceof", "new", "typeof", "void"].includes(tmp.value)) { - unexpected(tmp); - } - /* falls through */ - case "name": - case "privatename": - case "string": - case "num": - case "big_int": - case "keyword": - case "atom": - next(); - return tmp.value; - default: - unexpected(tmp); - } - } - - function as_name() { - var tmp = S.token; - if (tmp.type != "name" && tmp.type != "privatename") unexpected(); - next(); - return tmp.value; - } - - function _make_symbol(type) { - var name = S.token.value; - return new (name == "this" ? AST_This : - name == "super" ? AST_Super : - type)({ - name : String(name), - start : S.token, - end : S.token - }); - } - - function _verify_symbol(sym) { - var name = sym.name; - if (is_in_generator() && name == "yield") { - token_error(sym.start, "Yield cannot be used as identifier inside generators"); - } - if (S.input.has_directive("use strict")) { - if (name == "yield") { - token_error(sym.start, "Unexpected yield identifier inside strict mode"); - } - if (sym instanceof AST_SymbolDeclaration && (name == "arguments" || name == "eval")) { - token_error(sym.start, "Unexpected " + name + " in strict mode"); - } - } - } - - function as_symbol(type, noerror) { - if (!is("name")) { - if (!noerror) croak("Name expected"); - return null; - } - var sym = _make_symbol(type); - _verify_symbol(sym); - next(); - return sym; - } - - // Annotate AST_Call, AST_Lambda or AST_New with the special comments - function annotate(node) { - var start = node.start; - var comments = start.comments_before; - const comments_outside_parens = outer_comments_before_counts.get(start); - var i = comments_outside_parens != null ? comments_outside_parens : comments.length; - while (--i >= 0) { - var comment = comments[i]; - if (/[@#]__/.test(comment.value)) { - if (/[@#]__PURE__/.test(comment.value)) { - set_annotation(node, _PURE); - break; - } - if (/[@#]__INLINE__/.test(comment.value)) { - set_annotation(node, _INLINE); - break; - } - if (/[@#]__NOINLINE__/.test(comment.value)) { - set_annotation(node, _NOINLINE); - break; - } - } - } - } - - var subscripts = function(expr, allow_calls, is_chain) { - var start = expr.start; - if (is("punc", ".")) { - next(); - const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; - return subscripts(new AST_DotVariant({ - start : start, - expression : expr, - optional : false, - property : as_name(), - end : prev() - }), allow_calls, is_chain); - } - if (is("punc", "[")) { - next(); - var prop = expression(true); - expect("]"); - return subscripts(new AST_Sub({ - start : start, - expression : expr, - optional : false, - property : prop, - end : prev() - }), allow_calls, is_chain); - } - if (allow_calls && is("punc", "(")) { - next(); - var call = new AST_Call({ - start : start, - expression : expr, - optional : false, - args : call_args(), - end : prev() - }); - annotate(call); - return subscripts(call, true, is_chain); - } - - if (is("punc", "?.")) { - next(); - - let chain_contents; - - if (allow_calls && is("punc", "(")) { - next(); - - const call = new AST_Call({ - start, - optional: true, - expression: expr, - args: call_args(), - end: prev() - }); - annotate(call); - - chain_contents = subscripts(call, true, true); - } else if (is("name") || is("privatename")) { - const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; - chain_contents = subscripts(new AST_DotVariant({ - start, - expression: expr, - optional: true, - property: as_name(), - end: prev() - }), allow_calls, true); - } else if (is("punc", "[")) { - next(); - const property = expression(true); - expect("]"); - chain_contents = subscripts(new AST_Sub({ - start, - expression: expr, - optional: true, - property, - end: prev() - }), allow_calls, true); - } - - if (!chain_contents) unexpected(); - - if (chain_contents instanceof AST_Chain) return chain_contents; - - return new AST_Chain({ - start, - expression: chain_contents, - end: prev() - }); - } - - if (is("template_head")) { - if (is_chain) { - // a?.b`c` is a syntax error - unexpected(); - } - - return subscripts(new AST_PrefixedTemplateString({ - start: start, - prefix: expr, - template_string: template_string(), - end: prev() - }), allow_calls); - } - - return expr; - }; - - function call_args() { - var args = []; - while (!is("punc", ")")) { - if (is("expand", "...")) { - next(); - args.push(new AST_Expansion({ - start: prev(), - expression: expression(false), - end: prev() - })); - } else { - args.push(expression(false)); - } - if (!is("punc", ")")) { - expect(","); - } - } - next(); - return args; - } - - var maybe_unary = function(allow_calls, allow_arrows) { - var start = S.token; - if (start.type == "name" && start.value == "await" && can_await()) { - next(); - return _await_expression(); - } - if (is("operator") && UNARY_PREFIX.has(start.value)) { - next(); - handle_regexp(); - var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(allow_calls)); - ex.start = start; - ex.end = prev(); - return ex; - } - var val = expr_atom(allow_calls, allow_arrows); - while (is("operator") && UNARY_POSTFIX.has(S.token.value) && !has_newline_before(S.token)) { - if (val instanceof AST_Arrow) unexpected(); - val = make_unary(AST_UnaryPostfix, S.token, val); - val.start = start; - val.end = S.token; - next(); - } - return val; - }; - - function make_unary(ctor, token, expr) { - var op = token.value; - switch (op) { - case "++": - case "--": - if (!is_assignable(expr)) - croak("Invalid use of " + op + " operator", token.line, token.col, token.pos); - break; - case "delete": - if (expr instanceof AST_SymbolRef && S.input.has_directive("use strict")) - croak("Calling delete on expression not allowed in strict mode", expr.start.line, expr.start.col, expr.start.pos); - break; - } - return new ctor({ operator: op, expression: expr }); - } - - var expr_op = function(left, min_prec, no_in) { - var op = is("operator") ? S.token.value : null; - if (op == "in" && no_in) op = null; - if (op == "**" && left instanceof AST_UnaryPrefix - /* unary token in front not allowed - parenthesis required */ - && !is_token(left.start, "punc", "(") - && left.operator !== "--" && left.operator !== "++") - unexpected(left.start); - var prec = op != null ? PRECEDENCE[op] : null; - if (prec != null && (prec > min_prec || (op === "**" && min_prec === prec))) { - next(); - var right = expr_op(maybe_unary(true), prec, no_in); - return expr_op(new AST_Binary({ - start : left.start, - left : left, - operator : op, - right : right, - end : right.end - }), min_prec, no_in); - } - return left; - }; - - function expr_ops(no_in) { - return expr_op(maybe_unary(true, true), 0, no_in); - } - - var maybe_conditional = function(no_in) { - var start = S.token; - var expr = expr_ops(no_in); - if (is("operator", "?")) { - next(); - var yes = expression(false); - expect(":"); - return new AST_Conditional({ - start : start, - condition : expr, - consequent : yes, - alternative : expression(false, no_in), - end : prev() - }); - } - return expr; - }; - - function is_assignable(expr) { - return expr instanceof AST_PropAccess || expr instanceof AST_SymbolRef; - } - - function to_destructuring(node) { - if (node instanceof AST_Object) { - node = new AST_Destructuring({ - start: node.start, - names: node.properties.map(to_destructuring), - is_array: false, - end: node.end - }); - } else if (node instanceof AST_Array) { - var names = []; - - for (var i = 0; i < node.elements.length; i++) { - // Only allow expansion as last element - if (node.elements[i] instanceof AST_Expansion) { - if (i + 1 !== node.elements.length) { - token_error(node.elements[i].start, "Spread must the be last element in destructuring array"); - } - node.elements[i].expression = to_destructuring(node.elements[i].expression); - } - - names.push(to_destructuring(node.elements[i])); - } - - node = new AST_Destructuring({ - start: node.start, - names: names, - is_array: true, - end: node.end - }); - } else if (node instanceof AST_ObjectProperty) { - node.value = to_destructuring(node.value); - } else if (node instanceof AST_Assign) { - node = new AST_DefaultAssign({ - start: node.start, - left: node.left, - operator: "=", - right: node.right, - end: node.end - }); - } - return node; - } - - // In ES6, AssignmentExpression can also be an ArrowFunction - var maybe_assign = function(no_in) { - handle_regexp(); - var start = S.token; - - if (start.type == "name" && start.value == "yield") { - if (is_in_generator()) { - next(); - return _yield_expression(); - } else if (S.input.has_directive("use strict")) { - token_error(S.token, "Unexpected yield identifier inside strict mode"); - } - } - - var left = maybe_conditional(no_in); - var val = S.token.value; - - if (is("operator") && ASSIGNMENT.has(val)) { - if (is_assignable(left) || (left = to_destructuring(left)) instanceof AST_Destructuring) { - next(); - - return new AST_Assign({ - start : start, - left : left, - operator : val, - right : maybe_assign(no_in), - logical : LOGICAL_ASSIGNMENT.has(val), - end : prev() - }); - } - croak("Invalid assignment"); - } - return left; - }; - - var expression = function(commas, no_in) { - var start = S.token; - var exprs = []; - while (true) { - exprs.push(maybe_assign(no_in)); - if (!commas || !is("punc", ",")) break; - next(); - commas = true; - } - return exprs.length == 1 ? exprs[0] : new AST_Sequence({ - start : start, - expressions : exprs, - end : peek() - }); - }; - - function in_loop(cont) { - ++S.in_loop; - var ret = cont(); - --S.in_loop; - return ret; - } - - if (options.expression) { - return expression(true); - } - - return (function parse_toplevel() { - var start = S.token; - var body = []; - S.input.push_directives_stack(); - if (options.module) S.input.add_directive("use strict"); - while (!is("eof")) { - body.push(statement()); - } - S.input.pop_directives_stack(); - var end = prev(); - var toplevel = options.toplevel; - if (toplevel) { - toplevel.body = toplevel.body.concat(body); - toplevel.end = end; - } else { - toplevel = new AST_Toplevel({ start: start, body: body, end: end }); - } - return toplevel; - })(); - -} - -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -function DEFNODE(type, props, methods, base = AST_Node) { - if (!props) props = []; - else props = props.split(/\s+/); - var self_props = props; - if (base && base.PROPS) - props = props.concat(base.PROPS); - var code = "return function AST_" + type + "(props){ if (props) { "; - for (var i = props.length; --i >= 0;) { - code += "this." + props[i] + " = props." + props[i] + ";"; - } - const proto = base && Object.create(base.prototype); - if (proto && proto.initialize || (methods && methods.initialize)) - code += "this.initialize();"; - code += "}"; - code += "this.flags = 0;"; - code += "}"; - var ctor = new Function(code)(); - if (proto) { - ctor.prototype = proto; - ctor.BASE = base; - } - if (base) base.SUBCLASSES.push(ctor); - ctor.prototype.CTOR = ctor; - ctor.prototype.constructor = ctor; - ctor.PROPS = props || null; - ctor.SELF_PROPS = self_props; - ctor.SUBCLASSES = []; - if (type) { - ctor.prototype.TYPE = ctor.TYPE = type; - } - if (methods) for (i in methods) if (HOP(methods, i)) { - if (i[0] === "$") { - ctor[i.substr(1)] = methods[i]; - } else { - ctor.prototype[i] = methods[i]; - } - } - ctor.DEFMETHOD = function(name, method) { - this.prototype[name] = method; - }; - return ctor; -} - -const has_tok_flag = (tok, flag) => Boolean(tok.flags & flag); -const set_tok_flag = (tok, flag, truth) => { - if (truth) { - tok.flags |= flag; - } else { - tok.flags &= ~flag; - } -}; - -const TOK_FLAG_NLB = 0b0001; -const TOK_FLAG_QUOTE_SINGLE = 0b0010; -const TOK_FLAG_QUOTE_EXISTS = 0b0100; - -class AST_Token { - constructor(type, value, line, col, pos, nlb, comments_before, comments_after, file) { - this.flags = (nlb ? 1 : 0); - - this.type = type; - this.value = value; - this.line = line; - this.col = col; - this.pos = pos; - this.comments_before = comments_before; - this.comments_after = comments_after; - this.file = file; - - Object.seal(this); - } - - get nlb() { - return has_tok_flag(this, TOK_FLAG_NLB); - } - - set nlb(new_nlb) { - set_tok_flag(this, TOK_FLAG_NLB, new_nlb); - } - - get quote() { - return !has_tok_flag(this, TOK_FLAG_QUOTE_EXISTS) - ? "" - : (has_tok_flag(this, TOK_FLAG_QUOTE_SINGLE) ? "'" : '"'); - } - - set quote(quote_type) { - set_tok_flag(this, TOK_FLAG_QUOTE_SINGLE, quote_type === "'"); - set_tok_flag(this, TOK_FLAG_QUOTE_EXISTS, !!quote_type); - } -} - -var AST_Node = DEFNODE("Node", "start end", { - _clone: function(deep) { - if (deep) { - var self = this.clone(); - return self.transform(new TreeTransformer(function(node) { - if (node !== self) { - return node.clone(true); - } - })); - } - return new this.CTOR(this); - }, - clone: function(deep) { - return this._clone(deep); - }, - $documentation: "Base class of all AST nodes", - $propdoc: { - start: "[AST_Token] The first token of this node", - end: "[AST_Token] The last token of this node" - }, - _walk: function(visitor) { - return visitor._visit(this); - }, - walk: function(visitor) { - return this._walk(visitor); // not sure the indirection will be any help - }, - _children_backwards: () => {} -}, null); - -/* -----[ statements ]----- */ - -var AST_Statement = DEFNODE("Statement", null, { - $documentation: "Base class of all statements", -}); - -var AST_Debugger = DEFNODE("Debugger", null, { - $documentation: "Represents a debugger statement", -}, AST_Statement); - -var AST_Directive = DEFNODE("Directive", "value quote", { - $documentation: "Represents a directive, like \"use strict\";", - $propdoc: { - value: "[string] The value of this directive as a plain string (it's not an AST_String!)", - quote: "[string] the original quote character" - }, -}, AST_Statement); - -var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", { - $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", - $propdoc: { - body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.body._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.body); - } -}, AST_Statement); - -function walk_body(node, visitor) { - const body = node.body; - for (var i = 0, len = body.length; i < len; i++) { - body[i]._walk(visitor); - } -} - -function clone_block_scope(deep) { - var clone = this._clone(deep); - if (this.block_scope) { - // TODO this is sometimes undefined during compression. - // But it should always have a value! - clone.block_scope = this.block_scope.clone(); - } - return clone; -} - -var AST_Block = DEFNODE("Block", "body block_scope", { - $documentation: "A body of statements (usually braced)", - $propdoc: { - body: "[AST_Statement*] an array of statements", - block_scope: "[AST_Scope] the block scope" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - walk_body(this, visitor); - }); - }, - _children_backwards(push) { - let i = this.body.length; - while (i--) push(this.body[i]); - }, - clone: clone_block_scope -}, AST_Statement); - -var AST_BlockStatement = DEFNODE("BlockStatement", null, { - $documentation: "A block statement", -}, AST_Block); - -var AST_EmptyStatement = DEFNODE("EmptyStatement", null, { - $documentation: "The empty statement (empty block or simply a semicolon)" -}, AST_Statement); - -var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { - $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", - $propdoc: { - body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" - } -}, AST_Statement); - -var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { - $documentation: "Statement with a label", - $propdoc: { - label: "[AST_Label] a label definition" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.label._walk(visitor); - this.body._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.body); - push(this.label); - }, - clone: function(deep) { - var node = this._clone(deep); - if (deep) { - var label = node.label; - var def = this.label; - node.walk(new TreeWalker(function(node) { - if (node instanceof AST_LoopControl - && node.label && node.label.thedef === def) { - node.label.thedef = label; - label.references.push(node); - } - })); - } - return node; - } -}, AST_StatementWithBody); - -var AST_IterationStatement = DEFNODE("IterationStatement", "block_scope", { - $documentation: "Internal class. All loops inherit from it.", - $propdoc: { - block_scope: "[AST_Scope] the block scope for this iteration statement." - }, - clone: clone_block_scope -}, AST_StatementWithBody); - -var AST_DWLoop = DEFNODE("DWLoop", "condition", { - $documentation: "Base class for do/while statements", - $propdoc: { - condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" - } -}, AST_IterationStatement); - -var AST_Do = DEFNODE("Do", null, { - $documentation: "A `do` statement", - _walk: function(visitor) { - return visitor._visit(this, function() { - this.body._walk(visitor); - this.condition._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.condition); - push(this.body); - } -}, AST_DWLoop); - -var AST_While = DEFNODE("While", null, { - $documentation: "A `while` statement", - _walk: function(visitor) { - return visitor._visit(this, function() { - this.condition._walk(visitor); - this.body._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.body); - push(this.condition); - }, -}, AST_DWLoop); - -var AST_For = DEFNODE("For", "init condition step", { - $documentation: "A `for` statement", - $propdoc: { - init: "[AST_Node?] the `for` initialization code, or null if empty", - condition: "[AST_Node?] the `for` termination clause, or null if empty", - step: "[AST_Node?] the `for` update clause, or null if empty" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - if (this.init) this.init._walk(visitor); - if (this.condition) this.condition._walk(visitor); - if (this.step) this.step._walk(visitor); - this.body._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.body); - if (this.step) push(this.step); - if (this.condition) push(this.condition); - if (this.init) push(this.init); - }, -}, AST_IterationStatement); - -var AST_ForIn = DEFNODE("ForIn", "init object", { - $documentation: "A `for ... in` statement", - $propdoc: { - init: "[AST_Node] the `for/in` initialization code", - object: "[AST_Node] the object that we're looping through" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.init._walk(visitor); - this.object._walk(visitor); - this.body._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.body); - if (this.object) push(this.object); - if (this.init) push(this.init); - }, -}, AST_IterationStatement); - -var AST_ForOf = DEFNODE("ForOf", "await", { - $documentation: "A `for ... of` statement", -}, AST_ForIn); - -var AST_With = DEFNODE("With", "expression", { - $documentation: "A `with` statement", - $propdoc: { - expression: "[AST_Node] the `with` expression" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.expression._walk(visitor); - this.body._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.body); - push(this.expression); - }, -}, AST_StatementWithBody); - -/* -----[ scope and functions ]----- */ - -var AST_Scope = DEFNODE("Scope", "variables functions uses_with uses_eval parent_scope enclosed cname", { - $documentation: "Base class for all statements introducing a lexical scope", - $propdoc: { - variables: "[Map/S] a map of name -> SymbolDef for all variables/functions defined in this scope", - functions: "[Map/S] like `variables`, but only lists function declarations", - uses_with: "[boolean/S] tells whether this scope uses the `with` statement", - uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", - parent_scope: "[AST_Scope?/S] link to the parent scope", - enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", - cname: "[integer/S] current index for mangling variables (used internally by the mangler)", - }, - get_defun_scope: function() { - var self = this; - while (self.is_block_scope()) { - self = self.parent_scope; - } - return self; - }, - clone: function(deep, toplevel) { - var node = this._clone(deep); - if (deep && this.variables && toplevel && !this._block_scope) { - node.figure_out_scope({}, { - toplevel: toplevel, - parent_scope: this.parent_scope - }); - } else { - if (this.variables) node.variables = new Map(this.variables); - if (this.functions) node.functions = new Map(this.functions); - if (this.enclosed) node.enclosed = this.enclosed.slice(); - if (this._block_scope) node._block_scope = this._block_scope; - } - return node; - }, - pinned: function() { - return this.uses_eval || this.uses_with; - } -}, AST_Block); - -var AST_Toplevel = DEFNODE("Toplevel", "globals", { - $documentation: "The toplevel scope", - $propdoc: { - globals: "[Map/S] a map of name -> SymbolDef for all undeclared names", - }, - wrap_commonjs: function(name) { - var body = this.body; - var wrapped_tl = "(function(exports){'$ORIG';})(typeof " + name + "=='undefined'?(" + name + "={}):" + name + ");"; - wrapped_tl = parse(wrapped_tl); - wrapped_tl = wrapped_tl.transform(new TreeTransformer(function(node) { - if (node instanceof AST_Directive && node.value == "$ORIG") { - return MAP.splice(body); - } - })); - return wrapped_tl; - }, - wrap_enclose: function(args_values) { - if (typeof args_values != "string") args_values = ""; - var index = args_values.indexOf(":"); - if (index < 0) index = args_values.length; - var body = this.body; - return parse([ - "(function(", - args_values.slice(0, index), - '){"$ORIG"})(', - args_values.slice(index + 1), - ")" - ].join("")).transform(new TreeTransformer(function(node) { - if (node instanceof AST_Directive && node.value == "$ORIG") { - return MAP.splice(body); - } - })); - } -}, AST_Scope); - -var AST_Expansion = DEFNODE("Expansion", "expression", { - $documentation: "An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list", - $propdoc: { - expression: "[AST_Node] the thing to be expanded" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.expression.walk(visitor); - }); - }, - _children_backwards(push) { - push(this.expression); - }, -}); - -var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments is_generator async", { - $documentation: "Base class for functions", - $propdoc: { - name: "[AST_SymbolDeclaration?] the name of this function", - argnames: "[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments", - uses_arguments: "[boolean/S] tells whether this function accesses the arguments array", - is_generator: "[boolean] is this a generator method", - async: "[boolean] is this method async", - }, - args_as_names: function () { - var out = []; - for (var i = 0; i < this.argnames.length; i++) { - if (this.argnames[i] instanceof AST_Destructuring) { - out.push(...this.argnames[i].all_symbols()); - } else { - out.push(this.argnames[i]); - } - } - return out; - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - if (this.name) this.name._walk(visitor); - var argnames = this.argnames; - for (var i = 0, len = argnames.length; i < len; i++) { - argnames[i]._walk(visitor); - } - walk_body(this, visitor); - }); - }, - _children_backwards(push) { - let i = this.body.length; - while (i--) push(this.body[i]); - - i = this.argnames.length; - while (i--) push(this.argnames[i]); - - if (this.name) push(this.name); - }, - is_braceless() { - return this.body[0] instanceof AST_Return && this.body[0].value; - } -}, AST_Scope); - -var AST_Accessor = DEFNODE("Accessor", null, { - $documentation: "A setter/getter function. The `name` property is always null." -}, AST_Lambda); - -var AST_Function = DEFNODE("Function", null, { - $documentation: "A function expression" -}, AST_Lambda); - -var AST_Arrow = DEFNODE("Arrow", null, { - $documentation: "An ES6 Arrow function ((a) => b)" -}, AST_Lambda); - -var AST_Defun = DEFNODE("Defun", null, { - $documentation: "A function definition" -}, AST_Lambda); - -/* -----[ DESTRUCTURING ]----- */ -var AST_Destructuring = DEFNODE("Destructuring", "names is_array", { - $documentation: "A destructuring of several names. Used in destructuring assignment and with destructuring function argument names", - $propdoc: { - "names": "[AST_Node*] Array of properties or elements", - "is_array": "[Boolean] Whether the destructuring represents an object or array" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.names.forEach(function(name) { - name._walk(visitor); - }); - }); - }, - _children_backwards(push) { - let i = this.names.length; - while (i--) push(this.names[i]); - }, - all_symbols: function() { - var out = []; - this.walk(new TreeWalker(function (node) { - if (node instanceof AST_Symbol) { - out.push(node); - } - })); - return out; - } -}); - -var AST_PrefixedTemplateString = DEFNODE("PrefixedTemplateString", "template_string prefix", { - $documentation: "A templatestring with a prefix, such as String.raw`foobarbaz`", - $propdoc: { - template_string: "[AST_TemplateString] The template string", - prefix: "[AST_Node] The prefix, which will get called." - }, - _walk: function(visitor) { - return visitor._visit(this, function () { - this.prefix._walk(visitor); - this.template_string._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.template_string); - push(this.prefix); - }, -}); - -var AST_TemplateString = DEFNODE("TemplateString", "segments", { - $documentation: "A template string literal", - $propdoc: { - segments: "[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment." - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.segments.forEach(function(seg) { - seg._walk(visitor); - }); - }); - }, - _children_backwards(push) { - let i = this.segments.length; - while (i--) push(this.segments[i]); - } -}); - -var AST_TemplateSegment = DEFNODE("TemplateSegment", "value raw", { - $documentation: "A segment of a template string literal", - $propdoc: { - value: "Content of the segment", - raw: "Raw source of the segment", - } -}); - -/* -----[ JUMPS ]----- */ - -var AST_Jump = DEFNODE("Jump", null, { - $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)" -}, AST_Statement); - -var AST_Exit = DEFNODE("Exit", "value", { - $documentation: "Base class for “exits” (`return` and `throw`)", - $propdoc: { - value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" - }, - _walk: function(visitor) { - return visitor._visit(this, this.value && function() { - this.value._walk(visitor); - }); - }, - _children_backwards(push) { - if (this.value) push(this.value); - }, -}, AST_Jump); - -var AST_Return = DEFNODE("Return", null, { - $documentation: "A `return` statement" -}, AST_Exit); - -var AST_Throw = DEFNODE("Throw", null, { - $documentation: "A `throw` statement" -}, AST_Exit); - -var AST_LoopControl = DEFNODE("LoopControl", "label", { - $documentation: "Base class for loop control statements (`break` and `continue`)", - $propdoc: { - label: "[AST_LabelRef?] the label, or null if none", - }, - _walk: function(visitor) { - return visitor._visit(this, this.label && function() { - this.label._walk(visitor); - }); - }, - _children_backwards(push) { - if (this.label) push(this.label); - }, -}, AST_Jump); - -var AST_Break = DEFNODE("Break", null, { - $documentation: "A `break` statement" -}, AST_LoopControl); - -var AST_Continue = DEFNODE("Continue", null, { - $documentation: "A `continue` statement" -}, AST_LoopControl); - -var AST_Await = DEFNODE("Await", "expression", { - $documentation: "An `await` statement", - $propdoc: { - expression: "[AST_Node] the mandatory expression being awaited", - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.expression._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.expression); - }, -}); - -var AST_Yield = DEFNODE("Yield", "expression is_star", { - $documentation: "A `yield` statement", - $propdoc: { - expression: "[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false", - is_star: "[Boolean] Whether this is a yield or yield* statement" - }, - _walk: function(visitor) { - return visitor._visit(this, this.expression && function() { - this.expression._walk(visitor); - }); - }, - _children_backwards(push) { - if (this.expression) push(this.expression); - } -}); - -/* -----[ IF ]----- */ - -var AST_If = DEFNODE("If", "condition alternative", { - $documentation: "A `if` statement", - $propdoc: { - condition: "[AST_Node] the `if` condition", - alternative: "[AST_Statement?] the `else` part, or null if not present" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.condition._walk(visitor); - this.body._walk(visitor); - if (this.alternative) this.alternative._walk(visitor); - }); - }, - _children_backwards(push) { - if (this.alternative) { - push(this.alternative); - } - push(this.body); - push(this.condition); - } -}, AST_StatementWithBody); - -/* -----[ SWITCH ]----- */ - -var AST_Switch = DEFNODE("Switch", "expression", { - $documentation: "A `switch` statement", - $propdoc: { - expression: "[AST_Node] the `switch` “discriminant”" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.expression._walk(visitor); - walk_body(this, visitor); - }); - }, - _children_backwards(push) { - let i = this.body.length; - while (i--) push(this.body[i]); - push(this.expression); - } -}, AST_Block); - -var AST_SwitchBranch = DEFNODE("SwitchBranch", null, { - $documentation: "Base class for `switch` branches", -}, AST_Block); - -var AST_Default = DEFNODE("Default", null, { - $documentation: "A `default` switch branch", -}, AST_SwitchBranch); - -var AST_Case = DEFNODE("Case", "expression", { - $documentation: "A `case` switch branch", - $propdoc: { - expression: "[AST_Node] the `case` expression" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.expression._walk(visitor); - walk_body(this, visitor); - }); - }, - _children_backwards(push) { - let i = this.body.length; - while (i--) push(this.body[i]); - push(this.expression); - }, -}, AST_SwitchBranch); - -/* -----[ EXCEPTIONS ]----- */ - -var AST_Try = DEFNODE("Try", "bcatch bfinally", { - $documentation: "A `try` statement", - $propdoc: { - bcatch: "[AST_Catch?] the catch block, or null if not present", - bfinally: "[AST_Finally?] the finally block, or null if not present" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - walk_body(this, visitor); - if (this.bcatch) this.bcatch._walk(visitor); - if (this.bfinally) this.bfinally._walk(visitor); - }); - }, - _children_backwards(push) { - if (this.bfinally) push(this.bfinally); - if (this.bcatch) push(this.bcatch); - let i = this.body.length; - while (i--) push(this.body[i]); - }, -}, AST_Block); - -var AST_Catch = DEFNODE("Catch", "argname", { - $documentation: "A `catch` node; only makes sense as part of a `try` statement", - $propdoc: { - argname: "[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - if (this.argname) this.argname._walk(visitor); - walk_body(this, visitor); - }); - }, - _children_backwards(push) { - let i = this.body.length; - while (i--) push(this.body[i]); - if (this.argname) push(this.argname); - }, -}, AST_Block); - -var AST_Finally = DEFNODE("Finally", null, { - $documentation: "A `finally` node; only makes sense as part of a `try` statement" -}, AST_Block); - -/* -----[ VAR/CONST ]----- */ - -var AST_Definitions = DEFNODE("Definitions", "definitions", { - $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", - $propdoc: { - definitions: "[AST_VarDef*] array of variable definitions" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - var definitions = this.definitions; - for (var i = 0, len = definitions.length; i < len; i++) { - definitions[i]._walk(visitor); - } - }); - }, - _children_backwards(push) { - let i = this.definitions.length; - while (i--) push(this.definitions[i]); - }, -}, AST_Statement); - -var AST_Var = DEFNODE("Var", null, { - $documentation: "A `var` statement" -}, AST_Definitions); - -var AST_Let = DEFNODE("Let", null, { - $documentation: "A `let` statement" -}, AST_Definitions); - -var AST_Const = DEFNODE("Const", null, { - $documentation: "A `const` statement" -}, AST_Definitions); - -var AST_VarDef = DEFNODE("VarDef", "name value", { - $documentation: "A variable declaration; only appears in a AST_Definitions node", - $propdoc: { - name: "[AST_Destructuring|AST_SymbolConst|AST_SymbolLet|AST_SymbolVar] name of the variable", - value: "[AST_Node?] initializer, or null of there's no initializer" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.name._walk(visitor); - if (this.value) this.value._walk(visitor); - }); - }, - _children_backwards(push) { - if (this.value) push(this.value); - push(this.name); - }, -}); - -var AST_NameMapping = DEFNODE("NameMapping", "foreign_name name", { - $documentation: "The part of the export/import statement that declare names from a module.", - $propdoc: { - foreign_name: "[AST_SymbolExportForeign|AST_SymbolImportForeign] The name being exported/imported (as specified in the module)", - name: "[AST_SymbolExport|AST_SymbolImport] The name as it is visible to this module." - }, - _walk: function (visitor) { - return visitor._visit(this, function() { - this.foreign_name._walk(visitor); - this.name._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.name); - push(this.foreign_name); - }, -}); - -var AST_Import = DEFNODE("Import", "imported_name imported_names module_name", { - $documentation: "An `import` statement", - $propdoc: { - imported_name: "[AST_SymbolImport] The name of the variable holding the module's default export.", - imported_names: "[AST_NameMapping*] The names of non-default imported variables", - module_name: "[AST_String] String literal describing where this module came from", - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - if (this.imported_name) { - this.imported_name._walk(visitor); - } - if (this.imported_names) { - this.imported_names.forEach(function(name_import) { - name_import._walk(visitor); - }); - } - this.module_name._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.module_name); - if (this.imported_names) { - let i = this.imported_names.length; - while (i--) push(this.imported_names[i]); - } - if (this.imported_name) push(this.imported_name); - }, -}); - -var AST_ImportMeta = DEFNODE("ImportMeta", null, { - $documentation: "A reference to import.meta", -}); - -var AST_Export = DEFNODE("Export", "exported_definition exported_value is_default exported_names module_name", { - $documentation: "An `export` statement", - $propdoc: { - exported_definition: "[AST_Defun|AST_Definitions|AST_DefClass?] An exported definition", - exported_value: "[AST_Node?] An exported value", - exported_names: "[AST_NameMapping*?] List of exported names", - module_name: "[AST_String?] Name of the file to load exports from", - is_default: "[Boolean] Whether this is the default exported value of this module" - }, - _walk: function (visitor) { - return visitor._visit(this, function () { - if (this.exported_definition) { - this.exported_definition._walk(visitor); - } - if (this.exported_value) { - this.exported_value._walk(visitor); - } - if (this.exported_names) { - this.exported_names.forEach(function(name_export) { - name_export._walk(visitor); - }); - } - if (this.module_name) { - this.module_name._walk(visitor); - } - }); - }, - _children_backwards(push) { - if (this.module_name) push(this.module_name); - if (this.exported_names) { - let i = this.exported_names.length; - while (i--) push(this.exported_names[i]); - } - if (this.exported_value) push(this.exported_value); - if (this.exported_definition) push(this.exported_definition); - } -}, AST_Statement); - -/* -----[ OTHER ]----- */ - -var AST_Call = DEFNODE("Call", "expression args optional _annotations", { - $documentation: "A function call expression", - $propdoc: { - expression: "[AST_Node] expression to invoke as function", - args: "[AST_Node*] array of arguments", - optional: "[boolean] whether this is an optional call (IE ?.() )", - _annotations: "[number] bitfield containing information about the call" - }, - initialize() { - if (this._annotations == null) this._annotations = 0; - }, - _walk(visitor) { - return visitor._visit(this, function() { - var args = this.args; - for (var i = 0, len = args.length; i < len; i++) { - args[i]._walk(visitor); - } - this.expression._walk(visitor); // TODO why do we need to crawl this last? - }); - }, - _children_backwards(push) { - let i = this.args.length; - while (i--) push(this.args[i]); - push(this.expression); - }, -}); - -var AST_New = DEFNODE("New", null, { - $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" -}, AST_Call); - -var AST_Sequence = DEFNODE("Sequence", "expressions", { - $documentation: "A sequence expression (comma-separated expressions)", - $propdoc: { - expressions: "[AST_Node*] array of expressions (at least two)" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.expressions.forEach(function(node) { - node._walk(visitor); - }); - }); - }, - _children_backwards(push) { - let i = this.expressions.length; - while (i--) push(this.expressions[i]); - }, -}); - -var AST_PropAccess = DEFNODE("PropAccess", "expression property optional", { - $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", - $propdoc: { - expression: "[AST_Node] the “container” expression", - property: "[AST_Node|string] the property to access. For AST_Dot & AST_DotHash this is always a plain string, while for AST_Sub it's an arbitrary AST_Node", - - optional: "[boolean] whether this is an optional property access (IE ?.)" - } -}); - -var AST_Dot = DEFNODE("Dot", "quote", { - $documentation: "A dotted property access expression", - $propdoc: { - quote: "[string] the original quote character when transformed from AST_Sub", - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.expression._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.expression); - }, -}, AST_PropAccess); - -var AST_DotHash = DEFNODE("DotHash", "", { - $documentation: "A dotted property access to a private property", - _walk: function(visitor) { - return visitor._visit(this, function() { - this.expression._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.expression); - }, -}, AST_PropAccess); - -var AST_Sub = DEFNODE("Sub", null, { - $documentation: "Index-style property access, i.e. `a[\"foo\"]`", - _walk: function(visitor) { - return visitor._visit(this, function() { - this.expression._walk(visitor); - this.property._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.property); - push(this.expression); - }, -}, AST_PropAccess); - -var AST_Chain = DEFNODE("Chain", "expression", { - $documentation: "A chain expression like a?.b?.(c)?.[d]", - $propdoc: { - expression: "[AST_Call|AST_Dot|AST_DotHash|AST_Sub] chain element." - }, - _walk: function (visitor) { - return visitor._visit(this, function() { - this.expression._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.expression); - }, -}); - -var AST_Unary = DEFNODE("Unary", "operator expression", { - $documentation: "Base class for unary expressions", - $propdoc: { - operator: "[string] the operator", - expression: "[AST_Node] expression that this unary operator applies to" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.expression._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.expression); - }, -}); - -var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, { - $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" -}, AST_Unary); - -var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, { - $documentation: "Unary postfix expression, i.e. `i++`" -}, AST_Unary); - -var AST_Binary = DEFNODE("Binary", "operator left right", { - $documentation: "Binary expression, i.e. `a + b`", - $propdoc: { - left: "[AST_Node] left-hand side expression", - operator: "[string] the operator", - right: "[AST_Node] right-hand side expression" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.left._walk(visitor); - this.right._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.right); - push(this.left); - }, -}); - -var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", { - $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", - $propdoc: { - condition: "[AST_Node]", - consequent: "[AST_Node]", - alternative: "[AST_Node]" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - this.condition._walk(visitor); - this.consequent._walk(visitor); - this.alternative._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.alternative); - push(this.consequent); - push(this.condition); - }, -}); - -var AST_Assign = DEFNODE("Assign", "logical", { - $documentation: "An assignment expression — `a = b + 5`", - $propdoc: { - logical: "Whether it's a logical assignment" - } -}, AST_Binary); - -var AST_DefaultAssign = DEFNODE("DefaultAssign", null, { - $documentation: "A default assignment expression like in `(a = 3) => a`" -}, AST_Binary); - -/* -----[ LITERALS ]----- */ - -var AST_Array = DEFNODE("Array", "elements", { - $documentation: "An array literal", - $propdoc: { - elements: "[AST_Node*] array of elements" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - var elements = this.elements; - for (var i = 0, len = elements.length; i < len; i++) { - elements[i]._walk(visitor); - } - }); - }, - _children_backwards(push) { - let i = this.elements.length; - while (i--) push(this.elements[i]); - }, -}); - -var AST_Object = DEFNODE("Object", "properties", { - $documentation: "An object literal", - $propdoc: { - properties: "[AST_ObjectProperty*] array of properties" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - var properties = this.properties; - for (var i = 0, len = properties.length; i < len; i++) { - properties[i]._walk(visitor); - } - }); - }, - _children_backwards(push) { - let i = this.properties.length; - while (i--) push(this.properties[i]); - }, -}); - -var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { - $documentation: "Base class for literal object properties", - $propdoc: { - key: "[string|AST_Node] property name. For ObjectKeyVal this is a string. For getters, setters and computed property this is an AST_Node.", - value: "[AST_Node] property value. For getters and setters this is an AST_Accessor." - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - if (this.key instanceof AST_Node) - this.key._walk(visitor); - this.value._walk(visitor); - }); - }, - _children_backwards(push) { - push(this.value); - if (this.key instanceof AST_Node) push(this.key); - } -}); - -var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", { - $documentation: "A key: value object property", - $propdoc: { - quote: "[string] the original quote character" - }, - computed_key() { - return this.key instanceof AST_Node; - } -}, AST_ObjectProperty); - -var AST_PrivateSetter = DEFNODE("PrivateSetter", "static", { - $propdoc: { - static: "[boolean] whether this is a static private setter" - }, - $documentation: "A private setter property", - computed_key() { - return false; - } -}, AST_ObjectProperty); - -var AST_PrivateGetter = DEFNODE("PrivateGetter", "static", { - $propdoc: { - static: "[boolean] whether this is a static private getter" - }, - $documentation: "A private getter property", - computed_key() { - return false; - } -}, AST_ObjectProperty); - -var AST_ObjectSetter = DEFNODE("ObjectSetter", "quote static", { - $propdoc: { - quote: "[string|undefined] the original quote character, if any", - static: "[boolean] whether this is a static setter (classes only)" - }, - $documentation: "An object setter property", - computed_key() { - return !(this.key instanceof AST_SymbolMethod); - } -}, AST_ObjectProperty); - -var AST_ObjectGetter = DEFNODE("ObjectGetter", "quote static", { - $propdoc: { - quote: "[string|undefined] the original quote character, if any", - static: "[boolean] whether this is a static getter (classes only)" - }, - $documentation: "An object getter property", - computed_key() { - return !(this.key instanceof AST_SymbolMethod); - } -}, AST_ObjectProperty); - -var AST_ConciseMethod = DEFNODE("ConciseMethod", "quote static is_generator async", { - $propdoc: { - quote: "[string|undefined] the original quote character, if any", - static: "[boolean] is this method static (classes only)", - is_generator: "[boolean] is this a generator method", - async: "[boolean] is this method async", - }, - $documentation: "An ES6 concise method inside an object or class", - computed_key() { - return !(this.key instanceof AST_SymbolMethod); - } -}, AST_ObjectProperty); - -var AST_PrivateMethod = DEFNODE("PrivateMethod", "", { - $documentation: "A private class method inside a class", -}, AST_ConciseMethod); - -var AST_Class = DEFNODE("Class", "name extends properties", { - $propdoc: { - name: "[AST_SymbolClass|AST_SymbolDefClass?] optional class name.", - extends: "[AST_Node]? optional parent class", - properties: "[AST_ObjectProperty*] array of properties" - }, - $documentation: "An ES6 class", - _walk: function(visitor) { - return visitor._visit(this, function() { - if (this.name) { - this.name._walk(visitor); - } - if (this.extends) { - this.extends._walk(visitor); - } - this.properties.forEach((prop) => prop._walk(visitor)); - }); - }, - _children_backwards(push) { - let i = this.properties.length; - while (i--) push(this.properties[i]); - if (this.extends) push(this.extends); - if (this.name) push(this.name); - }, -}, AST_Scope /* TODO a class might have a scope but it's not a scope */); - -var AST_ClassProperty = DEFNODE("ClassProperty", "static quote", { - $documentation: "A class property", - $propdoc: { - static: "[boolean] whether this is a static key", - quote: "[string] which quote is being used" - }, - _walk: function(visitor) { - return visitor._visit(this, function() { - if (this.key instanceof AST_Node) - this.key._walk(visitor); - if (this.value instanceof AST_Node) - this.value._walk(visitor); - }); - }, - _children_backwards(push) { - if (this.value instanceof AST_Node) push(this.value); - if (this.key instanceof AST_Node) push(this.key); - }, - computed_key() { - return !(this.key instanceof AST_SymbolClassProperty); - } -}, AST_ObjectProperty); - -var AST_ClassPrivateProperty = DEFNODE("ClassProperty", "", { - $documentation: "A class property for a private property", -}, AST_ClassProperty); - -var AST_DefClass = DEFNODE("DefClass", null, { - $documentation: "A class definition", -}, AST_Class); - -var AST_ClassExpression = DEFNODE("ClassExpression", null, { - $documentation: "A class expression." -}, AST_Class); - -var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { - $propdoc: { - name: "[string] name of this symbol", - scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", - thedef: "[SymbolDef/S] the definition of this symbol" - }, - $documentation: "Base class for all symbols" -}); - -var AST_NewTarget = DEFNODE("NewTarget", null, { - $documentation: "A reference to new.target" -}); - -var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { - $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", -}, AST_Symbol); - -var AST_SymbolVar = DEFNODE("SymbolVar", null, { - $documentation: "Symbol defining a variable", -}, AST_SymbolDeclaration); - -var AST_SymbolBlockDeclaration = DEFNODE("SymbolBlockDeclaration", null, { - $documentation: "Base class for block-scoped declaration symbols" -}, AST_SymbolDeclaration); - -var AST_SymbolConst = DEFNODE("SymbolConst", null, { - $documentation: "A constant declaration" -}, AST_SymbolBlockDeclaration); - -var AST_SymbolLet = DEFNODE("SymbolLet", null, { - $documentation: "A block-scoped `let` declaration" -}, AST_SymbolBlockDeclaration); - -var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, { - $documentation: "Symbol naming a function argument", -}, AST_SymbolVar); - -var AST_SymbolDefun = DEFNODE("SymbolDefun", null, { - $documentation: "Symbol defining a function", -}, AST_SymbolDeclaration); - -var AST_SymbolMethod = DEFNODE("SymbolMethod", null, { - $documentation: "Symbol in an object defining a method", -}, AST_Symbol); - -var AST_SymbolClassProperty = DEFNODE("SymbolClassProperty", null, { - $documentation: "Symbol for a class property", -}, AST_Symbol); - -var AST_SymbolLambda = DEFNODE("SymbolLambda", null, { - $documentation: "Symbol naming a function expression", -}, AST_SymbolDeclaration); - -var AST_SymbolDefClass = DEFNODE("SymbolDefClass", null, { - $documentation: "Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class." -}, AST_SymbolBlockDeclaration); - -var AST_SymbolClass = DEFNODE("SymbolClass", null, { - $documentation: "Symbol naming a class's name. Lexically scoped to the class." -}, AST_SymbolDeclaration); - -var AST_SymbolCatch = DEFNODE("SymbolCatch", null, { - $documentation: "Symbol naming the exception in catch", -}, AST_SymbolBlockDeclaration); - -var AST_SymbolImport = DEFNODE("SymbolImport", null, { - $documentation: "Symbol referring to an imported name", -}, AST_SymbolBlockDeclaration); - -var AST_SymbolImportForeign = DEFNODE("SymbolImportForeign", null, { - $documentation: "A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes", -}, AST_Symbol); - -var AST_Label = DEFNODE("Label", "references", { - $documentation: "Symbol naming a label (declaration)", - $propdoc: { - references: "[AST_LoopControl*] a list of nodes referring to this label" - }, - initialize: function() { - this.references = []; - this.thedef = this; - } -}, AST_Symbol); - -var AST_SymbolRef = DEFNODE("SymbolRef", null, { - $documentation: "Reference to some symbol (not definition/declaration)", -}, AST_Symbol); - -var AST_SymbolExport = DEFNODE("SymbolExport", null, { - $documentation: "Symbol referring to a name to export", -}, AST_SymbolRef); - -var AST_SymbolExportForeign = DEFNODE("SymbolExportForeign", null, { - $documentation: "A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes", -}, AST_Symbol); - -var AST_LabelRef = DEFNODE("LabelRef", null, { - $documentation: "Reference to a label symbol", -}, AST_Symbol); - -var AST_This = DEFNODE("This", null, { - $documentation: "The `this` symbol", -}, AST_Symbol); - -var AST_Super = DEFNODE("Super", null, { - $documentation: "The `super` symbol", -}, AST_This); - -var AST_Constant = DEFNODE("Constant", null, { - $documentation: "Base class for all constants", - getValue: function() { - return this.value; - } -}); - -var AST_String = DEFNODE("String", "value quote", { - $documentation: "A string literal", - $propdoc: { - value: "[string] the contents of this string", - quote: "[string] the original quote character" - } -}, AST_Constant); - -var AST_Number = DEFNODE("Number", "value raw", { - $documentation: "A number literal", - $propdoc: { - value: "[number] the numeric value", - raw: "[string] numeric value as string" - } -}, AST_Constant); - -var AST_BigInt = DEFNODE("BigInt", "value", { - $documentation: "A big int literal", - $propdoc: { - value: "[string] big int value" - } -}, AST_Constant); - -var AST_RegExp = DEFNODE("RegExp", "value", { - $documentation: "A regexp literal", - $propdoc: { - value: "[RegExp] the actual regexp", - } -}, AST_Constant); - -var AST_Atom = DEFNODE("Atom", null, { - $documentation: "Base class for atoms", -}, AST_Constant); - -var AST_Null = DEFNODE("Null", null, { - $documentation: "The `null` atom", - value: null -}, AST_Atom); - -var AST_NaN = DEFNODE("NaN", null, { - $documentation: "The impossible value", - value: 0/0 -}, AST_Atom); - -var AST_Undefined = DEFNODE("Undefined", null, { - $documentation: "The `undefined` value", - value: (function() {}()) -}, AST_Atom); - -var AST_Hole = DEFNODE("Hole", null, { - $documentation: "A hole in an array", - value: (function() {}()) -}, AST_Atom); - -var AST_Infinity = DEFNODE("Infinity", null, { - $documentation: "The `Infinity` value", - value: 1/0 -}, AST_Atom); - -var AST_Boolean = DEFNODE("Boolean", null, { - $documentation: "Base class for booleans", -}, AST_Atom); - -var AST_False = DEFNODE("False", null, { - $documentation: "The `false` atom", - value: false -}, AST_Boolean); - -var AST_True = DEFNODE("True", null, { - $documentation: "The `true` atom", - value: true -}, AST_Boolean); - -/* -----[ Walk function ]---- */ - -/** - * Walk nodes in depth-first search fashion. - * Callback can return `walk_abort` symbol to stop iteration. - * It can also return `true` to stop iteration just for child nodes. - * Iteration can be stopped and continued by passing the `to_visit` argument, - * which is given to the callback in the second argument. - **/ -function walk(node, cb, to_visit = [node]) { - const push = to_visit.push.bind(to_visit); - while (to_visit.length) { - const node = to_visit.pop(); - const ret = cb(node, to_visit); - - if (ret) { - if (ret === walk_abort) return true; - continue; - } - - node._children_backwards(push); - } - return false; -} - -function walk_parent(node, cb, initial_stack) { - const to_visit = [node]; - const push = to_visit.push.bind(to_visit); - const stack = initial_stack ? initial_stack.slice() : []; - const parent_pop_indices = []; - - let current; - - const info = { - parent: (n = 0) => { - if (n === -1) { - return current; - } - - // [ p1 p0 ] [ 1 0 ] - if (initial_stack && n >= stack.length) { - n -= stack.length; - return initial_stack[ - initial_stack.length - (n + 1) - ]; - } - - return stack[stack.length - (1 + n)]; - }, - }; - - while (to_visit.length) { - current = to_visit.pop(); - - while ( - parent_pop_indices.length && - to_visit.length == parent_pop_indices[parent_pop_indices.length - 1] - ) { - stack.pop(); - parent_pop_indices.pop(); - } - - const ret = cb(current, info); - - if (ret) { - if (ret === walk_abort) return true; - continue; - } - - const visit_length = to_visit.length; - - current._children_backwards(push); - - // Push only if we're going to traverse the children - if (to_visit.length > visit_length) { - stack.push(current); - parent_pop_indices.push(visit_length - 1); - } - } - - return false; -} - -const walk_abort = Symbol("abort walk"); - -/* -----[ TreeWalker ]----- */ - -class TreeWalker { - constructor(callback) { - this.visit = callback; - this.stack = []; - this.directives = Object.create(null); - } - - _visit(node, descend) { - this.push(node); - var ret = this.visit(node, descend ? function() { - descend.call(node); - } : noop); - if (!ret && descend) { - descend.call(node); - } - this.pop(); - return ret; - } - - parent(n) { - return this.stack[this.stack.length - 2 - (n || 0)]; - } - - push(node) { - if (node instanceof AST_Lambda) { - this.directives = Object.create(this.directives); - } else if (node instanceof AST_Directive && !this.directives[node.value]) { - this.directives[node.value] = node; - } else if (node instanceof AST_Class) { - this.directives = Object.create(this.directives); - if (!this.directives["use strict"]) { - this.directives["use strict"] = node; - } - } - this.stack.push(node); - } - - pop() { - var node = this.stack.pop(); - if (node instanceof AST_Lambda || node instanceof AST_Class) { - this.directives = Object.getPrototypeOf(this.directives); - } - } - - self() { - return this.stack[this.stack.length - 1]; - } - - find_parent(type) { - var stack = this.stack; - for (var i = stack.length; --i >= 0;) { - var x = stack[i]; - if (x instanceof type) return x; - } - } - - has_directive(type) { - var dir = this.directives[type]; - if (dir) return dir; - var node = this.stack[this.stack.length - 1]; - if (node instanceof AST_Scope && node.body) { - for (var i = 0; i < node.body.length; ++i) { - var st = node.body[i]; - if (!(st instanceof AST_Directive)) break; - if (st.value == type) return st; - } - } - } - - loopcontrol_target(node) { - var stack = this.stack; - if (node.label) for (var i = stack.length; --i >= 0;) { - var x = stack[i]; - if (x instanceof AST_LabeledStatement && x.label.name == node.label.name) - return x.body; - } else for (var i = stack.length; --i >= 0;) { - var x = stack[i]; - if (x instanceof AST_IterationStatement - || node instanceof AST_Break && x instanceof AST_Switch) - return x; - } - } -} - -// Tree transformer helpers. -class TreeTransformer extends TreeWalker { - constructor(before, after) { - super(); - this.before = before; - this.after = after; - } -} - -const _PURE = 0b00000001; -const _INLINE = 0b00000010; -const _NOINLINE = 0b00000100; - -var ast = /*#__PURE__*/Object.freeze({ -__proto__: null, -AST_Accessor: AST_Accessor, -AST_Array: AST_Array, -AST_Arrow: AST_Arrow, -AST_Assign: AST_Assign, -AST_Atom: AST_Atom, -AST_Await: AST_Await, -AST_BigInt: AST_BigInt, -AST_Binary: AST_Binary, -AST_Block: AST_Block, -AST_BlockStatement: AST_BlockStatement, -AST_Boolean: AST_Boolean, -AST_Break: AST_Break, -AST_Call: AST_Call, -AST_Case: AST_Case, -AST_Catch: AST_Catch, -AST_Chain: AST_Chain, -AST_Class: AST_Class, -AST_ClassExpression: AST_ClassExpression, -AST_ClassPrivateProperty: AST_ClassPrivateProperty, -AST_ClassProperty: AST_ClassProperty, -AST_ConciseMethod: AST_ConciseMethod, -AST_Conditional: AST_Conditional, -AST_Const: AST_Const, -AST_Constant: AST_Constant, -AST_Continue: AST_Continue, -AST_Debugger: AST_Debugger, -AST_Default: AST_Default, -AST_DefaultAssign: AST_DefaultAssign, -AST_DefClass: AST_DefClass, -AST_Definitions: AST_Definitions, -AST_Defun: AST_Defun, -AST_Destructuring: AST_Destructuring, -AST_Directive: AST_Directive, -AST_Do: AST_Do, -AST_Dot: AST_Dot, -AST_DotHash: AST_DotHash, -AST_DWLoop: AST_DWLoop, -AST_EmptyStatement: AST_EmptyStatement, -AST_Exit: AST_Exit, -AST_Expansion: AST_Expansion, -AST_Export: AST_Export, -AST_False: AST_False, -AST_Finally: AST_Finally, -AST_For: AST_For, -AST_ForIn: AST_ForIn, -AST_ForOf: AST_ForOf, -AST_Function: AST_Function, -AST_Hole: AST_Hole, -AST_If: AST_If, -AST_Import: AST_Import, -AST_ImportMeta: AST_ImportMeta, -AST_Infinity: AST_Infinity, -AST_IterationStatement: AST_IterationStatement, -AST_Jump: AST_Jump, -AST_Label: AST_Label, -AST_LabeledStatement: AST_LabeledStatement, -AST_LabelRef: AST_LabelRef, -AST_Lambda: AST_Lambda, -AST_Let: AST_Let, -AST_LoopControl: AST_LoopControl, -AST_NameMapping: AST_NameMapping, -AST_NaN: AST_NaN, -AST_New: AST_New, -AST_NewTarget: AST_NewTarget, -AST_Node: AST_Node, -AST_Null: AST_Null, -AST_Number: AST_Number, -AST_Object: AST_Object, -AST_ObjectGetter: AST_ObjectGetter, -AST_ObjectKeyVal: AST_ObjectKeyVal, -AST_ObjectProperty: AST_ObjectProperty, -AST_ObjectSetter: AST_ObjectSetter, -AST_PrefixedTemplateString: AST_PrefixedTemplateString, -AST_PrivateGetter: AST_PrivateGetter, -AST_PrivateMethod: AST_PrivateMethod, -AST_PrivateSetter: AST_PrivateSetter, -AST_PropAccess: AST_PropAccess, -AST_RegExp: AST_RegExp, -AST_Return: AST_Return, -AST_Scope: AST_Scope, -AST_Sequence: AST_Sequence, -AST_SimpleStatement: AST_SimpleStatement, -AST_Statement: AST_Statement, -AST_StatementWithBody: AST_StatementWithBody, -AST_String: AST_String, -AST_Sub: AST_Sub, -AST_Super: AST_Super, -AST_Switch: AST_Switch, -AST_SwitchBranch: AST_SwitchBranch, -AST_Symbol: AST_Symbol, -AST_SymbolBlockDeclaration: AST_SymbolBlockDeclaration, -AST_SymbolCatch: AST_SymbolCatch, -AST_SymbolClass: AST_SymbolClass, -AST_SymbolClassProperty: AST_SymbolClassProperty, -AST_SymbolConst: AST_SymbolConst, -AST_SymbolDeclaration: AST_SymbolDeclaration, -AST_SymbolDefClass: AST_SymbolDefClass, -AST_SymbolDefun: AST_SymbolDefun, -AST_SymbolExport: AST_SymbolExport, -AST_SymbolExportForeign: AST_SymbolExportForeign, -AST_SymbolFunarg: AST_SymbolFunarg, -AST_SymbolImport: AST_SymbolImport, -AST_SymbolImportForeign: AST_SymbolImportForeign, -AST_SymbolLambda: AST_SymbolLambda, -AST_SymbolLet: AST_SymbolLet, -AST_SymbolMethod: AST_SymbolMethod, -AST_SymbolRef: AST_SymbolRef, -AST_SymbolVar: AST_SymbolVar, -AST_TemplateSegment: AST_TemplateSegment, -AST_TemplateString: AST_TemplateString, -AST_This: AST_This, -AST_Throw: AST_Throw, -AST_Token: AST_Token, -AST_Toplevel: AST_Toplevel, -AST_True: AST_True, -AST_Try: AST_Try, -AST_Unary: AST_Unary, -AST_UnaryPostfix: AST_UnaryPostfix, -AST_UnaryPrefix: AST_UnaryPrefix, -AST_Undefined: AST_Undefined, -AST_Var: AST_Var, -AST_VarDef: AST_VarDef, -AST_While: AST_While, -AST_With: AST_With, -AST_Yield: AST_Yield, -TreeTransformer: TreeTransformer, -TreeWalker: TreeWalker, -walk: walk, -walk_abort: walk_abort, -walk_body: walk_body, -walk_parent: walk_parent, -_INLINE: _INLINE, -_NOINLINE: _NOINLINE, -_PURE: _PURE -}); - -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -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); -}); - -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -(function() { - - var normalize_directives = function(body) { - var in_directive = true; - - for (var i = 0; i < body.length; i++) { - if (in_directive && body[i] instanceof AST_Statement && body[i].body instanceof AST_String) { - body[i] = new AST_Directive({ - start: body[i].start, - end: body[i].end, - value: body[i].body.value - }); - } else if (in_directive && !(body[i] instanceof AST_Statement && body[i].body instanceof AST_String)) { - in_directive = false; - } - } - - return body; - }; - - var MOZ_TO_ME = { - Program: function(M) { - return new AST_Toplevel({ - start: my_start_token(M), - end: my_end_token(M), - body: normalize_directives(M.body.map(from_moz)) - }); - }, - ArrayPattern: function(M) { - return new AST_Destructuring({ - start: my_start_token(M), - end: my_end_token(M), - names: M.elements.map(function(elm) { - if (elm === null) { - return new AST_Hole(); - } - return from_moz(elm); - }), - is_array: true - }); - }, - ObjectPattern: function(M) { - return new AST_Destructuring({ - start: my_start_token(M), - end: my_end_token(M), - names: M.properties.map(from_moz), - is_array: false - }); - }, - AssignmentPattern: function(M) { - return new AST_DefaultAssign({ - start: my_start_token(M), - end: my_end_token(M), - left: from_moz(M.left), - operator: "=", - right: from_moz(M.right) - }); - }, - SpreadElement: function(M) { - return new AST_Expansion({ - start: my_start_token(M), - end: my_end_token(M), - expression: from_moz(M.argument) - }); - }, - RestElement: function(M) { - return new AST_Expansion({ - start: my_start_token(M), - end: my_end_token(M), - expression: from_moz(M.argument) - }); - }, - TemplateElement: function(M) { - return new AST_TemplateSegment({ - start: my_start_token(M), - end: my_end_token(M), - value: M.value.cooked, - raw: M.value.raw - }); - }, - TemplateLiteral: function(M) { - var segments = []; - for (var i = 0; i < M.quasis.length; i++) { - segments.push(from_moz(M.quasis[i])); - if (M.expressions[i]) { - segments.push(from_moz(M.expressions[i])); - } - } - return new AST_TemplateString({ - start: my_start_token(M), - end: my_end_token(M), - segments: segments - }); - }, - TaggedTemplateExpression: function(M) { - return new AST_PrefixedTemplateString({ - start: my_start_token(M), - end: my_end_token(M), - template_string: from_moz(M.quasi), - prefix: from_moz(M.tag) - }); - }, - FunctionDeclaration: function(M) { - return new AST_Defun({ - start: my_start_token(M), - end: my_end_token(M), - name: from_moz(M.id), - argnames: M.params.map(from_moz), - is_generator: M.generator, - async: M.async, - body: normalize_directives(from_moz(M.body).body) - }); - }, - FunctionExpression: function(M) { - return new AST_Function({ - start: my_start_token(M), - end: my_end_token(M), - name: from_moz(M.id), - argnames: M.params.map(from_moz), - is_generator: M.generator, - async: M.async, - body: normalize_directives(from_moz(M.body).body) - }); - }, - ArrowFunctionExpression: function(M) { - const body = M.body.type === "BlockStatement" - ? from_moz(M.body).body - : [make_node(AST_Return, {}, { value: from_moz(M.body) })]; - return new AST_Arrow({ - start: my_start_token(M), - end: my_end_token(M), - argnames: M.params.map(from_moz), - body, - async: M.async, - }); - }, - ExpressionStatement: function(M) { - return new AST_SimpleStatement({ - start: my_start_token(M), - end: my_end_token(M), - body: from_moz(M.expression) - }); - }, - TryStatement: function(M) { - var handlers = M.handlers || [M.handler]; - if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) { - throw new Error("Multiple catch clauses are not supported."); - } - return new AST_Try({ - start : my_start_token(M), - end : my_end_token(M), - body : from_moz(M.block).body, - bcatch : from_moz(handlers[0]), - bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null - }); - }, - Property: function(M) { - var key = M.key; - var args = { - start : my_start_token(key || M.value), - end : my_end_token(M.value), - key : key.type == "Identifier" ? key.name : key.value, - value : from_moz(M.value) - }; - if (M.computed) { - args.key = from_moz(M.key); - } - if (M.method) { - args.is_generator = M.value.generator; - args.async = M.value.async; - if (!M.computed) { - args.key = new AST_SymbolMethod({ name: args.key }); - } else { - args.key = from_moz(M.key); - } - return new AST_ConciseMethod(args); - } - if (M.kind == "init") { - if (key.type != "Identifier" && key.type != "Literal") { - args.key = from_moz(key); - } - return new AST_ObjectKeyVal(args); - } - if (typeof args.key === "string" || typeof args.key === "number") { - args.key = new AST_SymbolMethod({ - name: args.key - }); - } - args.value = new AST_Accessor(args.value); - if (M.kind == "get") return new AST_ObjectGetter(args); - if (M.kind == "set") return new AST_ObjectSetter(args); - if (M.kind == "method") { - args.async = M.value.async; - args.is_generator = M.value.generator; - args.quote = M.computed ? "\"" : null; - return new AST_ConciseMethod(args); - } - }, - MethodDefinition: function(M) { - var args = { - start : my_start_token(M), - end : my_end_token(M), - key : M.computed ? from_moz(M.key) : new AST_SymbolMethod({ name: M.key.name || M.key.value }), - value : from_moz(M.value), - static : M.static, - }; - if (M.kind == "get") { - return new AST_ObjectGetter(args); - } - if (M.kind == "set") { - return new AST_ObjectSetter(args); - } - args.is_generator = M.value.generator; - args.async = M.value.async; - return new AST_ConciseMethod(args); - }, - FieldDefinition: function(M) { - let key; - if (M.computed) { - key = from_moz(M.key); - } else { - if (M.key.type !== "Identifier") throw new Error("Non-Identifier key in FieldDefinition"); - key = from_moz(M.key); - } - return new AST_ClassProperty({ - start : my_start_token(M), - end : my_end_token(M), - key, - value : from_moz(M.value), - static : M.static, - }); - }, - PropertyDefinition: function(M) { - let key; - if (M.computed) { - key = from_moz(M.key); - } else { - if (M.key.type !== "Identifier") throw new Error("Non-Identifier key in PropertyDefinition"); - key = from_moz(M.key); - } - - return new AST_ClassProperty({ - start : my_start_token(M), - end : my_end_token(M), - key, - value : from_moz(M.value), - static : M.static, - }); - }, - ArrayExpression: function(M) { - return new AST_Array({ - start : my_start_token(M), - end : my_end_token(M), - elements : M.elements.map(function(elem) { - return elem === null ? new AST_Hole() : from_moz(elem); - }) - }); - }, - ObjectExpression: function(M) { - return new AST_Object({ - start : my_start_token(M), - end : my_end_token(M), - properties : M.properties.map(function(prop) { - if (prop.type === "SpreadElement") { - return from_moz(prop); - } - prop.type = "Property"; - return from_moz(prop); - }) - }); - }, - SequenceExpression: function(M) { - return new AST_Sequence({ - start : my_start_token(M), - end : my_end_token(M), - expressions: M.expressions.map(from_moz) - }); - }, - MemberExpression: function(M) { - return new (M.computed ? AST_Sub : AST_Dot)({ - start : my_start_token(M), - end : my_end_token(M), - property : M.computed ? from_moz(M.property) : M.property.name, - expression : from_moz(M.object), - optional : M.optional || false - }); - }, - ChainExpression: function(M) { - return new AST_Chain({ - start : my_start_token(M), - end : my_end_token(M), - expression : from_moz(M.expression) - }); - }, - SwitchCase: function(M) { - return new (M.test ? AST_Case : AST_Default)({ - start : my_start_token(M), - end : my_end_token(M), - expression : from_moz(M.test), - body : M.consequent.map(from_moz) - }); - }, - VariableDeclaration: function(M) { - return new (M.kind === "const" ? AST_Const : - M.kind === "let" ? AST_Let : AST_Var)({ - start : my_start_token(M), - end : my_end_token(M), - definitions : M.declarations.map(from_moz) - }); - }, - - ImportDeclaration: function(M) { - var imported_name = null; - var imported_names = null; - M.specifiers.forEach(function (specifier) { - if (specifier.type === "ImportSpecifier") { - if (!imported_names) { imported_names = []; } - imported_names.push(new AST_NameMapping({ - start: my_start_token(specifier), - end: my_end_token(specifier), - foreign_name: from_moz(specifier.imported), - name: from_moz(specifier.local) - })); - } else if (specifier.type === "ImportDefaultSpecifier") { - imported_name = from_moz(specifier.local); - } else if (specifier.type === "ImportNamespaceSpecifier") { - if (!imported_names) { imported_names = []; } - imported_names.push(new AST_NameMapping({ - start: my_start_token(specifier), - end: my_end_token(specifier), - foreign_name: new AST_SymbolImportForeign({ name: "*" }), - name: from_moz(specifier.local) - })); - } - }); - return new AST_Import({ - start : my_start_token(M), - end : my_end_token(M), - imported_name: imported_name, - imported_names : imported_names, - module_name : from_moz(M.source) - }); - }, - ExportAllDeclaration: function(M) { - return new AST_Export({ - start: my_start_token(M), - end: my_end_token(M), - exported_names: [ - new AST_NameMapping({ - name: new AST_SymbolExportForeign({ name: "*" }), - foreign_name: new AST_SymbolExportForeign({ name: "*" }) - }) - ], - module_name: from_moz(M.source) - }); - }, - ExportNamedDeclaration: function(M) { - return new AST_Export({ - start: my_start_token(M), - end: my_end_token(M), - exported_definition: from_moz(M.declaration), - exported_names: M.specifiers && M.specifiers.length ? M.specifiers.map(function (specifier) { - return new AST_NameMapping({ - foreign_name: from_moz(specifier.exported), - name: from_moz(specifier.local) - }); - }) : null, - module_name: from_moz(M.source) - }); - }, - ExportDefaultDeclaration: function(M) { - return new AST_Export({ - start: my_start_token(M), - end: my_end_token(M), - exported_value: from_moz(M.declaration), - is_default: true - }); - }, - Literal: function(M) { - var val = M.value, args = { - start : my_start_token(M), - end : my_end_token(M) - }; - var rx = M.regex; - if (rx && rx.pattern) { - // RegExpLiteral as per ESTree AST spec - args.value = { - source: rx.pattern, - flags: rx.flags - }; - return new AST_RegExp(args); - } else if (rx) { - // support legacy RegExp - const rx_source = M.raw || val; - const match = rx_source.match(/^\/(.*)\/(\w*)$/); - if (!match) throw new Error("Invalid regex source " + rx_source); - const [_, source, flags] = match; - args.value = { source, flags }; - return new AST_RegExp(args); - } - if (val === null) return new AST_Null(args); - switch (typeof val) { - case "string": - args.value = val; - return new AST_String(args); - case "number": - args.value = val; - args.raw = M.raw || val.toString(); - return new AST_Number(args); - case "boolean": - return new (val ? AST_True : AST_False)(args); - } - }, - MetaProperty: function(M) { - if (M.meta.name === "new" && M.property.name === "target") { - return new AST_NewTarget({ - start: my_start_token(M), - end: my_end_token(M) - }); - } else if (M.meta.name === "import" && M.property.name === "meta") { - return new AST_ImportMeta({ - start: my_start_token(M), - end: my_end_token(M) - }); - } - }, - Identifier: function(M) { - var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; - return new ( p.type == "LabeledStatement" ? AST_Label - : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : p.kind == "let" ? AST_SymbolLet : AST_SymbolVar) - : /Import.*Specifier/.test(p.type) ? (p.local === M ? AST_SymbolImport : AST_SymbolImportForeign) - : p.type == "ExportSpecifier" ? (p.local === M ? AST_SymbolExport : AST_SymbolExportForeign) - : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) - : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) - : p.type == "ArrowFunctionExpression" ? (p.params.includes(M)) ? AST_SymbolFunarg : AST_SymbolRef - : p.type == "ClassExpression" ? (p.id === M ? AST_SymbolClass : AST_SymbolRef) - : p.type == "Property" ? (p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolMethod) - : p.type == "PropertyDefinition" || p.type === "FieldDefinition" ? (p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolClassProperty) - : p.type == "ClassDeclaration" ? (p.id === M ? AST_SymbolDefClass : AST_SymbolRef) - : p.type == "MethodDefinition" ? (p.computed ? AST_SymbolRef : AST_SymbolMethod) - : p.type == "CatchClause" ? AST_SymbolCatch - : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef - : AST_SymbolRef)({ - start : my_start_token(M), - end : my_end_token(M), - name : M.name - }); - }, - BigIntLiteral(M) { - return new AST_BigInt({ - start : my_start_token(M), - end : my_end_token(M), - value : M.value - }); - } - }; - - MOZ_TO_ME.UpdateExpression = - MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) { - var prefix = "prefix" in M ? M.prefix - : M.type == "UnaryExpression" ? true : false; - return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ - start : my_start_token(M), - end : my_end_token(M), - operator : M.operator, - expression : from_moz(M.argument) - }); - }; - - MOZ_TO_ME.ClassDeclaration = - MOZ_TO_ME.ClassExpression = function From_Moz_Class(M) { - return new (M.type === "ClassDeclaration" ? AST_DefClass : AST_ClassExpression)({ - start : my_start_token(M), - end : my_end_token(M), - name : from_moz(M.id), - extends : from_moz(M.superClass), - properties: M.body.body.map(from_moz) - }); - }; - - map("EmptyStatement", AST_EmptyStatement); - map("BlockStatement", AST_BlockStatement, "body@body"); - map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"); - map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"); - map("BreakStatement", AST_Break, "label>label"); - map("ContinueStatement", AST_Continue, "label>label"); - map("WithStatement", AST_With, "object>expression, body>body"); - map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"); - map("ReturnStatement", AST_Return, "argument>value"); - map("ThrowStatement", AST_Throw, "argument>value"); - map("WhileStatement", AST_While, "test>condition, body>body"); - map("DoWhileStatement", AST_Do, "test>condition, body>body"); - map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"); - map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"); - map("ForOfStatement", AST_ForOf, "left>init, right>object, body>body, await=await"); - map("AwaitExpression", AST_Await, "argument>expression"); - map("YieldExpression", AST_Yield, "argument>expression, delegate=is_star"); - map("DebuggerStatement", AST_Debugger); - map("VariableDeclarator", AST_VarDef, "id>name, init>value"); - map("CatchClause", AST_Catch, "param>argname, body%body"); - - map("ThisExpression", AST_This); - map("Super", AST_Super); - map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"); - map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"); - map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"); - map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"); - map("NewExpression", AST_New, "callee>expression, arguments@args"); - map("CallExpression", AST_Call, "callee>expression, optional=optional, arguments@args"); - - def_to_moz(AST_Toplevel, function To_Moz_Program(M) { - return to_moz_scope("Program", M); - }); - - def_to_moz(AST_Expansion, function To_Moz_Spread(M) { - return { - type: to_moz_in_destructuring() ? "RestElement" : "SpreadElement", - argument: to_moz(M.expression) - }; - }); - - def_to_moz(AST_PrefixedTemplateString, function To_Moz_TaggedTemplateExpression(M) { - return { - type: "TaggedTemplateExpression", - tag: to_moz(M.prefix), - quasi: to_moz(M.template_string) - }; - }); - - def_to_moz(AST_TemplateString, function To_Moz_TemplateLiteral(M) { - var quasis = []; - var expressions = []; - for (var i = 0; i < M.segments.length; i++) { - if (i % 2 !== 0) { - expressions.push(to_moz(M.segments[i])); - } else { - quasis.push({ - type: "TemplateElement", - value: { - raw: M.segments[i].raw, - cooked: M.segments[i].value - }, - tail: i === M.segments.length - 1 - }); - } - } - return { - type: "TemplateLiteral", - quasis: quasis, - expressions: expressions - }; - }); - - def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) { - return { - type: "FunctionDeclaration", - id: to_moz(M.name), - params: M.argnames.map(to_moz), - generator: M.is_generator, - async: M.async, - body: to_moz_scope("BlockStatement", M) - }; - }); - - def_to_moz(AST_Function, function To_Moz_FunctionExpression(M, parent) { - var is_generator = parent.is_generator !== undefined ? - parent.is_generator : M.is_generator; - return { - type: "FunctionExpression", - id: to_moz(M.name), - params: M.argnames.map(to_moz), - generator: is_generator, - async: M.async, - body: to_moz_scope("BlockStatement", M) - }; - }); - - def_to_moz(AST_Arrow, function To_Moz_ArrowFunctionExpression(M) { - var body = { - type: "BlockStatement", - body: M.body.map(to_moz) - }; - return { - type: "ArrowFunctionExpression", - params: M.argnames.map(to_moz), - async: M.async, - body: body - }; - }); - - def_to_moz(AST_Destructuring, function To_Moz_ObjectPattern(M) { - if (M.is_array) { - return { - type: "ArrayPattern", - elements: M.names.map(to_moz) - }; - } - return { - type: "ObjectPattern", - properties: M.names.map(to_moz) - }; - }); - - def_to_moz(AST_Directive, function To_Moz_Directive(M) { - return { - type: "ExpressionStatement", - expression: { - type: "Literal", - value: M.value, - raw: M.print_to_string() - }, - directive: M.value - }; - }); - - def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) { - return { - type: "ExpressionStatement", - expression: to_moz(M.body) - }; - }); - - def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) { - return { - type: "SwitchCase", - test: to_moz(M.expression), - consequent: M.body.map(to_moz) - }; - }); - - def_to_moz(AST_Try, function To_Moz_TryStatement(M) { - return { - type: "TryStatement", - block: to_moz_block(M), - handler: to_moz(M.bcatch), - guardedHandlers: [], - finalizer: to_moz(M.bfinally) - }; - }); - - def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { - return { - type: "CatchClause", - param: to_moz(M.argname), - guard: null, - body: to_moz_block(M) - }; - }); - - def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) { - return { - type: "VariableDeclaration", - kind: - M instanceof AST_Const ? "const" : - M instanceof AST_Let ? "let" : "var", - declarations: M.definitions.map(to_moz) - }; - }); - - def_to_moz(AST_Export, function To_Moz_ExportDeclaration(M) { - if (M.exported_names) { - if (M.exported_names[0].name.name === "*") { - return { - type: "ExportAllDeclaration", - source: to_moz(M.module_name) - }; - } - return { - type: "ExportNamedDeclaration", - specifiers: M.exported_names.map(function (name_mapping) { - return { - type: "ExportSpecifier", - exported: to_moz(name_mapping.foreign_name), - local: to_moz(name_mapping.name) - }; - }), - declaration: to_moz(M.exported_definition), - source: to_moz(M.module_name) - }; - } - return { - type: M.is_default ? "ExportDefaultDeclaration" : "ExportNamedDeclaration", - declaration: to_moz(M.exported_value || M.exported_definition) - }; - }); - - def_to_moz(AST_Import, function To_Moz_ImportDeclaration(M) { - var specifiers = []; - if (M.imported_name) { - specifiers.push({ - type: "ImportDefaultSpecifier", - local: to_moz(M.imported_name) - }); - } - if (M.imported_names && M.imported_names[0].foreign_name.name === "*") { - specifiers.push({ - type: "ImportNamespaceSpecifier", - local: to_moz(M.imported_names[0].name) - }); - } else if (M.imported_names) { - M.imported_names.forEach(function(name_mapping) { - specifiers.push({ - type: "ImportSpecifier", - local: to_moz(name_mapping.name), - imported: to_moz(name_mapping.foreign_name) - }); - }); - } - return { - type: "ImportDeclaration", - specifiers: specifiers, - source: to_moz(M.module_name) - }; - }); - - def_to_moz(AST_ImportMeta, function To_Moz_MetaProperty() { - return { - type: "MetaProperty", - meta: { - type: "Identifier", - name: "import" - }, - property: { - type: "Identifier", - name: "meta" - } - }; - }); - - def_to_moz(AST_Sequence, function To_Moz_SequenceExpression(M) { - return { - type: "SequenceExpression", - expressions: M.expressions.map(to_moz) - }; - }); - - def_to_moz(AST_DotHash, function To_Moz_PrivateMemberExpression(M) { - return { - type: "MemberExpression", - object: to_moz(M.expression), - computed: false, - property: { - type: "PrivateIdentifier", - name: M.property - }, - optional: M.optional - }; - }); - - def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) { - var isComputed = M instanceof AST_Sub; - return { - type: "MemberExpression", - object: to_moz(M.expression), - computed: isComputed, - property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}, - optional: M.optional - }; - }); - - def_to_moz(AST_Chain, function To_Moz_ChainExpression(M) { - return { - type: "ChainExpression", - expression: to_moz(M.expression) - }; - }); - - def_to_moz(AST_Unary, function To_Moz_Unary(M) { - return { - type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression", - operator: M.operator, - prefix: M instanceof AST_UnaryPrefix, - argument: to_moz(M.expression) - }; - }); - - def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { - if (M.operator == "=" && to_moz_in_destructuring()) { - return { - type: "AssignmentPattern", - left: to_moz(M.left), - right: to_moz(M.right) - }; - } - - const type = M.operator == "&&" || M.operator == "||" || M.operator === "??" - ? "LogicalExpression" - : "BinaryExpression"; - - return { - type, - left: to_moz(M.left), - operator: M.operator, - right: to_moz(M.right) - }; - }); - - def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) { - return { - type: "ArrayExpression", - elements: M.elements.map(to_moz) - }; - }); - - def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) { - return { - type: "ObjectExpression", - properties: M.properties.map(to_moz) - }; - }); - - def_to_moz(AST_ObjectProperty, function To_Moz_Property(M, parent) { - var key = M.key instanceof AST_Node ? to_moz(M.key) : { - type: "Identifier", - value: M.key - }; - if (typeof M.key === "number") { - key = { - type: "Literal", - value: Number(M.key) - }; - } - if (typeof M.key === "string") { - key = { - type: "Identifier", - name: M.key - }; - } - var kind; - var string_or_num = typeof M.key === "string" || typeof M.key === "number"; - var computed = string_or_num ? false : !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef; - if (M instanceof AST_ObjectKeyVal) { - kind = "init"; - computed = !string_or_num; - } else - if (M instanceof AST_ObjectGetter) { - kind = "get"; - } else - if (M instanceof AST_ObjectSetter) { - kind = "set"; - } - if (M instanceof AST_PrivateGetter || M instanceof AST_PrivateSetter) { - const kind = M instanceof AST_PrivateGetter ? "get" : "set"; - return { - type: "MethodDefinition", - computed: false, - kind: kind, - static: M.static, - key: { - type: "PrivateIdentifier", - name: M.key.name - }, - value: to_moz(M.value) - }; - } - if (M instanceof AST_ClassPrivateProperty) { - return { - type: "PropertyDefinition", - key: { - type: "PrivateIdentifier", - name: M.key.name - }, - value: to_moz(M.value), - computed: false, - static: M.static - }; - } - if (M instanceof AST_ClassProperty) { - return { - type: "PropertyDefinition", - key, - value: to_moz(M.value), - computed, - static: M.static - }; - } - if (parent instanceof AST_Class) { - return { - type: "MethodDefinition", - computed: computed, - kind: kind, - static: M.static, - key: to_moz(M.key), - value: to_moz(M.value) - }; - } - return { - type: "Property", - computed: computed, - kind: kind, - key: key, - value: to_moz(M.value) - }; - }); - - def_to_moz(AST_ConciseMethod, function To_Moz_MethodDefinition(M, parent) { - if (parent instanceof AST_Object) { - return { - type: "Property", - computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef, - kind: "init", - method: true, - shorthand: false, - key: to_moz(M.key), - value: to_moz(M.value) - }; - } - - const key = M instanceof AST_PrivateMethod - ? { - type: "PrivateIdentifier", - name: M.key.name - } - : to_moz(M.key); - - return { - type: "MethodDefinition", - kind: M.key === "constructor" ? "constructor" : "method", - key, - value: to_moz(M.value), - computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef, - static: M.static, - }; - }); - - def_to_moz(AST_Class, function To_Moz_Class(M) { - var type = M instanceof AST_ClassExpression ? "ClassExpression" : "ClassDeclaration"; - return { - type: type, - superClass: to_moz(M.extends), - id: M.name ? to_moz(M.name) : null, - body: { - type: "ClassBody", - body: M.properties.map(to_moz) - } - }; - }); - - def_to_moz(AST_NewTarget, function To_Moz_MetaProperty() { - return { - type: "MetaProperty", - meta: { - type: "Identifier", - name: "new" - }, - property: { - type: "Identifier", - name: "target" - } - }; - }); - - def_to_moz(AST_Symbol, function To_Moz_Identifier(M, parent) { - if (M instanceof AST_SymbolMethod && parent.quote) { - return { - type: "Literal", - value: M.name - }; - } - var def = M.definition(); - return { - type: "Identifier", - name: def ? def.mangled_name || def.name : M.name - }; - }); - - def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) { - const pattern = M.value.source; - const flags = M.value.flags; - return { - type: "Literal", - value: null, - raw: M.print_to_string(), - regex: { pattern, flags } - }; - }); - - def_to_moz(AST_Constant, function To_Moz_Literal(M) { - var value = M.value; - return { - type: "Literal", - value: value, - raw: M.raw || M.print_to_string() - }; - }); - - def_to_moz(AST_Atom, function To_Moz_Atom(M) { - return { - type: "Identifier", - name: String(M.value) - }; - }); - - def_to_moz(AST_BigInt, M => ({ - type: "BigIntLiteral", - value: M.value - })); - - AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); - AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); - AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null; }); - - AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast); - AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast); - - /* -----[ tools ]----- */ - - function my_start_token(moznode) { - var loc = moznode.loc, start = loc && loc.start; - var range = moznode.range; - return new AST_Token( - "", - "", - start && start.line || 0, - start && start.column || 0, - range ? range [0] : moznode.start, - false, - [], - [], - loc && loc.source, - ); - } - - function my_end_token(moznode) { - var loc = moznode.loc, end = loc && loc.end; - var range = moznode.range; - return new AST_Token( - "", - "", - end && end.line || 0, - end && end.column || 0, - range ? range [0] : moznode.end, - false, - [], - [], - loc && loc.source, - ); - } - - function map(moztype, mytype, propmap) { - var moz_to_me = "function From_Moz_" + moztype + "(M){\n"; - moz_to_me += "return new U2." + mytype.name + "({\n" + - "start: my_start_token(M),\n" + - "end: my_end_token(M)"; - - var me_to_moz = "function To_Moz_" + moztype + "(M){\n"; - me_to_moz += "return {\n" + - "type: " + JSON.stringify(moztype); - - if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop) { - var m = /([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(prop); - if (!m) throw new Error("Can't understand property map: " + prop); - var moz = m[1], how = m[2], my = m[3]; - moz_to_me += ",\n" + my + ": "; - me_to_moz += ",\n" + moz + ": "; - switch (how) { - case "@": - moz_to_me += "M." + moz + ".map(from_moz)"; - me_to_moz += "M." + my + ".map(to_moz)"; - break; - case ">": - moz_to_me += "from_moz(M." + moz + ")"; - me_to_moz += "to_moz(M." + my + ")"; - break; - case "=": - moz_to_me += "M." + moz; - me_to_moz += "M." + my; - break; - case "%": - moz_to_me += "from_moz(M." + moz + ").body"; - me_to_moz += "to_moz_block(M)"; - break; - default: - throw new Error("Can't understand operator in propmap: " + prop); - } - }); - - moz_to_me += "\n})\n}"; - me_to_moz += "\n}\n}"; - - moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")( - ast, my_start_token, my_end_token, from_moz - ); - me_to_moz = new Function("to_moz", "to_moz_block", "to_moz_scope", "return(" + me_to_moz + ")")( - to_moz, to_moz_block, to_moz_scope - ); - MOZ_TO_ME[moztype] = moz_to_me; - def_to_moz(mytype, me_to_moz); - } - - var FROM_MOZ_STACK = null; - - function from_moz(node) { - FROM_MOZ_STACK.push(node); - var ret = node != null ? MOZ_TO_ME[node.type](node) : null; - FROM_MOZ_STACK.pop(); - return ret; - } - - AST_Node.from_mozilla_ast = function(node) { - var save_stack = FROM_MOZ_STACK; - FROM_MOZ_STACK = []; - var ast = from_moz(node); - FROM_MOZ_STACK = save_stack; - return ast; - }; - - function set_moz_loc(mynode, moznode) { - var start = mynode.start; - var end = mynode.end; - if (!(start && end)) { - return moznode; - } - if (start.pos != null && end.endpos != null) { - moznode.range = [start.pos, end.endpos]; - } - if (start.line) { - moznode.loc = { - start: {line: start.line, column: start.col}, - end: end.endline ? {line: end.endline, column: end.endcol} : null - }; - if (start.file) { - moznode.loc.source = start.file; - } - } - return moznode; - } - - function def_to_moz(mytype, handler) { - mytype.DEFMETHOD("to_mozilla_ast", function(parent) { - return set_moz_loc(this, handler(this, parent)); - }); - } - - var TO_MOZ_STACK = null; - - function to_moz(node) { - if (TO_MOZ_STACK === null) { TO_MOZ_STACK = []; } - TO_MOZ_STACK.push(node); - var ast = node != null ? node.to_mozilla_ast(TO_MOZ_STACK[TO_MOZ_STACK.length - 2]) : null; - TO_MOZ_STACK.pop(); - if (TO_MOZ_STACK.length === 0) { TO_MOZ_STACK = null; } - return ast; - } - - function to_moz_in_destructuring() { - var i = TO_MOZ_STACK.length; - while (i--) { - if (TO_MOZ_STACK[i] instanceof AST_Destructuring) { - return true; - } - } - return false; - } - - function to_moz_block(node) { - return { - type: "BlockStatement", - body: node.body.map(to_moz) - }; - } - - function to_moz_scope(type, node) { - var body = node.body.map(to_moz); - if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) { - body.unshift(to_moz(new AST_EmptyStatement(node.body[0]))); - } - return { - type: type, - body: body - }; - } -})(); - -// 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; -} - -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -const EXPECT_DIRECTIVE = /^$|[;{][\s\n]*$/; -const CODE_LINE_BREAK = 10; -const CODE_SPACE = 32; - -const r_annotation = /[@#]__(PURE|INLINE|NOINLINE)__/g; - -function is_some_comments(comment) { - // multiline comment - return ( - (comment.type === "comment2" || comment.type === "comment1") - && /@preserve|@lic|@cc_on|^\**!/i.test(comment.value) - ); -} - -function OutputStream(options) { - - var readonly = !options; - options = defaults(options, { - ascii_only : false, - beautify : false, - braces : false, - comments : "some", - ecma : 5, - ie8 : false, - indent_level : 4, - indent_start : 0, - inline_script : true, - keep_numbers : false, - keep_quoted_props : false, - max_line_len : false, - preamble : null, - preserve_annotations : false, - quote_keys : false, - quote_style : 0, - safari10 : false, - semicolons : true, - shebang : true, - shorthand : undefined, - source_map : null, - webkit : false, - width : 80, - wrap_iife : false, - wrap_func_args : true, - }, true); - - if (options.shorthand === undefined) - options.shorthand = options.ecma > 5; - - // Convert comment option to RegExp if neccessary and set up comments filter - var comment_filter = return_false; // Default case, throw all comments away - if (options.comments) { - let comments = options.comments; - if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) { - var regex_pos = options.comments.lastIndexOf("/"); - comments = new RegExp( - options.comments.substr(1, regex_pos - 1), - options.comments.substr(regex_pos + 1) - ); - } - if (comments instanceof RegExp) { - comment_filter = function(comment) { - return comment.type != "comment5" && comments.test(comment.value); - }; - } else if (typeof comments === "function") { - comment_filter = function(comment) { - return comment.type != "comment5" && comments(this, comment); - }; - } else if (comments === "some") { - comment_filter = is_some_comments; - } else { // NOTE includes "all" option - comment_filter = return_true; - } - } - - var indentation = 0; - var current_col = 0; - var current_line = 1; - var current_pos = 0; - var OUTPUT = ""; - let printed_comments = new Set(); - - var to_utf8 = options.ascii_only ? function(str, identifier) { - if (options.ecma >= 2015 && !options.safari10) { - str = str.replace(/[\ud800-\udbff][\udc00-\udfff]/g, function(ch) { - var code = get_full_char_code(ch, 0).toString(16); - return "\\u{" + code + "}"; - }); - } - return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) { - var code = ch.charCodeAt(0).toString(16); - if (code.length <= 2 && !identifier) { - while (code.length < 2) code = "0" + code; - return "\\x" + code; - } else { - while (code.length < 4) code = "0" + code; - return "\\u" + code; - } - }); - } : function(str) { - return str.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g, function(match, lone) { - if (lone) { - return "\\u" + lone.charCodeAt(0).toString(16); - } - return match; - }); - }; - - function make_string(str, quote) { - var dq = 0, sq = 0; - str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, - function(s, i) { - switch (s) { - case '"': ++dq; return '"'; - case "'": ++sq; return "'"; - case "\\": return "\\\\"; - case "\n": return "\\n"; - case "\r": return "\\r"; - case "\t": return "\\t"; - case "\b": return "\\b"; - case "\f": return "\\f"; - case "\x0B": return options.ie8 ? "\\x0B" : "\\v"; - case "\u2028": return "\\u2028"; - case "\u2029": return "\\u2029"; - case "\ufeff": return "\\ufeff"; - case "\0": - return /[0-9]/.test(get_full_char(str, i+1)) ? "\\x00" : "\\0"; - } - return s; - }); - function quote_single() { - return "'" + str.replace(/\x27/g, "\\'") + "'"; - } - function quote_double() { - return '"' + str.replace(/\x22/g, '\\"') + '"'; - } - function quote_template() { - return "`" + str.replace(/`/g, "\\`") + "`"; - } - str = to_utf8(str); - if (quote === "`") return quote_template(); - switch (options.quote_style) { - case 1: - return quote_single(); - case 2: - return quote_double(); - case 3: - return quote == "'" ? quote_single() : quote_double(); - default: - return dq > sq ? quote_single() : quote_double(); - } - } - - function encode_string(str, quote) { - var ret = make_string(str, quote); - if (options.inline_script) { - ret = ret.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2"); - ret = ret.replace(/\x3c!--/g, "\\x3c!--"); - ret = ret.replace(/--\x3e/g, "--\\x3e"); - } - return ret; - } - - function make_name(name) { - name = name.toString(); - name = to_utf8(name, true); - return name; - } - - function make_indent(back) { - return " ".repeat(options.indent_start + indentation - back * options.indent_level); - } - - /* -----[ beautification/minification ]----- */ - - var has_parens = false; - var might_need_space = false; - var might_need_semicolon = false; - var might_add_newline = 0; - var need_newline_indented = false; - var need_space = false; - var newline_insert = -1; - var last = ""; - var mapping_token, mapping_name, mappings = options.source_map && []; - - var do_add_mapping = mappings ? function() { - mappings.forEach(function(mapping) { - try { - options.source_map.add( - mapping.token.file, - mapping.line, mapping.col, - mapping.token.line, mapping.token.col, - !mapping.name && mapping.token.type == "name" ? mapping.token.value : mapping.name - ); - } catch(ex) { - // Ignore bad mapping - } - }); - mappings = []; - } : noop; - - var ensure_line_len = options.max_line_len ? function() { - if (current_col > options.max_line_len) { - if (might_add_newline) { - var left = OUTPUT.slice(0, might_add_newline); - var right = OUTPUT.slice(might_add_newline); - if (mappings) { - var delta = right.length - current_col; - mappings.forEach(function(mapping) { - mapping.line++; - mapping.col += delta; - }); - } - OUTPUT = left + "\n" + right; - current_line++; - current_pos++; - current_col = right.length; - } - } - if (might_add_newline) { - might_add_newline = 0; - do_add_mapping(); - } - } : noop; - - var requireSemicolonChars = makePredicate("( [ + * / - , . `"); - - function print(str) { - str = String(str); - var ch = get_full_char(str, 0); - if (need_newline_indented && ch) { - need_newline_indented = false; - if (ch !== "\n") { - print("\n"); - indent(); - } - } - if (need_space && ch) { - need_space = false; - if (!/[\s;})]/.test(ch)) { - space(); - } - } - newline_insert = -1; - var prev = last.charAt(last.length - 1); - if (might_need_semicolon) { - might_need_semicolon = false; - - if (prev === ":" && ch === "}" || (!ch || !";}".includes(ch)) && prev !== ";") { - if (options.semicolons || requireSemicolonChars.has(ch)) { - OUTPUT += ";"; - current_col++; - current_pos++; - } else { - ensure_line_len(); - if (current_col > 0) { - OUTPUT += "\n"; - current_pos++; - current_line++; - current_col = 0; - } - - if (/^\s+$/.test(str)) { - // reset the semicolon flag, since we didn't print one - // now and might still have to later - might_need_semicolon = true; - } - } - - if (!options.beautify) - might_need_space = false; - } - } - - if (might_need_space) { - if ((is_identifier_char(prev) - && (is_identifier_char(ch) || ch == "\\")) - || (ch == "/" && ch == prev) - || ((ch == "+" || ch == "-") && ch == last) - ) { - OUTPUT += " "; - current_col++; - current_pos++; - } - might_need_space = false; - } - - if (mapping_token) { - mappings.push({ - token: mapping_token, - name: mapping_name, - line: current_line, - col: current_col - }); - mapping_token = false; - if (!might_add_newline) do_add_mapping(); - } - - OUTPUT += str; - has_parens = str[str.length - 1] == "("; - current_pos += str.length; - var a = str.split(/\r?\n/), n = a.length - 1; - current_line += n; - current_col += a[0].length; - if (n > 0) { - ensure_line_len(); - current_col = a[n].length; - } - last = str; - } - - var star = function() { - print("*"); - }; - - var space = options.beautify ? function() { - print(" "); - } : function() { - might_need_space = true; - }; - - var indent = options.beautify ? function(half) { - if (options.beautify) { - print(make_indent(half ? 0.5 : 0)); - } - } : noop; - - var with_indent = options.beautify ? function(col, cont) { - if (col === true) col = next_indent(); - var save_indentation = indentation; - indentation = col; - var ret = cont(); - indentation = save_indentation; - return ret; - } : function(col, cont) { return cont(); }; - - var newline = options.beautify ? function() { - if (newline_insert < 0) return print("\n"); - if (OUTPUT[newline_insert] != "\n") { - OUTPUT = OUTPUT.slice(0, newline_insert) + "\n" + OUTPUT.slice(newline_insert); - current_pos++; - current_line++; - } - newline_insert++; - } : options.max_line_len ? function() { - ensure_line_len(); - might_add_newline = OUTPUT.length; - } : noop; - - var semicolon = options.beautify ? function() { - print(";"); - } : function() { - might_need_semicolon = true; - }; - - function force_semicolon() { - might_need_semicolon = false; - print(";"); - } - - function next_indent() { - return indentation + options.indent_level; - } - - function with_block(cont) { - var ret; - print("{"); - newline(); - with_indent(next_indent(), function() { - ret = cont(); - }); - indent(); - print("}"); - return ret; - } - - function with_parens(cont) { - print("("); - //XXX: still nice to have that for argument lists - //var ret = with_indent(current_col, cont); - var ret = cont(); - print(")"); - return ret; - } - - function with_square(cont) { - print("["); - //var ret = with_indent(current_col, cont); - var ret = cont(); - print("]"); - return ret; - } - - function comma() { - print(","); - space(); - } - - function colon() { - print(":"); - space(); - } - - var add_mapping = mappings ? function(token, name) { - mapping_token = token; - mapping_name = name; - } : noop; - - function get() { - if (might_add_newline) { - ensure_line_len(); - } - return OUTPUT; - } - - function has_nlb() { - let n = OUTPUT.length - 1; - while (n >= 0) { - const code = OUTPUT.charCodeAt(n); - if (code === CODE_LINE_BREAK) { - return true; - } - - if (code !== CODE_SPACE) { - return false; - } - n--; - } - return true; - } - - function filter_comment(comment) { - if (!options.preserve_annotations) { - comment = comment.replace(r_annotation, " "); - } - if (/^\s*$/.test(comment)) { - return ""; - } - return comment.replace(/(<\s*\/\s*)(script)/i, "<\\/$2"); - } - - function prepend_comments(node) { - var self = this; - var start = node.start; - if (!start) return; - var printed_comments = self.printed_comments; - - // There cannot be a newline between return and its value. - const return_with_value = node instanceof AST_Exit && node.value; - - if ( - start.comments_before - && printed_comments.has(start.comments_before) - ) { - if (return_with_value) { - start.comments_before = []; - } else { - return; - } - } - - var comments = start.comments_before; - if (!comments) { - comments = start.comments_before = []; - } - printed_comments.add(comments); - - if (return_with_value) { - var tw = new TreeWalker(function(node) { - var parent = tw.parent(); - if (parent instanceof AST_Exit - || parent instanceof AST_Binary && parent.left === node - || parent.TYPE == "Call" && parent.expression === node - || parent instanceof AST_Conditional && parent.condition === node - || parent instanceof AST_Dot && parent.expression === node - || parent instanceof AST_Sequence && parent.expressions[0] === node - || parent instanceof AST_Sub && parent.expression === node - || parent instanceof AST_UnaryPostfix) { - if (!node.start) return; - var text = node.start.comments_before; - if (text && !printed_comments.has(text)) { - printed_comments.add(text); - comments = comments.concat(text); - } - } else { - return true; - } - }); - tw.push(node); - node.value.walk(tw); - } - - if (current_pos == 0) { - if (comments.length > 0 && options.shebang && comments[0].type === "comment5" - && !printed_comments.has(comments[0])) { - print("#!" + comments.shift().value + "\n"); - indent(); - } - var preamble = options.preamble; - if (preamble) { - print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n")); - } - } - - comments = comments.filter(comment_filter, node).filter(c => !printed_comments.has(c)); - if (comments.length == 0) return; - var last_nlb = has_nlb(); - comments.forEach(function(c, i) { - printed_comments.add(c); - if (!last_nlb) { - if (c.nlb) { - print("\n"); - indent(); - last_nlb = true; - } else if (i > 0) { - space(); - } - } - - if (/comment[134]/.test(c.type)) { - var value = filter_comment(c.value); - if (value) { - print("//" + value + "\n"); - indent(); - } - last_nlb = true; - } else if (c.type == "comment2") { - var value = filter_comment(c.value); - if (value) { - print("/*" + value + "*/"); - } - last_nlb = false; - } - }); - if (!last_nlb) { - if (start.nlb) { - print("\n"); - indent(); - } else { - space(); - } - } - } - - function append_comments(node, tail) { - var self = this; - var token = node.end; - if (!token) return; - var printed_comments = self.printed_comments; - var comments = token[tail ? "comments_before" : "comments_after"]; - if (!comments || printed_comments.has(comments)) return; - if (!(node instanceof AST_Statement || comments.every((c) => - !/comment[134]/.test(c.type) - ))) return; - printed_comments.add(comments); - var insert = OUTPUT.length; - comments.filter(comment_filter, node).forEach(function(c, i) { - if (printed_comments.has(c)) return; - printed_comments.add(c); - need_space = false; - if (need_newline_indented) { - print("\n"); - indent(); - need_newline_indented = false; - } else if (c.nlb && (i > 0 || !has_nlb())) { - print("\n"); - indent(); - } else if (i > 0 || !tail) { - space(); - } - if (/comment[134]/.test(c.type)) { - const value = filter_comment(c.value); - if (value) { - print("//" + value); - } - need_newline_indented = true; - } else if (c.type == "comment2") { - const value = filter_comment(c.value); - if (value) { - print("/*" + value + "*/"); - } - need_space = true; - } - }); - if (OUTPUT.length > insert) newline_insert = insert; - } - - var stack = []; - return { - get : get, - toString : get, - indent : indent, - in_directive : false, - use_asm : null, - active_scope : null, - indentation : function() { return indentation; }, - current_width : function() { return current_col - indentation; }, - should_break : function() { return options.width && this.current_width() >= options.width; }, - has_parens : function() { return has_parens; }, - newline : newline, - print : print, - star : star, - space : space, - comma : comma, - colon : colon, - last : function() { return last; }, - semicolon : semicolon, - force_semicolon : force_semicolon, - to_utf8 : to_utf8, - print_name : function(name) { print(make_name(name)); }, - print_string : function(str, quote, escape_directive) { - var encoded = encode_string(str, quote); - if (escape_directive === true && !encoded.includes("\\")) { - // Insert semicolons to break directive prologue - if (!EXPECT_DIRECTIVE.test(OUTPUT)) { - force_semicolon(); - } - force_semicolon(); - } - print(encoded); - }, - print_template_string_chars: function(str) { - var encoded = encode_string(str, "`").replace(/\${/g, "\\${"); - return print(encoded.substr(1, encoded.length - 2)); - }, - encode_string : encode_string, - next_indent : next_indent, - with_indent : with_indent, - with_block : with_block, - with_parens : with_parens, - with_square : with_square, - add_mapping : add_mapping, - option : function(opt) { return options[opt]; }, - printed_comments: printed_comments, - prepend_comments: readonly ? noop : prepend_comments, - append_comments : readonly || comment_filter === return_false ? noop : append_comments, - line : function() { return current_line; }, - col : function() { return current_col; }, - pos : function() { return current_pos; }, - push_node : function(node) { stack.push(node); }, - pop_node : function() { return stack.pop(); }, - parent : function(n) { - return stack[stack.length - 2 - (n || 0)]; - } - }; - -} - -/* -----[ code generators ]----- */ - -(function() { - - /* -----[ utils ]----- */ - - function DEFPRINT(nodetype, generator) { - nodetype.DEFMETHOD("_codegen", generator); - } - - AST_Node.DEFMETHOD("print", function(output, force_parens) { - var self = this, generator = self._codegen; - if (self instanceof AST_Scope) { - output.active_scope = self; - } else if (!output.use_asm && self instanceof AST_Directive && self.value == "use asm") { - output.use_asm = output.active_scope; - } - function doit() { - output.prepend_comments(self); - self.add_source_map(output); - generator(self, output); - output.append_comments(self); - } - output.push_node(self); - if (force_parens || self.needs_parens(output)) { - output.with_parens(doit); - } else { - doit(); - } - output.pop_node(); - if (self === output.use_asm) { - output.use_asm = null; - } - }); - AST_Node.DEFMETHOD("_print", AST_Node.prototype.print); - - AST_Node.DEFMETHOD("print_to_string", function(options) { - var output = OutputStream(options); - this.print(output); - return output.get(); - }); - - /* -----[ PARENTHESES ]----- */ - - function PARENS(nodetype, func) { - if (Array.isArray(nodetype)) { - nodetype.forEach(function(nodetype) { - PARENS(nodetype, func); - }); - } else { - nodetype.DEFMETHOD("needs_parens", func); - } - } - - PARENS(AST_Node, return_false); - - // a function expression needs parens around it when it's provably - // the first token to appear in a statement. - PARENS(AST_Function, function(output) { - if (!output.has_parens() && first_in_statement(output)) { - return true; - } - - if (output.option("webkit")) { - var p = output.parent(); - if (p instanceof AST_PropAccess && p.expression === this) { - return true; - } - } - - if (output.option("wrap_iife")) { - var p = output.parent(); - if (p instanceof AST_Call && p.expression === this) { - return true; - } - } - - if (output.option("wrap_func_args")) { - var p = output.parent(); - if (p instanceof AST_Call && p.args.includes(this)) { - return true; - } - } - - return false; - }); - - PARENS(AST_Arrow, function(output) { - var p = output.parent(); - - if ( - output.option("wrap_func_args") - && p instanceof AST_Call - && p.args.includes(this) - ) { - return true; - } - return p instanceof AST_PropAccess && p.expression === this; - }); - - // same goes for an object literal (as in AST_Function), because - // otherwise {...} would be interpreted as a block of code. - PARENS(AST_Object, function(output) { - return !output.has_parens() && first_in_statement(output); - }); - - PARENS(AST_ClassExpression, first_in_statement); - - PARENS(AST_Unary, function(output) { - var p = output.parent(); - return p instanceof AST_PropAccess && p.expression === this - || p instanceof AST_Call && p.expression === this - || p instanceof AST_Binary - && p.operator === "**" - && this instanceof AST_UnaryPrefix - && p.left === this - && this.operator !== "++" - && this.operator !== "--"; - }); - - PARENS(AST_Await, function(output) { - var p = output.parent(); - return p instanceof AST_PropAccess && p.expression === this - || p instanceof AST_Call && p.expression === this - || p instanceof AST_Binary && p.operator === "**" && p.left === this - || output.option("safari10") && p instanceof AST_UnaryPrefix; - }); - - PARENS(AST_Sequence, function(output) { - var p = output.parent(); - return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) - || p instanceof AST_Unary // !(foo, bar, baz) - || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 - || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 - || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 - || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] - || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 - || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) - * ==> 20 (side effect, set a := 10 and b := 20) */ - || p instanceof AST_Arrow // x => (x, x) - || p instanceof AST_DefaultAssign // x => (x = (0, function(){})) - || p instanceof AST_Expansion // [...(a, b)] - || p instanceof AST_ForOf && this === p.object // for (e of (foo, bar)) {} - || p instanceof AST_Yield // yield (foo, bar) - || p instanceof AST_Export // export default (foo, bar) - ; - }); - - PARENS(AST_Binary, function(output) { - var p = output.parent(); - // (foo && bar)() - if (p instanceof AST_Call && p.expression === this) - return true; - // typeof (foo && bar) - if (p instanceof AST_Unary) - return true; - // (foo && bar)["prop"], (foo && bar).prop - if (p instanceof AST_PropAccess && p.expression === this) - return true; - // this deals with precedence: 3 * (2 + 1) - if (p instanceof AST_Binary) { - const po = p.operator; - const so = this.operator; - - if (so === "??" && (po === "||" || po === "&&")) { - return true; - } - - if (po === "??" && (so === "||" || so === "&&")) { - return true; - } - - const pp = PRECEDENCE[po]; - const sp = PRECEDENCE[so]; - if (pp > sp - || (pp == sp - && (this === p.right || po == "**"))) { - return true; - } - } - }); - - PARENS(AST_Yield, function(output) { - var p = output.parent(); - // (yield 1) + (yield 2) - // a = yield 3 - if (p instanceof AST_Binary && p.operator !== "=") - return true; - // (yield 1)() - // new (yield 1)() - if (p instanceof AST_Call && p.expression === this) - return true; - // (yield 1) ? yield 2 : yield 3 - if (p instanceof AST_Conditional && p.condition === this) - return true; - // -(yield 4) - if (p instanceof AST_Unary) - return true; - // (yield x).foo - // (yield x)['foo'] - if (p instanceof AST_PropAccess && p.expression === this) - return true; - }); - - PARENS(AST_PropAccess, function(output) { - var p = output.parent(); - if (p instanceof AST_New && p.expression === this) { - // i.e. new (foo.bar().baz) - // - // if there's one call into this subtree, then we need - // parens around it too, otherwise the call will be - // interpreted as passing the arguments to the upper New - // expression. - return walk(this, node => { - if (node instanceof AST_Scope) return true; - if (node instanceof AST_Call) { - return walk_abort; // makes walk() return true. - } - }); - } - }); - - PARENS(AST_Call, function(output) { - var p = output.parent(), p1; - if (p instanceof AST_New && p.expression === this - || p instanceof AST_Export && p.is_default && this.expression instanceof AST_Function) - return true; - - // workaround for Safari bug. - // https://bugs.webkit.org/show_bug.cgi?id=123506 - return this.expression instanceof AST_Function - && p instanceof AST_PropAccess - && p.expression === this - && (p1 = output.parent(1)) instanceof AST_Assign - && p1.left === p; - }); - - PARENS(AST_New, function(output) { - var p = output.parent(); - if (this.args.length === 0 - && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() - || p instanceof AST_Call && p.expression === this)) // (new foo)(bar) - return true; - }); - - PARENS(AST_Number, function(output) { - var p = output.parent(); - if (p instanceof AST_PropAccess && p.expression === this) { - var value = this.getValue(); - if (value < 0 || /^0/.test(make_num(value))) { - return true; - } - } - }); - - PARENS(AST_BigInt, function(output) { - var p = output.parent(); - if (p instanceof AST_PropAccess && p.expression === this) { - var value = this.getValue(); - if (value.startsWith("-")) { - return true; - } - } - }); - - PARENS([ AST_Assign, AST_Conditional ], function(output) { - var p = output.parent(); - // !(a = false) → true - if (p instanceof AST_Unary) - return true; - // 1 + (a = 2) + 3 → 6, side effect setting a = 2 - if (p instanceof AST_Binary && !(p instanceof AST_Assign)) - return true; - // (a = func)() —or— new (a = Object)() - if (p instanceof AST_Call && p.expression === this) - return true; - // (a = foo) ? bar : baz - if (p instanceof AST_Conditional && p.condition === this) - return true; - // (a = foo)["prop"] —or— (a = foo).prop - if (p instanceof AST_PropAccess && p.expression === this) - return true; - // ({a, b} = {a: 1, b: 2}), a destructuring assignment - if (this instanceof AST_Assign && this.left instanceof AST_Destructuring && this.left.is_array === false) - return true; - }); - - /* -----[ PRINTERS ]----- */ - - DEFPRINT(AST_Directive, function(self, output) { - output.print_string(self.value, self.quote); - output.semicolon(); - }); - - DEFPRINT(AST_Expansion, function (self, output) { - output.print("..."); - self.expression.print(output); - }); - - DEFPRINT(AST_Destructuring, function (self, output) { - output.print(self.is_array ? "[" : "{"); - var len = self.names.length; - self.names.forEach(function (name, i) { - if (i > 0) output.comma(); - name.print(output); - // If the final element is a hole, we need to make sure it - // doesn't look like a trailing comma, by inserting an actual - // trailing comma. - if (i == len - 1 && name instanceof AST_Hole) output.comma(); - }); - output.print(self.is_array ? "]" : "}"); - }); - - DEFPRINT(AST_Debugger, function(self, output) { - output.print("debugger"); - output.semicolon(); - }); - - /* -----[ statements ]----- */ - - function display_body(body, is_toplevel, output, allow_directives) { - var last = body.length - 1; - output.in_directive = allow_directives; - body.forEach(function(stmt, i) { - if (output.in_directive === true && !(stmt instanceof AST_Directive || - stmt instanceof AST_EmptyStatement || - (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String) - )) { - output.in_directive = false; - } - if (!(stmt instanceof AST_EmptyStatement)) { - output.indent(); - stmt.print(output); - if (!(i == last && is_toplevel)) { - output.newline(); - if (is_toplevel) output.newline(); - } - } - if (output.in_directive === true && - stmt instanceof AST_SimpleStatement && - stmt.body instanceof AST_String - ) { - output.in_directive = false; - } - }); - output.in_directive = false; - } - - AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output) { - force_statement(this.body, output); - }); - - DEFPRINT(AST_Statement, function(self, output) { - self.body.print(output); - output.semicolon(); - }); - DEFPRINT(AST_Toplevel, function(self, output) { - display_body(self.body, true, output, true); - output.print(""); - }); - DEFPRINT(AST_LabeledStatement, function(self, output) { - self.label.print(output); - output.colon(); - self.body.print(output); - }); - DEFPRINT(AST_SimpleStatement, function(self, output) { - self.body.print(output); - output.semicolon(); - }); - function print_braced_empty(self, output) { - output.print("{"); - output.with_indent(output.next_indent(), function() { - output.append_comments(self, true); - }); - output.print("}"); - } - function print_braced(self, output, allow_directives) { - if (self.body.length > 0) { - output.with_block(function() { - display_body(self.body, false, output, allow_directives); - }); - } else print_braced_empty(self, output); - } - DEFPRINT(AST_BlockStatement, function(self, output) { - print_braced(self, output); - }); - DEFPRINT(AST_EmptyStatement, function(self, output) { - output.semicolon(); - }); - DEFPRINT(AST_Do, function(self, output) { - output.print("do"); - output.space(); - make_block(self.body, output); - output.space(); - output.print("while"); - output.space(); - output.with_parens(function() { - self.condition.print(output); - }); - output.semicolon(); - }); - DEFPRINT(AST_While, function(self, output) { - output.print("while"); - output.space(); - output.with_parens(function() { - self.condition.print(output); - }); - output.space(); - self._do_print_body(output); - }); - DEFPRINT(AST_For, function(self, output) { - output.print("for"); - output.space(); - output.with_parens(function() { - if (self.init) { - if (self.init instanceof AST_Definitions) { - self.init.print(output); - } else { - parenthesize_for_noin(self.init, output, true); - } - output.print(";"); - output.space(); - } else { - output.print(";"); - } - if (self.condition) { - self.condition.print(output); - output.print(";"); - output.space(); - } else { - output.print(";"); - } - if (self.step) { - self.step.print(output); - } - }); - output.space(); - self._do_print_body(output); - }); - DEFPRINT(AST_ForIn, function(self, output) { - output.print("for"); - if (self.await) { - output.space(); - output.print("await"); - } - output.space(); - output.with_parens(function() { - self.init.print(output); - output.space(); - output.print(self instanceof AST_ForOf ? "of" : "in"); - output.space(); - self.object.print(output); - }); - output.space(); - self._do_print_body(output); - }); - DEFPRINT(AST_With, function(self, output) { - output.print("with"); - output.space(); - output.with_parens(function() { - self.expression.print(output); - }); - output.space(); - self._do_print_body(output); - }); - - /* -----[ functions ]----- */ - AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword) { - var self = this; - if (!nokeyword) { - if (self.async) { - output.print("async"); - output.space(); - } - output.print("function"); - if (self.is_generator) { - output.star(); - } - if (self.name) { - output.space(); - } - } - if (self.name instanceof AST_Symbol) { - self.name.print(output); - } else if (nokeyword && self.name instanceof AST_Node) { - output.with_square(function() { - self.name.print(output); // Computed method name - }); - } - output.with_parens(function() { - self.argnames.forEach(function(arg, i) { - if (i) output.comma(); - arg.print(output); - }); - }); - output.space(); - print_braced(self, output, true); - }); - DEFPRINT(AST_Lambda, function(self, output) { - self._do_print(output); - }); - - DEFPRINT(AST_PrefixedTemplateString, function(self, output) { - var tag = self.prefix; - var parenthesize_tag = tag instanceof AST_Lambda - || tag instanceof AST_Binary - || tag instanceof AST_Conditional - || tag instanceof AST_Sequence - || tag instanceof AST_Unary - || tag instanceof AST_Dot && tag.expression instanceof AST_Object; - if (parenthesize_tag) output.print("("); - self.prefix.print(output); - if (parenthesize_tag) output.print(")"); - self.template_string.print(output); - }); - DEFPRINT(AST_TemplateString, function(self, output) { - var is_tagged = output.parent() instanceof AST_PrefixedTemplateString; - - output.print("`"); - for (var i = 0; i < self.segments.length; i++) { - if (!(self.segments[i] instanceof AST_TemplateSegment)) { - output.print("${"); - self.segments[i].print(output); - output.print("}"); - } else if (is_tagged) { - output.print(self.segments[i].raw); - } else { - output.print_template_string_chars(self.segments[i].value); - } - } - output.print("`"); - }); - DEFPRINT(AST_TemplateSegment, function(self, output) { - output.print_template_string_chars(self.value); - }); - - AST_Arrow.DEFMETHOD("_do_print", function(output) { - var self = this; - var parent = output.parent(); - var needs_parens = (parent instanceof AST_Binary && !(parent instanceof AST_Assign)) || - parent instanceof AST_Unary || - (parent instanceof AST_Call && self === parent.expression); - if (needs_parens) { output.print("("); } - if (self.async) { - output.print("async"); - output.space(); - } - if (self.argnames.length === 1 && self.argnames[0] instanceof AST_Symbol) { - self.argnames[0].print(output); - } else { - output.with_parens(function() { - self.argnames.forEach(function(arg, i) { - if (i) output.comma(); - arg.print(output); - }); - }); - } - output.space(); - output.print("=>"); - output.space(); - const first_statement = self.body[0]; - if ( - self.body.length === 1 - && first_statement instanceof AST_Return - ) { - const returned = first_statement.value; - if (!returned) { - output.print("{}"); - } else if (left_is_object(returned)) { - output.print("("); - returned.print(output); - output.print(")"); - } else { - returned.print(output); - } - } else { - print_braced(self, output); - } - if (needs_parens) { output.print(")"); } - }); - - /* -----[ exits ]----- */ - AST_Exit.DEFMETHOD("_do_print", function(output, kind) { - output.print(kind); - if (this.value) { - output.space(); - const comments = this.value.start.comments_before; - if (comments && comments.length && !output.printed_comments.has(comments)) { - output.print("("); - this.value.print(output); - output.print(")"); - } else { - this.value.print(output); - } - } - output.semicolon(); - }); - DEFPRINT(AST_Return, function(self, output) { - self._do_print(output, "return"); - }); - DEFPRINT(AST_Throw, function(self, output) { - self._do_print(output, "throw"); - }); - - /* -----[ yield ]----- */ - - DEFPRINT(AST_Yield, function(self, output) { - var star = self.is_star ? "*" : ""; - output.print("yield" + star); - if (self.expression) { - output.space(); - self.expression.print(output); - } - }); - - DEFPRINT(AST_Await, function(self, output) { - output.print("await"); - output.space(); - var e = self.expression; - var parens = !( - e instanceof AST_Call - || e instanceof AST_SymbolRef - || e instanceof AST_PropAccess - || e instanceof AST_Unary - || e instanceof AST_Constant - || e instanceof AST_Await - || e instanceof AST_Object - ); - if (parens) output.print("("); - self.expression.print(output); - if (parens) output.print(")"); - }); - - /* -----[ loop control ]----- */ - AST_LoopControl.DEFMETHOD("_do_print", function(output, kind) { - output.print(kind); - if (this.label) { - output.space(); - this.label.print(output); - } - output.semicolon(); - }); - DEFPRINT(AST_Break, function(self, output) { - self._do_print(output, "break"); - }); - DEFPRINT(AST_Continue, function(self, output) { - self._do_print(output, "continue"); - }); - - /* -----[ if ]----- */ - function make_then(self, output) { - var b = self.body; - if (output.option("braces") - || output.option("ie8") && b instanceof AST_Do) - return make_block(b, output); - // The squeezer replaces "block"-s that contain only a single - // statement with the statement itself; technically, the AST - // is correct, but this can create problems when we output an - // IF having an ELSE clause where the THEN clause ends in an - // IF *without* an ELSE block (then the outer ELSE would refer - // to the inner IF). This function checks for this case and - // adds the block braces if needed. - if (!b) return output.force_semicolon(); - while (true) { - if (b instanceof AST_If) { - if (!b.alternative) { - make_block(self.body, output); - return; - } - b = b.alternative; - } else if (b instanceof AST_StatementWithBody) { - b = b.body; - } else break; - } - force_statement(self.body, output); - } - DEFPRINT(AST_If, function(self, output) { - output.print("if"); - output.space(); - output.with_parens(function() { - self.condition.print(output); - }); - output.space(); - if (self.alternative) { - make_then(self, output); - output.space(); - output.print("else"); - output.space(); - if (self.alternative instanceof AST_If) - self.alternative.print(output); - else - force_statement(self.alternative, output); - } else { - self._do_print_body(output); - } - }); - - /* -----[ switch ]----- */ - DEFPRINT(AST_Switch, function(self, output) { - output.print("switch"); - output.space(); - output.with_parens(function() { - self.expression.print(output); - }); - output.space(); - var last = self.body.length - 1; - if (last < 0) print_braced_empty(self, output); - else output.with_block(function() { - self.body.forEach(function(branch, i) { - output.indent(true); - branch.print(output); - if (i < last && branch.body.length > 0) - output.newline(); - }); - }); - }); - AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output) { - output.newline(); - this.body.forEach(function(stmt) { - output.indent(); - stmt.print(output); - output.newline(); - }); - }); - DEFPRINT(AST_Default, function(self, output) { - output.print("default:"); - self._do_print_body(output); - }); - DEFPRINT(AST_Case, function(self, output) { - output.print("case"); - output.space(); - self.expression.print(output); - output.print(":"); - self._do_print_body(output); - }); - - /* -----[ exceptions ]----- */ - DEFPRINT(AST_Try, function(self, output) { - output.print("try"); - output.space(); - print_braced(self, output); - if (self.bcatch) { - output.space(); - self.bcatch.print(output); - } - if (self.bfinally) { - output.space(); - self.bfinally.print(output); - } - }); - DEFPRINT(AST_Catch, function(self, output) { - output.print("catch"); - if (self.argname) { - output.space(); - output.with_parens(function() { - self.argname.print(output); - }); - } - output.space(); - print_braced(self, output); - }); - DEFPRINT(AST_Finally, function(self, output) { - output.print("finally"); - output.space(); - print_braced(self, output); - }); - - /* -----[ var/const ]----- */ - AST_Definitions.DEFMETHOD("_do_print", function(output, kind) { - output.print(kind); - output.space(); - this.definitions.forEach(function(def, i) { - if (i) output.comma(); - def.print(output); - }); - var p = output.parent(); - var in_for = p instanceof AST_For || p instanceof AST_ForIn; - var output_semicolon = !in_for || p && p.init !== this; - if (output_semicolon) - output.semicolon(); - }); - DEFPRINT(AST_Let, function(self, output) { - self._do_print(output, "let"); - }); - DEFPRINT(AST_Var, function(self, output) { - self._do_print(output, "var"); - }); - DEFPRINT(AST_Const, function(self, output) { - self._do_print(output, "const"); - }); - DEFPRINT(AST_Import, function(self, output) { - output.print("import"); - output.space(); - if (self.imported_name) { - self.imported_name.print(output); - } - if (self.imported_name && self.imported_names) { - output.print(","); - output.space(); - } - if (self.imported_names) { - if (self.imported_names.length === 1 && self.imported_names[0].foreign_name.name === "*") { - self.imported_names[0].print(output); - } else { - output.print("{"); - self.imported_names.forEach(function (name_import, i) { - output.space(); - name_import.print(output); - if (i < self.imported_names.length - 1) { - output.print(","); - } - }); - output.space(); - output.print("}"); - } - } - if (self.imported_name || self.imported_names) { - output.space(); - output.print("from"); - output.space(); - } - self.module_name.print(output); - output.semicolon(); - }); - DEFPRINT(AST_ImportMeta, function(self, output) { - output.print("import.meta"); - }); - - DEFPRINT(AST_NameMapping, function(self, output) { - var is_import = output.parent() instanceof AST_Import; - var definition = self.name.definition(); - var names_are_different = - (definition && definition.mangled_name || self.name.name) !== - self.foreign_name.name; - if (names_are_different) { - if (is_import) { - output.print(self.foreign_name.name); - } else { - self.name.print(output); - } - output.space(); - output.print("as"); - output.space(); - if (is_import) { - self.name.print(output); - } else { - output.print(self.foreign_name.name); - } - } else { - self.name.print(output); - } - }); - - DEFPRINT(AST_Export, function(self, output) { - output.print("export"); - output.space(); - if (self.is_default) { - output.print("default"); - output.space(); - } - if (self.exported_names) { - if (self.exported_names.length === 1 && self.exported_names[0].name.name === "*") { - self.exported_names[0].print(output); - } else { - output.print("{"); - self.exported_names.forEach(function(name_export, i) { - output.space(); - name_export.print(output); - if (i < self.exported_names.length - 1) { - output.print(","); - } - }); - output.space(); - output.print("}"); - } - } else if (self.exported_value) { - self.exported_value.print(output); - } else if (self.exported_definition) { - self.exported_definition.print(output); - if (self.exported_definition instanceof AST_Definitions) return; - } - if (self.module_name) { - output.space(); - output.print("from"); - output.space(); - self.module_name.print(output); - } - if (self.exported_value - && !(self.exported_value instanceof AST_Defun || - self.exported_value instanceof AST_Function || - self.exported_value instanceof AST_Class) - || self.module_name - || self.exported_names - ) { - output.semicolon(); - } - }); - - function parenthesize_for_noin(node, output, noin) { - var parens = false; - // need to take some precautions here: - // https://github.com/mishoo/UglifyJS2/issues/60 - if (noin) { - parens = walk(node, node => { - if (node instanceof AST_Scope) return true; - if (node instanceof AST_Binary && node.operator == "in") { - return walk_abort; // makes walk() return true - } - }); - } - node.print(output, parens); - } - - DEFPRINT(AST_VarDef, function(self, output) { - self.name.print(output); - if (self.value) { - output.space(); - output.print("="); - output.space(); - var p = output.parent(1); - var noin = p instanceof AST_For || p instanceof AST_ForIn; - parenthesize_for_noin(self.value, output, noin); - } - }); - - /* -----[ other expressions ]----- */ - DEFPRINT(AST_Call, function(self, output) { - self.expression.print(output); - if (self instanceof AST_New && self.args.length === 0) - return; - if (self.expression instanceof AST_Call || self.expression instanceof AST_Lambda) { - output.add_mapping(self.start); - } - if (self.optional) output.print("?."); - output.with_parens(function() { - self.args.forEach(function(expr, i) { - if (i) output.comma(); - expr.print(output); - }); - }); - }); - DEFPRINT(AST_New, function(self, output) { - output.print("new"); - output.space(); - AST_Call.prototype._codegen(self, output); - }); - - AST_Sequence.DEFMETHOD("_do_print", function(output) { - this.expressions.forEach(function(node, index) { - if (index > 0) { - output.comma(); - if (output.should_break()) { - output.newline(); - output.indent(); - } - } - node.print(output); - }); - }); - DEFPRINT(AST_Sequence, function(self, output) { - self._do_print(output); - // var p = output.parent(); - // if (p instanceof AST_Statement) { - // output.with_indent(output.next_indent(), function(){ - // self._do_print(output); - // }); - // } else { - // self._do_print(output); - // } - }); - DEFPRINT(AST_Dot, function(self, output) { - var expr = self.expression; - expr.print(output); - var prop = self.property; - var print_computed = RESERVED_WORDS.has(prop) - ? output.option("ie8") - : !is_identifier_string( - prop, - output.option("ecma") >= 2015 || output.option("safari10") - ); - - if (self.optional) output.print("?."); - - if (print_computed) { - output.print("["); - output.add_mapping(self.end); - output.print_string(prop); - output.print("]"); - } else { - if (expr instanceof AST_Number && expr.getValue() >= 0) { - if (!/[xa-f.)]/i.test(output.last())) { - output.print("."); - } - } - if (!self.optional) output.print("."); - // the name after dot would be mapped about here. - output.add_mapping(self.end); - output.print_name(prop); - } - }); - DEFPRINT(AST_DotHash, function(self, output) { - var expr = self.expression; - expr.print(output); - var prop = self.property; - - if (self.optional) output.print("?"); - output.print(".#"); - output.print_name(prop); - }); - DEFPRINT(AST_Sub, function(self, output) { - self.expression.print(output); - if (self.optional) output.print("?."); - output.print("["); - self.property.print(output); - output.print("]"); - }); - DEFPRINT(AST_Chain, function(self, output) { - self.expression.print(output); - }); - DEFPRINT(AST_UnaryPrefix, function(self, output) { - var op = self.operator; - output.print(op); - if (/^[a-z]/i.test(op) - || (/[+-]$/.test(op) - && self.expression instanceof AST_UnaryPrefix - && /^[+-]/.test(self.expression.operator))) { - output.space(); - } - self.expression.print(output); - }); - DEFPRINT(AST_UnaryPostfix, function(self, output) { - self.expression.print(output); - output.print(self.operator); - }); - DEFPRINT(AST_Binary, function(self, output) { - var op = self.operator; - self.left.print(output); - if (op[0] == ">" /* ">>" ">>>" ">" ">=" */ - && self.left instanceof AST_UnaryPostfix - && self.left.operator == "--") { - // space is mandatory to avoid outputting --> - output.print(" "); - } else { - // the space is optional depending on "beautify" - output.space(); - } - output.print(op); - if ((op == "<" || op == "<<") - && self.right instanceof AST_UnaryPrefix - && self.right.operator == "!" - && self.right.expression instanceof AST_UnaryPrefix - && self.right.expression.operator == "--") { - // space is mandatory to avoid outputting x ? y : false - if (self.left.operator == "||") { - var lr = self.left.right.evaluate(compressor); - if (!lr) return make_node(AST_Conditional, self, { - condition: self.left.left, - consequent: self.right, - alternative: self.left.right - }).optimize(compressor); - } - break; - case "||": - var ll = has_flag(self.left, TRUTHY) - ? true - : has_flag(self.left, FALSY) - ? false - : self.left.evaluate(compressor); - if (!ll) { - return make_sequence(self, [ self.left, self.right ]).optimize(compressor); - } else if (!(ll instanceof AST_Node)) { - return maintain_this_binding(compressor.parent(), compressor.self(), self.left).optimize(compressor); - } - var rr = self.right.evaluate(compressor); - if (!rr) { - var parent = compressor.parent(); - if (parent.operator == "||" && parent.left === compressor.self() || compressor.in_boolean_context()) { - return self.left.optimize(compressor); - } - } else if (!(rr instanceof AST_Node)) { - if (compressor.in_boolean_context()) { - return make_sequence(self, [ - self.left, - make_node(AST_True, self) - ]).optimize(compressor); - } else { - set_flag(self, TRUTHY); - } - } - if (self.left.operator == "&&") { - var lr = self.left.right.evaluate(compressor); - if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self, { - condition: self.left.left, - consequent: self.left.right, - alternative: self.right - }).optimize(compressor); - } - break; - case "??": - if (is_nullish(self.left)) { - return self.right; - } - - var ll = self.left.evaluate(compressor); - if (!(ll instanceof AST_Node)) { - // if we know the value for sure we can simply compute right away. - return ll == null ? self.right : self.left; - } - - if (compressor.in_boolean_context()) { - const rr = self.right.evaluate(compressor); - if (!(rr instanceof AST_Node) && !rr) { - return self.left; - } - } - } - var associative = true; - switch (self.operator) { - case "+": - // (x + "foo") + "bar" => x + "foobar" - if (self.right instanceof AST_Constant - && self.left instanceof AST_Binary - && self.left.operator == "+" - && self.left.is_string(compressor)) { - var binary = make_node(AST_Binary, self, { - operator: "+", - left: self.left.right, - right: self.right, - }); - var r = binary.optimize(compressor); - if (binary !== r) { - self = make_node(AST_Binary, self, { - operator: "+", - left: self.left.left, - right: r - }); - } - } - // (x + "foo") + ("bar" + y) => (x + "foobar") + y - if (self.left instanceof AST_Binary - && self.left.operator == "+" - && self.left.is_string(compressor) - && self.right instanceof AST_Binary - && self.right.operator == "+" - && self.right.is_string(compressor)) { - var binary = make_node(AST_Binary, self, { - operator: "+", - left: self.left.right, - right: self.right.left, - }); - var m = binary.optimize(compressor); - if (binary !== m) { - self = make_node(AST_Binary, self, { - operator: "+", - left: make_node(AST_Binary, self.left, { - operator: "+", - left: self.left.left, - right: m - }), - right: self.right.right - }); - } - } - // a + -b => a - b - if (self.right instanceof AST_UnaryPrefix - && self.right.operator == "-" - && self.left.is_number(compressor)) { - self = make_node(AST_Binary, self, { - operator: "-", - left: self.left, - right: self.right.expression - }); - break; - } - // -a + b => b - a - if (self.left instanceof AST_UnaryPrefix - && self.left.operator == "-" - && reversible() - && self.right.is_number(compressor)) { - self = make_node(AST_Binary, self, { - operator: "-", - left: self.right, - right: self.left.expression - }); - break; - } - // `foo${bar}baz` + 1 => `foo${bar}baz1` - if (self.left instanceof AST_TemplateString) { - var l = self.left; - var r = self.right.evaluate(compressor); - if (r != self.right) { - l.segments[l.segments.length - 1].value += String(r); - return l; - } - } - // 1 + `foo${bar}baz` => `1foo${bar}baz` - if (self.right instanceof AST_TemplateString) { - var r = self.right; - var l = self.left.evaluate(compressor); - if (l != self.left) { - r.segments[0].value = String(l) + r.segments[0].value; - return r; - } - } - // `1${bar}2` + `foo${bar}baz` => `1${bar}2foo${bar}baz` - if (self.left instanceof AST_TemplateString - && self.right instanceof AST_TemplateString) { - var l = self.left; - var segments = l.segments; - var r = self.right; - segments[segments.length - 1].value += r.segments[0].value; - for (var i = 1; i < r.segments.length; i++) { - segments.push(r.segments[i]); - } - return l; - } - case "*": - associative = compressor.option("unsafe_math"); - case "&": - case "|": - case "^": - // a + +b => +b + a - if (self.left.is_number(compressor) - && self.right.is_number(compressor) - && reversible() - && !(self.left instanceof AST_Binary - && self.left.operator != self.operator - && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { - var reversed = make_node(AST_Binary, self, { - operator: self.operator, - left: self.right, - right: self.left - }); - if (self.right instanceof AST_Constant - && !(self.left instanceof AST_Constant)) { - self = best_of(compressor, reversed, self); - } else { - self = best_of(compressor, self, reversed); - } - } - if (associative && self.is_number(compressor)) { - // a + (b + c) => (a + b) + c - if (self.right instanceof AST_Binary - && self.right.operator == self.operator) { - self = make_node(AST_Binary, self, { - operator: self.operator, - left: make_node(AST_Binary, self.left, { - operator: self.operator, - left: self.left, - right: self.right.left, - start: self.left.start, - end: self.right.left.end - }), - right: self.right.right - }); - } - // (n + 2) + 3 => 5 + n - // (2 * n) * 3 => 6 + n - if (self.right instanceof AST_Constant - && self.left instanceof AST_Binary - && self.left.operator == self.operator) { - if (self.left.left instanceof AST_Constant) { - self = make_node(AST_Binary, self, { - operator: self.operator, - left: make_node(AST_Binary, self.left, { - operator: self.operator, - left: self.left.left, - right: self.right, - start: self.left.left.start, - end: self.right.end - }), - right: self.left.right - }); - } else if (self.left.right instanceof AST_Constant) { - self = make_node(AST_Binary, self, { - operator: self.operator, - left: make_node(AST_Binary, self.left, { - operator: self.operator, - left: self.left.right, - right: self.right, - start: self.left.right.start, - end: self.right.end - }), - right: self.left.left - }); - } - } - // (a | 1) | (2 | d) => (3 | a) | b - if (self.left instanceof AST_Binary - && self.left.operator == self.operator - && self.left.right instanceof AST_Constant - && self.right instanceof AST_Binary - && self.right.operator == self.operator - && self.right.left instanceof AST_Constant) { - self = make_node(AST_Binary, self, { - operator: self.operator, - left: make_node(AST_Binary, self.left, { - operator: self.operator, - left: make_node(AST_Binary, self.left.left, { - operator: self.operator, - left: self.left.right, - right: self.right.left, - start: self.left.right.start, - end: self.right.left.end - }), - right: self.left.left - }), - right: self.right.right - }); - } - } - } - } - // x && (y && z) ==> x && y && z - // x || (y || z) ==> x || y || z - // x + ("y" + z) ==> x + "y" + z - // "x" + (y + "z")==> "x" + y + "z" - if (self.right instanceof AST_Binary - && self.right.operator == self.operator - && (lazy_op.has(self.operator) - || (self.operator == "+" - && (self.right.left.is_string(compressor) - || (self.left.is_string(compressor) - && self.right.right.is_string(compressor))))) - ) { - self.left = make_node(AST_Binary, self.left, { - operator : self.operator, - left : self.left.transform(compressor), - right : self.right.left.transform(compressor) - }); - self.right = self.right.right.transform(compressor); - return self.transform(compressor); - } - var ev = self.evaluate(compressor); - if (ev !== self) { - ev = make_node_from_constant(ev, self).optimize(compressor); - return best_of(compressor, ev, self); - } - return self; -}); - -def_optimize(AST_SymbolExport, function(self) { - return self; -}); - -function recursive_ref(compressor, def) { - var node; - for (var i = 0; node = compressor.parent(i); i++) { - if ( - node instanceof AST_Lambda - || node instanceof AST_Class - ) { - var name = node.name; - if (name && name.definition() === def) break; - } - } - return node; -} - -function within_array_or_object_literal(compressor) { - var node, level = 0; - while (node = compressor.parent(level++)) { - if (node instanceof AST_Statement) return false; - if (node instanceof AST_Array - || node instanceof AST_ObjectKeyVal - || node instanceof AST_Object) { - return true; - } - } - return false; -} - -def_optimize(AST_SymbolRef, function(self, compressor) { - if ( - !compressor.option("ie8") - && is_undeclared_ref(self) - && !compressor.find_parent(AST_With) - ) { - switch (self.name) { - case "undefined": - return make_node(AST_Undefined, self).optimize(compressor); - case "NaN": - return make_node(AST_NaN, self).optimize(compressor); - case "Infinity": - return make_node(AST_Infinity, self).optimize(compressor); - } - } - - const parent = compressor.parent(); - if (compressor.option("reduce_vars") && is_lhs(self, parent) !== self) { - const def = self.definition(); - const nearest_scope = find_scope(compressor); - if (compressor.top_retain && def.global && compressor.top_retain(def)) { - def.fixed = false; - def.single_use = false; - return self; - } - - let fixed = self.fixed_value(); - let single_use = def.single_use - && !(parent instanceof AST_Call - && (parent.is_expr_pure(compressor)) - || has_annotation(parent, _NOINLINE)) - && !(parent instanceof AST_Export - && fixed instanceof AST_Lambda - && fixed.name); - - if (single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) { - if (retain_top_func(fixed, compressor)) { - single_use = false; - } else if (def.scope !== self.scope - && (def.escaped == 1 - || has_flag(fixed, INLINED) - || within_array_or_object_literal(compressor))) { - single_use = false; - } else if (recursive_ref(compressor, def)) { - single_use = false; - } else if (def.scope !== self.scope || def.orig[0] instanceof AST_SymbolFunarg) { - single_use = fixed.is_constant_expression(self.scope); - if (single_use == "f") { - var scope = self.scope; - do { - if (scope instanceof AST_Defun || is_func_expr(scope)) { - set_flag(scope, INLINED); - } - } while (scope = scope.parent_scope); - } - } - } - if (single_use && fixed instanceof AST_Lambda) { - single_use = - def.scope === self.scope - && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) - || parent instanceof AST_Call - && parent.expression === self - && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) - && !(fixed.name && fixed.name.definition().recursive_refs > 0); - } - if (single_use && fixed instanceof AST_Class) { - const extends_inert = !fixed.extends - || !fixed.extends.may_throw(compressor) - && !fixed.extends.has_side_effects(compressor); - single_use = extends_inert - && !fixed.properties.some(prop => - prop.may_throw(compressor) || prop.has_side_effects(compressor) - ); - } - - if (single_use && fixed) { - if (fixed instanceof AST_DefClass) { - set_flag(fixed, SQUEEZED); - fixed = make_node(AST_ClassExpression, fixed, fixed); - } - if (fixed instanceof AST_Defun) { - set_flag(fixed, SQUEEZED); - fixed = make_node(AST_Function, fixed, fixed); - } - if (def.recursive_refs > 0 && fixed.name instanceof AST_SymbolDefun) { - const defun_def = fixed.name.definition(); - let lambda_def = fixed.variables.get(fixed.name.name); - let name = lambda_def && lambda_def.orig[0]; - if (!(name instanceof AST_SymbolLambda)) { - name = make_node(AST_SymbolLambda, fixed.name, fixed.name); - name.scope = fixed; - fixed.name = name; - lambda_def = fixed.def_function(name); - } - walk(fixed, node => { - if (node instanceof AST_SymbolRef && node.definition() === defun_def) { - node.thedef = lambda_def; - lambda_def.references.push(node); - } - }); - } - if ( - (fixed instanceof AST_Lambda || fixed instanceof AST_Class) - && fixed.parent_scope !== nearest_scope - ) { - fixed = fixed.clone(true, compressor.get_toplevel()); - - nearest_scope.add_child_scope(fixed); - } - return fixed.optimize(compressor); - } - - // multiple uses - if (fixed) { - let replace; - - if (fixed instanceof AST_This) { - if (!(def.orig[0] instanceof AST_SymbolFunarg) - && def.references.every((ref) => - def.scope === ref.scope - )) { - replace = fixed; - } - } else { - var ev = fixed.evaluate(compressor); - if ( - ev !== fixed - && (compressor.option("unsafe_regexp") || !(ev instanceof RegExp)) - ) { - replace = make_node_from_constant(ev, fixed); - } - } - - if (replace) { - const name_length = self.size(compressor); - const replace_size = replace.size(compressor); - - let overhead = 0; - if (compressor.option("unused") && !compressor.exposed(def)) { - overhead = - (name_length + 2 + replace_size) / - (def.references.length - def.assignments); - } - - if (replace_size <= name_length + overhead) { - return replace; - } - } - } - } - return self; -}); - -function scope_encloses_variables_in_this_scope(scope, pulled_scope) { - for (const enclosed of pulled_scope.enclosed) { - if (pulled_scope.variables.has(enclosed.name)) { - continue; - } - const looked_up = scope.find_variable(enclosed.name); - if (looked_up) { - if (looked_up === enclosed) continue; - return true; - } - } - return false; -} - -function is_atomic(lhs, self) { - return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE; -} - -def_optimize(AST_Undefined, function(self, compressor) { - if (compressor.option("unsafe_undefined")) { - var undef = find_variable(compressor, "undefined"); - if (undef) { - var ref = make_node(AST_SymbolRef, self, { - name : "undefined", - scope : undef.scope, - thedef : undef - }); - set_flag(ref, UNDEFINED); - return ref; - } - } - var lhs = is_lhs(compressor.self(), compressor.parent()); - if (lhs && is_atomic(lhs, self)) return self; - return make_node(AST_UnaryPrefix, self, { - operator: "void", - expression: make_node(AST_Number, self, { - value: 0 - }) - }); -}); - -def_optimize(AST_Infinity, function(self, compressor) { - var lhs = is_lhs(compressor.self(), compressor.parent()); - if (lhs && is_atomic(lhs, self)) return self; - if ( - compressor.option("keep_infinity") - && !(lhs && !is_atomic(lhs, self)) - && !find_variable(compressor, "Infinity") - ) { - return self; - } - return make_node(AST_Binary, self, { - operator: "/", - left: make_node(AST_Number, self, { - value: 1 - }), - right: make_node(AST_Number, self, { - value: 0 - }) - }); -}); - -def_optimize(AST_NaN, function(self, compressor) { - var lhs = is_lhs(compressor.self(), compressor.parent()); - if (lhs && !is_atomic(lhs, self) - || find_variable(compressor, "NaN")) { - return make_node(AST_Binary, self, { - operator: "/", - left: make_node(AST_Number, self, { - value: 0 - }), - right: make_node(AST_Number, self, { - value: 0 - }) - }); - } - return self; -}); - -function is_reachable(self, defs) { - const find_ref = node => { - if (node instanceof AST_SymbolRef && member(node.definition(), defs)) { - return walk_abort; - } - }; - - return walk_parent(self, (node, info) => { - if (node instanceof AST_Scope && node !== self) { - var parent = info.parent(); - - if (parent instanceof AST_Call && parent.expression === node) return; - - if (walk(node, find_ref)) return walk_abort; - - return true; - } - }); -} - -const ASSIGN_OPS = makePredicate("+ - / * % >> << >>> | ^ &"); -const ASSIGN_OPS_COMMUTATIVE = makePredicate("* | ^ &"); -def_optimize(AST_Assign, function(self, compressor) { - if (self.logical) { - return self.lift_sequences(compressor); - } - - var def; - if (compressor.option("dead_code") - && self.left instanceof AST_SymbolRef - && (def = self.left.definition()).scope === compressor.find_parent(AST_Lambda)) { - var level = 0, node, parent = self; - do { - node = parent; - parent = compressor.parent(level++); - if (parent instanceof AST_Exit) { - if (in_try(level, parent)) break; - if (is_reachable(def.scope, [ def ])) break; - if (self.operator == "=") return self.right; - def.fixed = false; - return make_node(AST_Binary, self, { - operator: self.operator.slice(0, -1), - left: self.left, - right: self.right - }).optimize(compressor); - } - } while (parent instanceof AST_Binary && parent.right === node - || parent instanceof AST_Sequence && parent.tail_node() === node); - } - self = self.lift_sequences(compressor); - if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) { - // x = expr1 OP expr2 - if (self.right.left instanceof AST_SymbolRef - && self.right.left.name == self.left.name - && ASSIGN_OPS.has(self.right.operator)) { - // x = x - 2 ---> x -= 2 - self.operator = self.right.operator + "="; - self.right = self.right.right; - } else if (self.right.right instanceof AST_SymbolRef - && self.right.right.name == self.left.name - && ASSIGN_OPS_COMMUTATIVE.has(self.right.operator) - && !self.right.left.has_side_effects(compressor)) { - // x = 2 & x ---> x &= 2 - self.operator = self.right.operator + "="; - self.right = self.right.left; - } - } - return self; - - function in_try(level, node) { - var right = self.right; - self.right = make_node(AST_Null, right); - var may_throw = node.may_throw(compressor); - self.right = right; - var scope = self.left.definition().scope; - var parent; - while ((parent = compressor.parent(level++)) !== scope) { - if (parent instanceof AST_Try) { - if (parent.bfinally) return true; - if (may_throw && parent.bcatch) return true; - } - } - } -}); - -def_optimize(AST_DefaultAssign, function(self, compressor) { - if (!compressor.option("evaluate")) { - return self; - } - var evaluateRight = self.right.evaluate(compressor); - - // `[x = undefined] = foo` ---> `[x] = foo` - if (evaluateRight === undefined) { - self = self.left; - } else if (evaluateRight !== self.right) { - evaluateRight = make_node_from_constant(evaluateRight, self.right); - self.right = best_of_expression(evaluateRight, self.right); - } - - return self; -}); - -function is_nullish(node) { - let fixed; - return ( - node instanceof AST_Null - || is_undefined(node) - || ( - node instanceof AST_SymbolRef - && (fixed = node.definition().fixed) instanceof AST_Node - && is_nullish(fixed) - ) - // Recurse into those optional chains! - || node instanceof AST_PropAccess && node.optional && is_nullish(node.expression) - || node instanceof AST_Call && node.optional && is_nullish(node.expression) - || node instanceof AST_Chain && is_nullish(node.expression) - ); -} - -function is_nullish_check(check, check_subject, compressor) { - if (check_subject.may_throw(compressor)) return false; - - let nullish_side; - - // foo == null - if ( - check instanceof AST_Binary - && check.operator === "==" - // which side is nullish? - && ( - (nullish_side = is_nullish(check.left) && check.left) - || (nullish_side = is_nullish(check.right) && check.right) - ) - // is the other side the same as the check_subject - && ( - nullish_side === check.left - ? check.right - : check.left - ).equivalent_to(check_subject) - ) { - return true; - } - - // foo === null || foo === undefined - if (check instanceof AST_Binary && check.operator === "||") { - let null_cmp; - let undefined_cmp; - - const find_comparison = cmp => { - if (!( - cmp instanceof AST_Binary - && (cmp.operator === "===" || cmp.operator === "==") - )) { - return false; - } - - let found = 0; - let defined_side; - - if (cmp.left instanceof AST_Null) { - found++; - null_cmp = cmp; - defined_side = cmp.right; - } - if (cmp.right instanceof AST_Null) { - found++; - null_cmp = cmp; - defined_side = cmp.left; - } - if (is_undefined(cmp.left)) { - found++; - undefined_cmp = cmp; - defined_side = cmp.right; - } - if (is_undefined(cmp.right)) { - found++; - undefined_cmp = cmp; - defined_side = cmp.left; - } - - if (found !== 1) { - return false; - } - - if (!defined_side.equivalent_to(check_subject)) { - return false; - } - - return true; - }; - - if (!find_comparison(check.left)) return false; - if (!find_comparison(check.right)) return false; - - if (null_cmp && undefined_cmp && null_cmp !== undefined_cmp) { - return true; - } - } - - return false; -} - -def_optimize(AST_Conditional, function(self, compressor) { - if (!compressor.option("conditionals")) return self; - // This looks like lift_sequences(), should probably be under "sequences" - if (self.condition instanceof AST_Sequence) { - var expressions = self.condition.expressions.slice(); - self.condition = expressions.pop(); - expressions.push(self); - return make_sequence(self, expressions); - } - var cond = self.condition.evaluate(compressor); - if (cond !== self.condition) { - if (cond) { - return maintain_this_binding(compressor.parent(), compressor.self(), self.consequent); - } else { - return maintain_this_binding(compressor.parent(), compressor.self(), self.alternative); - } - } - var negated = cond.negate(compressor, first_in_statement(compressor)); - if (best_of(compressor, cond, negated) === negated) { - self = make_node(AST_Conditional, self, { - condition: negated, - consequent: self.alternative, - alternative: self.consequent - }); - } - var condition = self.condition; - var consequent = self.consequent; - var alternative = self.alternative; - // x?x:y --> x||y - if (condition instanceof AST_SymbolRef - && consequent instanceof AST_SymbolRef - && condition.definition() === consequent.definition()) { - return make_node(AST_Binary, self, { - operator: "||", - left: condition, - right: alternative - }); - } - // if (foo) exp = something; else exp = something_else; - // | - // v - // exp = foo ? something : something_else; - if ( - consequent instanceof AST_Assign - && alternative instanceof AST_Assign - && consequent.operator === alternative.operator - && consequent.logical === alternative.logical - && consequent.left.equivalent_to(alternative.left) - && (!self.condition.has_side_effects(compressor) - || consequent.operator == "=" - && !consequent.left.has_side_effects(compressor)) - ) { - return make_node(AST_Assign, self, { - operator: consequent.operator, - left: consequent.left, - logical: consequent.logical, - right: make_node(AST_Conditional, self, { - condition: self.condition, - consequent: consequent.right, - alternative: alternative.right - }) - }); - } - // x ? y(a) : y(b) --> y(x ? a : b) - var arg_index; - if (consequent instanceof AST_Call - && alternative.TYPE === consequent.TYPE - && consequent.args.length > 0 - && consequent.args.length == alternative.args.length - && consequent.expression.equivalent_to(alternative.expression) - && !self.condition.has_side_effects(compressor) - && !consequent.expression.has_side_effects(compressor) - && typeof (arg_index = single_arg_diff()) == "number") { - var node = consequent.clone(); - node.args[arg_index] = make_node(AST_Conditional, self, { - condition: self.condition, - consequent: consequent.args[arg_index], - alternative: alternative.args[arg_index] - }); - return node; - } - // a ? b : c ? b : d --> (a || c) ? b : d - if (alternative instanceof AST_Conditional - && consequent.equivalent_to(alternative.consequent)) { - return make_node(AST_Conditional, self, { - condition: make_node(AST_Binary, self, { - operator: "||", - left: condition, - right: alternative.condition - }), - consequent: consequent, - alternative: alternative.alternative - }).optimize(compressor); - } - - // a == null ? b : a -> a ?? b - if ( - compressor.option("ecma") >= 2020 && - is_nullish_check(condition, alternative, compressor) - ) { - return make_node(AST_Binary, self, { - operator: "??", - left: alternative, - right: consequent - }).optimize(compressor); - } - - // a ? b : (c, b) --> (a || c), b - if (alternative instanceof AST_Sequence - && consequent.equivalent_to(alternative.expressions[alternative.expressions.length - 1])) { - return make_sequence(self, [ - make_node(AST_Binary, self, { - operator: "||", - left: condition, - right: make_sequence(self, alternative.expressions.slice(0, -1)) - }), - consequent - ]).optimize(compressor); - } - // a ? b : (c && b) --> (a || c) && b - if (alternative instanceof AST_Binary - && alternative.operator == "&&" - && consequent.equivalent_to(alternative.right)) { - return make_node(AST_Binary, self, { - operator: "&&", - left: make_node(AST_Binary, self, { - operator: "||", - left: condition, - right: alternative.left - }), - right: consequent - }).optimize(compressor); - } - // x?y?z:a:a --> x&&y?z:a - if (consequent instanceof AST_Conditional - && consequent.alternative.equivalent_to(alternative)) { - return make_node(AST_Conditional, self, { - condition: make_node(AST_Binary, self, { - left: self.condition, - operator: "&&", - right: consequent.condition - }), - consequent: consequent.consequent, - alternative: alternative - }); - } - // x ? y : y --> x, y - if (consequent.equivalent_to(alternative)) { - return make_sequence(self, [ - self.condition, - consequent - ]).optimize(compressor); - } - // x ? y || z : z --> x && y || z - if (consequent instanceof AST_Binary - && consequent.operator == "||" - && consequent.right.equivalent_to(alternative)) { - return make_node(AST_Binary, self, { - operator: "||", - left: make_node(AST_Binary, self, { - operator: "&&", - left: self.condition, - right: consequent.left - }), - right: alternative - }).optimize(compressor); - } - var in_bool = compressor.in_boolean_context(); - if (is_true(self.consequent)) { - if (is_false(self.alternative)) { - // c ? true : false ---> !!c - return booleanize(self.condition); - } - // c ? true : x ---> !!c || x - return make_node(AST_Binary, self, { - operator: "||", - left: booleanize(self.condition), - right: self.alternative - }); - } - if (is_false(self.consequent)) { - if (is_true(self.alternative)) { - // c ? false : true ---> !c - return booleanize(self.condition.negate(compressor)); - } - // c ? false : x ---> !c && x - return make_node(AST_Binary, self, { - operator: "&&", - left: booleanize(self.condition.negate(compressor)), - right: self.alternative - }); - } - if (is_true(self.alternative)) { - // c ? x : true ---> !c || x - return make_node(AST_Binary, self, { - operator: "||", - left: booleanize(self.condition.negate(compressor)), - right: self.consequent - }); - } - if (is_false(self.alternative)) { - // c ? x : false ---> !!c && x - return make_node(AST_Binary, self, { - operator: "&&", - left: booleanize(self.condition), - right: self.consequent - }); - } - - return self; - - function booleanize(node) { - if (node.is_boolean()) return node; - // !!expression - return make_node(AST_UnaryPrefix, node, { - operator: "!", - expression: node.negate(compressor) - }); - } - - // AST_True or !0 - function is_true(node) { - return node instanceof AST_True - || in_bool - && node instanceof AST_Constant - && node.getValue() - || (node instanceof AST_UnaryPrefix - && node.operator == "!" - && node.expression instanceof AST_Constant - && !node.expression.getValue()); - } - // AST_False or !1 - function is_false(node) { - return node instanceof AST_False - || in_bool - && node instanceof AST_Constant - && !node.getValue() - || (node instanceof AST_UnaryPrefix - && node.operator == "!" - && node.expression instanceof AST_Constant - && node.expression.getValue()); - } - - function single_arg_diff() { - var a = consequent.args; - var b = alternative.args; - for (var i = 0, len = a.length; i < len; i++) { - if (a[i] instanceof AST_Expansion) return; - if (!a[i].equivalent_to(b[i])) { - if (b[i] instanceof AST_Expansion) return; - for (var j = i + 1; j < len; j++) { - if (a[j] instanceof AST_Expansion) return; - if (!a[j].equivalent_to(b[j])) return; - } - return i; - } - } - } -}); - -def_optimize(AST_Boolean, function(self, compressor) { - if (compressor.in_boolean_context()) return make_node(AST_Number, self, { - value: +self.value - }); - var p = compressor.parent(); - if (compressor.option("booleans_as_integers")) { - if (p instanceof AST_Binary && (p.operator == "===" || p.operator == "!==")) { - p.operator = p.operator.replace(/=$/, ""); - } - return make_node(AST_Number, self, { - value: +self.value - }); - } - if (compressor.option("booleans")) { - if (p instanceof AST_Binary && (p.operator == "==" - || p.operator == "!=")) { - return make_node(AST_Number, self, { - value: +self.value - }); - } - return make_node(AST_UnaryPrefix, self, { - operator: "!", - expression: make_node(AST_Number, self, { - value: 1 - self.value - }) - }); - } - return self; -}); - -function safe_to_flatten(value, compressor) { - if (value instanceof AST_SymbolRef) { - value = value.fixed_value(); - } - if (!value) return false; - if (!(value instanceof AST_Lambda || value instanceof AST_Class)) return true; - if (!(value instanceof AST_Lambda && value.contains_this())) return true; - return compressor.parent() instanceof AST_New; -} - -AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) { - if (!compressor.option("properties")) return; - var arrows = compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015; - var expr = this.expression; - if (expr instanceof AST_Object) { - var props = expr.properties; - for (var i = props.length; --i >= 0;) { - var prop = props[i]; - if ("" + (prop instanceof AST_ConciseMethod ? prop.key.name : prop.key) == key) { - if (!props.every((prop) => { - return prop instanceof AST_ObjectKeyVal - || arrows && prop instanceof AST_ConciseMethod && !prop.is_generator; - })) break; - if (!safe_to_flatten(prop.value, compressor)) break; - return make_node(AST_Sub, this, { - expression: make_node(AST_Array, expr, { - elements: props.map(function(prop) { - var v = prop.value; - if (v instanceof AST_Accessor) v = make_node(AST_Function, v, v); - var k = prop.key; - if (k instanceof AST_Node && !(k instanceof AST_SymbolMethod)) { - return make_sequence(prop, [ k, v ]); - } - return v; - }) - }), - property: make_node(AST_Number, this, { - value: i - }) - }); - } - } - } -}); - -def_optimize(AST_Sub, function(self, compressor) { - var expr = self.expression; - var prop = self.property; - if (compressor.option("properties")) { - var key = prop.evaluate(compressor); - if (key !== prop) { - if (typeof key == "string") { - if (key == "undefined") { - key = undefined; - } else { - var value = parseFloat(key); - if (value.toString() == key) { - key = value; - } - } - } - prop = self.property = best_of_expression(prop, make_node_from_constant(key, prop).transform(compressor)); - var property = "" + key; - if (is_basic_identifier_string(property) - && property.length <= prop.size() + 1) { - return make_node(AST_Dot, self, { - expression: expr, - optional: self.optional, - property: property, - quote: prop.quote, - }).optimize(compressor); - } - } - } - var fn; - OPT_ARGUMENTS: if (compressor.option("arguments") - && expr instanceof AST_SymbolRef - && expr.name == "arguments" - && expr.definition().orig.length == 1 - && (fn = expr.scope) instanceof AST_Lambda - && fn.uses_arguments - && !(fn instanceof AST_Arrow) - && prop instanceof AST_Number) { - var index = prop.getValue(); - var params = new Set(); - var argnames = fn.argnames; - for (var n = 0; n < argnames.length; n++) { - if (!(argnames[n] instanceof AST_SymbolFunarg)) { - break OPT_ARGUMENTS; // destructuring parameter - bail - } - var param = argnames[n].name; - if (params.has(param)) { - break OPT_ARGUMENTS; // duplicate parameter - bail - } - params.add(param); - } - var argname = fn.argnames[index]; - if (argname && compressor.has_directive("use strict")) { - var def = argname.definition(); - if (!compressor.option("reduce_vars") || def.assignments || def.orig.length > 1) { - argname = null; - } - } else if (!argname && !compressor.option("keep_fargs") && index < fn.argnames.length + 5) { - while (index >= fn.argnames.length) { - argname = fn.create_symbol(AST_SymbolFunarg, { - source: fn, - scope: fn, - tentative_name: "argument_" + fn.argnames.length, - }); - fn.argnames.push(argname); - } - } - if (argname) { - var sym = make_node(AST_SymbolRef, self, argname); - sym.reference({}); - clear_flag(argname, UNUSED); - return sym; - } - } - if (is_lhs(self, compressor.parent())) return self; - if (key !== prop) { - var sub = self.flatten_object(property, compressor); - if (sub) { - expr = self.expression = sub.expression; - prop = self.property = sub.property; - } - } - if (compressor.option("properties") && compressor.option("side_effects") - && prop instanceof AST_Number && expr instanceof AST_Array) { - var index = prop.getValue(); - var elements = expr.elements; - var retValue = elements[index]; - FLATTEN: if (safe_to_flatten(retValue, compressor)) { - var flatten = true; - var values = []; - for (var i = elements.length; --i > index;) { - var value = elements[i].drop_side_effect_free(compressor); - if (value) { - values.unshift(value); - if (flatten && value.has_side_effects(compressor)) flatten = false; - } - } - if (retValue instanceof AST_Expansion) break FLATTEN; - retValue = retValue instanceof AST_Hole ? make_node(AST_Undefined, retValue) : retValue; - if (!flatten) values.unshift(retValue); - while (--i >= 0) { - var value = elements[i]; - if (value instanceof AST_Expansion) break FLATTEN; - value = value.drop_side_effect_free(compressor); - if (value) values.unshift(value); - else index--; - } - if (flatten) { - values.push(retValue); - return make_sequence(self, values).optimize(compressor); - } else return make_node(AST_Sub, self, { - expression: make_node(AST_Array, expr, { - elements: values - }), - property: make_node(AST_Number, prop, { - value: index - }) - }); - } - } - var ev = self.evaluate(compressor); - if (ev !== self) { - ev = make_node_from_constant(ev, self).optimize(compressor); - return best_of(compressor, ev, self); - } - if (self.optional && is_nullish(self.expression)) { - return make_node(AST_Undefined, self); - } - return self; -}); - -def_optimize(AST_Chain, function (self, compressor) { - self.expression = self.expression.optimize(compressor); - return self; -}); - -AST_Lambda.DEFMETHOD("contains_this", function() { - return walk(this, node => { - if (node instanceof AST_This) return walk_abort; - if ( - node !== this - && node instanceof AST_Scope - && !(node instanceof AST_Arrow) - ) { - return true; - } - }); -}); - -def_optimize(AST_Dot, function(self, compressor) { - const parent = compressor.parent(); - if (is_lhs(self, parent)) return self; - if (compressor.option("unsafe_proto") - && self.expression instanceof AST_Dot - && self.expression.property == "prototype") { - var exp = self.expression.expression; - if (is_undeclared_ref(exp)) switch (exp.name) { - case "Array": - self.expression = make_node(AST_Array, self.expression, { - elements: [] - }); - break; - case "Function": - self.expression = make_node(AST_Function, self.expression, { - argnames: [], - body: [] - }); - break; - case "Number": - self.expression = make_node(AST_Number, self.expression, { - value: 0 - }); - break; - case "Object": - self.expression = make_node(AST_Object, self.expression, { - properties: [] - }); - break; - case "RegExp": - self.expression = make_node(AST_RegExp, self.expression, { - value: { source: "t", flags: "" } - }); - break; - case "String": - self.expression = make_node(AST_String, self.expression, { - value: "" - }); - break; - } - } - if (!(parent instanceof AST_Call) || !has_annotation(parent, _NOINLINE)) { - const sub = self.flatten_object(self.property, compressor); - if (sub) return sub.optimize(compressor); - } - let ev = self.evaluate(compressor); - if (ev !== self) { - ev = make_node_from_constant(ev, self).optimize(compressor); - return best_of(compressor, ev, self); - } - if (self.optional && is_nullish(self.expression)) { - return make_node(AST_Undefined, self); - } - return self; -}); - -function literals_in_boolean_context(self, compressor) { - if (compressor.in_boolean_context()) { - return best_of(compressor, self, make_sequence(self, [ - self, - make_node(AST_True, self) - ]).optimize(compressor)); - } - return self; -} - -function inline_array_like_spread(elements) { - for (var i = 0; i < elements.length; i++) { - var el = elements[i]; - if (el instanceof AST_Expansion) { - var expr = el.expression; - if ( - expr instanceof AST_Array - && !expr.elements.some(elm => elm instanceof AST_Hole) - ) { - elements.splice(i, 1, ...expr.elements); - // Step back one, as the element at i is now new. - i--; - } - // In array-like spread, spreading a non-iterable value is TypeError. - // We therefore can’t optimize anything else, unlike with object spread. - } - } -} - -def_optimize(AST_Array, function(self, compressor) { - var optimized = literals_in_boolean_context(self, compressor); - if (optimized !== self) { - return optimized; - } - inline_array_like_spread(self.elements); - return self; -}); - -function inline_object_prop_spread(props) { - for (var i = 0; i < props.length; i++) { - var prop = props[i]; - if (prop instanceof AST_Expansion) { - const expr = prop.expression; - if ( - expr instanceof AST_Object - && expr.properties.every(prop => prop instanceof AST_ObjectKeyVal) - ) { - props.splice(i, 1, ...expr.properties); - // Step back one, as the property at i is now new. - i--; - } else if (expr instanceof AST_Constant - && !(expr instanceof AST_String)) { - // Unlike array-like spread, in object spread, spreading a - // non-iterable value silently does nothing; it is thus safe - // to remove. AST_String is the only iterable AST_Constant. - props.splice(i, 1); - } - } - } -} - -def_optimize(AST_Object, function(self, compressor) { - var optimized = literals_in_boolean_context(self, compressor); - if (optimized !== self) { - return optimized; - } - inline_object_prop_spread(self.properties); - return self; -}); - -def_optimize(AST_RegExp, literals_in_boolean_context); - -def_optimize(AST_Return, function(self, compressor) { - if (self.value && is_undefined(self.value, compressor)) { - self.value = null; - } - return self; -}); - -def_optimize(AST_Arrow, opt_AST_Lambda); - -def_optimize(AST_Function, function(self, compressor) { - self = opt_AST_Lambda(self, compressor); - if (compressor.option("unsafe_arrows") - && compressor.option("ecma") >= 2015 - && !self.name - && !self.is_generator - && !self.uses_arguments - && !self.pinned()) { - const uses_this = walk(self, node => { - if (node instanceof AST_This) return walk_abort; - }); - if (!uses_this) return make_node(AST_Arrow, self, self).optimize(compressor); - } - return self; -}); - -def_optimize(AST_Class, function(self) { - // HACK to avoid compress failure. - // AST_Class is not really an AST_Scope/AST_Block as it lacks a body. - return self; -}); - -def_optimize(AST_Yield, function(self, compressor) { - if (self.expression && !self.is_star && is_undefined(self.expression, compressor)) { - self.expression = null; - } - return self; -}); - -def_optimize(AST_TemplateString, function(self, compressor) { - if ( - !compressor.option("evaluate") - || compressor.parent() instanceof AST_PrefixedTemplateString - ) { - return self; - } - - var segments = []; - for (var i = 0; i < self.segments.length; i++) { - var segment = self.segments[i]; - if (segment instanceof AST_Node) { - var result = segment.evaluate(compressor); - // Evaluate to constant value - // Constant value shorter than ${segment} - if (result !== segment && (result + "").length <= segment.size() + "${}".length) { - // There should always be a previous and next segment if segment is a node - segments[segments.length - 1].value = segments[segments.length - 1].value + result + self.segments[++i].value; - continue; - } - // `before ${`innerBefore ${any} innerAfter`} after` => `before innerBefore ${any} innerAfter after` - // TODO: - // `before ${'test' + foo} after` => `before innerBefore ${any} innerAfter after` - // `before ${foo + 'test} after` => `before innerBefore ${any} innerAfter after` - if (segment instanceof AST_TemplateString) { - var inners = segment.segments; - segments[segments.length - 1].value += inners[0].value; - for (var j = 1; j < inners.length; j++) { - segment = inners[j]; - segments.push(segment); - } - continue; - } - } - segments.push(segment); - } - self.segments = segments; - - // `foo` => "foo" - if (segments.length == 1) { - return make_node(AST_String, self, segments[0]); - } - - if ( - segments.length === 3 - && segments[1] instanceof AST_Node - && ( - segments[1].is_string(compressor) - || segments[1].is_number(compressor) - || is_nullish(segments[1]) - || compressor.option("unsafe") - ) - ) { - // `foo${bar}` => "foo" + bar - if (segments[2].value === "") { - return make_node(AST_Binary, self, { - operator: "+", - left: make_node(AST_String, self, { - value: segments[0].value, - }), - right: segments[1], - }); - } - // `${bar}baz` => bar + "baz" - if (segments[0].value === "") { - return make_node(AST_Binary, self, { - operator: "+", - left: segments[1], - right: make_node(AST_String, self, { - value: segments[2].value, - }), - }); - } - } - return self; -}); - -def_optimize(AST_PrefixedTemplateString, function(self) { - return self; -}); - -// ["p"]:1 ---> p:1 -// [42]:1 ---> 42:1 -function lift_key(self, compressor) { - if (!compressor.option("computed_props")) return self; - // save a comparison in the typical case - if (!(self.key instanceof AST_Constant)) return self; - // allow certain acceptable props as not all AST_Constants are true constants - if (self.key instanceof AST_String || self.key instanceof AST_Number) { - if (self.key.value === "__proto__") return self; - if (self.key.value == "constructor" - && compressor.parent() instanceof AST_Class) return self; - if (self instanceof AST_ObjectKeyVal) { - self.key = self.key.value; - } else if (self instanceof AST_ClassProperty) { - self.key = make_node(AST_SymbolClassProperty, self.key, { - name: self.key.value - }); - } else { - self.key = make_node(AST_SymbolMethod, self.key, { - name: self.key.value - }); - } - } - return self; -} - -def_optimize(AST_ObjectProperty, lift_key); - -def_optimize(AST_ConciseMethod, function(self, compressor) { - lift_key(self, compressor); - // p(){return x;} ---> p:()=>x - if (compressor.option("arrows") - && compressor.parent() instanceof AST_Object - && !self.is_generator - && !self.value.uses_arguments - && !self.value.pinned() - && self.value.body.length == 1 - && self.value.body[0] instanceof AST_Return - && self.value.body[0].value - && !self.value.contains_this()) { - var arrow = make_node(AST_Arrow, self.value, self.value); - arrow.async = self.async; - arrow.is_generator = self.is_generator; - return make_node(AST_ObjectKeyVal, self, { - key: self.key instanceof AST_SymbolMethod ? self.key.name : self.key, - value: arrow, - quote: self.quote, - }); - } - return self; -}); - -def_optimize(AST_ObjectKeyVal, function(self, compressor) { - lift_key(self, compressor); - // p:function(){} ---> p(){} - // p:function*(){} ---> *p(){} - // p:async function(){} ---> async p(){} - // p:()=>{} ---> p(){} - // p:async()=>{} ---> async p(){} - var unsafe_methods = compressor.option("unsafe_methods"); - if (unsafe_methods - && compressor.option("ecma") >= 2015 - && (!(unsafe_methods instanceof RegExp) || unsafe_methods.test(self.key + ""))) { - var key = self.key; - var value = self.value; - var is_arrow_with_block = value instanceof AST_Arrow - && Array.isArray(value.body) - && !value.contains_this(); - if ((is_arrow_with_block || value instanceof AST_Function) && !value.name) { - return make_node(AST_ConciseMethod, self, { - async: value.async, - is_generator: value.is_generator, - key: key instanceof AST_Node ? key : make_node(AST_SymbolMethod, self, { - name: key, - }), - value: make_node(AST_Accessor, value, value), - quote: self.quote, - }); - } - } - return self; -}); - -def_optimize(AST_Destructuring, function(self, compressor) { - if (compressor.option("pure_getters") == true - && compressor.option("unused") - && !self.is_array - && Array.isArray(self.names) - && !is_destructuring_export_decl(compressor) - && !(self.names[self.names.length - 1] instanceof AST_Expansion)) { - var keep = []; - for (var i = 0; i < self.names.length; i++) { - var elem = self.names[i]; - if (!(elem instanceof AST_ObjectKeyVal - && typeof elem.key == "string" - && elem.value instanceof AST_SymbolDeclaration - && !should_retain(compressor, elem.value.definition()))) { - keep.push(elem); - } - } - if (keep.length != self.names.length) { - self.names = keep; - } - } - return self; - - function is_destructuring_export_decl(compressor) { - var ancestors = [/^VarDef$/, /^(Const|Let|Var)$/, /^Export$/]; - for (var a = 0, p = 0, len = ancestors.length; a < len; p++) { - var parent = compressor.parent(p); - if (!parent) return false; - if (a === 0 && parent.TYPE == "Destructuring") continue; - if (!ancestors[a].test(parent.TYPE)) { - return false; - } - a++; - } - return true; - } - - function should_retain(compressor, def) { - if (def.references.length) return true; - if (!def.global) return false; - if (compressor.toplevel.vars) { - if (compressor.top_retain) { - return compressor.top_retain(def); - } - return false; - } - return true; - } -}); - -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -// 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__default['default'].SourceMapGenerator({ - file : options.file, - sourceRoot : options.root - }); - - if (options.orig) { - orig_map = await new MOZ_SourceMap__default['default'].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(); - } - } - }; -} - -var domprops = [ - "$&", - "$'", - "$*", - "$+", - "$1", - "$2", - "$3", - "$4", - "$5", - "$6", - "$7", - "$8", - "$9", - "$_", - "$`", - "$input", - "-moz-animation", - "-moz-animation-delay", - "-moz-animation-direction", - "-moz-animation-duration", - "-moz-animation-fill-mode", - "-moz-animation-iteration-count", - "-moz-animation-name", - "-moz-animation-play-state", - "-moz-animation-timing-function", - "-moz-appearance", - "-moz-backface-visibility", - "-moz-border-end", - "-moz-border-end-color", - "-moz-border-end-style", - "-moz-border-end-width", - "-moz-border-image", - "-moz-border-start", - "-moz-border-start-color", - "-moz-border-start-style", - "-moz-border-start-width", - "-moz-box-align", - "-moz-box-direction", - "-moz-box-flex", - "-moz-box-ordinal-group", - "-moz-box-orient", - "-moz-box-pack", - "-moz-box-sizing", - "-moz-float-edge", - "-moz-font-feature-settings", - "-moz-font-language-override", - "-moz-force-broken-image-icon", - "-moz-hyphens", - "-moz-image-region", - "-moz-margin-end", - "-moz-margin-start", - "-moz-orient", - "-moz-osx-font-smoothing", - "-moz-outline-radius", - "-moz-outline-radius-bottomleft", - "-moz-outline-radius-bottomright", - "-moz-outline-radius-topleft", - "-moz-outline-radius-topright", - "-moz-padding-end", - "-moz-padding-start", - "-moz-perspective", - "-moz-perspective-origin", - "-moz-tab-size", - "-moz-text-size-adjust", - "-moz-transform", - "-moz-transform-origin", - "-moz-transform-style", - "-moz-transition", - "-moz-transition-delay", - "-moz-transition-duration", - "-moz-transition-property", - "-moz-transition-timing-function", - "-moz-user-focus", - "-moz-user-input", - "-moz-user-modify", - "-moz-user-select", - "-moz-window-dragging", - "-webkit-align-content", - "-webkit-align-items", - "-webkit-align-self", - "-webkit-animation", - "-webkit-animation-delay", - "-webkit-animation-direction", - "-webkit-animation-duration", - "-webkit-animation-fill-mode", - "-webkit-animation-iteration-count", - "-webkit-animation-name", - "-webkit-animation-play-state", - "-webkit-animation-timing-function", - "-webkit-appearance", - "-webkit-backface-visibility", - "-webkit-background-clip", - "-webkit-background-origin", - "-webkit-background-size", - "-webkit-border-bottom-left-radius", - "-webkit-border-bottom-right-radius", - "-webkit-border-image", - "-webkit-border-radius", - "-webkit-border-top-left-radius", - "-webkit-border-top-right-radius", - "-webkit-box-align", - "-webkit-box-direction", - "-webkit-box-flex", - "-webkit-box-ordinal-group", - "-webkit-box-orient", - "-webkit-box-pack", - "-webkit-box-shadow", - "-webkit-box-sizing", - "-webkit-filter", - "-webkit-flex", - "-webkit-flex-basis", - "-webkit-flex-direction", - "-webkit-flex-flow", - "-webkit-flex-grow", - "-webkit-flex-shrink", - "-webkit-flex-wrap", - "-webkit-justify-content", - "-webkit-line-clamp", - "-webkit-mask", - "-webkit-mask-clip", - "-webkit-mask-composite", - "-webkit-mask-image", - "-webkit-mask-origin", - "-webkit-mask-position", - "-webkit-mask-position-x", - "-webkit-mask-position-y", - "-webkit-mask-repeat", - "-webkit-mask-size", - "-webkit-order", - "-webkit-perspective", - "-webkit-perspective-origin", - "-webkit-text-fill-color", - "-webkit-text-size-adjust", - "-webkit-text-stroke", - "-webkit-text-stroke-color", - "-webkit-text-stroke-width", - "-webkit-transform", - "-webkit-transform-origin", - "-webkit-transform-style", - "-webkit-transition", - "-webkit-transition-delay", - "-webkit-transition-duration", - "-webkit-transition-property", - "-webkit-transition-timing-function", - "-webkit-user-select", - "0", - "1", - "10", - "11", - "12", - "13", - "14", - "15", - "16", - "17", - "18", - "19", - "2", - "20", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - "@@iterator", - "ABORT_ERR", - "ACTIVE", - "ACTIVE_ATTRIBUTES", - "ACTIVE_TEXTURE", - "ACTIVE_UNIFORMS", - "ACTIVE_UNIFORM_BLOCKS", - "ADDITION", - "ALIASED_LINE_WIDTH_RANGE", - "ALIASED_POINT_SIZE_RANGE", - "ALLOW_KEYBOARD_INPUT", - "ALLPASS", - "ALPHA", - "ALPHA_BITS", - "ALREADY_SIGNALED", - "ALT_MASK", - "ALWAYS", - "ANY_SAMPLES_PASSED", - "ANY_SAMPLES_PASSED_CONSERVATIVE", - "ANY_TYPE", - "ANY_UNORDERED_NODE_TYPE", - "ARRAY_BUFFER", - "ARRAY_BUFFER_BINDING", - "ATTACHED_SHADERS", - "ATTRIBUTE_NODE", - "AT_TARGET", - "AbortController", - "AbortSignal", - "AbsoluteOrientationSensor", - "AbstractRange", - "Accelerometer", - "AddSearchProvider", - "AggregateError", - "AnalyserNode", - "Animation", - "AnimationEffect", - "AnimationEvent", - "AnimationPlaybackEvent", - "AnimationTimeline", - "AnonXMLHttpRequest", - "Any", - "ApplicationCache", - "ApplicationCacheErrorEvent", - "Array", - "ArrayBuffer", - "ArrayType", - "Atomics", - "Attr", - "Audio", - "AudioBuffer", - "AudioBufferSourceNode", - "AudioContext", - "AudioDestinationNode", - "AudioListener", - "AudioNode", - "AudioParam", - "AudioParamMap", - "AudioProcessingEvent", - "AudioScheduledSourceNode", - "AudioStreamTrack", - "AudioWorklet", - "AudioWorkletNode", - "AuthenticatorAssertionResponse", - "AuthenticatorAttestationResponse", - "AuthenticatorResponse", - "AutocompleteErrorEvent", - "BACK", - "BAD_BOUNDARYPOINTS_ERR", - "BAD_REQUEST", - "BANDPASS", - "BLEND", - "BLEND_COLOR", - "BLEND_DST_ALPHA", - "BLEND_DST_RGB", - "BLEND_EQUATION", - "BLEND_EQUATION_ALPHA", - "BLEND_EQUATION_RGB", - "BLEND_SRC_ALPHA", - "BLEND_SRC_RGB", - "BLUE_BITS", - "BLUR", - "BOOL", - "BOOLEAN_TYPE", - "BOOL_VEC2", - "BOOL_VEC3", - "BOOL_VEC4", - "BOTH", - "BROWSER_DEFAULT_WEBGL", - "BUBBLING_PHASE", - "BUFFER_SIZE", - "BUFFER_USAGE", - "BYTE", - "BYTES_PER_ELEMENT", - "BackgroundFetchManager", - "BackgroundFetchRecord", - "BackgroundFetchRegistration", - "BarProp", - "BarcodeDetector", - "BaseAudioContext", - "BaseHref", - "BatteryManager", - "BeforeInstallPromptEvent", - "BeforeLoadEvent", - "BeforeUnloadEvent", - "BigInt", - "BigInt64Array", - "BigUint64Array", - "BiquadFilterNode", - "Blob", - "BlobEvent", - "Bluetooth", - "BluetoothCharacteristicProperties", - "BluetoothDevice", - "BluetoothRemoteGATTCharacteristic", - "BluetoothRemoteGATTDescriptor", - "BluetoothRemoteGATTServer", - "BluetoothRemoteGATTService", - "BluetoothUUID", - "Boolean", - "BroadcastChannel", - "ByteLengthQueuingStrategy", - "CAPTURING_PHASE", - "CCW", - "CDATASection", - "CDATA_SECTION_NODE", - "CHANGE", - "CHARSET_RULE", - "CHECKING", - "CLAMP_TO_EDGE", - "CLICK", - "CLOSED", - "CLOSING", - "COLOR", - "COLOR_ATTACHMENT0", - "COLOR_ATTACHMENT1", - "COLOR_ATTACHMENT10", - "COLOR_ATTACHMENT11", - "COLOR_ATTACHMENT12", - "COLOR_ATTACHMENT13", - "COLOR_ATTACHMENT14", - "COLOR_ATTACHMENT15", - "COLOR_ATTACHMENT2", - "COLOR_ATTACHMENT3", - "COLOR_ATTACHMENT4", - "COLOR_ATTACHMENT5", - "COLOR_ATTACHMENT6", - "COLOR_ATTACHMENT7", - "COLOR_ATTACHMENT8", - "COLOR_ATTACHMENT9", - "COLOR_BUFFER_BIT", - "COLOR_CLEAR_VALUE", - "COLOR_WRITEMASK", - "COMMENT_NODE", - "COMPARE_REF_TO_TEXTURE", - "COMPILE_STATUS", - "COMPRESSED_RGBA_S3TC_DXT1_EXT", - "COMPRESSED_RGBA_S3TC_DXT3_EXT", - "COMPRESSED_RGBA_S3TC_DXT5_EXT", - "COMPRESSED_RGB_S3TC_DXT1_EXT", - "COMPRESSED_TEXTURE_FORMATS", - "CONDITION_SATISFIED", - "CONFIGURATION_UNSUPPORTED", - "CONNECTING", - "CONSTANT_ALPHA", - "CONSTANT_COLOR", - "CONSTRAINT_ERR", - "CONTEXT_LOST_WEBGL", - "CONTROL_MASK", - "COPY_READ_BUFFER", - "COPY_READ_BUFFER_BINDING", - "COPY_WRITE_BUFFER", - "COPY_WRITE_BUFFER_BINDING", - "COUNTER_STYLE_RULE", - "CSS", - "CSS2Properties", - "CSSAnimation", - "CSSCharsetRule", - "CSSConditionRule", - "CSSCounterStyleRule", - "CSSFontFaceRule", - "CSSFontFeatureValuesRule", - "CSSGroupingRule", - "CSSImageValue", - "CSSImportRule", - "CSSKeyframeRule", - "CSSKeyframesRule", - "CSSKeywordValue", - "CSSMathInvert", - "CSSMathMax", - "CSSMathMin", - "CSSMathNegate", - "CSSMathProduct", - "CSSMathSum", - "CSSMathValue", - "CSSMatrixComponent", - "CSSMediaRule", - "CSSMozDocumentRule", - "CSSNameSpaceRule", - "CSSNamespaceRule", - "CSSNumericArray", - "CSSNumericValue", - "CSSPageRule", - "CSSPerspective", - "CSSPositionValue", - "CSSPrimitiveValue", - "CSSRotate", - "CSSRule", - "CSSRuleList", - "CSSScale", - "CSSSkew", - "CSSSkewX", - "CSSSkewY", - "CSSStyleDeclaration", - "CSSStyleRule", - "CSSStyleSheet", - "CSSStyleValue", - "CSSSupportsRule", - "CSSTransformComponent", - "CSSTransformValue", - "CSSTransition", - "CSSTranslate", - "CSSUnitValue", - "CSSUnknownRule", - "CSSUnparsedValue", - "CSSValue", - "CSSValueList", - "CSSVariableReferenceValue", - "CSSVariablesDeclaration", - "CSSVariablesRule", - "CSSViewportRule", - "CSS_ATTR", - "CSS_CM", - "CSS_COUNTER", - "CSS_CUSTOM", - "CSS_DEG", - "CSS_DIMENSION", - "CSS_EMS", - "CSS_EXS", - "CSS_FILTER_BLUR", - "CSS_FILTER_BRIGHTNESS", - "CSS_FILTER_CONTRAST", - "CSS_FILTER_CUSTOM", - "CSS_FILTER_DROP_SHADOW", - "CSS_FILTER_GRAYSCALE", - "CSS_FILTER_HUE_ROTATE", - "CSS_FILTER_INVERT", - "CSS_FILTER_OPACITY", - "CSS_FILTER_REFERENCE", - "CSS_FILTER_SATURATE", - "CSS_FILTER_SEPIA", - "CSS_GRAD", - "CSS_HZ", - "CSS_IDENT", - "CSS_IN", - "CSS_INHERIT", - "CSS_KHZ", - "CSS_MATRIX", - "CSS_MATRIX3D", - "CSS_MM", - "CSS_MS", - "CSS_NUMBER", - "CSS_PC", - "CSS_PERCENTAGE", - "CSS_PERSPECTIVE", - "CSS_PRIMITIVE_VALUE", - "CSS_PT", - "CSS_PX", - "CSS_RAD", - "CSS_RECT", - "CSS_RGBCOLOR", - "CSS_ROTATE", - "CSS_ROTATE3D", - "CSS_ROTATEX", - "CSS_ROTATEY", - "CSS_ROTATEZ", - "CSS_S", - "CSS_SCALE", - "CSS_SCALE3D", - "CSS_SCALEX", - "CSS_SCALEY", - "CSS_SCALEZ", - "CSS_SKEW", - "CSS_SKEWX", - "CSS_SKEWY", - "CSS_STRING", - "CSS_TRANSLATE", - "CSS_TRANSLATE3D", - "CSS_TRANSLATEX", - "CSS_TRANSLATEY", - "CSS_TRANSLATEZ", - "CSS_UNKNOWN", - "CSS_URI", - "CSS_VALUE_LIST", - "CSS_VH", - "CSS_VMAX", - "CSS_VMIN", - "CSS_VW", - "CULL_FACE", - "CULL_FACE_MODE", - "CURRENT_PROGRAM", - "CURRENT_QUERY", - "CURRENT_VERTEX_ATTRIB", - "CUSTOM", - "CW", - "Cache", - "CacheStorage", - "CanvasCaptureMediaStream", - "CanvasCaptureMediaStreamTrack", - "CanvasGradient", - "CanvasPattern", - "CanvasRenderingContext2D", - "CaretPosition", - "ChannelMergerNode", - "ChannelSplitterNode", - "CharacterData", - "ClientRect", - "ClientRectList", - "Clipboard", - "ClipboardEvent", - "ClipboardItem", - "CloseEvent", - "Collator", - "CommandEvent", - "Comment", - "CompileError", - "CompositionEvent", - "CompressionStream", - "Console", - "ConstantSourceNode", - "Controllers", - "ConvolverNode", - "CountQueuingStrategy", - "Counter", - "Credential", - "CredentialsContainer", - "Crypto", - "CryptoKey", - "CustomElementRegistry", - "CustomEvent", - "DATABASE_ERR", - "DATA_CLONE_ERR", - "DATA_ERR", - "DBLCLICK", - "DECR", - "DECR_WRAP", - "DELETE_STATUS", - "DEPTH", - "DEPTH24_STENCIL8", - "DEPTH32F_STENCIL8", - "DEPTH_ATTACHMENT", - "DEPTH_BITS", - "DEPTH_BUFFER_BIT", - "DEPTH_CLEAR_VALUE", - "DEPTH_COMPONENT", - "DEPTH_COMPONENT16", - "DEPTH_COMPONENT24", - "DEPTH_COMPONENT32F", - "DEPTH_FUNC", - "DEPTH_RANGE", - "DEPTH_STENCIL", - "DEPTH_STENCIL_ATTACHMENT", - "DEPTH_TEST", - "DEPTH_WRITEMASK", - "DEVICE_INELIGIBLE", - "DIRECTION_DOWN", - "DIRECTION_LEFT", - "DIRECTION_RIGHT", - "DIRECTION_UP", - "DISABLED", - "DISPATCH_REQUEST_ERR", - "DITHER", - "DOCUMENT_FRAGMENT_NODE", - "DOCUMENT_NODE", - "DOCUMENT_POSITION_CONTAINED_BY", - "DOCUMENT_POSITION_CONTAINS", - "DOCUMENT_POSITION_DISCONNECTED", - "DOCUMENT_POSITION_FOLLOWING", - "DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC", - "DOCUMENT_POSITION_PRECEDING", - "DOCUMENT_TYPE_NODE", - "DOMCursor", - "DOMError", - "DOMException", - "DOMImplementation", - "DOMImplementationLS", - "DOMMatrix", - "DOMMatrixReadOnly", - "DOMParser", - "DOMPoint", - "DOMPointReadOnly", - "DOMQuad", - "DOMRect", - "DOMRectList", - "DOMRectReadOnly", - "DOMRequest", - "DOMSTRING_SIZE_ERR", - "DOMSettableTokenList", - "DOMStringList", - "DOMStringMap", - "DOMTokenList", - "DOMTransactionEvent", - "DOM_DELTA_LINE", - "DOM_DELTA_PAGE", - "DOM_DELTA_PIXEL", - "DOM_INPUT_METHOD_DROP", - "DOM_INPUT_METHOD_HANDWRITING", - "DOM_INPUT_METHOD_IME", - "DOM_INPUT_METHOD_KEYBOARD", - "DOM_INPUT_METHOD_MULTIMODAL", - "DOM_INPUT_METHOD_OPTION", - "DOM_INPUT_METHOD_PASTE", - "DOM_INPUT_METHOD_SCRIPT", - "DOM_INPUT_METHOD_UNKNOWN", - "DOM_INPUT_METHOD_VOICE", - "DOM_KEY_LOCATION_JOYSTICK", - "DOM_KEY_LOCATION_LEFT", - "DOM_KEY_LOCATION_MOBILE", - "DOM_KEY_LOCATION_NUMPAD", - "DOM_KEY_LOCATION_RIGHT", - "DOM_KEY_LOCATION_STANDARD", - "DOM_VK_0", - "DOM_VK_1", - "DOM_VK_2", - "DOM_VK_3", - "DOM_VK_4", - "DOM_VK_5", - "DOM_VK_6", - "DOM_VK_7", - "DOM_VK_8", - "DOM_VK_9", - "DOM_VK_A", - "DOM_VK_ACCEPT", - "DOM_VK_ADD", - "DOM_VK_ALT", - "DOM_VK_ALTGR", - "DOM_VK_AMPERSAND", - "DOM_VK_ASTERISK", - "DOM_VK_AT", - "DOM_VK_ATTN", - "DOM_VK_B", - "DOM_VK_BACKSPACE", - "DOM_VK_BACK_QUOTE", - "DOM_VK_BACK_SLASH", - "DOM_VK_BACK_SPACE", - "DOM_VK_C", - "DOM_VK_CANCEL", - "DOM_VK_CAPS_LOCK", - "DOM_VK_CIRCUMFLEX", - "DOM_VK_CLEAR", - "DOM_VK_CLOSE_BRACKET", - "DOM_VK_CLOSE_CURLY_BRACKET", - "DOM_VK_CLOSE_PAREN", - "DOM_VK_COLON", - "DOM_VK_COMMA", - "DOM_VK_CONTEXT_MENU", - "DOM_VK_CONTROL", - "DOM_VK_CONVERT", - "DOM_VK_CRSEL", - "DOM_VK_CTRL", - "DOM_VK_D", - "DOM_VK_DECIMAL", - "DOM_VK_DELETE", - "DOM_VK_DIVIDE", - "DOM_VK_DOLLAR", - "DOM_VK_DOUBLE_QUOTE", - "DOM_VK_DOWN", - "DOM_VK_E", - "DOM_VK_EISU", - "DOM_VK_END", - "DOM_VK_ENTER", - "DOM_VK_EQUALS", - "DOM_VK_EREOF", - "DOM_VK_ESCAPE", - "DOM_VK_EXCLAMATION", - "DOM_VK_EXECUTE", - "DOM_VK_EXSEL", - "DOM_VK_F", - "DOM_VK_F1", - "DOM_VK_F10", - "DOM_VK_F11", - "DOM_VK_F12", - "DOM_VK_F13", - "DOM_VK_F14", - "DOM_VK_F15", - "DOM_VK_F16", - "DOM_VK_F17", - "DOM_VK_F18", - "DOM_VK_F19", - "DOM_VK_F2", - "DOM_VK_F20", - "DOM_VK_F21", - "DOM_VK_F22", - "DOM_VK_F23", - "DOM_VK_F24", - "DOM_VK_F25", - "DOM_VK_F26", - "DOM_VK_F27", - "DOM_VK_F28", - "DOM_VK_F29", - "DOM_VK_F3", - "DOM_VK_F30", - "DOM_VK_F31", - "DOM_VK_F32", - "DOM_VK_F33", - "DOM_VK_F34", - "DOM_VK_F35", - "DOM_VK_F36", - "DOM_VK_F4", - "DOM_VK_F5", - "DOM_VK_F6", - "DOM_VK_F7", - "DOM_VK_F8", - "DOM_VK_F9", - "DOM_VK_FINAL", - "DOM_VK_FRONT", - "DOM_VK_G", - "DOM_VK_GREATER_THAN", - "DOM_VK_H", - "DOM_VK_HANGUL", - "DOM_VK_HANJA", - "DOM_VK_HASH", - "DOM_VK_HELP", - "DOM_VK_HK_TOGGLE", - "DOM_VK_HOME", - "DOM_VK_HYPHEN_MINUS", - "DOM_VK_I", - "DOM_VK_INSERT", - "DOM_VK_J", - "DOM_VK_JUNJA", - "DOM_VK_K", - "DOM_VK_KANA", - "DOM_VK_KANJI", - "DOM_VK_L", - "DOM_VK_LEFT", - "DOM_VK_LEFT_TAB", - "DOM_VK_LESS_THAN", - "DOM_VK_M", - "DOM_VK_META", - "DOM_VK_MODECHANGE", - "DOM_VK_MULTIPLY", - "DOM_VK_N", - "DOM_VK_NONCONVERT", - "DOM_VK_NUMPAD0", - "DOM_VK_NUMPAD1", - "DOM_VK_NUMPAD2", - "DOM_VK_NUMPAD3", - "DOM_VK_NUMPAD4", - "DOM_VK_NUMPAD5", - "DOM_VK_NUMPAD6", - "DOM_VK_NUMPAD7", - "DOM_VK_NUMPAD8", - "DOM_VK_NUMPAD9", - "DOM_VK_NUM_LOCK", - "DOM_VK_O", - "DOM_VK_OEM_1", - "DOM_VK_OEM_102", - "DOM_VK_OEM_2", - "DOM_VK_OEM_3", - "DOM_VK_OEM_4", - "DOM_VK_OEM_5", - "DOM_VK_OEM_6", - "DOM_VK_OEM_7", - "DOM_VK_OEM_8", - "DOM_VK_OEM_COMMA", - "DOM_VK_OEM_MINUS", - "DOM_VK_OEM_PERIOD", - "DOM_VK_OEM_PLUS", - "DOM_VK_OPEN_BRACKET", - "DOM_VK_OPEN_CURLY_BRACKET", - "DOM_VK_OPEN_PAREN", - "DOM_VK_P", - "DOM_VK_PA1", - "DOM_VK_PAGEDOWN", - "DOM_VK_PAGEUP", - "DOM_VK_PAGE_DOWN", - "DOM_VK_PAGE_UP", - "DOM_VK_PAUSE", - "DOM_VK_PERCENT", - "DOM_VK_PERIOD", - "DOM_VK_PIPE", - "DOM_VK_PLAY", - "DOM_VK_PLUS", - "DOM_VK_PRINT", - "DOM_VK_PRINTSCREEN", - "DOM_VK_PROCESSKEY", - "DOM_VK_PROPERITES", - "DOM_VK_Q", - "DOM_VK_QUESTION_MARK", - "DOM_VK_QUOTE", - "DOM_VK_R", - "DOM_VK_REDO", - "DOM_VK_RETURN", - "DOM_VK_RIGHT", - "DOM_VK_S", - "DOM_VK_SCROLL_LOCK", - "DOM_VK_SELECT", - "DOM_VK_SEMICOLON", - "DOM_VK_SEPARATOR", - "DOM_VK_SHIFT", - "DOM_VK_SLASH", - "DOM_VK_SLEEP", - "DOM_VK_SPACE", - "DOM_VK_SUBTRACT", - "DOM_VK_T", - "DOM_VK_TAB", - "DOM_VK_TILDE", - "DOM_VK_U", - "DOM_VK_UNDERSCORE", - "DOM_VK_UNDO", - "DOM_VK_UNICODE", - "DOM_VK_UP", - "DOM_VK_V", - "DOM_VK_VOLUME_DOWN", - "DOM_VK_VOLUME_MUTE", - "DOM_VK_VOLUME_UP", - "DOM_VK_W", - "DOM_VK_WIN", - "DOM_VK_WINDOW", - "DOM_VK_WIN_ICO_00", - "DOM_VK_WIN_ICO_CLEAR", - "DOM_VK_WIN_ICO_HELP", - "DOM_VK_WIN_OEM_ATTN", - "DOM_VK_WIN_OEM_AUTO", - "DOM_VK_WIN_OEM_BACKTAB", - "DOM_VK_WIN_OEM_CLEAR", - "DOM_VK_WIN_OEM_COPY", - "DOM_VK_WIN_OEM_CUSEL", - "DOM_VK_WIN_OEM_ENLW", - "DOM_VK_WIN_OEM_FINISH", - "DOM_VK_WIN_OEM_FJ_JISHO", - "DOM_VK_WIN_OEM_FJ_LOYA", - "DOM_VK_WIN_OEM_FJ_MASSHOU", - "DOM_VK_WIN_OEM_FJ_ROYA", - "DOM_VK_WIN_OEM_FJ_TOUROKU", - "DOM_VK_WIN_OEM_JUMP", - "DOM_VK_WIN_OEM_PA1", - "DOM_VK_WIN_OEM_PA2", - "DOM_VK_WIN_OEM_PA3", - "DOM_VK_WIN_OEM_RESET", - "DOM_VK_WIN_OEM_WSCTRL", - "DOM_VK_X", - "DOM_VK_XF86XK_ADD_FAVORITE", - "DOM_VK_XF86XK_APPLICATION_LEFT", - "DOM_VK_XF86XK_APPLICATION_RIGHT", - "DOM_VK_XF86XK_AUDIO_CYCLE_TRACK", - "DOM_VK_XF86XK_AUDIO_FORWARD", - "DOM_VK_XF86XK_AUDIO_LOWER_VOLUME", - "DOM_VK_XF86XK_AUDIO_MEDIA", - "DOM_VK_XF86XK_AUDIO_MUTE", - "DOM_VK_XF86XK_AUDIO_NEXT", - "DOM_VK_XF86XK_AUDIO_PAUSE", - "DOM_VK_XF86XK_AUDIO_PLAY", - "DOM_VK_XF86XK_AUDIO_PREV", - "DOM_VK_XF86XK_AUDIO_RAISE_VOLUME", - "DOM_VK_XF86XK_AUDIO_RANDOM_PLAY", - "DOM_VK_XF86XK_AUDIO_RECORD", - "DOM_VK_XF86XK_AUDIO_REPEAT", - "DOM_VK_XF86XK_AUDIO_REWIND", - "DOM_VK_XF86XK_AUDIO_STOP", - "DOM_VK_XF86XK_AWAY", - "DOM_VK_XF86XK_BACK", - "DOM_VK_XF86XK_BACK_FORWARD", - "DOM_VK_XF86XK_BATTERY", - "DOM_VK_XF86XK_BLUE", - "DOM_VK_XF86XK_BLUETOOTH", - "DOM_VK_XF86XK_BOOK", - "DOM_VK_XF86XK_BRIGHTNESS_ADJUST", - "DOM_VK_XF86XK_CALCULATOR", - "DOM_VK_XF86XK_CALENDAR", - "DOM_VK_XF86XK_CD", - "DOM_VK_XF86XK_CLOSE", - "DOM_VK_XF86XK_COMMUNITY", - "DOM_VK_XF86XK_CONTRAST_ADJUST", - "DOM_VK_XF86XK_COPY", - "DOM_VK_XF86XK_CUT", - "DOM_VK_XF86XK_CYCLE_ANGLE", - "DOM_VK_XF86XK_DISPLAY", - "DOM_VK_XF86XK_DOCUMENTS", - "DOM_VK_XF86XK_DOS", - "DOM_VK_XF86XK_EJECT", - "DOM_VK_XF86XK_EXCEL", - "DOM_VK_XF86XK_EXPLORER", - "DOM_VK_XF86XK_FAVORITES", - "DOM_VK_XF86XK_FINANCE", - "DOM_VK_XF86XK_FORWARD", - "DOM_VK_XF86XK_FRAME_BACK", - "DOM_VK_XF86XK_FRAME_FORWARD", - "DOM_VK_XF86XK_GAME", - "DOM_VK_XF86XK_GO", - "DOM_VK_XF86XK_GREEN", - "DOM_VK_XF86XK_HIBERNATE", - "DOM_VK_XF86XK_HISTORY", - "DOM_VK_XF86XK_HOME_PAGE", - "DOM_VK_XF86XK_HOT_LINKS", - "DOM_VK_XF86XK_I_TOUCH", - "DOM_VK_XF86XK_KBD_BRIGHTNESS_DOWN", - "DOM_VK_XF86XK_KBD_BRIGHTNESS_UP", - "DOM_VK_XF86XK_KBD_LIGHT_ON_OFF", - "DOM_VK_XF86XK_LAUNCH0", - "DOM_VK_XF86XK_LAUNCH1", - "DOM_VK_XF86XK_LAUNCH2", - "DOM_VK_XF86XK_LAUNCH3", - "DOM_VK_XF86XK_LAUNCH4", - "DOM_VK_XF86XK_LAUNCH5", - "DOM_VK_XF86XK_LAUNCH6", - "DOM_VK_XF86XK_LAUNCH7", - "DOM_VK_XF86XK_LAUNCH8", - "DOM_VK_XF86XK_LAUNCH9", - "DOM_VK_XF86XK_LAUNCH_A", - "DOM_VK_XF86XK_LAUNCH_B", - "DOM_VK_XF86XK_LAUNCH_C", - "DOM_VK_XF86XK_LAUNCH_D", - "DOM_VK_XF86XK_LAUNCH_E", - "DOM_VK_XF86XK_LAUNCH_F", - "DOM_VK_XF86XK_LIGHT_BULB", - "DOM_VK_XF86XK_LOG_OFF", - "DOM_VK_XF86XK_MAIL", - "DOM_VK_XF86XK_MAIL_FORWARD", - "DOM_VK_XF86XK_MARKET", - "DOM_VK_XF86XK_MEETING", - "DOM_VK_XF86XK_MEMO", - "DOM_VK_XF86XK_MENU_KB", - "DOM_VK_XF86XK_MENU_PB", - "DOM_VK_XF86XK_MESSENGER", - "DOM_VK_XF86XK_MON_BRIGHTNESS_DOWN", - "DOM_VK_XF86XK_MON_BRIGHTNESS_UP", - "DOM_VK_XF86XK_MUSIC", - "DOM_VK_XF86XK_MY_COMPUTER", - "DOM_VK_XF86XK_MY_SITES", - "DOM_VK_XF86XK_NEW", - "DOM_VK_XF86XK_NEWS", - "DOM_VK_XF86XK_OFFICE_HOME", - "DOM_VK_XF86XK_OPEN", - "DOM_VK_XF86XK_OPEN_URL", - "DOM_VK_XF86XK_OPTION", - "DOM_VK_XF86XK_PASTE", - "DOM_VK_XF86XK_PHONE", - "DOM_VK_XF86XK_PICTURES", - "DOM_VK_XF86XK_POWER_DOWN", - "DOM_VK_XF86XK_POWER_OFF", - "DOM_VK_XF86XK_RED", - "DOM_VK_XF86XK_REFRESH", - "DOM_VK_XF86XK_RELOAD", - "DOM_VK_XF86XK_REPLY", - "DOM_VK_XF86XK_ROCKER_DOWN", - "DOM_VK_XF86XK_ROCKER_ENTER", - "DOM_VK_XF86XK_ROCKER_UP", - "DOM_VK_XF86XK_ROTATE_WINDOWS", - "DOM_VK_XF86XK_ROTATION_KB", - "DOM_VK_XF86XK_ROTATION_PB", - "DOM_VK_XF86XK_SAVE", - "DOM_VK_XF86XK_SCREEN_SAVER", - "DOM_VK_XF86XK_SCROLL_CLICK", - "DOM_VK_XF86XK_SCROLL_DOWN", - "DOM_VK_XF86XK_SCROLL_UP", - "DOM_VK_XF86XK_SEARCH", - "DOM_VK_XF86XK_SEND", - "DOM_VK_XF86XK_SHOP", - "DOM_VK_XF86XK_SPELL", - "DOM_VK_XF86XK_SPLIT_SCREEN", - "DOM_VK_XF86XK_STANDBY", - "DOM_VK_XF86XK_START", - "DOM_VK_XF86XK_STOP", - "DOM_VK_XF86XK_SUBTITLE", - "DOM_VK_XF86XK_SUPPORT", - "DOM_VK_XF86XK_SUSPEND", - "DOM_VK_XF86XK_TASK_PANE", - "DOM_VK_XF86XK_TERMINAL", - "DOM_VK_XF86XK_TIME", - "DOM_VK_XF86XK_TOOLS", - "DOM_VK_XF86XK_TOP_MENU", - "DOM_VK_XF86XK_TO_DO_LIST", - "DOM_VK_XF86XK_TRAVEL", - "DOM_VK_XF86XK_USER1KB", - "DOM_VK_XF86XK_USER2KB", - "DOM_VK_XF86XK_USER_PB", - "DOM_VK_XF86XK_UWB", - "DOM_VK_XF86XK_VENDOR_HOME", - "DOM_VK_XF86XK_VIDEO", - "DOM_VK_XF86XK_VIEW", - "DOM_VK_XF86XK_WAKE_UP", - "DOM_VK_XF86XK_WEB_CAM", - "DOM_VK_XF86XK_WHEEL_BUTTON", - "DOM_VK_XF86XK_WLAN", - "DOM_VK_XF86XK_WORD", - "DOM_VK_XF86XK_WWW", - "DOM_VK_XF86XK_XFER", - "DOM_VK_XF86XK_YELLOW", - "DOM_VK_XF86XK_ZOOM_IN", - "DOM_VK_XF86XK_ZOOM_OUT", - "DOM_VK_Y", - "DOM_VK_Z", - "DOM_VK_ZOOM", - "DONE", - "DONT_CARE", - "DOWNLOADING", - "DRAGDROP", - "DRAW_BUFFER0", - "DRAW_BUFFER1", - "DRAW_BUFFER10", - "DRAW_BUFFER11", - "DRAW_BUFFER12", - "DRAW_BUFFER13", - "DRAW_BUFFER14", - "DRAW_BUFFER15", - "DRAW_BUFFER2", - "DRAW_BUFFER3", - "DRAW_BUFFER4", - "DRAW_BUFFER5", - "DRAW_BUFFER6", - "DRAW_BUFFER7", - "DRAW_BUFFER8", - "DRAW_BUFFER9", - "DRAW_FRAMEBUFFER", - "DRAW_FRAMEBUFFER_BINDING", - "DST_ALPHA", - "DST_COLOR", - "DYNAMIC_COPY", - "DYNAMIC_DRAW", - "DYNAMIC_READ", - "DataChannel", - "DataTransfer", - "DataTransferItem", - "DataTransferItemList", - "DataView", - "Date", - "DateTimeFormat", - "DecompressionStream", - "DelayNode", - "DeprecationReportBody", - "DesktopNotification", - "DesktopNotificationCenter", - "DeviceLightEvent", - "DeviceMotionEvent", - "DeviceMotionEventAcceleration", - "DeviceMotionEventRotationRate", - "DeviceOrientationEvent", - "DeviceProximityEvent", - "DeviceStorage", - "DeviceStorageChangeEvent", - "Directory", - "DisplayNames", - "Document", - "DocumentFragment", - "DocumentTimeline", - "DocumentType", - "DragEvent", - "DynamicsCompressorNode", - "E", - "ELEMENT_ARRAY_BUFFER", - "ELEMENT_ARRAY_BUFFER_BINDING", - "ELEMENT_NODE", - "EMPTY", - "ENCODING_ERR", - "ENDED", - "END_TO_END", - "END_TO_START", - "ENTITY_NODE", - "ENTITY_REFERENCE_NODE", - "EPSILON", - "EQUAL", - "EQUALPOWER", - "ERROR", - "EXPONENTIAL_DISTANCE", - "Element", - "ElementInternals", - "ElementQuery", - "EnterPictureInPictureEvent", - "Entity", - "EntityReference", - "Error", - "ErrorEvent", - "EvalError", - "Event", - "EventException", - "EventSource", - "EventTarget", - "External", - "FASTEST", - "FIDOSDK", - "FILTER_ACCEPT", - "FILTER_INTERRUPT", - "FILTER_REJECT", - "FILTER_SKIP", - "FINISHED_STATE", - "FIRST_ORDERED_NODE_TYPE", - "FLOAT", - "FLOAT_32_UNSIGNED_INT_24_8_REV", - "FLOAT_MAT2", - "FLOAT_MAT2x3", - "FLOAT_MAT2x4", - "FLOAT_MAT3", - "FLOAT_MAT3x2", - "FLOAT_MAT3x4", - "FLOAT_MAT4", - "FLOAT_MAT4x2", - "FLOAT_MAT4x3", - "FLOAT_VEC2", - "FLOAT_VEC3", - "FLOAT_VEC4", - "FOCUS", - "FONT_FACE_RULE", - "FONT_FEATURE_VALUES_RULE", - "FRAGMENT_SHADER", - "FRAGMENT_SHADER_DERIVATIVE_HINT", - "FRAGMENT_SHADER_DERIVATIVE_HINT_OES", - "FRAMEBUFFER", - "FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE", - "FRAMEBUFFER_ATTACHMENT_BLUE_SIZE", - "FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING", - "FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE", - "FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE", - "FRAMEBUFFER_ATTACHMENT_GREEN_SIZE", - "FRAMEBUFFER_ATTACHMENT_OBJECT_NAME", - "FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE", - "FRAMEBUFFER_ATTACHMENT_RED_SIZE", - "FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE", - "FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE", - "FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER", - "FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL", - "FRAMEBUFFER_BINDING", - "FRAMEBUFFER_COMPLETE", - "FRAMEBUFFER_DEFAULT", - "FRAMEBUFFER_INCOMPLETE_ATTACHMENT", - "FRAMEBUFFER_INCOMPLETE_DIMENSIONS", - "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT", - "FRAMEBUFFER_INCOMPLETE_MULTISAMPLE", - "FRAMEBUFFER_UNSUPPORTED", - "FRONT", - "FRONT_AND_BACK", - "FRONT_FACE", - "FUNC_ADD", - "FUNC_REVERSE_SUBTRACT", - "FUNC_SUBTRACT", - "FeaturePolicy", - "FeaturePolicyViolationReportBody", - "FederatedCredential", - "Feed", - "FeedEntry", - "File", - "FileError", - "FileList", - "FileReader", - "FileSystem", - "FileSystemDirectoryEntry", - "FileSystemDirectoryReader", - "FileSystemEntry", - "FileSystemFileEntry", - "FinalizationRegistry", - "FindInPage", - "Float32Array", - "Float64Array", - "FocusEvent", - "FontFace", - "FontFaceSet", - "FontFaceSetLoadEvent", - "FormData", - "FormDataEvent", - "FragmentDirective", - "Function", - "GENERATE_MIPMAP_HINT", - "GEQUAL", - "GREATER", - "GREEN_BITS", - "GainNode", - "Gamepad", - "GamepadAxisMoveEvent", - "GamepadButton", - "GamepadButtonEvent", - "GamepadEvent", - "GamepadHapticActuator", - "GamepadPose", - "Geolocation", - "GeolocationCoordinates", - "GeolocationPosition", - "GeolocationPositionError", - "GestureEvent", - "Global", - "Gyroscope", - "HALF_FLOAT", - "HAVE_CURRENT_DATA", - "HAVE_ENOUGH_DATA", - "HAVE_FUTURE_DATA", - "HAVE_METADATA", - "HAVE_NOTHING", - "HEADERS_RECEIVED", - "HIDDEN", - "HIERARCHY_REQUEST_ERR", - "HIGHPASS", - "HIGHSHELF", - "HIGH_FLOAT", - "HIGH_INT", - "HORIZONTAL", - "HORIZONTAL_AXIS", - "HRTF", - "HTMLAllCollection", - "HTMLAnchorElement", - "HTMLAppletElement", - "HTMLAreaElement", - "HTMLAudioElement", - "HTMLBRElement", - "HTMLBaseElement", - "HTMLBaseFontElement", - "HTMLBlockquoteElement", - "HTMLBodyElement", - "HTMLButtonElement", - "HTMLCanvasElement", - "HTMLCollection", - "HTMLCommandElement", - "HTMLContentElement", - "HTMLDListElement", - "HTMLDataElement", - "HTMLDataListElement", - "HTMLDetailsElement", - "HTMLDialogElement", - "HTMLDirectoryElement", - "HTMLDivElement", - "HTMLDocument", - "HTMLElement", - "HTMLEmbedElement", - "HTMLFieldSetElement", - "HTMLFontElement", - "HTMLFormControlsCollection", - "HTMLFormElement", - "HTMLFrameElement", - "HTMLFrameSetElement", - "HTMLHRElement", - "HTMLHeadElement", - "HTMLHeadingElement", - "HTMLHtmlElement", - "HTMLIFrameElement", - "HTMLImageElement", - "HTMLInputElement", - "HTMLIsIndexElement", - "HTMLKeygenElement", - "HTMLLIElement", - "HTMLLabelElement", - "HTMLLegendElement", - "HTMLLinkElement", - "HTMLMapElement", - "HTMLMarqueeElement", - "HTMLMediaElement", - "HTMLMenuElement", - "HTMLMenuItemElement", - "HTMLMetaElement", - "HTMLMeterElement", - "HTMLModElement", - "HTMLOListElement", - "HTMLObjectElement", - "HTMLOptGroupElement", - "HTMLOptionElement", - "HTMLOptionsCollection", - "HTMLOutputElement", - "HTMLParagraphElement", - "HTMLParamElement", - "HTMLPictureElement", - "HTMLPreElement", - "HTMLProgressElement", - "HTMLPropertiesCollection", - "HTMLQuoteElement", - "HTMLScriptElement", - "HTMLSelectElement", - "HTMLShadowElement", - "HTMLSlotElement", - "HTMLSourceElement", - "HTMLSpanElement", - "HTMLStyleElement", - "HTMLTableCaptionElement", - "HTMLTableCellElement", - "HTMLTableColElement", - "HTMLTableElement", - "HTMLTableRowElement", - "HTMLTableSectionElement", - "HTMLTemplateElement", - "HTMLTextAreaElement", - "HTMLTimeElement", - "HTMLTitleElement", - "HTMLTrackElement", - "HTMLUListElement", - "HTMLUnknownElement", - "HTMLVideoElement", - "HashChangeEvent", - "Headers", - "History", - "Hz", - "ICE_CHECKING", - "ICE_CLOSED", - "ICE_COMPLETED", - "ICE_CONNECTED", - "ICE_FAILED", - "ICE_GATHERING", - "ICE_WAITING", - "IDBCursor", - "IDBCursorWithValue", - "IDBDatabase", - "IDBDatabaseException", - "IDBFactory", - "IDBFileHandle", - "IDBFileRequest", - "IDBIndex", - "IDBKeyRange", - "IDBMutableFile", - "IDBObjectStore", - "IDBOpenDBRequest", - "IDBRequest", - "IDBTransaction", - "IDBVersionChangeEvent", - "IDLE", - "IIRFilterNode", - "IMPLEMENTATION_COLOR_READ_FORMAT", - "IMPLEMENTATION_COLOR_READ_TYPE", - "IMPORT_RULE", - "INCR", - "INCR_WRAP", - "INDEX_SIZE_ERR", - "INT", - "INTERLEAVED_ATTRIBS", - "INT_2_10_10_10_REV", - "INT_SAMPLER_2D", - "INT_SAMPLER_2D_ARRAY", - "INT_SAMPLER_3D", - "INT_SAMPLER_CUBE", - "INT_VEC2", - "INT_VEC3", - "INT_VEC4", - "INUSE_ATTRIBUTE_ERR", - "INVALID_ACCESS_ERR", - "INVALID_CHARACTER_ERR", - "INVALID_ENUM", - "INVALID_EXPRESSION_ERR", - "INVALID_FRAMEBUFFER_OPERATION", - "INVALID_INDEX", - "INVALID_MODIFICATION_ERR", - "INVALID_NODE_TYPE_ERR", - "INVALID_OPERATION", - "INVALID_STATE_ERR", - "INVALID_VALUE", - "INVERSE_DISTANCE", - "INVERT", - "IceCandidate", - "IdleDeadline", - "Image", - "ImageBitmap", - "ImageBitmapRenderingContext", - "ImageCapture", - "ImageData", - "Infinity", - "InputDeviceCapabilities", - "InputDeviceInfo", - "InputEvent", - "InputMethodContext", - "InstallTrigger", - "InstallTriggerImpl", - "Instance", - "Int16Array", - "Int32Array", - "Int8Array", - "Intent", - "InternalError", - "IntersectionObserver", - "IntersectionObserverEntry", - "Intl", - "IsSearchProviderInstalled", - "Iterator", - "JSON", - "KEEP", - "KEYDOWN", - "KEYFRAMES_RULE", - "KEYFRAME_RULE", - "KEYPRESS", - "KEYUP", - "KeyEvent", - "Keyboard", - "KeyboardEvent", - "KeyboardLayoutMap", - "KeyframeEffect", - "LENGTHADJUST_SPACING", - "LENGTHADJUST_SPACINGANDGLYPHS", - "LENGTHADJUST_UNKNOWN", - "LEQUAL", - "LESS", - "LINEAR", - "LINEAR_DISTANCE", - "LINEAR_MIPMAP_LINEAR", - "LINEAR_MIPMAP_NEAREST", - "LINES", - "LINE_LOOP", - "LINE_STRIP", - "LINE_WIDTH", - "LINK_STATUS", - "LIVE", - "LN10", - "LN2", - "LOADED", - "LOADING", - "LOG10E", - "LOG2E", - "LOWPASS", - "LOWSHELF", - "LOW_FLOAT", - "LOW_INT", - "LSException", - "LSParserFilter", - "LUMINANCE", - "LUMINANCE_ALPHA", - "LargestContentfulPaint", - "LayoutShift", - "LayoutShiftAttribution", - "LinearAccelerationSensor", - "LinkError", - "ListFormat", - "LocalMediaStream", - "Locale", - "Location", - "Lock", - "LockManager", - "MAX", - "MAX_3D_TEXTURE_SIZE", - "MAX_ARRAY_TEXTURE_LAYERS", - "MAX_CLIENT_WAIT_TIMEOUT_WEBGL", - "MAX_COLOR_ATTACHMENTS", - "MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS", - "MAX_COMBINED_TEXTURE_IMAGE_UNITS", - "MAX_COMBINED_UNIFORM_BLOCKS", - "MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS", - "MAX_CUBE_MAP_TEXTURE_SIZE", - "MAX_DRAW_BUFFERS", - "MAX_ELEMENTS_INDICES", - "MAX_ELEMENTS_VERTICES", - "MAX_ELEMENT_INDEX", - "MAX_FRAGMENT_INPUT_COMPONENTS", - "MAX_FRAGMENT_UNIFORM_BLOCKS", - "MAX_FRAGMENT_UNIFORM_COMPONENTS", - "MAX_FRAGMENT_UNIFORM_VECTORS", - "MAX_PROGRAM_TEXEL_OFFSET", - "MAX_RENDERBUFFER_SIZE", - "MAX_SAFE_INTEGER", - "MAX_SAMPLES", - "MAX_SERVER_WAIT_TIMEOUT", - "MAX_TEXTURE_IMAGE_UNITS", - "MAX_TEXTURE_LOD_BIAS", - "MAX_TEXTURE_MAX_ANISOTROPY_EXT", - "MAX_TEXTURE_SIZE", - "MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS", - "MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS", - "MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS", - "MAX_UNIFORM_BLOCK_SIZE", - "MAX_UNIFORM_BUFFER_BINDINGS", - "MAX_VALUE", - "MAX_VARYING_COMPONENTS", - "MAX_VARYING_VECTORS", - "MAX_VERTEX_ATTRIBS", - "MAX_VERTEX_OUTPUT_COMPONENTS", - "MAX_VERTEX_TEXTURE_IMAGE_UNITS", - "MAX_VERTEX_UNIFORM_BLOCKS", - "MAX_VERTEX_UNIFORM_COMPONENTS", - "MAX_VERTEX_UNIFORM_VECTORS", - "MAX_VIEWPORT_DIMS", - "MEDIA_ERR_ABORTED", - "MEDIA_ERR_DECODE", - "MEDIA_ERR_ENCRYPTED", - "MEDIA_ERR_NETWORK", - "MEDIA_ERR_SRC_NOT_SUPPORTED", - "MEDIA_KEYERR_CLIENT", - "MEDIA_KEYERR_DOMAIN", - "MEDIA_KEYERR_HARDWARECHANGE", - "MEDIA_KEYERR_OUTPUT", - "MEDIA_KEYERR_SERVICE", - "MEDIA_KEYERR_UNKNOWN", - "MEDIA_RULE", - "MEDIUM_FLOAT", - "MEDIUM_INT", - "META_MASK", - "MIDIAccess", - "MIDIConnectionEvent", - "MIDIInput", - "MIDIInputMap", - "MIDIMessageEvent", - "MIDIOutput", - "MIDIOutputMap", - "MIDIPort", - "MIN", - "MIN_PROGRAM_TEXEL_OFFSET", - "MIN_SAFE_INTEGER", - "MIN_VALUE", - "MIRRORED_REPEAT", - "MODE_ASYNCHRONOUS", - "MODE_SYNCHRONOUS", - "MODIFICATION", - "MOUSEDOWN", - "MOUSEDRAG", - "MOUSEMOVE", - "MOUSEOUT", - "MOUSEOVER", - "MOUSEUP", - "MOZ_KEYFRAMES_RULE", - "MOZ_KEYFRAME_RULE", - "MOZ_SOURCE_CURSOR", - "MOZ_SOURCE_ERASER", - "MOZ_SOURCE_KEYBOARD", - "MOZ_SOURCE_MOUSE", - "MOZ_SOURCE_PEN", - "MOZ_SOURCE_TOUCH", - "MOZ_SOURCE_UNKNOWN", - "MSGESTURE_FLAG_BEGIN", - "MSGESTURE_FLAG_CANCEL", - "MSGESTURE_FLAG_END", - "MSGESTURE_FLAG_INERTIA", - "MSGESTURE_FLAG_NONE", - "MSPOINTER_TYPE_MOUSE", - "MSPOINTER_TYPE_PEN", - "MSPOINTER_TYPE_TOUCH", - "MS_ASYNC_CALLBACK_STATUS_ASSIGN_DELEGATE", - "MS_ASYNC_CALLBACK_STATUS_CANCEL", - "MS_ASYNC_CALLBACK_STATUS_CHOOSEANY", - "MS_ASYNC_CALLBACK_STATUS_ERROR", - "MS_ASYNC_CALLBACK_STATUS_JOIN", - "MS_ASYNC_OP_STATUS_CANCELED", - "MS_ASYNC_OP_STATUS_ERROR", - "MS_ASYNC_OP_STATUS_SUCCESS", - "MS_MANIPULATION_STATE_ACTIVE", - "MS_MANIPULATION_STATE_CANCELLED", - "MS_MANIPULATION_STATE_COMMITTED", - "MS_MANIPULATION_STATE_DRAGGING", - "MS_MANIPULATION_STATE_INERTIA", - "MS_MANIPULATION_STATE_PRESELECT", - "MS_MANIPULATION_STATE_SELECTING", - "MS_MANIPULATION_STATE_STOPPED", - "MS_MEDIA_ERR_ENCRYPTED", - "MS_MEDIA_KEYERR_CLIENT", - "MS_MEDIA_KEYERR_DOMAIN", - "MS_MEDIA_KEYERR_HARDWARECHANGE", - "MS_MEDIA_KEYERR_OUTPUT", - "MS_MEDIA_KEYERR_SERVICE", - "MS_MEDIA_KEYERR_UNKNOWN", - "Map", - "Math", - "MathMLElement", - "MediaCapabilities", - "MediaCapabilitiesInfo", - "MediaController", - "MediaDeviceInfo", - "MediaDevices", - "MediaElementAudioSourceNode", - "MediaEncryptedEvent", - "MediaError", - "MediaKeyError", - "MediaKeyEvent", - "MediaKeyMessageEvent", - "MediaKeyNeededEvent", - "MediaKeySession", - "MediaKeyStatusMap", - "MediaKeySystemAccess", - "MediaKeys", - "MediaList", - "MediaMetadata", - "MediaQueryList", - "MediaQueryListEvent", - "MediaRecorder", - "MediaRecorderErrorEvent", - "MediaSession", - "MediaSettingsRange", - "MediaSource", - "MediaStream", - "MediaStreamAudioDestinationNode", - "MediaStreamAudioSourceNode", - "MediaStreamEvent", - "MediaStreamTrack", - "MediaStreamTrackAudioSourceNode", - "MediaStreamTrackEvent", - "Memory", - "MessageChannel", - "MessageEvent", - "MessagePort", - "Methods", - "MimeType", - "MimeTypeArray", - "Module", - "MouseEvent", - "MouseScrollEvent", - "MozAnimation", - "MozAnimationDelay", - "MozAnimationDirection", - "MozAnimationDuration", - "MozAnimationFillMode", - "MozAnimationIterationCount", - "MozAnimationName", - "MozAnimationPlayState", - "MozAnimationTimingFunction", - "MozAppearance", - "MozBackfaceVisibility", - "MozBinding", - "MozBorderBottomColors", - "MozBorderEnd", - "MozBorderEndColor", - "MozBorderEndStyle", - "MozBorderEndWidth", - "MozBorderImage", - "MozBorderLeftColors", - "MozBorderRightColors", - "MozBorderStart", - "MozBorderStartColor", - "MozBorderStartStyle", - "MozBorderStartWidth", - "MozBorderTopColors", - "MozBoxAlign", - "MozBoxDirection", - "MozBoxFlex", - "MozBoxOrdinalGroup", - "MozBoxOrient", - "MozBoxPack", - "MozBoxSizing", - "MozCSSKeyframeRule", - "MozCSSKeyframesRule", - "MozColumnCount", - "MozColumnFill", - "MozColumnGap", - "MozColumnRule", - "MozColumnRuleColor", - "MozColumnRuleStyle", - "MozColumnRuleWidth", - "MozColumnWidth", - "MozColumns", - "MozContactChangeEvent", - "MozFloatEdge", - "MozFontFeatureSettings", - "MozFontLanguageOverride", - "MozForceBrokenImageIcon", - "MozHyphens", - "MozImageRegion", - "MozMarginEnd", - "MozMarginStart", - "MozMmsEvent", - "MozMmsMessage", - "MozMobileMessageThread", - "MozOSXFontSmoothing", - "MozOrient", - "MozOsxFontSmoothing", - "MozOutlineRadius", - "MozOutlineRadiusBottomleft", - "MozOutlineRadiusBottomright", - "MozOutlineRadiusTopleft", - "MozOutlineRadiusTopright", - "MozPaddingEnd", - "MozPaddingStart", - "MozPerspective", - "MozPerspectiveOrigin", - "MozPowerManager", - "MozSettingsEvent", - "MozSmsEvent", - "MozSmsMessage", - "MozStackSizing", - "MozTabSize", - "MozTextAlignLast", - "MozTextDecorationColor", - "MozTextDecorationLine", - "MozTextDecorationStyle", - "MozTextSizeAdjust", - "MozTransform", - "MozTransformOrigin", - "MozTransformStyle", - "MozTransition", - "MozTransitionDelay", - "MozTransitionDuration", - "MozTransitionProperty", - "MozTransitionTimingFunction", - "MozUserFocus", - "MozUserInput", - "MozUserModify", - "MozUserSelect", - "MozWindowDragging", - "MozWindowShadow", - "MutationEvent", - "MutationObserver", - "MutationRecord", - "NAMESPACE_ERR", - "NAMESPACE_RULE", - "NEAREST", - "NEAREST_MIPMAP_LINEAR", - "NEAREST_MIPMAP_NEAREST", - "NEGATIVE_INFINITY", - "NETWORK_EMPTY", - "NETWORK_ERR", - "NETWORK_IDLE", - "NETWORK_LOADED", - "NETWORK_LOADING", - "NETWORK_NO_SOURCE", - "NEVER", - "NEW", - "NEXT", - "NEXT_NO_DUPLICATE", - "NICEST", - "NODE_AFTER", - "NODE_BEFORE", - "NODE_BEFORE_AND_AFTER", - "NODE_INSIDE", - "NONE", - "NON_TRANSIENT_ERR", - "NOTATION_NODE", - "NOTCH", - "NOTEQUAL", - "NOT_ALLOWED_ERR", - "NOT_FOUND_ERR", - "NOT_READABLE_ERR", - "NOT_SUPPORTED_ERR", - "NO_DATA_ALLOWED_ERR", - "NO_ERR", - "NO_ERROR", - "NO_MODIFICATION_ALLOWED_ERR", - "NUMBER_TYPE", - "NUM_COMPRESSED_TEXTURE_FORMATS", - "NaN", - "NamedNodeMap", - "NavigationPreloadManager", - "Navigator", - "NearbyLinks", - "NetworkInformation", - "Node", - "NodeFilter", - "NodeIterator", - "NodeList", - "Notation", - "Notification", - "NotifyPaintEvent", - "Number", - "NumberFormat", - "OBJECT_TYPE", - "OBSOLETE", - "OK", - "ONE", - "ONE_MINUS_CONSTANT_ALPHA", - "ONE_MINUS_CONSTANT_COLOR", - "ONE_MINUS_DST_ALPHA", - "ONE_MINUS_DST_COLOR", - "ONE_MINUS_SRC_ALPHA", - "ONE_MINUS_SRC_COLOR", - "OPEN", - "OPENED", - "OPENING", - "ORDERED_NODE_ITERATOR_TYPE", - "ORDERED_NODE_SNAPSHOT_TYPE", - "OTHER_ERROR", - "OUT_OF_MEMORY", - "Object", - "OfflineAudioCompletionEvent", - "OfflineAudioContext", - "OfflineResourceList", - "OffscreenCanvas", - "OffscreenCanvasRenderingContext2D", - "Option", - "OrientationSensor", - "OscillatorNode", - "OverconstrainedError", - "OverflowEvent", - "PACK_ALIGNMENT", - "PACK_ROW_LENGTH", - "PACK_SKIP_PIXELS", - "PACK_SKIP_ROWS", - "PAGE_RULE", - "PARSE_ERR", - "PATHSEG_ARC_ABS", - "PATHSEG_ARC_REL", - "PATHSEG_CLOSEPATH", - "PATHSEG_CURVETO_CUBIC_ABS", - "PATHSEG_CURVETO_CUBIC_REL", - "PATHSEG_CURVETO_CUBIC_SMOOTH_ABS", - "PATHSEG_CURVETO_CUBIC_SMOOTH_REL", - "PATHSEG_CURVETO_QUADRATIC_ABS", - "PATHSEG_CURVETO_QUADRATIC_REL", - "PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS", - "PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL", - "PATHSEG_LINETO_ABS", - "PATHSEG_LINETO_HORIZONTAL_ABS", - "PATHSEG_LINETO_HORIZONTAL_REL", - "PATHSEG_LINETO_REL", - "PATHSEG_LINETO_VERTICAL_ABS", - "PATHSEG_LINETO_VERTICAL_REL", - "PATHSEG_MOVETO_ABS", - "PATHSEG_MOVETO_REL", - "PATHSEG_UNKNOWN", - "PATH_EXISTS_ERR", - "PEAKING", - "PERMISSION_DENIED", - "PERSISTENT", - "PI", - "PIXEL_PACK_BUFFER", - "PIXEL_PACK_BUFFER_BINDING", - "PIXEL_UNPACK_BUFFER", - "PIXEL_UNPACK_BUFFER_BINDING", - "PLAYING_STATE", - "POINTS", - "POLYGON_OFFSET_FACTOR", - "POLYGON_OFFSET_FILL", - "POLYGON_OFFSET_UNITS", - "POSITION_UNAVAILABLE", - "POSITIVE_INFINITY", - "PREV", - "PREV_NO_DUPLICATE", - "PROCESSING_INSTRUCTION_NODE", - "PageChangeEvent", - "PageTransitionEvent", - "PaintRequest", - "PaintRequestList", - "PannerNode", - "PasswordCredential", - "Path2D", - "PaymentAddress", - "PaymentInstruments", - "PaymentManager", - "PaymentMethodChangeEvent", - "PaymentRequest", - "PaymentRequestUpdateEvent", - "PaymentResponse", - "Performance", - "PerformanceElementTiming", - "PerformanceEntry", - "PerformanceEventTiming", - "PerformanceLongTaskTiming", - "PerformanceMark", - "PerformanceMeasure", - "PerformanceNavigation", - "PerformanceNavigationTiming", - "PerformanceObserver", - "PerformanceObserverEntryList", - "PerformancePaintTiming", - "PerformanceResourceTiming", - "PerformanceServerTiming", - "PerformanceTiming", - "PeriodicSyncManager", - "PeriodicWave", - "PermissionStatus", - "Permissions", - "PhotoCapabilities", - "PictureInPictureWindow", - "Plugin", - "PluginArray", - "PluralRules", - "PointerEvent", - "PopStateEvent", - "PopupBlockedEvent", - "Presentation", - "PresentationAvailability", - "PresentationConnection", - "PresentationConnectionAvailableEvent", - "PresentationConnectionCloseEvent", - "PresentationConnectionList", - "PresentationReceiver", - "PresentationRequest", - "ProcessingInstruction", - "ProgressEvent", - "Promise", - "PromiseRejectionEvent", - "PropertyNodeList", - "Proxy", - "PublicKeyCredential", - "PushManager", - "PushSubscription", - "PushSubscriptionOptions", - "Q", - "QUERY_RESULT", - "QUERY_RESULT_AVAILABLE", - "QUOTA_ERR", - "QUOTA_EXCEEDED_ERR", - "QueryInterface", - "R11F_G11F_B10F", - "R16F", - "R16I", - "R16UI", - "R32F", - "R32I", - "R32UI", - "R8", - "R8I", - "R8UI", - "R8_SNORM", - "RASTERIZER_DISCARD", - "READ_BUFFER", - "READ_FRAMEBUFFER", - "READ_FRAMEBUFFER_BINDING", - "READ_ONLY", - "READ_ONLY_ERR", - "READ_WRITE", - "RED", - "RED_BITS", - "RED_INTEGER", - "REMOVAL", - "RENDERBUFFER", - "RENDERBUFFER_ALPHA_SIZE", - "RENDERBUFFER_BINDING", - "RENDERBUFFER_BLUE_SIZE", - "RENDERBUFFER_DEPTH_SIZE", - "RENDERBUFFER_GREEN_SIZE", - "RENDERBUFFER_HEIGHT", - "RENDERBUFFER_INTERNAL_FORMAT", - "RENDERBUFFER_RED_SIZE", - "RENDERBUFFER_SAMPLES", - "RENDERBUFFER_STENCIL_SIZE", - "RENDERBUFFER_WIDTH", - "RENDERER", - "RENDERING_INTENT_ABSOLUTE_COLORIMETRIC", - "RENDERING_INTENT_AUTO", - "RENDERING_INTENT_PERCEPTUAL", - "RENDERING_INTENT_RELATIVE_COLORIMETRIC", - "RENDERING_INTENT_SATURATION", - "RENDERING_INTENT_UNKNOWN", - "REPEAT", - "REPLACE", - "RG", - "RG16F", - "RG16I", - "RG16UI", - "RG32F", - "RG32I", - "RG32UI", - "RG8", - "RG8I", - "RG8UI", - "RG8_SNORM", - "RGB", - "RGB10_A2", - "RGB10_A2UI", - "RGB16F", - "RGB16I", - "RGB16UI", - "RGB32F", - "RGB32I", - "RGB32UI", - "RGB565", - "RGB5_A1", - "RGB8", - "RGB8I", - "RGB8UI", - "RGB8_SNORM", - "RGB9_E5", - "RGBA", - "RGBA16F", - "RGBA16I", - "RGBA16UI", - "RGBA32F", - "RGBA32I", - "RGBA32UI", - "RGBA4", - "RGBA8", - "RGBA8I", - "RGBA8UI", - "RGBA8_SNORM", - "RGBA_INTEGER", - "RGBColor", - "RGB_INTEGER", - "RG_INTEGER", - "ROTATION_CLOCKWISE", - "ROTATION_COUNTERCLOCKWISE", - "RTCCertificate", - "RTCDTMFSender", - "RTCDTMFToneChangeEvent", - "RTCDataChannel", - "RTCDataChannelEvent", - "RTCDtlsTransport", - "RTCError", - "RTCErrorEvent", - "RTCIceCandidate", - "RTCIceTransport", - "RTCPeerConnection", - "RTCPeerConnectionIceErrorEvent", - "RTCPeerConnectionIceEvent", - "RTCRtpReceiver", - "RTCRtpSender", - "RTCRtpTransceiver", - "RTCSctpTransport", - "RTCSessionDescription", - "RTCStatsReport", - "RTCTrackEvent", - "RadioNodeList", - "Range", - "RangeError", - "RangeException", - "ReadableStream", - "ReadableStreamDefaultReader", - "RecordErrorEvent", - "Rect", - "ReferenceError", - "Reflect", - "RegExp", - "RelativeOrientationSensor", - "RelativeTimeFormat", - "RemotePlayback", - "Report", - "ReportBody", - "ReportingObserver", - "Request", - "ResizeObserver", - "ResizeObserverEntry", - "ResizeObserverSize", - "Response", - "RuntimeError", - "SAMPLER_2D", - "SAMPLER_2D_ARRAY", - "SAMPLER_2D_ARRAY_SHADOW", - "SAMPLER_2D_SHADOW", - "SAMPLER_3D", - "SAMPLER_BINDING", - "SAMPLER_CUBE", - "SAMPLER_CUBE_SHADOW", - "SAMPLES", - "SAMPLE_ALPHA_TO_COVERAGE", - "SAMPLE_BUFFERS", - "SAMPLE_COVERAGE", - "SAMPLE_COVERAGE_INVERT", - "SAMPLE_COVERAGE_VALUE", - "SAWTOOTH", - "SCHEDULED_STATE", - "SCISSOR_BOX", - "SCISSOR_TEST", - "SCROLL_PAGE_DOWN", - "SCROLL_PAGE_UP", - "SDP_ANSWER", - "SDP_OFFER", - "SDP_PRANSWER", - "SECURITY_ERR", - "SELECT", - "SEPARATE_ATTRIBS", - "SERIALIZE_ERR", - "SEVERITY_ERROR", - "SEVERITY_FATAL_ERROR", - "SEVERITY_WARNING", - "SHADER_COMPILER", - "SHADER_TYPE", - "SHADING_LANGUAGE_VERSION", - "SHIFT_MASK", - "SHORT", - "SHOWING", - "SHOW_ALL", - "SHOW_ATTRIBUTE", - "SHOW_CDATA_SECTION", - "SHOW_COMMENT", - "SHOW_DOCUMENT", - "SHOW_DOCUMENT_FRAGMENT", - "SHOW_DOCUMENT_TYPE", - "SHOW_ELEMENT", - "SHOW_ENTITY", - "SHOW_ENTITY_REFERENCE", - "SHOW_NOTATION", - "SHOW_PROCESSING_INSTRUCTION", - "SHOW_TEXT", - "SIGNALED", - "SIGNED_NORMALIZED", - "SINE", - "SOUNDFIELD", - "SQLException", - "SQRT1_2", - "SQRT2", - "SQUARE", - "SRC_ALPHA", - "SRC_ALPHA_SATURATE", - "SRC_COLOR", - "SRGB", - "SRGB8", - "SRGB8_ALPHA8", - "START_TO_END", - "START_TO_START", - "STATIC_COPY", - "STATIC_DRAW", - "STATIC_READ", - "STENCIL", - "STENCIL_ATTACHMENT", - "STENCIL_BACK_FAIL", - "STENCIL_BACK_FUNC", - "STENCIL_BACK_PASS_DEPTH_FAIL", - "STENCIL_BACK_PASS_DEPTH_PASS", - "STENCIL_BACK_REF", - "STENCIL_BACK_VALUE_MASK", - "STENCIL_BACK_WRITEMASK", - "STENCIL_BITS", - "STENCIL_BUFFER_BIT", - "STENCIL_CLEAR_VALUE", - "STENCIL_FAIL", - "STENCIL_FUNC", - "STENCIL_INDEX", - "STENCIL_INDEX8", - "STENCIL_PASS_DEPTH_FAIL", - "STENCIL_PASS_DEPTH_PASS", - "STENCIL_REF", - "STENCIL_TEST", - "STENCIL_VALUE_MASK", - "STENCIL_WRITEMASK", - "STREAM_COPY", - "STREAM_DRAW", - "STREAM_READ", - "STRING_TYPE", - "STYLE_RULE", - "SUBPIXEL_BITS", - "SUPPORTS_RULE", - "SVGAElement", - "SVGAltGlyphDefElement", - "SVGAltGlyphElement", - "SVGAltGlyphItemElement", - "SVGAngle", - "SVGAnimateColorElement", - "SVGAnimateElement", - "SVGAnimateMotionElement", - "SVGAnimateTransformElement", - "SVGAnimatedAngle", - "SVGAnimatedBoolean", - "SVGAnimatedEnumeration", - "SVGAnimatedInteger", - "SVGAnimatedLength", - "SVGAnimatedLengthList", - "SVGAnimatedNumber", - "SVGAnimatedNumberList", - "SVGAnimatedPreserveAspectRatio", - "SVGAnimatedRect", - "SVGAnimatedString", - "SVGAnimatedTransformList", - "SVGAnimationElement", - "SVGCircleElement", - "SVGClipPathElement", - "SVGColor", - "SVGComponentTransferFunctionElement", - "SVGCursorElement", - "SVGDefsElement", - "SVGDescElement", - "SVGDiscardElement", - "SVGDocument", - "SVGElement", - "SVGElementInstance", - "SVGElementInstanceList", - "SVGEllipseElement", - "SVGException", - "SVGFEBlendElement", - "SVGFEColorMatrixElement", - "SVGFEComponentTransferElement", - "SVGFECompositeElement", - "SVGFEConvolveMatrixElement", - "SVGFEDiffuseLightingElement", - "SVGFEDisplacementMapElement", - "SVGFEDistantLightElement", - "SVGFEDropShadowElement", - "SVGFEFloodElement", - "SVGFEFuncAElement", - "SVGFEFuncBElement", - "SVGFEFuncGElement", - "SVGFEFuncRElement", - "SVGFEGaussianBlurElement", - "SVGFEImageElement", - "SVGFEMergeElement", - "SVGFEMergeNodeElement", - "SVGFEMorphologyElement", - "SVGFEOffsetElement", - "SVGFEPointLightElement", - "SVGFESpecularLightingElement", - "SVGFESpotLightElement", - "SVGFETileElement", - "SVGFETurbulenceElement", - "SVGFilterElement", - "SVGFontElement", - "SVGFontFaceElement", - "SVGFontFaceFormatElement", - "SVGFontFaceNameElement", - "SVGFontFaceSrcElement", - "SVGFontFaceUriElement", - "SVGForeignObjectElement", - "SVGGElement", - "SVGGeometryElement", - "SVGGlyphElement", - "SVGGlyphRefElement", - "SVGGradientElement", - "SVGGraphicsElement", - "SVGHKernElement", - "SVGImageElement", - "SVGLength", - "SVGLengthList", - "SVGLineElement", - "SVGLinearGradientElement", - "SVGMPathElement", - "SVGMarkerElement", - "SVGMaskElement", - "SVGMatrix", - "SVGMetadataElement", - "SVGMissingGlyphElement", - "SVGNumber", - "SVGNumberList", - "SVGPaint", - "SVGPathElement", - "SVGPathSeg", - "SVGPathSegArcAbs", - "SVGPathSegArcRel", - "SVGPathSegClosePath", - "SVGPathSegCurvetoCubicAbs", - "SVGPathSegCurvetoCubicRel", - "SVGPathSegCurvetoCubicSmoothAbs", - "SVGPathSegCurvetoCubicSmoothRel", - "SVGPathSegCurvetoQuadraticAbs", - "SVGPathSegCurvetoQuadraticRel", - "SVGPathSegCurvetoQuadraticSmoothAbs", - "SVGPathSegCurvetoQuadraticSmoothRel", - "SVGPathSegLinetoAbs", - "SVGPathSegLinetoHorizontalAbs", - "SVGPathSegLinetoHorizontalRel", - "SVGPathSegLinetoRel", - "SVGPathSegLinetoVerticalAbs", - "SVGPathSegLinetoVerticalRel", - "SVGPathSegList", - "SVGPathSegMovetoAbs", - "SVGPathSegMovetoRel", - "SVGPatternElement", - "SVGPoint", - "SVGPointList", - "SVGPolygonElement", - "SVGPolylineElement", - "SVGPreserveAspectRatio", - "SVGRadialGradientElement", - "SVGRect", - "SVGRectElement", - "SVGRenderingIntent", - "SVGSVGElement", - "SVGScriptElement", - "SVGSetElement", - "SVGStopElement", - "SVGStringList", - "SVGStyleElement", - "SVGSwitchElement", - "SVGSymbolElement", - "SVGTRefElement", - "SVGTSpanElement", - "SVGTextContentElement", - "SVGTextElement", - "SVGTextPathElement", - "SVGTextPositioningElement", - "SVGTitleElement", - "SVGTransform", - "SVGTransformList", - "SVGUnitTypes", - "SVGUseElement", - "SVGVKernElement", - "SVGViewElement", - "SVGViewSpec", - "SVGZoomAndPan", - "SVGZoomEvent", - "SVG_ANGLETYPE_DEG", - "SVG_ANGLETYPE_GRAD", - "SVG_ANGLETYPE_RAD", - "SVG_ANGLETYPE_UNKNOWN", - "SVG_ANGLETYPE_UNSPECIFIED", - "SVG_CHANNEL_A", - "SVG_CHANNEL_B", - "SVG_CHANNEL_G", - "SVG_CHANNEL_R", - "SVG_CHANNEL_UNKNOWN", - "SVG_COLORTYPE_CURRENTCOLOR", - "SVG_COLORTYPE_RGBCOLOR", - "SVG_COLORTYPE_RGBCOLOR_ICCCOLOR", - "SVG_COLORTYPE_UNKNOWN", - "SVG_EDGEMODE_DUPLICATE", - "SVG_EDGEMODE_NONE", - "SVG_EDGEMODE_UNKNOWN", - "SVG_EDGEMODE_WRAP", - "SVG_FEBLEND_MODE_COLOR", - "SVG_FEBLEND_MODE_COLOR_BURN", - "SVG_FEBLEND_MODE_COLOR_DODGE", - "SVG_FEBLEND_MODE_DARKEN", - "SVG_FEBLEND_MODE_DIFFERENCE", - "SVG_FEBLEND_MODE_EXCLUSION", - "SVG_FEBLEND_MODE_HARD_LIGHT", - "SVG_FEBLEND_MODE_HUE", - "SVG_FEBLEND_MODE_LIGHTEN", - "SVG_FEBLEND_MODE_LUMINOSITY", - "SVG_FEBLEND_MODE_MULTIPLY", - "SVG_FEBLEND_MODE_NORMAL", - "SVG_FEBLEND_MODE_OVERLAY", - "SVG_FEBLEND_MODE_SATURATION", - "SVG_FEBLEND_MODE_SCREEN", - "SVG_FEBLEND_MODE_SOFT_LIGHT", - "SVG_FEBLEND_MODE_UNKNOWN", - "SVG_FECOLORMATRIX_TYPE_HUEROTATE", - "SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA", - "SVG_FECOLORMATRIX_TYPE_MATRIX", - "SVG_FECOLORMATRIX_TYPE_SATURATE", - "SVG_FECOLORMATRIX_TYPE_UNKNOWN", - "SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE", - "SVG_FECOMPONENTTRANSFER_TYPE_GAMMA", - "SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY", - "SVG_FECOMPONENTTRANSFER_TYPE_LINEAR", - "SVG_FECOMPONENTTRANSFER_TYPE_TABLE", - "SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN", - "SVG_FECOMPOSITE_OPERATOR_ARITHMETIC", - "SVG_FECOMPOSITE_OPERATOR_ATOP", - "SVG_FECOMPOSITE_OPERATOR_IN", - "SVG_FECOMPOSITE_OPERATOR_OUT", - "SVG_FECOMPOSITE_OPERATOR_OVER", - "SVG_FECOMPOSITE_OPERATOR_UNKNOWN", - "SVG_FECOMPOSITE_OPERATOR_XOR", - "SVG_INVALID_VALUE_ERR", - "SVG_LENGTHTYPE_CM", - "SVG_LENGTHTYPE_EMS", - "SVG_LENGTHTYPE_EXS", - "SVG_LENGTHTYPE_IN", - "SVG_LENGTHTYPE_MM", - "SVG_LENGTHTYPE_NUMBER", - "SVG_LENGTHTYPE_PC", - "SVG_LENGTHTYPE_PERCENTAGE", - "SVG_LENGTHTYPE_PT", - "SVG_LENGTHTYPE_PX", - "SVG_LENGTHTYPE_UNKNOWN", - "SVG_MARKERUNITS_STROKEWIDTH", - "SVG_MARKERUNITS_UNKNOWN", - "SVG_MARKERUNITS_USERSPACEONUSE", - "SVG_MARKER_ORIENT_ANGLE", - "SVG_MARKER_ORIENT_AUTO", - "SVG_MARKER_ORIENT_UNKNOWN", - "SVG_MASKTYPE_ALPHA", - "SVG_MASKTYPE_LUMINANCE", - "SVG_MATRIX_NOT_INVERTABLE", - "SVG_MEETORSLICE_MEET", - "SVG_MEETORSLICE_SLICE", - "SVG_MEETORSLICE_UNKNOWN", - "SVG_MORPHOLOGY_OPERATOR_DILATE", - "SVG_MORPHOLOGY_OPERATOR_ERODE", - "SVG_MORPHOLOGY_OPERATOR_UNKNOWN", - "SVG_PAINTTYPE_CURRENTCOLOR", - "SVG_PAINTTYPE_NONE", - "SVG_PAINTTYPE_RGBCOLOR", - "SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR", - "SVG_PAINTTYPE_UNKNOWN", - "SVG_PAINTTYPE_URI", - "SVG_PAINTTYPE_URI_CURRENTCOLOR", - "SVG_PAINTTYPE_URI_NONE", - "SVG_PAINTTYPE_URI_RGBCOLOR", - "SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR", - "SVG_PRESERVEASPECTRATIO_NONE", - "SVG_PRESERVEASPECTRATIO_UNKNOWN", - "SVG_PRESERVEASPECTRATIO_XMAXYMAX", - "SVG_PRESERVEASPECTRATIO_XMAXYMID", - "SVG_PRESERVEASPECTRATIO_XMAXYMIN", - "SVG_PRESERVEASPECTRATIO_XMIDYMAX", - "SVG_PRESERVEASPECTRATIO_XMIDYMID", - "SVG_PRESERVEASPECTRATIO_XMIDYMIN", - "SVG_PRESERVEASPECTRATIO_XMINYMAX", - "SVG_PRESERVEASPECTRATIO_XMINYMID", - "SVG_PRESERVEASPECTRATIO_XMINYMIN", - "SVG_SPREADMETHOD_PAD", - "SVG_SPREADMETHOD_REFLECT", - "SVG_SPREADMETHOD_REPEAT", - "SVG_SPREADMETHOD_UNKNOWN", - "SVG_STITCHTYPE_NOSTITCH", - "SVG_STITCHTYPE_STITCH", - "SVG_STITCHTYPE_UNKNOWN", - "SVG_TRANSFORM_MATRIX", - "SVG_TRANSFORM_ROTATE", - "SVG_TRANSFORM_SCALE", - "SVG_TRANSFORM_SKEWX", - "SVG_TRANSFORM_SKEWY", - "SVG_TRANSFORM_TRANSLATE", - "SVG_TRANSFORM_UNKNOWN", - "SVG_TURBULENCE_TYPE_FRACTALNOISE", - "SVG_TURBULENCE_TYPE_TURBULENCE", - "SVG_TURBULENCE_TYPE_UNKNOWN", - "SVG_UNIT_TYPE_OBJECTBOUNDINGBOX", - "SVG_UNIT_TYPE_UNKNOWN", - "SVG_UNIT_TYPE_USERSPACEONUSE", - "SVG_WRONG_TYPE_ERR", - "SVG_ZOOMANDPAN_DISABLE", - "SVG_ZOOMANDPAN_MAGNIFY", - "SVG_ZOOMANDPAN_UNKNOWN", - "SYNC_CONDITION", - "SYNC_FENCE", - "SYNC_FLAGS", - "SYNC_FLUSH_COMMANDS_BIT", - "SYNC_GPU_COMMANDS_COMPLETE", - "SYNC_STATUS", - "SYNTAX_ERR", - "SavedPages", - "Screen", - "ScreenOrientation", - "Script", - "ScriptProcessorNode", - "ScrollAreaEvent", - "SecurityPolicyViolationEvent", - "Selection", - "Sensor", - "SensorErrorEvent", - "ServiceWorker", - "ServiceWorkerContainer", - "ServiceWorkerRegistration", - "SessionDescription", - "Set", - "ShadowRoot", - "SharedArrayBuffer", - "SharedWorker", - "SimpleGestureEvent", - "SourceBuffer", - "SourceBufferList", - "SpeechSynthesis", - "SpeechSynthesisErrorEvent", - "SpeechSynthesisEvent", - "SpeechSynthesisUtterance", - "SpeechSynthesisVoice", - "StaticRange", - "StereoPannerNode", - "StopIteration", - "Storage", - "StorageEvent", - "StorageManager", - "String", - "StructType", - "StylePropertyMap", - "StylePropertyMapReadOnly", - "StyleSheet", - "StyleSheetList", - "SubmitEvent", - "SubtleCrypto", - "Symbol", - "SyncManager", - "SyntaxError", - "TEMPORARY", - "TEXTPATH_METHODTYPE_ALIGN", - "TEXTPATH_METHODTYPE_STRETCH", - "TEXTPATH_METHODTYPE_UNKNOWN", - "TEXTPATH_SPACINGTYPE_AUTO", - "TEXTPATH_SPACINGTYPE_EXACT", - "TEXTPATH_SPACINGTYPE_UNKNOWN", - "TEXTURE", - "TEXTURE0", - "TEXTURE1", - "TEXTURE10", - "TEXTURE11", - "TEXTURE12", - "TEXTURE13", - "TEXTURE14", - "TEXTURE15", - "TEXTURE16", - "TEXTURE17", - "TEXTURE18", - "TEXTURE19", - "TEXTURE2", - "TEXTURE20", - "TEXTURE21", - "TEXTURE22", - "TEXTURE23", - "TEXTURE24", - "TEXTURE25", - "TEXTURE26", - "TEXTURE27", - "TEXTURE28", - "TEXTURE29", - "TEXTURE3", - "TEXTURE30", - "TEXTURE31", - "TEXTURE4", - "TEXTURE5", - "TEXTURE6", - "TEXTURE7", - "TEXTURE8", - "TEXTURE9", - "TEXTURE_2D", - "TEXTURE_2D_ARRAY", - "TEXTURE_3D", - "TEXTURE_BASE_LEVEL", - "TEXTURE_BINDING_2D", - "TEXTURE_BINDING_2D_ARRAY", - "TEXTURE_BINDING_3D", - "TEXTURE_BINDING_CUBE_MAP", - "TEXTURE_COMPARE_FUNC", - "TEXTURE_COMPARE_MODE", - "TEXTURE_CUBE_MAP", - "TEXTURE_CUBE_MAP_NEGATIVE_X", - "TEXTURE_CUBE_MAP_NEGATIVE_Y", - "TEXTURE_CUBE_MAP_NEGATIVE_Z", - "TEXTURE_CUBE_MAP_POSITIVE_X", - "TEXTURE_CUBE_MAP_POSITIVE_Y", - "TEXTURE_CUBE_MAP_POSITIVE_Z", - "TEXTURE_IMMUTABLE_FORMAT", - "TEXTURE_IMMUTABLE_LEVELS", - "TEXTURE_MAG_FILTER", - "TEXTURE_MAX_ANISOTROPY_EXT", - "TEXTURE_MAX_LEVEL", - "TEXTURE_MAX_LOD", - "TEXTURE_MIN_FILTER", - "TEXTURE_MIN_LOD", - "TEXTURE_WRAP_R", - "TEXTURE_WRAP_S", - "TEXTURE_WRAP_T", - "TEXT_NODE", - "TIMEOUT", - "TIMEOUT_ERR", - "TIMEOUT_EXPIRED", - "TIMEOUT_IGNORED", - "TOO_LARGE_ERR", - "TRANSACTION_INACTIVE_ERR", - "TRANSFORM_FEEDBACK", - "TRANSFORM_FEEDBACK_ACTIVE", - "TRANSFORM_FEEDBACK_BINDING", - "TRANSFORM_FEEDBACK_BUFFER", - "TRANSFORM_FEEDBACK_BUFFER_BINDING", - "TRANSFORM_FEEDBACK_BUFFER_MODE", - "TRANSFORM_FEEDBACK_BUFFER_SIZE", - "TRANSFORM_FEEDBACK_BUFFER_START", - "TRANSFORM_FEEDBACK_PAUSED", - "TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN", - "TRANSFORM_FEEDBACK_VARYINGS", - "TRIANGLE", - "TRIANGLES", - "TRIANGLE_FAN", - "TRIANGLE_STRIP", - "TYPE_BACK_FORWARD", - "TYPE_ERR", - "TYPE_MISMATCH_ERR", - "TYPE_NAVIGATE", - "TYPE_RELOAD", - "TYPE_RESERVED", - "Table", - "TaskAttributionTiming", - "Text", - "TextDecoder", - "TextDecoderStream", - "TextEncoder", - "TextEncoderStream", - "TextEvent", - "TextMetrics", - "TextTrack", - "TextTrackCue", - "TextTrackCueList", - "TextTrackList", - "TimeEvent", - "TimeRanges", - "Touch", - "TouchEvent", - "TouchList", - "TrackEvent", - "TransformStream", - "TransitionEvent", - "TreeWalker", - "TrustedHTML", - "TrustedScript", - "TrustedScriptURL", - "TrustedTypePolicy", - "TrustedTypePolicyFactory", - "TypeError", - "TypedObject", - "U2F", - "UIEvent", - "UNCACHED", - "UNIFORM_ARRAY_STRIDE", - "UNIFORM_BLOCK_ACTIVE_UNIFORMS", - "UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES", - "UNIFORM_BLOCK_BINDING", - "UNIFORM_BLOCK_DATA_SIZE", - "UNIFORM_BLOCK_INDEX", - "UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER", - "UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER", - "UNIFORM_BUFFER", - "UNIFORM_BUFFER_BINDING", - "UNIFORM_BUFFER_OFFSET_ALIGNMENT", - "UNIFORM_BUFFER_SIZE", - "UNIFORM_BUFFER_START", - "UNIFORM_IS_ROW_MAJOR", - "UNIFORM_MATRIX_STRIDE", - "UNIFORM_OFFSET", - "UNIFORM_SIZE", - "UNIFORM_TYPE", - "UNKNOWN_ERR", - "UNKNOWN_RULE", - "UNMASKED_RENDERER_WEBGL", - "UNMASKED_VENDOR_WEBGL", - "UNORDERED_NODE_ITERATOR_TYPE", - "UNORDERED_NODE_SNAPSHOT_TYPE", - "UNPACK_ALIGNMENT", - "UNPACK_COLORSPACE_CONVERSION_WEBGL", - "UNPACK_FLIP_Y_WEBGL", - "UNPACK_IMAGE_HEIGHT", - "UNPACK_PREMULTIPLY_ALPHA_WEBGL", - "UNPACK_ROW_LENGTH", - "UNPACK_SKIP_IMAGES", - "UNPACK_SKIP_PIXELS", - "UNPACK_SKIP_ROWS", - "UNSCHEDULED_STATE", - "UNSENT", - "UNSIGNALED", - "UNSIGNED_BYTE", - "UNSIGNED_INT", - "UNSIGNED_INT_10F_11F_11F_REV", - "UNSIGNED_INT_24_8", - "UNSIGNED_INT_2_10_10_10_REV", - "UNSIGNED_INT_5_9_9_9_REV", - "UNSIGNED_INT_SAMPLER_2D", - "UNSIGNED_INT_SAMPLER_2D_ARRAY", - "UNSIGNED_INT_SAMPLER_3D", - "UNSIGNED_INT_SAMPLER_CUBE", - "UNSIGNED_INT_VEC2", - "UNSIGNED_INT_VEC3", - "UNSIGNED_INT_VEC4", - "UNSIGNED_NORMALIZED", - "UNSIGNED_SHORT", - "UNSIGNED_SHORT_4_4_4_4", - "UNSIGNED_SHORT_5_5_5_1", - "UNSIGNED_SHORT_5_6_5", - "UNSPECIFIED_EVENT_TYPE_ERR", - "UPDATEREADY", - "URIError", - "URL", - "URLSearchParams", - "URLUnencoded", - "URL_MISMATCH_ERR", - "USB", - "USBAlternateInterface", - "USBConfiguration", - "USBConnectionEvent", - "USBDevice", - "USBEndpoint", - "USBInTransferResult", - "USBInterface", - "USBIsochronousInTransferPacket", - "USBIsochronousInTransferResult", - "USBIsochronousOutTransferPacket", - "USBIsochronousOutTransferResult", - "USBOutTransferResult", - "UTC", - "Uint16Array", - "Uint32Array", - "Uint8Array", - "Uint8ClampedArray", - "UserActivation", - "UserMessageHandler", - "UserMessageHandlersNamespace", - "UserProximityEvent", - "VALIDATE_STATUS", - "VALIDATION_ERR", - "VARIABLES_RULE", - "VENDOR", - "VERSION", - "VERSION_CHANGE", - "VERSION_ERR", - "VERTEX_ARRAY_BINDING", - "VERTEX_ATTRIB_ARRAY_BUFFER_BINDING", - "VERTEX_ATTRIB_ARRAY_DIVISOR", - "VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE", - "VERTEX_ATTRIB_ARRAY_ENABLED", - "VERTEX_ATTRIB_ARRAY_INTEGER", - "VERTEX_ATTRIB_ARRAY_NORMALIZED", - "VERTEX_ATTRIB_ARRAY_POINTER", - "VERTEX_ATTRIB_ARRAY_SIZE", - "VERTEX_ATTRIB_ARRAY_STRIDE", - "VERTEX_ATTRIB_ARRAY_TYPE", - "VERTEX_SHADER", - "VERTICAL", - "VERTICAL_AXIS", - "VER_ERR", - "VIEWPORT", - "VIEWPORT_RULE", - "VRDisplay", - "VRDisplayCapabilities", - "VRDisplayEvent", - "VREyeParameters", - "VRFieldOfView", - "VRFrameData", - "VRPose", - "VRStageParameters", - "VTTCue", - "VTTRegion", - "ValidityState", - "VideoPlaybackQuality", - "VideoStreamTrack", - "VisualViewport", - "WAIT_FAILED", - "WEBKIT_FILTER_RULE", - "WEBKIT_KEYFRAMES_RULE", - "WEBKIT_KEYFRAME_RULE", - "WEBKIT_REGION_RULE", - "WRONG_DOCUMENT_ERR", - "WakeLock", - "WakeLockSentinel", - "WasmAnyRef", - "WaveShaperNode", - "WeakMap", - "WeakRef", - "WeakSet", - "WebAssembly", - "WebGL2RenderingContext", - "WebGLActiveInfo", - "WebGLBuffer", - "WebGLContextEvent", - "WebGLFramebuffer", - "WebGLProgram", - "WebGLQuery", - "WebGLRenderbuffer", - "WebGLRenderingContext", - "WebGLSampler", - "WebGLShader", - "WebGLShaderPrecisionFormat", - "WebGLSync", - "WebGLTexture", - "WebGLTransformFeedback", - "WebGLUniformLocation", - "WebGLVertexArray", - "WebGLVertexArrayObject", - "WebKitAnimationEvent", - "WebKitBlobBuilder", - "WebKitCSSFilterRule", - "WebKitCSSFilterValue", - "WebKitCSSKeyframeRule", - "WebKitCSSKeyframesRule", - "WebKitCSSMatrix", - "WebKitCSSRegionRule", - "WebKitCSSTransformValue", - "WebKitDataCue", - "WebKitGamepad", - "WebKitMediaKeyError", - "WebKitMediaKeyMessageEvent", - "WebKitMediaKeySession", - "WebKitMediaKeys", - "WebKitMediaSource", - "WebKitMutationObserver", - "WebKitNamespace", - "WebKitPlaybackTargetAvailabilityEvent", - "WebKitPoint", - "WebKitShadowRoot", - "WebKitSourceBuffer", - "WebKitSourceBufferList", - "WebKitTransitionEvent", - "WebSocket", - "WebkitAlignContent", - "WebkitAlignItems", - "WebkitAlignSelf", - "WebkitAnimation", - "WebkitAnimationDelay", - "WebkitAnimationDirection", - "WebkitAnimationDuration", - "WebkitAnimationFillMode", - "WebkitAnimationIterationCount", - "WebkitAnimationName", - "WebkitAnimationPlayState", - "WebkitAnimationTimingFunction", - "WebkitAppearance", - "WebkitBackfaceVisibility", - "WebkitBackgroundClip", - "WebkitBackgroundOrigin", - "WebkitBackgroundSize", - "WebkitBorderBottomLeftRadius", - "WebkitBorderBottomRightRadius", - "WebkitBorderImage", - "WebkitBorderRadius", - "WebkitBorderTopLeftRadius", - "WebkitBorderTopRightRadius", - "WebkitBoxAlign", - "WebkitBoxDirection", - "WebkitBoxFlex", - "WebkitBoxOrdinalGroup", - "WebkitBoxOrient", - "WebkitBoxPack", - "WebkitBoxShadow", - "WebkitBoxSizing", - "WebkitFilter", - "WebkitFlex", - "WebkitFlexBasis", - "WebkitFlexDirection", - "WebkitFlexFlow", - "WebkitFlexGrow", - "WebkitFlexShrink", - "WebkitFlexWrap", - "WebkitJustifyContent", - "WebkitLineClamp", - "WebkitMask", - "WebkitMaskClip", - "WebkitMaskComposite", - "WebkitMaskImage", - "WebkitMaskOrigin", - "WebkitMaskPosition", - "WebkitMaskPositionX", - "WebkitMaskPositionY", - "WebkitMaskRepeat", - "WebkitMaskSize", - "WebkitOrder", - "WebkitPerspective", - "WebkitPerspectiveOrigin", - "WebkitTextFillColor", - "WebkitTextSizeAdjust", - "WebkitTextStroke", - "WebkitTextStrokeColor", - "WebkitTextStrokeWidth", - "WebkitTransform", - "WebkitTransformOrigin", - "WebkitTransformStyle", - "WebkitTransition", - "WebkitTransitionDelay", - "WebkitTransitionDuration", - "WebkitTransitionProperty", - "WebkitTransitionTimingFunction", - "WebkitUserSelect", - "WheelEvent", - "Window", - "Worker", - "Worklet", - "WritableStream", - "WritableStreamDefaultWriter", - "XMLDocument", - "XMLHttpRequest", - "XMLHttpRequestEventTarget", - "XMLHttpRequestException", - "XMLHttpRequestProgressEvent", - "XMLHttpRequestUpload", - "XMLSerializer", - "XMLStylesheetProcessingInstruction", - "XPathEvaluator", - "XPathException", - "XPathExpression", - "XPathNSResolver", - "XPathResult", - "XRBoundedReferenceSpace", - "XRDOMOverlayState", - "XRFrame", - "XRHitTestResult", - "XRHitTestSource", - "XRInputSource", - "XRInputSourceArray", - "XRInputSourceEvent", - "XRInputSourcesChangeEvent", - "XRLayer", - "XRPose", - "XRRay", - "XRReferenceSpace", - "XRReferenceSpaceEvent", - "XRRenderState", - "XRRigidTransform", - "XRSession", - "XRSessionEvent", - "XRSpace", - "XRSystem", - "XRTransientInputHitTestResult", - "XRTransientInputHitTestSource", - "XRView", - "XRViewerPose", - "XRViewport", - "XRWebGLLayer", - "XSLTProcessor", - "ZERO", - "_XD0M_", - "_YD0M_", - "__defineGetter__", - "__defineSetter__", - "__lookupGetter__", - "__lookupSetter__", - "__opera", - "__proto__", - "_browserjsran", - "a", - "aLink", - "abbr", - "abort", - "aborted", - "abs", - "absolute", - "acceleration", - "accelerationIncludingGravity", - "accelerator", - "accept", - "acceptCharset", - "acceptNode", - "accessKey", - "accessKeyLabel", - "accuracy", - "acos", - "acosh", - "action", - "actionURL", - "actions", - "activated", - "active", - "activeCues", - "activeElement", - "activeSourceBuffers", - "activeSourceCount", - "activeTexture", - "activeVRDisplays", - "actualBoundingBoxAscent", - "actualBoundingBoxDescent", - "actualBoundingBoxLeft", - "actualBoundingBoxRight", - "add", - "addAll", - "addBehavior", - "addCandidate", - "addColorStop", - "addCue", - "addElement", - "addEventListener", - "addFilter", - "addFromString", - "addFromUri", - "addIceCandidate", - "addImport", - "addListener", - "addModule", - "addNamed", - "addPageRule", - "addPath", - "addPointer", - "addRange", - "addRegion", - "addRule", - "addSearchEngine", - "addSourceBuffer", - "addStream", - "addTextTrack", - "addTrack", - "addTransceiver", - "addWakeLockListener", - "added", - "addedNodes", - "additionalName", - "additiveSymbols", - "addons", - "address", - "addressLine", - "adoptNode", - "adoptedStyleSheets", - "adr", - "advance", - "after", - "album", - "alert", - "algorithm", - "align", - "align-content", - "align-items", - "align-self", - "alignContent", - "alignItems", - "alignSelf", - "alignmentBaseline", - "alinkColor", - "all", - "allSettled", - "allow", - "allowFullscreen", - "allowPaymentRequest", - "allowedDirections", - "allowedFeatures", - "allowedToPlay", - "allowsFeature", - "alpha", - "alt", - "altGraphKey", - "altHtml", - "altKey", - "altLeft", - "alternate", - "alternateSetting", - "alternates", - "altitude", - "altitudeAccuracy", - "amplitude", - "ancestorOrigins", - "anchor", - "anchorNode", - "anchorOffset", - "anchors", - "and", - "angle", - "angularAcceleration", - "angularVelocity", - "animVal", - "animate", - "animatedInstanceRoot", - "animatedNormalizedPathSegList", - "animatedPathSegList", - "animatedPoints", - "animation", - "animation-delay", - "animation-direction", - "animation-duration", - "animation-fill-mode", - "animation-iteration-count", - "animation-name", - "animation-play-state", - "animation-timing-function", - "animationDelay", - "animationDirection", - "animationDuration", - "animationFillMode", - "animationIterationCount", - "animationName", - "animationPlayState", - "animationStartTime", - "animationTimingFunction", - "animationsPaused", - "anniversary", - "antialias", - "anticipatedRemoval", - "any", - "app", - "appCodeName", - "appMinorVersion", - "appName", - "appNotifications", - "appVersion", - "appearance", - "append", - "appendBuffer", - "appendChild", - "appendData", - "appendItem", - "appendMedium", - "appendNamed", - "appendRule", - "appendStream", - "appendWindowEnd", - "appendWindowStart", - "applets", - "applicationCache", - "applicationServerKey", - "apply", - "applyConstraints", - "applyElement", - "arc", - "arcTo", - "archive", - "areas", - "arguments", - "ariaAtomic", - "ariaAutoComplete", - "ariaBusy", - "ariaChecked", - "ariaColCount", - "ariaColIndex", - "ariaColSpan", - "ariaCurrent", - "ariaDescription", - "ariaDisabled", - "ariaExpanded", - "ariaHasPopup", - "ariaHidden", - "ariaKeyShortcuts", - "ariaLabel", - "ariaLevel", - "ariaLive", - "ariaModal", - "ariaMultiLine", - "ariaMultiSelectable", - "ariaOrientation", - "ariaPlaceholder", - "ariaPosInSet", - "ariaPressed", - "ariaReadOnly", - "ariaRelevant", - "ariaRequired", - "ariaRoleDescription", - "ariaRowCount", - "ariaRowIndex", - "ariaRowSpan", - "ariaSelected", - "ariaSetSize", - "ariaSort", - "ariaValueMax", - "ariaValueMin", - "ariaValueNow", - "ariaValueText", - "arrayBuffer", - "artist", - "artwork", - "as", - "asIntN", - "asUintN", - "asin", - "asinh", - "assert", - "assign", - "assignedElements", - "assignedNodes", - "assignedSlot", - "async", - "asyncIterator", - "atEnd", - "atan", - "atan2", - "atanh", - "atob", - "attachEvent", - "attachInternals", - "attachShader", - "attachShadow", - "attachments", - "attack", - "attestationObject", - "attrChange", - "attrName", - "attributeFilter", - "attributeName", - "attributeNamespace", - "attributeOldValue", - "attributeStyleMap", - "attributes", - "attribution", - "audioBitsPerSecond", - "audioTracks", - "audioWorklet", - "authenticatedSignedWrites", - "authenticatorData", - "autoIncrement", - "autobuffer", - "autocapitalize", - "autocomplete", - "autocorrect", - "autofocus", - "automationRate", - "autoplay", - "availHeight", - "availLeft", - "availTop", - "availWidth", - "availability", - "available", - "aversion", - "ax", - "axes", - "axis", - "ay", - "azimuth", - "b", - "back", - "backface-visibility", - "backfaceVisibility", - "background", - "background-attachment", - "background-blend-mode", - "background-clip", - "background-color", - "background-image", - "background-origin", - "background-position", - "background-position-x", - "background-position-y", - "background-repeat", - "background-size", - "backgroundAttachment", - "backgroundBlendMode", - "backgroundClip", - "backgroundColor", - "backgroundFetch", - "backgroundImage", - "backgroundOrigin", - "backgroundPosition", - "backgroundPositionX", - "backgroundPositionY", - "backgroundRepeat", - "backgroundSize", - "badInput", - "badge", - "balance", - "baseFrequencyX", - "baseFrequencyY", - "baseLatency", - "baseLayer", - "baseNode", - "baseOffset", - "baseURI", - "baseVal", - "baselineShift", - "battery", - "bday", - "before", - "beginElement", - "beginElementAt", - "beginPath", - "beginQuery", - "beginTransformFeedback", - "behavior", - "behaviorCookie", - "behaviorPart", - "behaviorUrns", - "beta", - "bezierCurveTo", - "bgColor", - "bgProperties", - "bias", - "big", - "bigint64", - "biguint64", - "binaryType", - "bind", - "bindAttribLocation", - "bindBuffer", - "bindBufferBase", - "bindBufferRange", - "bindFramebuffer", - "bindRenderbuffer", - "bindSampler", - "bindTexture", - "bindTransformFeedback", - "bindVertexArray", - "blendColor", - "blendEquation", - "blendEquationSeparate", - "blendFunc", - "blendFuncSeparate", - "blink", - "blitFramebuffer", - "blob", - "block-size", - "blockDirection", - "blockSize", - "blockedURI", - "blue", - "bluetooth", - "blur", - "body", - "bodyUsed", - "bold", - "bookmarks", - "booleanValue", - "border", - "border-block", - "border-block-color", - "border-block-end", - "border-block-end-color", - "border-block-end-style", - "border-block-end-width", - "border-block-start", - "border-block-start-color", - "border-block-start-style", - "border-block-start-width", - "border-block-style", - "border-block-width", - "border-bottom", - "border-bottom-color", - "border-bottom-left-radius", - "border-bottom-right-radius", - "border-bottom-style", - "border-bottom-width", - "border-collapse", - "border-color", - "border-end-end-radius", - "border-end-start-radius", - "border-image", - "border-image-outset", - "border-image-repeat", - "border-image-slice", - "border-image-source", - "border-image-width", - "border-inline", - "border-inline-color", - "border-inline-end", - "border-inline-end-color", - "border-inline-end-style", - "border-inline-end-width", - "border-inline-start", - "border-inline-start-color", - "border-inline-start-style", - "border-inline-start-width", - "border-inline-style", - "border-inline-width", - "border-left", - "border-left-color", - "border-left-style", - "border-left-width", - "border-radius", - "border-right", - "border-right-color", - "border-right-style", - "border-right-width", - "border-spacing", - "border-start-end-radius", - "border-start-start-radius", - "border-style", - "border-top", - "border-top-color", - "border-top-left-radius", - "border-top-right-radius", - "border-top-style", - "border-top-width", - "border-width", - "borderBlock", - "borderBlockColor", - "borderBlockEnd", - "borderBlockEndColor", - "borderBlockEndStyle", - "borderBlockEndWidth", - "borderBlockStart", - "borderBlockStartColor", - "borderBlockStartStyle", - "borderBlockStartWidth", - "borderBlockStyle", - "borderBlockWidth", - "borderBottom", - "borderBottomColor", - "borderBottomLeftRadius", - "borderBottomRightRadius", - "borderBottomStyle", - "borderBottomWidth", - "borderBoxSize", - "borderCollapse", - "borderColor", - "borderColorDark", - "borderColorLight", - "borderEndEndRadius", - "borderEndStartRadius", - "borderImage", - "borderImageOutset", - "borderImageRepeat", - "borderImageSlice", - "borderImageSource", - "borderImageWidth", - "borderInline", - "borderInlineColor", - "borderInlineEnd", - "borderInlineEndColor", - "borderInlineEndStyle", - "borderInlineEndWidth", - "borderInlineStart", - "borderInlineStartColor", - "borderInlineStartStyle", - "borderInlineStartWidth", - "borderInlineStyle", - "borderInlineWidth", - "borderLeft", - "borderLeftColor", - "borderLeftStyle", - "borderLeftWidth", - "borderRadius", - "borderRight", - "borderRightColor", - "borderRightStyle", - "borderRightWidth", - "borderSpacing", - "borderStartEndRadius", - "borderStartStartRadius", - "borderStyle", - "borderTop", - "borderTopColor", - "borderTopLeftRadius", - "borderTopRightRadius", - "borderTopStyle", - "borderTopWidth", - "borderWidth", - "bottom", - "bottomMargin", - "bound", - "boundElements", - "boundingClientRect", - "boundingHeight", - "boundingLeft", - "boundingTop", - "boundingWidth", - "bounds", - "boundsGeometry", - "box-decoration-break", - "box-shadow", - "box-sizing", - "boxDecorationBreak", - "boxShadow", - "boxSizing", - "break-after", - "break-before", - "break-inside", - "breakAfter", - "breakBefore", - "breakInside", - "broadcast", - "browserLanguage", - "btoa", - "bubbles", - "buffer", - "bufferData", - "bufferDepth", - "bufferSize", - "bufferSubData", - "buffered", - "bufferedAmount", - "bufferedAmountLowThreshold", - "buildID", - "buildNumber", - "button", - "buttonID", - "buttons", - "byteLength", - "byteOffset", - "bytesWritten", - "c", - "cache", - "caches", - "call", - "caller", - "canBeFormatted", - "canBeMounted", - "canBeShared", - "canHaveChildren", - "canHaveHTML", - "canInsertDTMF", - "canMakePayment", - "canPlayType", - "canPresent", - "canTrickleIceCandidates", - "cancel", - "cancelAndHoldAtTime", - "cancelAnimationFrame", - "cancelBubble", - "cancelIdleCallback", - "cancelScheduledValues", - "cancelVideoFrameCallback", - "cancelWatchAvailability", - "cancelable", - "candidate", - "canonicalUUID", - "canvas", - "capabilities", - "caption", - "caption-side", - "captionSide", - "capture", - "captureEvents", - "captureStackTrace", - "captureStream", - "caret-color", - "caretBidiLevel", - "caretColor", - "caretPositionFromPoint", - "caretRangeFromPoint", - "cast", - "catch", - "category", - "cbrt", - "cd", - "ceil", - "cellIndex", - "cellPadding", - "cellSpacing", - "cells", - "ch", - "chOff", - "chain", - "challenge", - "changeType", - "changedTouches", - "channel", - "channelCount", - "channelCountMode", - "channelInterpretation", - "char", - "charAt", - "charCode", - "charCodeAt", - "charIndex", - "charLength", - "characterData", - "characterDataOldValue", - "characterSet", - "characteristic", - "charging", - "chargingTime", - "charset", - "check", - "checkEnclosure", - "checkFramebufferStatus", - "checkIntersection", - "checkValidity", - "checked", - "childElementCount", - "childList", - "childNodes", - "children", - "chrome", - "ciphertext", - "cite", - "city", - "claimInterface", - "claimed", - "classList", - "className", - "classid", - "clear", - "clearAppBadge", - "clearAttributes", - "clearBufferfi", - "clearBufferfv", - "clearBufferiv", - "clearBufferuiv", - "clearColor", - "clearData", - "clearDepth", - "clearHalt", - "clearImmediate", - "clearInterval", - "clearLiveSeekableRange", - "clearMarks", - "clearMaxGCPauseAccumulator", - "clearMeasures", - "clearParameters", - "clearRect", - "clearResourceTimings", - "clearShadow", - "clearStencil", - "clearTimeout", - "clearWatch", - "click", - "clickCount", - "clientDataJSON", - "clientHeight", - "clientInformation", - "clientLeft", - "clientRect", - "clientRects", - "clientTop", - "clientWaitSync", - "clientWidth", - "clientX", - "clientY", - "clip", - "clip-path", - "clip-rule", - "clipBottom", - "clipLeft", - "clipPath", - "clipPathUnits", - "clipRight", - "clipRule", - "clipTop", - "clipboard", - "clipboardData", - "clone", - "cloneContents", - "cloneNode", - "cloneRange", - "close", - "closePath", - "closed", - "closest", - "clz", - "clz32", - "cm", - "cmp", - "code", - "codeBase", - "codePointAt", - "codeType", - "colSpan", - "collapse", - "collapseToEnd", - "collapseToStart", - "collapsed", - "collect", - "colno", - "color", - "color-adjust", - "color-interpolation", - "color-interpolation-filters", - "colorAdjust", - "colorDepth", - "colorInterpolation", - "colorInterpolationFilters", - "colorMask", - "colorType", - "cols", - "column-count", - "column-fill", - "column-gap", - "column-rule", - "column-rule-color", - "column-rule-style", - "column-rule-width", - "column-span", - "column-width", - "columnCount", - "columnFill", - "columnGap", - "columnNumber", - "columnRule", - "columnRuleColor", - "columnRuleStyle", - "columnRuleWidth", - "columnSpan", - "columnWidth", - "columns", - "command", - "commit", - "commitPreferences", - "commitStyles", - "commonAncestorContainer", - "compact", - "compareBoundaryPoints", - "compareDocumentPosition", - "compareEndPoints", - "compareExchange", - "compareNode", - "comparePoint", - "compatMode", - "compatible", - "compile", - "compileShader", - "compileStreaming", - "complete", - "component", - "componentFromPoint", - "composed", - "composedPath", - "composite", - "compositionEndOffset", - "compositionStartOffset", - "compressedTexImage2D", - "compressedTexImage3D", - "compressedTexSubImage2D", - "compressedTexSubImage3D", - "computedStyleMap", - "concat", - "conditionText", - "coneInnerAngle", - "coneOuterAngle", - "coneOuterGain", - "configuration", - "configurationName", - "configurationValue", - "configurations", - "confirm", - "confirmComposition", - "confirmSiteSpecificTrackingException", - "confirmWebWideTrackingException", - "connect", - "connectEnd", - "connectShark", - "connectStart", - "connected", - "connection", - "connectionList", - "connectionSpeed", - "connectionState", - "connections", - "console", - "consolidate", - "constraint", - "constrictionActive", - "construct", - "constructor", - "contactID", - "contain", - "containerId", - "containerName", - "containerSrc", - "containerType", - "contains", - "containsNode", - "content", - "contentBoxSize", - "contentDocument", - "contentEditable", - "contentHint", - "contentOverflow", - "contentRect", - "contentScriptType", - "contentStyleType", - "contentType", - "contentWindow", - "context", - "contextMenu", - "contextmenu", - "continue", - "continuePrimaryKey", - "continuous", - "control", - "controlTransferIn", - "controlTransferOut", - "controller", - "controls", - "controlsList", - "convertPointFromNode", - "convertQuadFromNode", - "convertRectFromNode", - "convertToBlob", - "convertToSpecifiedUnits", - "cookie", - "cookieEnabled", - "coords", - "copyBufferSubData", - "copyFromChannel", - "copyTexImage2D", - "copyTexSubImage2D", - "copyTexSubImage3D", - "copyToChannel", - "copyWithin", - "correspondingElement", - "correspondingUseElement", - "corruptedVideoFrames", - "cos", - "cosh", - "count", - "countReset", - "counter-increment", - "counter-reset", - "counter-set", - "counterIncrement", - "counterReset", - "counterSet", - "country", - "cpuClass", - "cpuSleepAllowed", - "create", - "createAnalyser", - "createAnswer", - "createAttribute", - "createAttributeNS", - "createBiquadFilter", - "createBuffer", - "createBufferSource", - "createCDATASection", - "createCSSStyleSheet", - "createCaption", - "createChannelMerger", - "createChannelSplitter", - "createComment", - "createConstantSource", - "createContextualFragment", - "createControlRange", - "createConvolver", - "createDTMFSender", - "createDataChannel", - "createDelay", - "createDelayNode", - "createDocument", - "createDocumentFragment", - "createDocumentType", - "createDynamicsCompressor", - "createElement", - "createElementNS", - "createEntityReference", - "createEvent", - "createEventObject", - "createExpression", - "createFramebuffer", - "createFunction", - "createGain", - "createGainNode", - "createHTML", - "createHTMLDocument", - "createIIRFilter", - "createImageBitmap", - "createImageData", - "createIndex", - "createJavaScriptNode", - "createLinearGradient", - "createMediaElementSource", - "createMediaKeys", - "createMediaStreamDestination", - "createMediaStreamSource", - "createMediaStreamTrackSource", - "createMutableFile", - "createNSResolver", - "createNodeIterator", - "createNotification", - "createObjectStore", - "createObjectURL", - "createOffer", - "createOscillator", - "createPanner", - "createPattern", - "createPeriodicWave", - "createPolicy", - "createPopup", - "createProcessingInstruction", - "createProgram", - "createQuery", - "createRadialGradient", - "createRange", - "createRangeCollection", - "createReader", - "createRenderbuffer", - "createSVGAngle", - "createSVGLength", - "createSVGMatrix", - "createSVGNumber", - "createSVGPathSegArcAbs", - "createSVGPathSegArcRel", - "createSVGPathSegClosePath", - "createSVGPathSegCurvetoCubicAbs", - "createSVGPathSegCurvetoCubicRel", - "createSVGPathSegCurvetoCubicSmoothAbs", - "createSVGPathSegCurvetoCubicSmoothRel", - "createSVGPathSegCurvetoQuadraticAbs", - "createSVGPathSegCurvetoQuadraticRel", - "createSVGPathSegCurvetoQuadraticSmoothAbs", - "createSVGPathSegCurvetoQuadraticSmoothRel", - "createSVGPathSegLinetoAbs", - "createSVGPathSegLinetoHorizontalAbs", - "createSVGPathSegLinetoHorizontalRel", - "createSVGPathSegLinetoRel", - "createSVGPathSegLinetoVerticalAbs", - "createSVGPathSegLinetoVerticalRel", - "createSVGPathSegMovetoAbs", - "createSVGPathSegMovetoRel", - "createSVGPoint", - "createSVGRect", - "createSVGTransform", - "createSVGTransformFromMatrix", - "createSampler", - "createScript", - "createScriptProcessor", - "createScriptURL", - "createSession", - "createShader", - "createShadowRoot", - "createStereoPanner", - "createStyleSheet", - "createTBody", - "createTFoot", - "createTHead", - "createTextNode", - "createTextRange", - "createTexture", - "createTouch", - "createTouchList", - "createTransformFeedback", - "createTreeWalker", - "createVertexArray", - "createWaveShaper", - "creationTime", - "credentials", - "crossOrigin", - "crossOriginIsolated", - "crypto", - "csi", - "csp", - "cssFloat", - "cssRules", - "cssText", - "cssValueType", - "ctrlKey", - "ctrlLeft", - "cues", - "cullFace", - "currentDirection", - "currentLocalDescription", - "currentNode", - "currentPage", - "currentRect", - "currentRemoteDescription", - "currentScale", - "currentScript", - "currentSrc", - "currentState", - "currentStyle", - "currentTarget", - "currentTime", - "currentTranslate", - "currentView", - "cursor", - "curve", - "customElements", - "customError", - "cx", - "cy", - "d", - "data", - "dataFld", - "dataFormatAs", - "dataLoss", - "dataLossMessage", - "dataPageSize", - "dataSrc", - "dataTransfer", - "database", - "databases", - "dataset", - "dateTime", - "db", - "debug", - "debuggerEnabled", - "declare", - "decode", - "decodeAudioData", - "decodeURI", - "decodeURIComponent", - "decodedBodySize", - "decoding", - "decodingInfo", - "decrypt", - "default", - "defaultCharset", - "defaultChecked", - "defaultMuted", - "defaultPlaybackRate", - "defaultPolicy", - "defaultPrevented", - "defaultRequest", - "defaultSelected", - "defaultStatus", - "defaultURL", - "defaultValue", - "defaultView", - "defaultstatus", - "defer", - "define", - "defineMagicFunction", - "defineMagicVariable", - "defineProperties", - "defineProperty", - "deg", - "delay", - "delayTime", - "delegatesFocus", - "delete", - "deleteBuffer", - "deleteCaption", - "deleteCell", - "deleteContents", - "deleteData", - "deleteDatabase", - "deleteFramebuffer", - "deleteFromDocument", - "deleteIndex", - "deleteMedium", - "deleteObjectStore", - "deleteProgram", - "deleteProperty", - "deleteQuery", - "deleteRenderbuffer", - "deleteRow", - "deleteRule", - "deleteSampler", - "deleteShader", - "deleteSync", - "deleteTFoot", - "deleteTHead", - "deleteTexture", - "deleteTransformFeedback", - "deleteVertexArray", - "deliverChangeRecords", - "delivery", - "deliveryInfo", - "deliveryStatus", - "deliveryTimestamp", - "delta", - "deltaMode", - "deltaX", - "deltaY", - "deltaZ", - "dependentLocality", - "depthFar", - "depthFunc", - "depthMask", - "depthNear", - "depthRange", - "deref", - "deriveBits", - "deriveKey", - "description", - "deselectAll", - "designMode", - "desiredSize", - "destination", - "destinationURL", - "detach", - "detachEvent", - "detachShader", - "detail", - "details", - "detect", - "detune", - "device", - "deviceClass", - "deviceId", - "deviceMemory", - "devicePixelContentBoxSize", - "devicePixelRatio", - "deviceProtocol", - "deviceSubclass", - "deviceVersionMajor", - "deviceVersionMinor", - "deviceVersionSubminor", - "deviceXDPI", - "deviceYDPI", - "didTimeout", - "diffuseConstant", - "digest", - "dimensions", - "dir", - "dirName", - "direction", - "dirxml", - "disable", - "disablePictureInPicture", - "disableRemotePlayback", - "disableVertexAttribArray", - "disabled", - "dischargingTime", - "disconnect", - "disconnectShark", - "dispatchEvent", - "display", - "displayId", - "displayName", - "disposition", - "distanceModel", - "div", - "divisor", - "djsapi", - "djsproxy", - "doImport", - "doNotTrack", - "doScroll", - "doctype", - "document", - "documentElement", - "documentMode", - "documentURI", - "dolphin", - "dolphinGameCenter", - "dolphininfo", - "dolphinmeta", - "domComplete", - "domContentLoadedEventEnd", - "domContentLoadedEventStart", - "domInteractive", - "domLoading", - "domOverlayState", - "domain", - "domainLookupEnd", - "domainLookupStart", - "dominant-baseline", - "dominantBaseline", - "done", - "dopplerFactor", - "dotAll", - "downDegrees", - "downlink", - "download", - "downloadTotal", - "downloaded", - "dpcm", - "dpi", - "dppx", - "dragDrop", - "draggable", - "drawArrays", - "drawArraysInstanced", - "drawArraysInstancedANGLE", - "drawBuffers", - "drawCustomFocusRing", - "drawElements", - "drawElementsInstanced", - "drawElementsInstancedANGLE", - "drawFocusIfNeeded", - "drawImage", - "drawImageFromRect", - "drawRangeElements", - "drawSystemFocusRing", - "drawingBufferHeight", - "drawingBufferWidth", - "dropEffect", - "droppedVideoFrames", - "dropzone", - "dtmf", - "dump", - "dumpProfile", - "duplicate", - "durability", - "duration", - "dvname", - "dvnum", - "dx", - "dy", - "dynsrc", - "e", - "edgeMode", - "effect", - "effectAllowed", - "effectiveDirective", - "effectiveType", - "elapsedTime", - "element", - "elementFromPoint", - "elementTiming", - "elements", - "elementsFromPoint", - "elevation", - "ellipse", - "em", - "email", - "embeds", - "emma", - "empty", - "empty-cells", - "emptyCells", - "emptyHTML", - "emptyScript", - "emulatedPosition", - "enable", - "enableBackground", - "enableDelegations", - "enableStyleSheetsForSet", - "enableVertexAttribArray", - "enabled", - "enabledPlugin", - "encode", - "encodeInto", - "encodeURI", - "encodeURIComponent", - "encodedBodySize", - "encoding", - "encodingInfo", - "encrypt", - "enctype", - "end", - "endContainer", - "endElement", - "endElementAt", - "endOfStream", - "endOffset", - "endQuery", - "endTime", - "endTransformFeedback", - "ended", - "endpoint", - "endpointNumber", - "endpoints", - "endsWith", - "enterKeyHint", - "entities", - "entries", - "entryType", - "enumerate", - "enumerateDevices", - "enumerateEditable", - "environmentBlendMode", - "equals", - "error", - "errorCode", - "errorDetail", - "errorText", - "escape", - "estimate", - "eval", - "evaluate", - "event", - "eventPhase", - "every", - "ex", - "exception", - "exchange", - "exec", - "execCommand", - "execCommandShowHelp", - "execScript", - "exitFullscreen", - "exitPictureInPicture", - "exitPointerLock", - "exitPresent", - "exp", - "expand", - "expandEntityReferences", - "expando", - "expansion", - "expiration", - "expirationTime", - "expires", - "expiryDate", - "explicitOriginalTarget", - "expm1", - "exponent", - "exponentialRampToValueAtTime", - "exportKey", - "exports", - "extend", - "extensions", - "extentNode", - "extentOffset", - "external", - "externalResourcesRequired", - "extractContents", - "extractable", - "eye", - "f", - "face", - "factoryReset", - "failureReason", - "fallback", - "family", - "familyName", - "farthestViewportElement", - "fastSeek", - "fatal", - "featureId", - "featurePolicy", - "featureSettings", - "features", - "fenceSync", - "fetch", - "fetchStart", - "fftSize", - "fgColor", - "fieldOfView", - "file", - "fileCreatedDate", - "fileHandle", - "fileModifiedDate", - "fileName", - "fileSize", - "fileUpdatedDate", - "filename", - "files", - "filesystem", - "fill", - "fill-opacity", - "fill-rule", - "fillLightMode", - "fillOpacity", - "fillRect", - "fillRule", - "fillStyle", - "fillText", - "filter", - "filterResX", - "filterResY", - "filterUnits", - "filters", - "finally", - "find", - "findIndex", - "findRule", - "findText", - "finish", - "finished", - "fireEvent", - "firesTouchEvents", - "firstChild", - "firstElementChild", - "firstPage", - "fixed", - "flags", - "flat", - "flatMap", - "flex", - "flex-basis", - "flex-direction", - "flex-flow", - "flex-grow", - "flex-shrink", - "flex-wrap", - "flexBasis", - "flexDirection", - "flexFlow", - "flexGrow", - "flexShrink", - "flexWrap", - "flipX", - "flipY", - "float", - "float32", - "float64", - "flood-color", - "flood-opacity", - "floodColor", - "floodOpacity", - "floor", - "flush", - "focus", - "focusNode", - "focusOffset", - "font", - "font-family", - "font-feature-settings", - "font-kerning", - "font-language-override", - "font-optical-sizing", - "font-size", - "font-size-adjust", - "font-stretch", - "font-style", - "font-synthesis", - "font-variant", - "font-variant-alternates", - "font-variant-caps", - "font-variant-east-asian", - "font-variant-ligatures", - "font-variant-numeric", - "font-variant-position", - "font-variation-settings", - "font-weight", - "fontFamily", - "fontFeatureSettings", - "fontKerning", - "fontLanguageOverride", - "fontOpticalSizing", - "fontSize", - "fontSizeAdjust", - "fontSmoothingEnabled", - "fontStretch", - "fontStyle", - "fontSynthesis", - "fontVariant", - "fontVariantAlternates", - "fontVariantCaps", - "fontVariantEastAsian", - "fontVariantLigatures", - "fontVariantNumeric", - "fontVariantPosition", - "fontVariationSettings", - "fontWeight", - "fontcolor", - "fontfaces", - "fonts", - "fontsize", - "for", - "forEach", - "force", - "forceRedraw", - "form", - "formAction", - "formData", - "formEnctype", - "formMethod", - "formNoValidate", - "formTarget", - "format", - "formatToParts", - "forms", - "forward", - "forwardX", - "forwardY", - "forwardZ", - "foundation", - "fr", - "fragmentDirective", - "frame", - "frameBorder", - "frameElement", - "frameSpacing", - "framebuffer", - "framebufferHeight", - "framebufferRenderbuffer", - "framebufferTexture2D", - "framebufferTextureLayer", - "framebufferWidth", - "frames", - "freeSpace", - "freeze", - "frequency", - "frequencyBinCount", - "from", - "fromCharCode", - "fromCodePoint", - "fromElement", - "fromEntries", - "fromFloat32Array", - "fromFloat64Array", - "fromMatrix", - "fromPoint", - "fromQuad", - "fromRect", - "frontFace", - "fround", - "fullPath", - "fullScreen", - "fullscreen", - "fullscreenElement", - "fullscreenEnabled", - "fx", - "fy", - "gain", - "gamepad", - "gamma", - "gap", - "gatheringState", - "gatt", - "genderIdentity", - "generateCertificate", - "generateKey", - "generateMipmap", - "generateRequest", - "geolocation", - "gestureObject", - "get", - "getActiveAttrib", - "getActiveUniform", - "getActiveUniformBlockName", - "getActiveUniformBlockParameter", - "getActiveUniforms", - "getAdjacentText", - "getAll", - "getAllKeys", - "getAllResponseHeaders", - "getAllowlistForFeature", - "getAnimations", - "getAsFile", - "getAsString", - "getAttachedShaders", - "getAttribLocation", - "getAttribute", - "getAttributeNS", - "getAttributeNames", - "getAttributeNode", - "getAttributeNodeNS", - "getAttributeType", - "getAudioTracks", - "getAvailability", - "getBBox", - "getBattery", - "getBigInt64", - "getBigUint64", - "getBlob", - "getBookmark", - "getBoundingClientRect", - "getBounds", - "getBoxQuads", - "getBufferParameter", - "getBufferSubData", - "getByteFrequencyData", - "getByteTimeDomainData", - "getCSSCanvasContext", - "getCTM", - "getCandidateWindowClientRect", - "getCanonicalLocales", - "getCapabilities", - "getChannelData", - "getCharNumAtPosition", - "getCharacteristic", - "getCharacteristics", - "getClientExtensionResults", - "getClientRect", - "getClientRects", - "getCoalescedEvents", - "getCompositionAlternatives", - "getComputedStyle", - "getComputedTextLength", - "getComputedTiming", - "getConfiguration", - "getConstraints", - "getContext", - "getContextAttributes", - "getContributingSources", - "getCounterValue", - "getCueAsHTML", - "getCueById", - "getCurrentPosition", - "getCurrentTime", - "getData", - "getDatabaseNames", - "getDate", - "getDay", - "getDefaultComputedStyle", - "getDescriptor", - "getDescriptors", - "getDestinationInsertionPoints", - "getDevices", - "getDirectory", - "getDisplayMedia", - "getDistributedNodes", - "getEditable", - "getElementById", - "getElementsByClassName", - "getElementsByName", - "getElementsByTagName", - "getElementsByTagNameNS", - "getEnclosureList", - "getEndPositionOfChar", - "getEntries", - "getEntriesByName", - "getEntriesByType", - "getError", - "getExtension", - "getExtentOfChar", - "getEyeParameters", - "getFeature", - "getFile", - "getFiles", - "getFilesAndDirectories", - "getFingerprints", - "getFloat32", - "getFloat64", - "getFloatFrequencyData", - "getFloatTimeDomainData", - "getFloatValue", - "getFragDataLocation", - "getFrameData", - "getFramebufferAttachmentParameter", - "getFrequencyResponse", - "getFullYear", - "getGamepads", - "getHitTestResults", - "getHitTestResultsForTransientInput", - "getHours", - "getIdentityAssertion", - "getIds", - "getImageData", - "getIndexedParameter", - "getInstalledRelatedApps", - "getInt16", - "getInt32", - "getInt8", - "getInternalformatParameter", - "getIntersectionList", - "getItem", - "getItems", - "getKey", - "getKeyframes", - "getLayers", - "getLayoutMap", - "getLineDash", - "getLocalCandidates", - "getLocalParameters", - "getLocalStreams", - "getMarks", - "getMatchedCSSRules", - "getMaxGCPauseSinceClear", - "getMeasures", - "getMetadata", - "getMilliseconds", - "getMinutes", - "getModifierState", - "getMonth", - "getNamedItem", - "getNamedItemNS", - "getNativeFramebufferScaleFactor", - "getNotifications", - "getNotifier", - "getNumberOfChars", - "getOffsetReferenceSpace", - "getOutputTimestamp", - "getOverrideHistoryNavigationMode", - "getOverrideStyle", - "getOwnPropertyDescriptor", - "getOwnPropertyDescriptors", - "getOwnPropertyNames", - "getOwnPropertySymbols", - "getParameter", - "getParameters", - "getParent", - "getPathSegAtLength", - "getPhotoCapabilities", - "getPhotoSettings", - "getPointAtLength", - "getPose", - "getPredictedEvents", - "getPreference", - "getPreferenceDefault", - "getPresentationAttribute", - "getPreventDefault", - "getPrimaryService", - "getPrimaryServices", - "getProgramInfoLog", - "getProgramParameter", - "getPropertyCSSValue", - "getPropertyPriority", - "getPropertyShorthand", - "getPropertyType", - "getPropertyValue", - "getPrototypeOf", - "getQuery", - "getQueryParameter", - "getRGBColorValue", - "getRandomValues", - "getRangeAt", - "getReader", - "getReceivers", - "getRectValue", - "getRegistration", - "getRegistrations", - "getRemoteCandidates", - "getRemoteCertificates", - "getRemoteParameters", - "getRemoteStreams", - "getRenderbufferParameter", - "getResponseHeader", - "getRoot", - "getRootNode", - "getRotationOfChar", - "getSVGDocument", - "getSamplerParameter", - "getScreenCTM", - "getSeconds", - "getSelectedCandidatePair", - "getSelection", - "getSenders", - "getService", - "getSettings", - "getShaderInfoLog", - "getShaderParameter", - "getShaderPrecisionFormat", - "getShaderSource", - "getSimpleDuration", - "getSiteIcons", - "getSources", - "getSpeculativeParserUrls", - "getStartPositionOfChar", - "getStartTime", - "getState", - "getStats", - "getStatusForPolicy", - "getStorageUpdates", - "getStreamById", - "getStringValue", - "getSubStringLength", - "getSubscription", - "getSupportedConstraints", - "getSupportedExtensions", - "getSupportedFormats", - "getSyncParameter", - "getSynchronizationSources", - "getTags", - "getTargetRanges", - "getTexParameter", - "getTime", - "getTimezoneOffset", - "getTiming", - "getTotalLength", - "getTrackById", - "getTracks", - "getTransceivers", - "getTransform", - "getTransformFeedbackVarying", - "getTransformToElement", - "getTransports", - "getType", - "getTypeMapping", - "getUTCDate", - "getUTCDay", - "getUTCFullYear", - "getUTCHours", - "getUTCMilliseconds", - "getUTCMinutes", - "getUTCMonth", - "getUTCSeconds", - "getUint16", - "getUint32", - "getUint8", - "getUniform", - "getUniformBlockIndex", - "getUniformIndices", - "getUniformLocation", - "getUserMedia", - "getVRDisplays", - "getValues", - "getVarDate", - "getVariableValue", - "getVertexAttrib", - "getVertexAttribOffset", - "getVideoPlaybackQuality", - "getVideoTracks", - "getViewerPose", - "getViewport", - "getVoices", - "getWakeLockState", - "getWriter", - "getYear", - "givenName", - "global", - "globalAlpha", - "globalCompositeOperation", - "globalThis", - "glyphOrientationHorizontal", - "glyphOrientationVertical", - "glyphRef", - "go", - "grabFrame", - "grad", - "gradientTransform", - "gradientUnits", - "grammars", - "green", - "grid", - "grid-area", - "grid-auto-columns", - "grid-auto-flow", - "grid-auto-rows", - "grid-column", - "grid-column-end", - "grid-column-gap", - "grid-column-start", - "grid-gap", - "grid-row", - "grid-row-end", - "grid-row-gap", - "grid-row-start", - "grid-template", - "grid-template-areas", - "grid-template-columns", - "grid-template-rows", - "gridArea", - "gridAutoColumns", - "gridAutoFlow", - "gridAutoRows", - "gridColumn", - "gridColumnEnd", - "gridColumnGap", - "gridColumnStart", - "gridGap", - "gridRow", - "gridRowEnd", - "gridRowGap", - "gridRowStart", - "gridTemplate", - "gridTemplateAreas", - "gridTemplateColumns", - "gridTemplateRows", - "gripSpace", - "group", - "groupCollapsed", - "groupEnd", - "groupId", - "hadRecentInput", - "hand", - "handedness", - "hapticActuators", - "hardwareConcurrency", - "has", - "hasAttribute", - "hasAttributeNS", - "hasAttributes", - "hasBeenActive", - "hasChildNodes", - "hasComposition", - "hasEnrolledInstrument", - "hasExtension", - "hasExternalDisplay", - "hasFeature", - "hasFocus", - "hasInstance", - "hasLayout", - "hasOrientation", - "hasOwnProperty", - "hasPointerCapture", - "hasPosition", - "hasReading", - "hasStorageAccess", - "hash", - "head", - "headers", - "heading", - "height", - "hidden", - "hide", - "hideFocus", - "high", - "highWaterMark", - "hint", - "history", - "honorificPrefix", - "honorificSuffix", - "horizontalOverflow", - "host", - "hostCandidate", - "hostname", - "href", - "hrefTranslate", - "hreflang", - "hspace", - "html5TagCheckInerface", - "htmlFor", - "htmlText", - "httpEquiv", - "httpRequestStatusCode", - "hwTimestamp", - "hyphens", - "hypot", - "iccId", - "iceConnectionState", - "iceGatheringState", - "iceTransport", - "icon", - "iconURL", - "id", - "identifier", - "identity", - "idpLoginUrl", - "ignoreBOM", - "ignoreCase", - "ignoreDepthValues", - "image-orientation", - "image-rendering", - "imageHeight", - "imageOrientation", - "imageRendering", - "imageSizes", - "imageSmoothingEnabled", - "imageSmoothingQuality", - "imageSrcset", - "imageWidth", - "images", - "ime-mode", - "imeMode", - "implementation", - "importKey", - "importNode", - "importStylesheet", - "imports", - "impp", - "imul", - "in", - "in1", - "in2", - "inBandMetadataTrackDispatchType", - "inRange", - "includes", - "incremental", - "indeterminate", - "index", - "indexNames", - "indexOf", - "indexedDB", - "indicate", - "inertiaDestinationX", - "inertiaDestinationY", - "info", - "init", - "initAnimationEvent", - "initBeforeLoadEvent", - "initClipboardEvent", - "initCloseEvent", - "initCommandEvent", - "initCompositionEvent", - "initCustomEvent", - "initData", - "initDataType", - "initDeviceMotionEvent", - "initDeviceOrientationEvent", - "initDragEvent", - "initErrorEvent", - "initEvent", - "initFocusEvent", - "initGestureEvent", - "initHashChangeEvent", - "initKeyEvent", - "initKeyboardEvent", - "initMSManipulationEvent", - "initMessageEvent", - "initMouseEvent", - "initMouseScrollEvent", - "initMouseWheelEvent", - "initMutationEvent", - "initNSMouseEvent", - "initOverflowEvent", - "initPageEvent", - "initPageTransitionEvent", - "initPointerEvent", - "initPopStateEvent", - "initProgressEvent", - "initScrollAreaEvent", - "initSimpleGestureEvent", - "initStorageEvent", - "initTextEvent", - "initTimeEvent", - "initTouchEvent", - "initTransitionEvent", - "initUIEvent", - "initWebKitAnimationEvent", - "initWebKitTransitionEvent", - "initWebKitWheelEvent", - "initWheelEvent", - "initialTime", - "initialize", - "initiatorType", - "inline-size", - "inlineSize", - "inlineVerticalFieldOfView", - "inner", - "innerHTML", - "innerHeight", - "innerText", - "innerWidth", - "input", - "inputBuffer", - "inputEncoding", - "inputMethod", - "inputMode", - "inputSource", - "inputSources", - "inputType", - "inputs", - "insertAdjacentElement", - "insertAdjacentHTML", - "insertAdjacentText", - "insertBefore", - "insertCell", - "insertDTMF", - "insertData", - "insertItemBefore", - "insertNode", - "insertRow", - "insertRule", - "inset", - "inset-block", - "inset-block-end", - "inset-block-start", - "inset-inline", - "inset-inline-end", - "inset-inline-start", - "insetBlock", - "insetBlockEnd", - "insetBlockStart", - "insetInline", - "insetInlineEnd", - "insetInlineStart", - "installing", - "instanceRoot", - "instantiate", - "instantiateStreaming", - "instruments", - "int16", - "int32", - "int8", - "integrity", - "interactionMode", - "intercept", - "interfaceClass", - "interfaceName", - "interfaceNumber", - "interfaceProtocol", - "interfaceSubclass", - "interfaces", - "interimResults", - "internalSubset", - "interpretation", - "intersectionRatio", - "intersectionRect", - "intersectsNode", - "interval", - "invalidIteratorState", - "invalidateFramebuffer", - "invalidateSubFramebuffer", - "inverse", - "invertSelf", - "is", - "is2D", - "isActive", - "isAlternate", - "isArray", - "isBingCurrentSearchDefault", - "isBuffer", - "isCandidateWindowVisible", - "isChar", - "isCollapsed", - "isComposing", - "isConcatSpreadable", - "isConnected", - "isContentEditable", - "isContentHandlerRegistered", - "isContextLost", - "isDefaultNamespace", - "isDirectory", - "isDisabled", - "isEnabled", - "isEqual", - "isEqualNode", - "isExtensible", - "isExternalCTAP2SecurityKeySupported", - "isFile", - "isFinite", - "isFramebuffer", - "isFrozen", - "isGenerator", - "isHTML", - "isHistoryNavigation", - "isId", - "isIdentity", - "isInjected", - "isInteger", - "isIntersecting", - "isLockFree", - "isMap", - "isMultiLine", - "isNaN", - "isOpen", - "isPointInFill", - "isPointInPath", - "isPointInRange", - "isPointInStroke", - "isPrefAlternate", - "isPresenting", - "isPrimary", - "isProgram", - "isPropertyImplicit", - "isProtocolHandlerRegistered", - "isPrototypeOf", - "isQuery", - "isRenderbuffer", - "isSafeInteger", - "isSameNode", - "isSampler", - "isScript", - "isScriptURL", - "isSealed", - "isSecureContext", - "isSessionSupported", - "isShader", - "isSupported", - "isSync", - "isTextEdit", - "isTexture", - "isTransformFeedback", - "isTrusted", - "isTypeSupported", - "isUserVerifyingPlatformAuthenticatorAvailable", - "isVertexArray", - "isView", - "isVisible", - "isochronousTransferIn", - "isochronousTransferOut", - "isolation", - "italics", - "item", - "itemId", - "itemProp", - "itemRef", - "itemScope", - "itemType", - "itemValue", - "items", - "iterateNext", - "iterationComposite", - "iterator", - "javaEnabled", - "jobTitle", - "join", - "json", - "justify-content", - "justify-items", - "justify-self", - "justifyContent", - "justifyItems", - "justifySelf", - "k1", - "k2", - "k3", - "k4", - "kHz", - "keepalive", - "kernelMatrix", - "kernelUnitLengthX", - "kernelUnitLengthY", - "kerning", - "key", - "keyCode", - "keyFor", - "keyIdentifier", - "keyLightEnabled", - "keyLocation", - "keyPath", - "keyStatuses", - "keySystem", - "keyText", - "keyUsage", - "keyboard", - "keys", - "keytype", - "kind", - "knee", - "label", - "labels", - "lang", - "language", - "languages", - "largeArcFlag", - "lastChild", - "lastElementChild", - "lastEventId", - "lastIndex", - "lastIndexOf", - "lastInputTime", - "lastMatch", - "lastMessageSubject", - "lastMessageType", - "lastModified", - "lastModifiedDate", - "lastPage", - "lastParen", - "lastState", - "lastStyleSheetSet", - "latitude", - "layerX", - "layerY", - "layoutFlow", - "layoutGrid", - "layoutGridChar", - "layoutGridLine", - "layoutGridMode", - "layoutGridType", - "lbound", - "left", - "leftContext", - "leftDegrees", - "leftMargin", - "leftProjectionMatrix", - "leftViewMatrix", - "length", - "lengthAdjust", - "lengthComputable", - "letter-spacing", - "letterSpacing", - "level", - "lighting-color", - "lightingColor", - "limitingConeAngle", - "line", - "line-break", - "line-height", - "lineAlign", - "lineBreak", - "lineCap", - "lineDashOffset", - "lineHeight", - "lineJoin", - "lineNumber", - "lineTo", - "lineWidth", - "linearAcceleration", - "linearRampToValueAtTime", - "linearVelocity", - "lineno", - "lines", - "link", - "linkColor", - "linkProgram", - "links", - "list", - "list-style", - "list-style-image", - "list-style-position", - "list-style-type", - "listStyle", - "listStyleImage", - "listStylePosition", - "listStyleType", - "listener", - "load", - "loadEventEnd", - "loadEventStart", - "loadTime", - "loadTimes", - "loaded", - "loading", - "localDescription", - "localName", - "localService", - "localStorage", - "locale", - "localeCompare", - "location", - "locationbar", - "lock", - "locked", - "lockedFile", - "locks", - "log", - "log10", - "log1p", - "log2", - "logicalXDPI", - "logicalYDPI", - "longDesc", - "longitude", - "lookupNamespaceURI", - "lookupPrefix", - "loop", - "loopEnd", - "loopStart", - "looping", - "low", - "lower", - "lowerBound", - "lowerOpen", - "lowsrc", - "m11", - "m12", - "m13", - "m14", - "m21", - "m22", - "m23", - "m24", - "m31", - "m32", - "m33", - "m34", - "m41", - "m42", - "m43", - "m44", - "makeXRCompatible", - "manifest", - "manufacturer", - "manufacturerName", - "map", - "mapping", - "margin", - "margin-block", - "margin-block-end", - "margin-block-start", - "margin-bottom", - "margin-inline", - "margin-inline-end", - "margin-inline-start", - "margin-left", - "margin-right", - "margin-top", - "marginBlock", - "marginBlockEnd", - "marginBlockStart", - "marginBottom", - "marginHeight", - "marginInline", - "marginInlineEnd", - "marginInlineStart", - "marginLeft", - "marginRight", - "marginTop", - "marginWidth", - "mark", - "marker", - "marker-end", - "marker-mid", - "marker-offset", - "marker-start", - "markerEnd", - "markerHeight", - "markerMid", - "markerOffset", - "markerStart", - "markerUnits", - "markerWidth", - "marks", - "mask", - "mask-clip", - "mask-composite", - "mask-image", - "mask-mode", - "mask-origin", - "mask-position", - "mask-position-x", - "mask-position-y", - "mask-repeat", - "mask-size", - "mask-type", - "maskClip", - "maskComposite", - "maskContentUnits", - "maskImage", - "maskMode", - "maskOrigin", - "maskPosition", - "maskPositionX", - "maskPositionY", - "maskRepeat", - "maskSize", - "maskType", - "maskUnits", - "match", - "matchAll", - "matchMedia", - "matchMedium", - "matches", - "matrix", - "matrixTransform", - "max", - "max-block-size", - "max-height", - "max-inline-size", - "max-width", - "maxActions", - "maxAlternatives", - "maxBlockSize", - "maxChannelCount", - "maxChannels", - "maxConnectionsPerServer", - "maxDecibels", - "maxDistance", - "maxHeight", - "maxInlineSize", - "maxLayers", - "maxLength", - "maxMessageSize", - "maxPacketLifeTime", - "maxRetransmits", - "maxTouchPoints", - "maxValue", - "maxWidth", - "measure", - "measureText", - "media", - "mediaCapabilities", - "mediaDevices", - "mediaElement", - "mediaGroup", - "mediaKeys", - "mediaSession", - "mediaStream", - "mediaText", - "meetOrSlice", - "memory", - "menubar", - "mergeAttributes", - "message", - "messageClass", - "messageHandlers", - "messageType", - "metaKey", - "metadata", - "method", - "methodDetails", - "methodName", - "mid", - "mimeType", - "mimeTypes", - "min", - "min-block-size", - "min-height", - "min-inline-size", - "min-width", - "minBlockSize", - "minDecibels", - "minHeight", - "minInlineSize", - "minLength", - "minValue", - "minWidth", - "miterLimit", - "mix-blend-mode", - "mixBlendMode", - "mm", - "mode", - "modify", - "mount", - "move", - "moveBy", - "moveEnd", - "moveFirst", - "moveFocusDown", - "moveFocusLeft", - "moveFocusRight", - "moveFocusUp", - "moveNext", - "moveRow", - "moveStart", - "moveTo", - "moveToBookmark", - "moveToElementText", - "moveToPoint", - "movementX", - "movementY", - "mozAdd", - "mozAnimationStartTime", - "mozAnon", - "mozApps", - "mozAudioCaptured", - "mozAudioChannelType", - "mozAutoplayEnabled", - "mozCancelAnimationFrame", - "mozCancelFullScreen", - "mozCancelRequestAnimationFrame", - "mozCaptureStream", - "mozCaptureStreamUntilEnded", - "mozClearDataAt", - "mozContact", - "mozContacts", - "mozCreateFileHandle", - "mozCurrentTransform", - "mozCurrentTransformInverse", - "mozCursor", - "mozDash", - "mozDashOffset", - "mozDecodedFrames", - "mozExitPointerLock", - "mozFillRule", - "mozFragmentEnd", - "mozFrameDelay", - "mozFullScreen", - "mozFullScreenElement", - "mozFullScreenEnabled", - "mozGetAll", - "mozGetAllKeys", - "mozGetAsFile", - "mozGetDataAt", - "mozGetMetadata", - "mozGetUserMedia", - "mozHasAudio", - "mozHasItem", - "mozHidden", - "mozImageSmoothingEnabled", - "mozIndexedDB", - "mozInnerScreenX", - "mozInnerScreenY", - "mozInputSource", - "mozIsTextField", - "mozItem", - "mozItemCount", - "mozItems", - "mozLength", - "mozLockOrientation", - "mozMatchesSelector", - "mozMovementX", - "mozMovementY", - "mozOpaque", - "mozOrientation", - "mozPaintCount", - "mozPaintedFrames", - "mozParsedFrames", - "mozPay", - "mozPointerLockElement", - "mozPresentedFrames", - "mozPreservesPitch", - "mozPressure", - "mozPrintCallback", - "mozRTCIceCandidate", - "mozRTCPeerConnection", - "mozRTCSessionDescription", - "mozRemove", - "mozRequestAnimationFrame", - "mozRequestFullScreen", - "mozRequestPointerLock", - "mozSetDataAt", - "mozSetImageElement", - "mozSourceNode", - "mozSrcObject", - "mozSystem", - "mozTCPSocket", - "mozTextStyle", - "mozTypesAt", - "mozUnlockOrientation", - "mozUserCancelled", - "mozVisibilityState", - "ms", - "msAnimation", - "msAnimationDelay", - "msAnimationDirection", - "msAnimationDuration", - "msAnimationFillMode", - "msAnimationIterationCount", - "msAnimationName", - "msAnimationPlayState", - "msAnimationStartTime", - "msAnimationTimingFunction", - "msBackfaceVisibility", - "msBlockProgression", - "msCSSOMElementFloatMetrics", - "msCaching", - "msCachingEnabled", - "msCancelRequestAnimationFrame", - "msCapsLockWarningOff", - "msClearImmediate", - "msClose", - "msContentZoomChaining", - "msContentZoomFactor", - "msContentZoomLimit", - "msContentZoomLimitMax", - "msContentZoomLimitMin", - "msContentZoomSnap", - "msContentZoomSnapPoints", - "msContentZoomSnapType", - "msContentZooming", - "msConvertURL", - "msCrypto", - "msDoNotTrack", - "msElementsFromPoint", - "msElementsFromRect", - "msExitFullscreen", - "msExtendedCode", - "msFillRule", - "msFirstPaint", - "msFlex", - "msFlexAlign", - "msFlexDirection", - "msFlexFlow", - "msFlexItemAlign", - "msFlexLinePack", - "msFlexNegative", - "msFlexOrder", - "msFlexPack", - "msFlexPositive", - "msFlexPreferredSize", - "msFlexWrap", - "msFlowFrom", - "msFlowInto", - "msFontFeatureSettings", - "msFullscreenElement", - "msFullscreenEnabled", - "msGetInputContext", - "msGetRegionContent", - "msGetUntransformedBounds", - "msGraphicsTrustStatus", - "msGridColumn", - "msGridColumnAlign", - "msGridColumnSpan", - "msGridColumns", - "msGridRow", - "msGridRowAlign", - "msGridRowSpan", - "msGridRows", - "msHidden", - "msHighContrastAdjust", - "msHyphenateLimitChars", - "msHyphenateLimitLines", - "msHyphenateLimitZone", - "msHyphens", - "msImageSmoothingEnabled", - "msImeAlign", - "msIndexedDB", - "msInterpolationMode", - "msIsStaticHTML", - "msKeySystem", - "msKeys", - "msLaunchUri", - "msLockOrientation", - "msManipulationViewsEnabled", - "msMatchMedia", - "msMatchesSelector", - "msMaxTouchPoints", - "msOrientation", - "msOverflowStyle", - "msPerspective", - "msPerspectiveOrigin", - "msPlayToDisabled", - "msPlayToPreferredSourceUri", - "msPlayToPrimary", - "msPointerEnabled", - "msRegionOverflow", - "msReleasePointerCapture", - "msRequestAnimationFrame", - "msRequestFullscreen", - "msSaveBlob", - "msSaveOrOpenBlob", - "msScrollChaining", - "msScrollLimit", - "msScrollLimitXMax", - "msScrollLimitXMin", - "msScrollLimitYMax", - "msScrollLimitYMin", - "msScrollRails", - "msScrollSnapPointsX", - "msScrollSnapPointsY", - "msScrollSnapType", - "msScrollSnapX", - "msScrollSnapY", - "msScrollTranslation", - "msSetImmediate", - "msSetMediaKeys", - "msSetPointerCapture", - "msTextCombineHorizontal", - "msTextSizeAdjust", - "msToBlob", - "msTouchAction", - "msTouchSelect", - "msTraceAsyncCallbackCompleted", - "msTraceAsyncCallbackStarting", - "msTraceAsyncOperationCompleted", - "msTraceAsyncOperationStarting", - "msTransform", - "msTransformOrigin", - "msTransformStyle", - "msTransition", - "msTransitionDelay", - "msTransitionDuration", - "msTransitionProperty", - "msTransitionTimingFunction", - "msUnlockOrientation", - "msUpdateAsyncCallbackRelation", - "msUserSelect", - "msVisibilityState", - "msWrapFlow", - "msWrapMargin", - "msWrapThrough", - "msWriteProfilerMark", - "msZoom", - "msZoomTo", - "mt", - "mul", - "multiEntry", - "multiSelectionObj", - "multiline", - "multiple", - "multiply", - "multiplySelf", - "mutableFile", - "muted", - "n", - "name", - "nameProp", - "namedItem", - "namedRecordset", - "names", - "namespaceURI", - "namespaces", - "naturalHeight", - "naturalWidth", - "navigate", - "navigation", - "navigationMode", - "navigationPreload", - "navigationStart", - "navigator", - "near", - "nearestViewportElement", - "negative", - "negotiated", - "netscape", - "networkState", - "newScale", - "newTranslate", - "newURL", - "newValue", - "newValueSpecifiedUnits", - "newVersion", - "newhome", - "next", - "nextElementSibling", - "nextHopProtocol", - "nextNode", - "nextPage", - "nextSibling", - "nickname", - "noHref", - "noModule", - "noResize", - "noShade", - "noValidate", - "noWrap", - "node", - "nodeName", - "nodeType", - "nodeValue", - "nonce", - "normalize", - "normalizedPathSegList", - "notationName", - "notations", - "note", - "noteGrainOn", - "noteOff", - "noteOn", - "notify", - "now", - "numOctaves", - "number", - "numberOfChannels", - "numberOfInputs", - "numberOfItems", - "numberOfOutputs", - "numberValue", - "oMatchesSelector", - "object", - "object-fit", - "object-position", - "objectFit", - "objectPosition", - "objectStore", - "objectStoreNames", - "objectType", - "observe", - "of", - "offscreenBuffering", - "offset", - "offset-anchor", - "offset-distance", - "offset-path", - "offset-rotate", - "offsetAnchor", - "offsetDistance", - "offsetHeight", - "offsetLeft", - "offsetNode", - "offsetParent", - "offsetPath", - "offsetRotate", - "offsetTop", - "offsetWidth", - "offsetX", - "offsetY", - "ok", - "oldURL", - "oldValue", - "oldVersion", - "olderShadowRoot", - "onLine", - "onabort", - "onabsolutedeviceorientation", - "onactivate", - "onactive", - "onaddsourcebuffer", - "onaddstream", - "onaddtrack", - "onafterprint", - "onafterscriptexecute", - "onafterupdate", - "onanimationcancel", - "onanimationend", - "onanimationiteration", - "onanimationstart", - "onappinstalled", - "onaudioend", - "onaudioprocess", - "onaudiostart", - "onautocomplete", - "onautocompleteerror", - "onauxclick", - "onbeforeactivate", - "onbeforecopy", - "onbeforecut", - "onbeforedeactivate", - "onbeforeeditfocus", - "onbeforeinstallprompt", - "onbeforepaste", - "onbeforeprint", - "onbeforescriptexecute", - "onbeforeunload", - "onbeforeupdate", - "onbeforexrselect", - "onbegin", - "onblocked", - "onblur", - "onbounce", - "onboundary", - "onbufferedamountlow", - "oncached", - "oncancel", - "oncandidatewindowhide", - "oncandidatewindowshow", - "oncandidatewindowupdate", - "oncanplay", - "oncanplaythrough", - "once", - "oncellchange", - "onchange", - "oncharacteristicvaluechanged", - "onchargingchange", - "onchargingtimechange", - "onchecking", - "onclick", - "onclose", - "onclosing", - "oncompassneedscalibration", - "oncomplete", - "onconnect", - "onconnecting", - "onconnectionavailable", - "onconnectionstatechange", - "oncontextmenu", - "oncontrollerchange", - "oncontrolselect", - "oncopy", - "oncuechange", - "oncut", - "ondataavailable", - "ondatachannel", - "ondatasetchanged", - "ondatasetcomplete", - "ondblclick", - "ondeactivate", - "ondevicechange", - "ondevicelight", - "ondevicemotion", - "ondeviceorientation", - "ondeviceorientationabsolute", - "ondeviceproximity", - "ondischargingtimechange", - "ondisconnect", - "ondisplay", - "ondownloading", - "ondrag", - "ondragend", - "ondragenter", - "ondragexit", - "ondragleave", - "ondragover", - "ondragstart", - "ondrop", - "ondurationchange", - "onemptied", - "onencrypted", - "onend", - "onended", - "onenter", - "onenterpictureinpicture", - "onerror", - "onerrorupdate", - "onexit", - "onfilterchange", - "onfinish", - "onfocus", - "onfocusin", - "onfocusout", - "onformdata", - "onfreeze", - "onfullscreenchange", - "onfullscreenerror", - "ongatheringstatechange", - "ongattserverdisconnected", - "ongesturechange", - "ongestureend", - "ongesturestart", - "ongotpointercapture", - "onhashchange", - "onhelp", - "onicecandidate", - "onicecandidateerror", - "oniceconnectionstatechange", - "onicegatheringstatechange", - "oninactive", - "oninput", - "oninputsourceschange", - "oninvalid", - "onkeydown", - "onkeypress", - "onkeystatuseschange", - "onkeyup", - "onlanguagechange", - "onlayoutcomplete", - "onleavepictureinpicture", - "onlevelchange", - "onload", - "onloadeddata", - "onloadedmetadata", - "onloadend", - "onloading", - "onloadingdone", - "onloadingerror", - "onloadstart", - "onlosecapture", - "onlostpointercapture", - "only", - "onmark", - "onmessage", - "onmessageerror", - "onmidimessage", - "onmousedown", - "onmouseenter", - "onmouseleave", - "onmousemove", - "onmouseout", - "onmouseover", - "onmouseup", - "onmousewheel", - "onmove", - "onmoveend", - "onmovestart", - "onmozfullscreenchange", - "onmozfullscreenerror", - "onmozorientationchange", - "onmozpointerlockchange", - "onmozpointerlockerror", - "onmscontentzoom", - "onmsfullscreenchange", - "onmsfullscreenerror", - "onmsgesturechange", - "onmsgesturedoubletap", - "onmsgestureend", - "onmsgesturehold", - "onmsgesturestart", - "onmsgesturetap", - "onmsgotpointercapture", - "onmsinertiastart", - "onmslostpointercapture", - "onmsmanipulationstatechanged", - "onmsneedkey", - "onmsorientationchange", - "onmspointercancel", - "onmspointerdown", - "onmspointerenter", - "onmspointerhover", - "onmspointerleave", - "onmspointermove", - "onmspointerout", - "onmspointerover", - "onmspointerup", - "onmssitemodejumplistitemremoved", - "onmsthumbnailclick", - "onmute", - "onnegotiationneeded", - "onnomatch", - "onnoupdate", - "onobsolete", - "onoffline", - "ononline", - "onopen", - "onorientationchange", - "onpagechange", - "onpagehide", - "onpageshow", - "onpaste", - "onpause", - "onpayerdetailchange", - "onpaymentmethodchange", - "onplay", - "onplaying", - "onpluginstreamstart", - "onpointercancel", - "onpointerdown", - "onpointerenter", - "onpointerleave", - "onpointerlockchange", - "onpointerlockerror", - "onpointermove", - "onpointerout", - "onpointerover", - "onpointerrawupdate", - "onpointerup", - "onpopstate", - "onprocessorerror", - "onprogress", - "onpropertychange", - "onratechange", - "onreading", - "onreadystatechange", - "onrejectionhandled", - "onrelease", - "onremove", - "onremovesourcebuffer", - "onremovestream", - "onremovetrack", - "onrepeat", - "onreset", - "onresize", - "onresizeend", - "onresizestart", - "onresourcetimingbufferfull", - "onresult", - "onresume", - "onrowenter", - "onrowexit", - "onrowsdelete", - "onrowsinserted", - "onscroll", - "onsearch", - "onsecuritypolicyviolation", - "onseeked", - "onseeking", - "onselect", - "onselectedcandidatepairchange", - "onselectend", - "onselectionchange", - "onselectstart", - "onshippingaddresschange", - "onshippingoptionchange", - "onshow", - "onsignalingstatechange", - "onsoundend", - "onsoundstart", - "onsourceclose", - "onsourceclosed", - "onsourceended", - "onsourceopen", - "onspeechend", - "onspeechstart", - "onsqueeze", - "onsqueezeend", - "onsqueezestart", - "onstalled", - "onstart", - "onstatechange", - "onstop", - "onstorage", - "onstoragecommit", - "onsubmit", - "onsuccess", - "onsuspend", - "onterminate", - "ontextinput", - "ontimeout", - "ontimeupdate", - "ontoggle", - "ontonechange", - "ontouchcancel", - "ontouchend", - "ontouchmove", - "ontouchstart", - "ontrack", - "ontransitioncancel", - "ontransitionend", - "ontransitionrun", - "ontransitionstart", - "onunhandledrejection", - "onunload", - "onunmute", - "onupdate", - "onupdateend", - "onupdatefound", - "onupdateready", - "onupdatestart", - "onupgradeneeded", - "onuserproximity", - "onversionchange", - "onvisibilitychange", - "onvoiceschanged", - "onvolumechange", - "onvrdisplayactivate", - "onvrdisplayconnect", - "onvrdisplaydeactivate", - "onvrdisplaydisconnect", - "onvrdisplaypresentchange", - "onwaiting", - "onwaitingforkey", - "onwarning", - "onwebkitanimationend", - "onwebkitanimationiteration", - "onwebkitanimationstart", - "onwebkitcurrentplaybacktargetiswirelesschanged", - "onwebkitfullscreenchange", - "onwebkitfullscreenerror", - "onwebkitkeyadded", - "onwebkitkeyerror", - "onwebkitkeymessage", - "onwebkitneedkey", - "onwebkitorientationchange", - "onwebkitplaybacktargetavailabilitychanged", - "onwebkitpointerlockchange", - "onwebkitpointerlockerror", - "onwebkitresourcetimingbufferfull", - "onwebkittransitionend", - "onwheel", - "onzoom", - "opacity", - "open", - "openCursor", - "openDatabase", - "openKeyCursor", - "opened", - "opener", - "opera", - "operationType", - "operator", - "opr", - "optimum", - "options", - "or", - "order", - "orderX", - "orderY", - "ordered", - "org", - "organization", - "orient", - "orientAngle", - "orientType", - "orientation", - "orientationX", - "orientationY", - "orientationZ", - "origin", - "originalPolicy", - "originalTarget", - "orphans", - "oscpu", - "outerHTML", - "outerHeight", - "outerText", - "outerWidth", - "outline", - "outline-color", - "outline-offset", - "outline-style", - "outline-width", - "outlineColor", - "outlineOffset", - "outlineStyle", - "outlineWidth", - "outputBuffer", - "outputLatency", - "outputs", - "overflow", - "overflow-anchor", - "overflow-block", - "overflow-inline", - "overflow-wrap", - "overflow-x", - "overflow-y", - "overflowAnchor", - "overflowBlock", - "overflowInline", - "overflowWrap", - "overflowX", - "overflowY", - "overrideMimeType", - "oversample", - "overscroll-behavior", - "overscroll-behavior-block", - "overscroll-behavior-inline", - "overscroll-behavior-x", - "overscroll-behavior-y", - "overscrollBehavior", - "overscrollBehaviorBlock", - "overscrollBehaviorInline", - "overscrollBehaviorX", - "overscrollBehaviorY", - "ownKeys", - "ownerDocument", - "ownerElement", - "ownerNode", - "ownerRule", - "ownerSVGElement", - "owningElement", - "p1", - "p2", - "p3", - "p4", - "packetSize", - "packets", - "pad", - "padEnd", - "padStart", - "padding", - "padding-block", - "padding-block-end", - "padding-block-start", - "padding-bottom", - "padding-inline", - "padding-inline-end", - "padding-inline-start", - "padding-left", - "padding-right", - "padding-top", - "paddingBlock", - "paddingBlockEnd", - "paddingBlockStart", - "paddingBottom", - "paddingInline", - "paddingInlineEnd", - "paddingInlineStart", - "paddingLeft", - "paddingRight", - "paddingTop", - "page", - "page-break-after", - "page-break-before", - "page-break-inside", - "pageBreakAfter", - "pageBreakBefore", - "pageBreakInside", - "pageCount", - "pageLeft", - "pageTop", - "pageX", - "pageXOffset", - "pageY", - "pageYOffset", - "pages", - "paint-order", - "paintOrder", - "paintRequests", - "paintType", - "paintWorklet", - "palette", - "pan", - "panningModel", - "parameters", - "parent", - "parentElement", - "parentNode", - "parentRule", - "parentStyleSheet", - "parentTextEdit", - "parentWindow", - "parse", - "parseAll", - "parseFloat", - "parseFromString", - "parseInt", - "part", - "participants", - "passive", - "password", - "pasteHTML", - "path", - "pathLength", - "pathSegList", - "pathSegType", - "pathSegTypeAsLetter", - "pathname", - "pattern", - "patternContentUnits", - "patternMismatch", - "patternTransform", - "patternUnits", - "pause", - "pauseAnimations", - "pauseOnExit", - "pauseProfilers", - "pauseTransformFeedback", - "paused", - "payerEmail", - "payerName", - "payerPhone", - "paymentManager", - "pc", - "peerIdentity", - "pending", - "pendingLocalDescription", - "pendingRemoteDescription", - "percent", - "performance", - "periodicSync", - "permission", - "permissionState", - "permissions", - "persist", - "persisted", - "personalbar", - "perspective", - "perspective-origin", - "perspectiveOrigin", - "phone", - "phoneticFamilyName", - "phoneticGivenName", - "photo", - "pictureInPictureElement", - "pictureInPictureEnabled", - "pictureInPictureWindow", - "ping", - "pipeThrough", - "pipeTo", - "pitch", - "pixelBottom", - "pixelDepth", - "pixelHeight", - "pixelLeft", - "pixelRight", - "pixelStorei", - "pixelTop", - "pixelUnitToMillimeterX", - "pixelUnitToMillimeterY", - "pixelWidth", - "place-content", - "place-items", - "place-self", - "placeContent", - "placeItems", - "placeSelf", - "placeholder", - "platform", - "platforms", - "play", - "playEffect", - "playState", - "playbackRate", - "playbackState", - "playbackTime", - "played", - "playoutDelayHint", - "playsInline", - "plugins", - "pluginspage", - "pname", - "pointer-events", - "pointerBeforeReferenceNode", - "pointerEnabled", - "pointerEvents", - "pointerId", - "pointerLockElement", - "pointerType", - "points", - "pointsAtX", - "pointsAtY", - "pointsAtZ", - "polygonOffset", - "pop", - "populateMatrix", - "popupWindowFeatures", - "popupWindowName", - "popupWindowURI", - "port", - "port1", - "port2", - "ports", - "posBottom", - "posHeight", - "posLeft", - "posRight", - "posTop", - "posWidth", - "pose", - "position", - "positionAlign", - "positionX", - "positionY", - "positionZ", - "postError", - "postMessage", - "postalCode", - "poster", - "pow", - "powerEfficient", - "powerOff", - "preMultiplySelf", - "precision", - "preferredStyleSheetSet", - "preferredStylesheetSet", - "prefix", - "preload", - "prepend", - "presentation", - "preserveAlpha", - "preserveAspectRatio", - "preserveAspectRatioString", - "pressed", - "pressure", - "prevValue", - "preventDefault", - "preventExtensions", - "preventSilentAccess", - "previousElementSibling", - "previousNode", - "previousPage", - "previousRect", - "previousScale", - "previousSibling", - "previousTranslate", - "primaryKey", - "primitiveType", - "primitiveUnits", - "principals", - "print", - "priority", - "privateKey", - "probablySupportsContext", - "process", - "processIceMessage", - "processingEnd", - "processingStart", - "product", - "productId", - "productName", - "productSub", - "profile", - "profileEnd", - "profiles", - "projectionMatrix", - "promise", - "prompt", - "properties", - "propertyIsEnumerable", - "propertyName", - "protocol", - "protocolLong", - "prototype", - "provider", - "pseudoClass", - "pseudoElement", - "pt", - "publicId", - "publicKey", - "published", - "pulse", - "push", - "pushManager", - "pushNotification", - "pushState", - "put", - "putImageData", - "px", - "quadraticCurveTo", - "qualifier", - "quaternion", - "query", - "queryCommandEnabled", - "queryCommandIndeterm", - "queryCommandState", - "queryCommandSupported", - "queryCommandText", - "queryCommandValue", - "querySelector", - "querySelectorAll", - "queueMicrotask", - "quote", - "quotes", - "r", - "r1", - "r2", - "race", - "rad", - "radiogroup", - "radiusX", - "radiusY", - "random", - "range", - "rangeCount", - "rangeMax", - "rangeMin", - "rangeOffset", - "rangeOverflow", - "rangeParent", - "rangeUnderflow", - "rate", - "ratio", - "raw", - "rawId", - "read", - "readAsArrayBuffer", - "readAsBinaryString", - "readAsBlob", - "readAsDataURL", - "readAsText", - "readBuffer", - "readEntries", - "readOnly", - "readPixels", - "readReportRequested", - "readText", - "readValue", - "readable", - "ready", - "readyState", - "reason", - "reboot", - "receivedAlert", - "receiver", - "receivers", - "recipient", - "reconnect", - "recordNumber", - "recordsAvailable", - "recordset", - "rect", - "red", - "redEyeReduction", - "redirect", - "redirectCount", - "redirectEnd", - "redirectStart", - "redirected", - "reduce", - "reduceRight", - "reduction", - "refDistance", - "refX", - "refY", - "referenceNode", - "referenceSpace", - "referrer", - "referrerPolicy", - "refresh", - "region", - "regionAnchorX", - "regionAnchorY", - "regionId", - "regions", - "register", - "registerContentHandler", - "registerElement", - "registerProperty", - "registerProtocolHandler", - "reject", - "rel", - "relList", - "relatedAddress", - "relatedNode", - "relatedPort", - "relatedTarget", - "release", - "releaseCapture", - "releaseEvents", - "releaseInterface", - "releaseLock", - "releasePointerCapture", - "releaseShaderCompiler", - "reliable", - "reliableWrite", - "reload", - "rem", - "remainingSpace", - "remote", - "remoteDescription", - "remove", - "removeAllRanges", - "removeAttribute", - "removeAttributeNS", - "removeAttributeNode", - "removeBehavior", - "removeChild", - "removeCue", - "removeEventListener", - "removeFilter", - "removeImport", - "removeItem", - "removeListener", - "removeNamedItem", - "removeNamedItemNS", - "removeNode", - "removeParameter", - "removeProperty", - "removeRange", - "removeRegion", - "removeRule", - "removeSiteSpecificTrackingException", - "removeSourceBuffer", - "removeStream", - "removeTrack", - "removeVariable", - "removeWakeLockListener", - "removeWebWideTrackingException", - "removed", - "removedNodes", - "renderHeight", - "renderState", - "renderTime", - "renderWidth", - "renderbufferStorage", - "renderbufferStorageMultisample", - "renderedBuffer", - "renderingMode", - "renotify", - "repeat", - "replace", - "replaceAdjacentText", - "replaceAll", - "replaceChild", - "replaceChildren", - "replaceData", - "replaceId", - "replaceItem", - "replaceNode", - "replaceState", - "replaceSync", - "replaceTrack", - "replaceWholeText", - "replaceWith", - "reportValidity", - "request", - "requestAnimationFrame", - "requestAutocomplete", - "requestData", - "requestDevice", - "requestFrame", - "requestFullscreen", - "requestHitTestSource", - "requestHitTestSourceForTransientInput", - "requestId", - "requestIdleCallback", - "requestMIDIAccess", - "requestMediaKeySystemAccess", - "requestPermission", - "requestPictureInPicture", - "requestPointerLock", - "requestPresent", - "requestReferenceSpace", - "requestSession", - "requestStart", - "requestStorageAccess", - "requestSubmit", - "requestVideoFrameCallback", - "requestingWindow", - "requireInteraction", - "required", - "requiredExtensions", - "requiredFeatures", - "reset", - "resetPose", - "resetTransform", - "resize", - "resizeBy", - "resizeTo", - "resolve", - "response", - "responseBody", - "responseEnd", - "responseReady", - "responseStart", - "responseText", - "responseType", - "responseURL", - "responseXML", - "restartIce", - "restore", - "result", - "resultIndex", - "resultType", - "results", - "resume", - "resumeProfilers", - "resumeTransformFeedback", - "retry", - "returnValue", - "rev", - "reverse", - "reversed", - "revocable", - "revokeObjectURL", - "rgbColor", - "right", - "rightContext", - "rightDegrees", - "rightMargin", - "rightProjectionMatrix", - "rightViewMatrix", - "role", - "rolloffFactor", - "root", - "rootBounds", - "rootElement", - "rootMargin", - "rotate", - "rotateAxisAngle", - "rotateAxisAngleSelf", - "rotateFromVector", - "rotateFromVectorSelf", - "rotateSelf", - "rotation", - "rotationAngle", - "rotationRate", - "round", - "row-gap", - "rowGap", - "rowIndex", - "rowSpan", - "rows", - "rtcpTransport", - "rtt", - "ruby-align", - "ruby-position", - "rubyAlign", - "rubyOverhang", - "rubyPosition", - "rules", - "runtime", - "runtimeStyle", - "rx", - "ry", - "s", - "safari", - "sample", - "sampleCoverage", - "sampleRate", - "samplerParameterf", - "samplerParameteri", - "sandbox", - "save", - "saveData", - "scale", - "scale3d", - "scale3dSelf", - "scaleNonUniform", - "scaleNonUniformSelf", - "scaleSelf", - "scheme", - "scissor", - "scope", - "scopeName", - "scoped", - "screen", - "screenBrightness", - "screenEnabled", - "screenLeft", - "screenPixelToMillimeterX", - "screenPixelToMillimeterY", - "screenTop", - "screenX", - "screenY", - "scriptURL", - "scripts", - "scroll", - "scroll-behavior", - "scroll-margin", - "scroll-margin-block", - "scroll-margin-block-end", - "scroll-margin-block-start", - "scroll-margin-bottom", - "scroll-margin-inline", - "scroll-margin-inline-end", - "scroll-margin-inline-start", - "scroll-margin-left", - "scroll-margin-right", - "scroll-margin-top", - "scroll-padding", - "scroll-padding-block", - "scroll-padding-block-end", - "scroll-padding-block-start", - "scroll-padding-bottom", - "scroll-padding-inline", - "scroll-padding-inline-end", - "scroll-padding-inline-start", - "scroll-padding-left", - "scroll-padding-right", - "scroll-padding-top", - "scroll-snap-align", - "scroll-snap-type", - "scrollAmount", - "scrollBehavior", - "scrollBy", - "scrollByLines", - "scrollByPages", - "scrollDelay", - "scrollHeight", - "scrollIntoView", - "scrollIntoViewIfNeeded", - "scrollLeft", - "scrollLeftMax", - "scrollMargin", - "scrollMarginBlock", - "scrollMarginBlockEnd", - "scrollMarginBlockStart", - "scrollMarginBottom", - "scrollMarginInline", - "scrollMarginInlineEnd", - "scrollMarginInlineStart", - "scrollMarginLeft", - "scrollMarginRight", - "scrollMarginTop", - "scrollMaxX", - "scrollMaxY", - "scrollPadding", - "scrollPaddingBlock", - "scrollPaddingBlockEnd", - "scrollPaddingBlockStart", - "scrollPaddingBottom", - "scrollPaddingInline", - "scrollPaddingInlineEnd", - "scrollPaddingInlineStart", - "scrollPaddingLeft", - "scrollPaddingRight", - "scrollPaddingTop", - "scrollRestoration", - "scrollSnapAlign", - "scrollSnapType", - "scrollTo", - "scrollTop", - "scrollTopMax", - "scrollWidth", - "scrollX", - "scrollY", - "scrollbar-color", - "scrollbar-width", - "scrollbar3dLightColor", - "scrollbarArrowColor", - "scrollbarBaseColor", - "scrollbarColor", - "scrollbarDarkShadowColor", - "scrollbarFaceColor", - "scrollbarHighlightColor", - "scrollbarShadowColor", - "scrollbarTrackColor", - "scrollbarWidth", - "scrollbars", - "scrolling", - "scrollingElement", - "sctp", - "sctpCauseCode", - "sdp", - "sdpLineNumber", - "sdpMLineIndex", - "sdpMid", - "seal", - "search", - "searchBox", - "searchBoxJavaBridge_", - "searchParams", - "sectionRowIndex", - "secureConnectionStart", - "security", - "seed", - "seekToNextFrame", - "seekable", - "seeking", - "select", - "selectAllChildren", - "selectAlternateInterface", - "selectConfiguration", - "selectNode", - "selectNodeContents", - "selectNodes", - "selectSingleNode", - "selectSubString", - "selected", - "selectedIndex", - "selectedOptions", - "selectedStyleSheetSet", - "selectedStylesheetSet", - "selection", - "selectionDirection", - "selectionEnd", - "selectionStart", - "selector", - "selectorText", - "self", - "send", - "sendAsBinary", - "sendBeacon", - "sender", - "sentAlert", - "sentTimestamp", - "separator", - "serialNumber", - "serializeToString", - "serverTiming", - "service", - "serviceWorker", - "session", - "sessionId", - "sessionStorage", - "set", - "setActionHandler", - "setActive", - "setAlpha", - "setAppBadge", - "setAttribute", - "setAttributeNS", - "setAttributeNode", - "setAttributeNodeNS", - "setBaseAndExtent", - "setBigInt64", - "setBigUint64", - "setBingCurrentSearchDefault", - "setCapture", - "setCodecPreferences", - "setColor", - "setCompositeOperation", - "setConfiguration", - "setCurrentTime", - "setCustomValidity", - "setData", - "setDate", - "setDragImage", - "setEnd", - "setEndAfter", - "setEndBefore", - "setEndPoint", - "setFillColor", - "setFilterRes", - "setFloat32", - "setFloat64", - "setFloatValue", - "setFormValue", - "setFullYear", - "setHeaderValue", - "setHours", - "setIdentityProvider", - "setImmediate", - "setInt16", - "setInt32", - "setInt8", - "setInterval", - "setItem", - "setKeyframes", - "setLineCap", - "setLineDash", - "setLineJoin", - "setLineWidth", - "setLiveSeekableRange", - "setLocalDescription", - "setMatrix", - "setMatrixValue", - "setMediaKeys", - "setMilliseconds", - "setMinutes", - "setMiterLimit", - "setMonth", - "setNamedItem", - "setNamedItemNS", - "setNonUserCodeExceptions", - "setOrientToAngle", - "setOrientToAuto", - "setOrientation", - "setOverrideHistoryNavigationMode", - "setPaint", - "setParameter", - "setParameters", - "setPeriodicWave", - "setPointerCapture", - "setPosition", - "setPositionState", - "setPreference", - "setProperty", - "setPrototypeOf", - "setRGBColor", - "setRGBColorICCColor", - "setRadius", - "setRangeText", - "setRemoteDescription", - "setRequestHeader", - "setResizable", - "setResourceTimingBufferSize", - "setRotate", - "setScale", - "setSeconds", - "setSelectionRange", - "setServerCertificate", - "setShadow", - "setSinkId", - "setSkewX", - "setSkewY", - "setStart", - "setStartAfter", - "setStartBefore", - "setStdDeviation", - "setStreams", - "setStringValue", - "setStrokeColor", - "setSuggestResult", - "setTargetAtTime", - "setTargetValueAtTime", - "setTime", - "setTimeout", - "setTransform", - "setTranslate", - "setUTCDate", - "setUTCFullYear", - "setUTCHours", - "setUTCMilliseconds", - "setUTCMinutes", - "setUTCMonth", - "setUTCSeconds", - "setUint16", - "setUint32", - "setUint8", - "setUri", - "setValidity", - "setValueAtTime", - "setValueCurveAtTime", - "setVariable", - "setVelocity", - "setVersion", - "setYear", - "settingName", - "settingValue", - "sex", - "shaderSource", - "shadowBlur", - "shadowColor", - "shadowOffsetX", - "shadowOffsetY", - "shadowRoot", - "shape", - "shape-image-threshold", - "shape-margin", - "shape-outside", - "shape-rendering", - "shapeImageThreshold", - "shapeMargin", - "shapeOutside", - "shapeRendering", - "sheet", - "shift", - "shiftKey", - "shiftLeft", - "shippingAddress", - "shippingOption", - "shippingType", - "show", - "showHelp", - "showModal", - "showModalDialog", - "showModelessDialog", - "showNotification", - "sidebar", - "sign", - "signal", - "signalingState", - "signature", - "silent", - "sin", - "singleNodeValue", - "sinh", - "sinkId", - "sittingToStandingTransform", - "size", - "sizeToContent", - "sizeX", - "sizeZ", - "sizes", - "skewX", - "skewXSelf", - "skewY", - "skewYSelf", - "slice", - "slope", - "slot", - "small", - "smil", - "smooth", - "smoothingTimeConstant", - "snapToLines", - "snapshotItem", - "snapshotLength", - "some", - "sort", - "sortingCode", - "source", - "sourceBuffer", - "sourceBuffers", - "sourceCapabilities", - "sourceFile", - "sourceIndex", - "sources", - "spacing", - "span", - "speak", - "speakAs", - "speaking", - "species", - "specified", - "specularConstant", - "specularExponent", - "speechSynthesis", - "speed", - "speedOfSound", - "spellcheck", - "splice", - "split", - "splitText", - "spreadMethod", - "sqrt", - "src", - "srcElement", - "srcFilter", - "srcObject", - "srcUrn", - "srcdoc", - "srclang", - "srcset", - "stack", - "stackTraceLimit", - "stacktrace", - "stageParameters", - "standalone", - "standby", - "start", - "startContainer", - "startIce", - "startMessages", - "startNotifications", - "startOffset", - "startProfiling", - "startRendering", - "startShark", - "startTime", - "startsWith", - "state", - "status", - "statusCode", - "statusMessage", - "statusText", - "statusbar", - "stdDeviationX", - "stdDeviationY", - "stencilFunc", - "stencilFuncSeparate", - "stencilMask", - "stencilMaskSeparate", - "stencilOp", - "stencilOpSeparate", - "step", - "stepDown", - "stepMismatch", - "stepUp", - "sticky", - "stitchTiles", - "stop", - "stop-color", - "stop-opacity", - "stopColor", - "stopImmediatePropagation", - "stopNotifications", - "stopOpacity", - "stopProfiling", - "stopPropagation", - "stopShark", - "stopped", - "storage", - "storageArea", - "storageName", - "storageStatus", - "store", - "storeSiteSpecificTrackingException", - "storeWebWideTrackingException", - "stpVersion", - "stream", - "streams", - "stretch", - "strike", - "string", - "stringValue", - "stringify", - "stroke", - "stroke-dasharray", - "stroke-dashoffset", - "stroke-linecap", - "stroke-linejoin", - "stroke-miterlimit", - "stroke-opacity", - "stroke-width", - "strokeDasharray", - "strokeDashoffset", - "strokeLinecap", - "strokeLinejoin", - "strokeMiterlimit", - "strokeOpacity", - "strokeRect", - "strokeStyle", - "strokeText", - "strokeWidth", - "style", - "styleFloat", - "styleMap", - "styleMedia", - "styleSheet", - "styleSheetSets", - "styleSheets", - "sub", - "subarray", - "subject", - "submit", - "submitFrame", - "submitter", - "subscribe", - "substr", - "substring", - "substringData", - "subtle", - "subtree", - "suffix", - "suffixes", - "summary", - "sup", - "supported", - "supportedContentEncodings", - "supportedEntryTypes", - "supports", - "supportsSession", - "surfaceScale", - "surroundContents", - "suspend", - "suspendRedraw", - "swapCache", - "swapNode", - "sweepFlag", - "symbols", - "sync", - "sysexEnabled", - "system", - "systemCode", - "systemId", - "systemLanguage", - "systemXDPI", - "systemYDPI", - "tBodies", - "tFoot", - "tHead", - "tabIndex", - "table", - "table-layout", - "tableLayout", - "tableValues", - "tag", - "tagName", - "tagUrn", - "tags", - "taintEnabled", - "takePhoto", - "takeRecords", - "tan", - "tangentialPressure", - "tanh", - "target", - "targetElement", - "targetRayMode", - "targetRaySpace", - "targetTouches", - "targetX", - "targetY", - "tcpType", - "tee", - "tel", - "terminate", - "test", - "texImage2D", - "texImage3D", - "texParameterf", - "texParameteri", - "texStorage2D", - "texStorage3D", - "texSubImage2D", - "texSubImage3D", - "text", - "text-align", - "text-align-last", - "text-anchor", - "text-combine-upright", - "text-decoration", - "text-decoration-color", - "text-decoration-line", - "text-decoration-skip-ink", - "text-decoration-style", - "text-decoration-thickness", - "text-emphasis", - "text-emphasis-color", - "text-emphasis-position", - "text-emphasis-style", - "text-indent", - "text-justify", - "text-orientation", - "text-overflow", - "text-rendering", - "text-shadow", - "text-transform", - "text-underline-offset", - "text-underline-position", - "textAlign", - "textAlignLast", - "textAnchor", - "textAutospace", - "textBaseline", - "textCombineUpright", - "textContent", - "textDecoration", - "textDecorationBlink", - "textDecorationColor", - "textDecorationLine", - "textDecorationLineThrough", - "textDecorationNone", - "textDecorationOverline", - "textDecorationSkipInk", - "textDecorationStyle", - "textDecorationThickness", - "textDecorationUnderline", - "textEmphasis", - "textEmphasisColor", - "textEmphasisPosition", - "textEmphasisStyle", - "textIndent", - "textJustify", - "textJustifyTrim", - "textKashida", - "textKashidaSpace", - "textLength", - "textOrientation", - "textOverflow", - "textRendering", - "textShadow", - "textTracks", - "textTransform", - "textUnderlineOffset", - "textUnderlinePosition", - "then", - "threadId", - "threshold", - "thresholds", - "tiltX", - "tiltY", - "time", - "timeEnd", - "timeLog", - "timeOrigin", - "timeRemaining", - "timeStamp", - "timecode", - "timeline", - "timelineTime", - "timeout", - "timestamp", - "timestampOffset", - "timing", - "title", - "to", - "toArray", - "toBlob", - "toDataURL", - "toDateString", - "toElement", - "toExponential", - "toFixed", - "toFloat32Array", - "toFloat64Array", - "toGMTString", - "toISOString", - "toJSON", - "toLocaleDateString", - "toLocaleFormat", - "toLocaleLowerCase", - "toLocaleString", - "toLocaleTimeString", - "toLocaleUpperCase", - "toLowerCase", - "toMatrix", - "toMethod", - "toPrecision", - "toPrimitive", - "toSdp", - "toSource", - "toStaticHTML", - "toString", - "toStringTag", - "toSum", - "toTimeString", - "toUTCString", - "toUpperCase", - "toggle", - "toggleAttribute", - "toggleLongPressEnabled", - "tone", - "toneBuffer", - "tooLong", - "tooShort", - "toolbar", - "top", - "topMargin", - "total", - "totalFrameDelay", - "totalVideoFrames", - "touch-action", - "touchAction", - "touched", - "touches", - "trace", - "track", - "trackVisibility", - "transaction", - "transactions", - "transceiver", - "transferControlToOffscreen", - "transferFromImageBitmap", - "transferImageBitmap", - "transferIn", - "transferOut", - "transferSize", - "transferToImageBitmap", - "transform", - "transform-box", - "transform-origin", - "transform-style", - "transformBox", - "transformFeedbackVaryings", - "transformOrigin", - "transformPoint", - "transformString", - "transformStyle", - "transformToDocument", - "transformToFragment", - "transition", - "transition-delay", - "transition-duration", - "transition-property", - "transition-timing-function", - "transitionDelay", - "transitionDuration", - "transitionProperty", - "transitionTimingFunction", - "translate", - "translateSelf", - "translationX", - "translationY", - "transport", - "trim", - "trimEnd", - "trimLeft", - "trimRight", - "trimStart", - "trueSpeed", - "trunc", - "truncate", - "trustedTypes", - "turn", - "twist", - "type", - "typeDetail", - "typeMismatch", - "typeMustMatch", - "types", - "u2f", - "ubound", - "uint16", - "uint32", - "uint8", - "uint8Clamped", - "undefined", - "unescape", - "uneval", - "unicode", - "unicode-bidi", - "unicodeBidi", - "unicodeRange", - "uniform1f", - "uniform1fv", - "uniform1i", - "uniform1iv", - "uniform1ui", - "uniform1uiv", - "uniform2f", - "uniform2fv", - "uniform2i", - "uniform2iv", - "uniform2ui", - "uniform2uiv", - "uniform3f", - "uniform3fv", - "uniform3i", - "uniform3iv", - "uniform3ui", - "uniform3uiv", - "uniform4f", - "uniform4fv", - "uniform4i", - "uniform4iv", - "uniform4ui", - "uniform4uiv", - "uniformBlockBinding", - "uniformMatrix2fv", - "uniformMatrix2x3fv", - "uniformMatrix2x4fv", - "uniformMatrix3fv", - "uniformMatrix3x2fv", - "uniformMatrix3x4fv", - "uniformMatrix4fv", - "uniformMatrix4x2fv", - "uniformMatrix4x3fv", - "unique", - "uniqueID", - "uniqueNumber", - "unit", - "unitType", - "units", - "unloadEventEnd", - "unloadEventStart", - "unlock", - "unmount", - "unobserve", - "unpause", - "unpauseAnimations", - "unreadCount", - "unregister", - "unregisterContentHandler", - "unregisterProtocolHandler", - "unscopables", - "unselectable", - "unshift", - "unsubscribe", - "unsuspendRedraw", - "unsuspendRedrawAll", - "unwatch", - "unwrapKey", - "upDegrees", - "upX", - "upY", - "upZ", - "update", - "updateCommands", - "updateIce", - "updateInterval", - "updatePlaybackRate", - "updateRenderState", - "updateSettings", - "updateTiming", - "updateViaCache", - "updateWith", - "updated", - "updating", - "upgrade", - "upload", - "uploadTotal", - "uploaded", - "upper", - "upperBound", - "upperOpen", - "uri", - "url", - "urn", - "urns", - "usages", - "usb", - "usbVersionMajor", - "usbVersionMinor", - "usbVersionSubminor", - "useCurrentView", - "useMap", - "useProgram", - "usedSpace", - "user-select", - "userActivation", - "userAgent", - "userChoice", - "userHandle", - "userHint", - "userLanguage", - "userSelect", - "userVisibleOnly", - "username", - "usernameFragment", - "utterance", - "uuid", - "v8BreakIterator", - "vAlign", - "vLink", - "valid", - "validate", - "validateProgram", - "validationMessage", - "validity", - "value", - "valueAsDate", - "valueAsNumber", - "valueAsString", - "valueInSpecifiedUnits", - "valueMissing", - "valueOf", - "valueText", - "valueType", - "values", - "variable", - "variant", - "variationSettings", - "vector-effect", - "vectorEffect", - "velocityAngular", - "velocityExpansion", - "velocityX", - "velocityY", - "vendor", - "vendorId", - "vendorSub", - "verify", - "version", - "vertexAttrib1f", - "vertexAttrib1fv", - "vertexAttrib2f", - "vertexAttrib2fv", - "vertexAttrib3f", - "vertexAttrib3fv", - "vertexAttrib4f", - "vertexAttrib4fv", - "vertexAttribDivisor", - "vertexAttribDivisorANGLE", - "vertexAttribI4i", - "vertexAttribI4iv", - "vertexAttribI4ui", - "vertexAttribI4uiv", - "vertexAttribIPointer", - "vertexAttribPointer", - "vertical", - "vertical-align", - "verticalAlign", - "verticalOverflow", - "vh", - "vibrate", - "vibrationActuator", - "videoBitsPerSecond", - "videoHeight", - "videoTracks", - "videoWidth", - "view", - "viewBox", - "viewBoxString", - "viewTarget", - "viewTargetString", - "viewport", - "viewportAnchorX", - "viewportAnchorY", - "viewportElement", - "views", - "violatedDirective", - "visibility", - "visibilityState", - "visible", - "visualViewport", - "vlinkColor", - "vmax", - "vmin", - "voice", - "voiceURI", - "volume", - "vrml", - "vspace", - "vw", - "w", - "wait", - "waitSync", - "waiting", - "wake", - "wakeLock", - "wand", - "warn", - "wasClean", - "wasDiscarded", - "watch", - "watchAvailability", - "watchPosition", - "webdriver", - "webkitAddKey", - "webkitAlignContent", - "webkitAlignItems", - "webkitAlignSelf", - "webkitAnimation", - "webkitAnimationDelay", - "webkitAnimationDirection", - "webkitAnimationDuration", - "webkitAnimationFillMode", - "webkitAnimationIterationCount", - "webkitAnimationName", - "webkitAnimationPlayState", - "webkitAnimationTimingFunction", - "webkitAppearance", - "webkitAudioContext", - "webkitAudioDecodedByteCount", - "webkitAudioPannerNode", - "webkitBackfaceVisibility", - "webkitBackground", - "webkitBackgroundAttachment", - "webkitBackgroundClip", - "webkitBackgroundColor", - "webkitBackgroundImage", - "webkitBackgroundOrigin", - "webkitBackgroundPosition", - "webkitBackgroundPositionX", - "webkitBackgroundPositionY", - "webkitBackgroundRepeat", - "webkitBackgroundSize", - "webkitBackingStorePixelRatio", - "webkitBorderBottomLeftRadius", - "webkitBorderBottomRightRadius", - "webkitBorderImage", - "webkitBorderImageOutset", - "webkitBorderImageRepeat", - "webkitBorderImageSlice", - "webkitBorderImageSource", - "webkitBorderImageWidth", - "webkitBorderRadius", - "webkitBorderTopLeftRadius", - "webkitBorderTopRightRadius", - "webkitBoxAlign", - "webkitBoxDirection", - "webkitBoxFlex", - "webkitBoxOrdinalGroup", - "webkitBoxOrient", - "webkitBoxPack", - "webkitBoxShadow", - "webkitBoxSizing", - "webkitCancelAnimationFrame", - "webkitCancelFullScreen", - "webkitCancelKeyRequest", - "webkitCancelRequestAnimationFrame", - "webkitClearResourceTimings", - "webkitClosedCaptionsVisible", - "webkitConvertPointFromNodeToPage", - "webkitConvertPointFromPageToNode", - "webkitCreateShadowRoot", - "webkitCurrentFullScreenElement", - "webkitCurrentPlaybackTargetIsWireless", - "webkitDecodedFrameCount", - "webkitDirectionInvertedFromDevice", - "webkitDisplayingFullscreen", - "webkitDroppedFrameCount", - "webkitEnterFullScreen", - "webkitEnterFullscreen", - "webkitEntries", - "webkitExitFullScreen", - "webkitExitFullscreen", - "webkitExitPointerLock", - "webkitFilter", - "webkitFlex", - "webkitFlexBasis", - "webkitFlexDirection", - "webkitFlexFlow", - "webkitFlexGrow", - "webkitFlexShrink", - "webkitFlexWrap", - "webkitFullScreenKeyboardInputAllowed", - "webkitFullscreenElement", - "webkitFullscreenEnabled", - "webkitGenerateKeyRequest", - "webkitGetAsEntry", - "webkitGetDatabaseNames", - "webkitGetEntries", - "webkitGetEntriesByName", - "webkitGetEntriesByType", - "webkitGetFlowByName", - "webkitGetGamepads", - "webkitGetImageDataHD", - "webkitGetNamedFlows", - "webkitGetRegionFlowRanges", - "webkitGetUserMedia", - "webkitHasClosedCaptions", - "webkitHidden", - "webkitIDBCursor", - "webkitIDBDatabase", - "webkitIDBDatabaseError", - "webkitIDBDatabaseException", - "webkitIDBFactory", - "webkitIDBIndex", - "webkitIDBKeyRange", - "webkitIDBObjectStore", - "webkitIDBRequest", - "webkitIDBTransaction", - "webkitImageSmoothingEnabled", - "webkitIndexedDB", - "webkitInitMessageEvent", - "webkitIsFullScreen", - "webkitJustifyContent", - "webkitKeys", - "webkitLineClamp", - "webkitLineDashOffset", - "webkitLockOrientation", - "webkitMask", - "webkitMaskClip", - "webkitMaskComposite", - "webkitMaskImage", - "webkitMaskOrigin", - "webkitMaskPosition", - "webkitMaskPositionX", - "webkitMaskPositionY", - "webkitMaskRepeat", - "webkitMaskSize", - "webkitMatchesSelector", - "webkitMediaStream", - "webkitNotifications", - "webkitOfflineAudioContext", - "webkitOrder", - "webkitOrientation", - "webkitPeerConnection00", - "webkitPersistentStorage", - "webkitPerspective", - "webkitPerspectiveOrigin", - "webkitPointerLockElement", - "webkitPostMessage", - "webkitPreservesPitch", - "webkitPutImageDataHD", - "webkitRTCPeerConnection", - "webkitRegionOverset", - "webkitRelativePath", - "webkitRequestAnimationFrame", - "webkitRequestFileSystem", - "webkitRequestFullScreen", - "webkitRequestFullscreen", - "webkitRequestPointerLock", - "webkitResolveLocalFileSystemURL", - "webkitSetMediaKeys", - "webkitSetResourceTimingBufferSize", - "webkitShadowRoot", - "webkitShowPlaybackTargetPicker", - "webkitSlice", - "webkitSpeechGrammar", - "webkitSpeechGrammarList", - "webkitSpeechRecognition", - "webkitSpeechRecognitionError", - "webkitSpeechRecognitionEvent", - "webkitStorageInfo", - "webkitSupportsFullscreen", - "webkitTemporaryStorage", - "webkitTextFillColor", - "webkitTextSizeAdjust", - "webkitTextStroke", - "webkitTextStrokeColor", - "webkitTextStrokeWidth", - "webkitTransform", - "webkitTransformOrigin", - "webkitTransformStyle", - "webkitTransition", - "webkitTransitionDelay", - "webkitTransitionDuration", - "webkitTransitionProperty", - "webkitTransitionTimingFunction", - "webkitURL", - "webkitUnlockOrientation", - "webkitUserSelect", - "webkitVideoDecodedByteCount", - "webkitVisibilityState", - "webkitWirelessVideoPlaybackDisabled", - "webkitdirectory", - "webkitdropzone", - "webstore", - "weight", - "whatToShow", - "wheelDelta", - "wheelDeltaX", - "wheelDeltaY", - "whenDefined", - "which", - "white-space", - "whiteSpace", - "wholeText", - "widows", - "width", - "will-change", - "willChange", - "willValidate", - "window", - "withCredentials", - "word-break", - "word-spacing", - "word-wrap", - "wordBreak", - "wordSpacing", - "wordWrap", - "workerStart", - "wrap", - "wrapKey", - "writable", - "writableAuxiliaries", - "write", - "writeText", - "writeValue", - "writeWithoutResponse", - "writeln", - "writing-mode", - "writingMode", - "x", - "x1", - "x2", - "xChannelSelector", - "xmlEncoding", - "xmlStandalone", - "xmlVersion", - "xmlbase", - "xmllang", - "xmlspace", - "xor", - "xr", - "y", - "y1", - "y2", - "yChannelSelector", - "yandex", - "z", - "z-index", - "zIndex", - "zoom", - "zoomAndPan", - "zoomRectScreen", -]; - -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -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 commonjsGlobal === "object" ? commonjsGlobal : 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; - })); - } -} - -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(); - 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; -} - -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 ", "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 ", "Output file (default STDOUT)."); - program.option("--comments [filter]", "Preserve copyright comments in the output."); - program.option("--config-file ", "Read minify() options from JSON file."); - program.option("-d, --define [=value]", "Global definitions.", parse_js("define")); - program.option("--ecma ", "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 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 ", "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 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"; - } -} - -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; - } -} - -exports._default_options = _default_options; -exports._run_cli = run_cli; -exports.minify = minify; - -}))); -}); - -module.exports = bundle_min; diff --git a/node_modules/vite/package.json b/node_modules/vite/package.json deleted file mode 100644 index 3ff6c45..0000000 --- a/node_modules/vite/package.json +++ /dev/null @@ -1,127 +0,0 @@ -{ - "name": "vite", - "version": "2.1.5", - "license": "MIT", - "author": "Evan You", - "description": "Native-ESM powered web dev build tool", - "bin": { - "vite": "bin/vite.js" - }, - "main": "dist/node/index.js", - "types": "dist/node/index.d.ts", - "files": [ - "bin", - "dist", - "client.d.ts" - ], - "engines": { - "node": ">=12.0.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/vitejs/vite.git", - "directory": "packages/vite" - }, - "bugs": { - "url": "https://github.com/vitejs/vite/issues" - }, - "homepage": "https://github.com/vitejs/vite/tree/main/#readme", - "scripts": { - "predev": "rimraf dist", - "dev": "run-p dev-client dev-node", - "dev-client": "tsc -w --incremental --p src/client", - "dev-node": "tsc -w --incremental --p src/node", - "prebuild": "rimraf dist && yarn lint", - "build": "run-s build-bundle build-types", - "build-bundle": "rollup -c", - "build-types": "run-s build-temp-types patch-types roll-types", - "build-temp-types": "tsc --emitDeclarationOnly --outDir temp/node -p src/node", - "patch-types": "node scripts/patchTypes", - "roll-types": "api-extractor run && rimraf temp", - "lint": "eslint --ext .ts src/**", - "format": "prettier --write --parser typescript \"src/**/*.ts\"", - "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path .", - "release": "node ../../scripts/release.js" - }, - "//": "READ .github/contributing.md to understand what to put under deps vs. devDeps!", - "dependencies": { - "esbuild": "^0.9.3", - "postcss": "^8.2.1", - "resolve": "^1.19.0", - "rollup": "^2.38.5" - }, - "optionalDependencies": { - "fsevents": "~2.3.1" - }, - "devDependencies": { - "@ampproject/remapping": "^1.0.1", - "@rollup/plugin-alias": "^3.1.1", - "@rollup/plugin-commonjs": "^17.0.0", - "@rollup/plugin-dynamic-import-vars": "^1.1.1", - "@rollup/plugin-json": "^4.1.0", - "@rollup/plugin-node-resolve": "^11.0.1", - "@rollup/plugin-typescript": "^8.0.0", - "@rollup/pluginutils": "^4.1.0", - "@types/clean-css": "^4.2.3", - "@types/convert-source-map": "^1.5.1", - "@types/debug": "^4.1.5", - "@types/es-module-lexer": "^0.3.0", - "@types/estree": "^0.0.45", - "@types/etag": "^1.8.0", - "@types/less": "^3.0.2", - "@types/mime": "^2.0.3", - "@types/node": "^14.14.10", - "@types/resolve": "^1.17.1", - "@types/sass": "^1.16.0", - "@types/stylus": "^0.48.33", - "@types/ws": "^7.4.0", - "@vue/compiler-dom": "^3.0.4", - "acorn": "^8.0.4", - "acorn-class-fields": "^0.3.7", - "acorn-numeric-separator": "^0.3.6", - "acorn-static-class-features": "^0.2.4", - "brotli-size": "^4.0.0", - "builtin-modules": "^3.2.0", - "cac": "^6.6.1", - "chalk": "^4.1.0", - "chokidar": "^3.5.1", - "clean-css": "^4.2.3", - "compression": "^1.7.4", - "connect": "^3.7.0", - "connect-history-api-fallback": "^1.6.0", - "convert-source-map": "^1.7.0", - "cors": "^2.8.5", - "debug": "^4.3.1", - "dotenv": "^8.2.0", - "dotenv-expand": "^5.1.0", - "enquirer": "^2.3.6", - "es-module-lexer": "^0.4.0", - "estree-walker": "^2.0.2", - "etag": "^1.8.1", - "execa": "^5.0.0", - "fast-glob": "^3.2.4", - "http-proxy": "^1.18.1", - "launch-editor-middleware": "^2.2.1", - "magic-string": "^0.25.7", - "mime": "^2.4.7", - "minimatch": "^3.0.4", - "okie": "^1.0.1", - "open": "^7.4.2", - "open-in-editor": "^2.2.0", - "periscopic": "^2.0.3", - "postcss-import": "^13.0.0", - "postcss-load-config": "^3.0.0", - "postcss-modules": "^4.0.0", - "resolve.exports": "^1.0.1", - "rollup-plugin-license": "^2.2.0", - "selfsigned": "^1.10.8", - "sirv": "^1.0.10", - "source-map": "^0.6.1", - "source-map-support": "^0.5.19", - "strip-ansi": "^6.0.0", - "terser": "^5.5.1", - "tslib": "^2.0.3", - "types": "link:./types", - "ws": "^7.4.1" - } -} diff --git a/package-lock.json b/package-lock.json index d45da34..35b6f49 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,8 +10,7 @@ "devDependencies": { "autoprefixer": "^10.2.5", "postcss": "^8.2.9", - "tailwindcss": "^2.1.1", - "vite": "^2.1.5" + "tailwindcss": "^2.1.1" } }, "node_modules/@fullhuman/postcss-purgecss": { @@ -408,16 +407,6 @@ "integrity": "sha512-LolItk2/ikSGQ7SN8UkuKVNMBZp3RG7Itgaxj1npsHRzQobj9JjMneZOZfLhtwlYBe5fCJ75k+cVCiDFUs23oA==", "dev": true }, - "node_modules/esbuild": { - "version": "0.9.7", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.9.7.tgz", - "integrity": "sha512-VtUf6aQ89VTmMLKrWHYG50uByMF4JQlVysb8dmg6cOgW8JnFCipmz7p+HNBl+RR3LLCuBxFGVauAe2wfnF9bLg==", - "dev": true, - "hasInstallScript": true, - "bin": { - "esbuild": "bin/esbuild" - } - }, "node_modules/escalade": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", @@ -1219,21 +1208,6 @@ "node": ">=0.10.0" } }, - "node_modules/rollup": { - "version": "2.44.0", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.44.0.tgz", - "integrity": "sha512-rGSF4pLwvuaH/x4nAS+zP6UNn5YUDWf/TeEU5IoXSZKBbKRNTCI3qMnYXKZgrC0D2KzS2baiOZt1OlqhMu5rnQ==", - "dev": true, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=10.0.0" - }, - "optionalDependencies": { - "fsevents": "~2.3.1" - } - }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -1366,27 +1340,6 @@ "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", "dev": true }, - "node_modules/vite": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-2.1.5.tgz", - "integrity": "sha512-tYU5iaYeUgQYvK/CNNz3tiJ8vYqPWfCE9IQ7K0iuzYovWw7lzty7KRYGWwV3CQPh0NKxWjOczAqiJsCL0Xb+Og==", - "dev": true, - "dependencies": { - "esbuild": "^0.9.3", - "postcss": "^8.2.1", - "resolve": "^1.19.0", - "rollup": "^2.38.5" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": ">=12.0.0" - }, - "optionalDependencies": { - "fsevents": "~2.3.1" - } - }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", @@ -1706,12 +1659,6 @@ "integrity": "sha512-LolItk2/ikSGQ7SN8UkuKVNMBZp3RG7Itgaxj1npsHRzQobj9JjMneZOZfLhtwlYBe5fCJ75k+cVCiDFUs23oA==", "dev": true }, - "esbuild": { - "version": "0.9.7", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.9.7.tgz", - "integrity": "sha512-VtUf6aQ89VTmMLKrWHYG50uByMF4JQlVysb8dmg6cOgW8JnFCipmz7p+HNBl+RR3LLCuBxFGVauAe2wfnF9bLg==", - "dev": true - }, "escalade": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", @@ -2320,15 +2267,6 @@ "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", "dev": true }, - "rollup": { - "version": "2.44.0", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.44.0.tgz", - "integrity": "sha512-rGSF4pLwvuaH/x4nAS+zP6UNn5YUDWf/TeEU5IoXSZKBbKRNTCI3qMnYXKZgrC0D2KzS2baiOZt1OlqhMu5rnQ==", - "dev": true, - "requires": { - "fsevents": "~2.3.1" - } - }, "run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -2424,19 +2362,6 @@ "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", "dev": true }, - "vite": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-2.1.5.tgz", - "integrity": "sha512-tYU5iaYeUgQYvK/CNNz3tiJ8vYqPWfCE9IQ7K0iuzYovWw7lzty7KRYGWwV3CQPh0NKxWjOczAqiJsCL0Xb+Og==", - "dev": true, - "requires": { - "esbuild": "^0.9.3", - "fsevents": "~2.3.1", - "postcss": "^8.2.1", - "resolve": "^1.19.0", - "rollup": "^2.38.5" - } - }, "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", diff --git a/package.json b/package.json index 2df97fe..227b22a 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,6 @@ "description": "## CDN", "main": "index.js", "scripts": { - "dev": "vite", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], @@ -13,7 +12,6 @@ "devDependencies": { "autoprefixer": "^10.2.5", "postcss": "^8.2.9", - "tailwindcss": "^2.1.1", - "vite": "^2.1.5" + "tailwindcss": "^2.1.1" } }