From 24b09ad4f89ce9b77b296223a99d1fc768e7b83f Mon Sep 17 00:00:00 2001 From: JJ Kasper Date: Mon, 16 Aug 2021 14:29:11 -0500 Subject: [PATCH] Add entrypoint tracing (#25538) This adds tracing entrypoints directly after they have have been transpiled to allow us to trace before the webpack runtime has been added to the modules. This should allow for more accurate tracing of entrypoints and allow the trace step to be cached. ## Bug - [x] Related issues linked using `fixes #number` - [x] Integration tests added x-ref: https://github.com/vercel/next.js/issues/24700 x-ref: https://github.com/vercel/next.js/issues/26200 x-ref: https://github.com/vercel/next.js/issues/23894 x-ref: https://github.com/vercel/next.js/issues/25431 --- packages/next/build/index.ts | 64 + packages/next/build/utils.ts | 8 +- packages/next/build/webpack-config.ts | 7 + .../plugins/next-trace-entrypoints-plugin.ts | 261 + packages/next/compiled/@vercel/nft/LICENSE | 7 + packages/next/compiled/@vercel/nft/index.js | 1 + .../next/compiled/@vercel/nft/package.json | 1 + packages/next/compiled/glob/LICENSE | 21 + packages/next/compiled/glob/glob.js | 1 + packages/next/compiled/glob/package.json | 1 + packages/next/compiled/terser/bundle.min.js | 2 +- packages/next/compiled/webpack/bundle4.js | 127640 +++++++-------- packages/next/package.json | 2 + packages/next/server/config-shared.ts | 2 + packages/next/shared/lib/constants.ts | 1 + packages/next/taskfile.js | 64 +- packages/next/types/index.d.ts | 2 + packages/next/types/misc.d.ts | 8 + .../prerender-native-module/next.config.js | 5 + .../test/index.test.js | 51 +- test/integration/prerender/next.config.js | 3 + .../prerender/pages/another/index.js | 11 +- test/integration/prerender/test/index.test.js | 94 +- test/integration/production/next.config.js | 3 + .../integration/production/test/index.test.js | 47 +- test/lib/next-test-utils.js | 5 +- yarn.lock | 91 +- 27 files changed, 64556 insertions(+), 63847 deletions(-) create mode 100644 packages/next/build/webpack/plugins/next-trace-entrypoints-plugin.ts create mode 100644 packages/next/compiled/@vercel/nft/LICENSE create mode 100644 packages/next/compiled/@vercel/nft/index.js create mode 100644 packages/next/compiled/@vercel/nft/package.json create mode 100644 packages/next/compiled/glob/LICENSE create mode 100644 packages/next/compiled/glob/glob.js create mode 100644 packages/next/compiled/glob/package.json create mode 100644 test/integration/prerender-native-module/next.config.js diff --git a/packages/next/build/index.ts b/packages/next/build/index.ts index 597edc53a3ebf37..d710791032ffc83 100644 --- a/packages/next/build/index.ts +++ b/packages/next/build/index.ts @@ -660,6 +660,8 @@ export default async function build( const serverPropsPages = new Set() const additionalSsgPaths = new Map>() const additionalSsgPathsEncoded = new Map>() + const pageTraceIncludes = new Map>() + const pageTraceExcludes = new Map>() const pageInfos = new Map() const pagesManifest = JSON.parse( await promises.readFile(manifestPath, 'utf8') @@ -841,6 +843,11 @@ export default async function build( ) }) + if (config.experimental.nftTracing) { + pageTraceIncludes.set(page, workerResult.traceIncludes || []) + pageTraceExcludes.set(page, workerResult.traceExcludes || []) + } + if ( workerResult.isStatic === false && (workerResult.isHybridAmp || workerResult.isAmpOnly) @@ -979,6 +986,63 @@ export default async function build( ) } + if (config.experimental.nftTracing) { + const globOrig = require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob') + const glob = (pattern: string): Promise => { + return new Promise((resolve, reject) => { + globOrig(pattern, { cwd: dir }, (err, files) => { + if (err) { + return reject(err) + } + resolve(files) + }) + }) + } + + for (const page of pageKeys) { + const includeGlobs = pageTraceIncludes.get(page) + const excludeGlobs = pageTraceExcludes.get(page) + + if (!includeGlobs?.length && !excludeGlobs?.length) { + continue + } + + const traceFile = path.join( + distDir, + 'server/pages', + `${page}.js.nft.json` + ) + const traceContent = JSON.parse( + await promises.readFile(traceFile, 'utf8') + ) + let includes: string[] = [] + let excludes: string[] = [] + + if (includeGlobs?.length) { + for (const includeGlob of includeGlobs) { + includes.push(...(await glob(includeGlob))) + } + } + + if (excludeGlobs?.length) { + for (const excludeGlob of excludeGlobs) { + excludes.push(...(await glob(excludeGlob))) + } + } + + const combined = new Set([...traceContent.files, ...includes]) + excludes.forEach((file) => combined.delete(file)) + + await promises.writeFile( + traceFile, + JSON.stringify({ + version: traceContent.version, + files: [...combined], + }) + ) + } + } + if (serverPropsPages.size > 0 || ssgPages.size > 0) { // We update the routes manifest after the build with the // data routes since we can't determine these until after build diff --git a/packages/next/build/utils.ts b/packages/next/build/utils.ts index 20c0913f5fc0ad6..aae35e54d86a865 100644 --- a/packages/next/build/utils.ts +++ b/packages/next/build/utils.ts @@ -23,7 +23,7 @@ import { getRouteMatcher, getRouteRegex } from '../shared/lib/router/utils' import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic' import escapePathDelimiters from '../shared/lib/router/utils/escape-path-delimiters' import { findPageFile } from '../server/lib/find-page-file' -import { GetStaticPaths } from 'next/types' +import { GetStaticPaths, PageConfig } from 'next/types' import { denormalizePagePath } from '../server/normalize-page-path' import { BuildManifest } from '../server/get-page-files' import { removePathTrailingSlash } from '../client/normalize-trailing-slash' @@ -831,6 +831,8 @@ export async function isPageStatic( encodedPrerenderRoutes?: string[] prerenderFallback?: boolean | 'blocking' isNextImageImported?: boolean + traceIncludes?: string[] + traceExcludes?: string[] }> { const isPageStaticSpan = trace('is-page-static-utils', parentId) return isPageStaticSpan.traceAsyncFn(async () => { @@ -925,7 +927,7 @@ export async function isPageStatic( } const isNextImageImported = (global as any).__NEXT_IMAGE_IMPORTED - const config = mod.config || {} + const config: PageConfig = mod.config || {} return { isStatic: !hasStaticProps && !hasGetInitialProps && !hasServerProps, isHybridAmp: config.amp === 'hybrid', @@ -936,6 +938,8 @@ export async function isPageStatic( hasStaticProps, hasServerProps, isNextImageImported, + traceIncludes: config.unstable_includeFiles || [], + traceExcludes: config.unstable_excludeFiles || [], } } catch (err) { if (err.code === 'MODULE_NOT_FOUND') return {} diff --git a/packages/next/build/webpack-config.ts b/packages/next/build/webpack-config.ts index 6ca7fe421a2c5ea..222a0918a598f82 100644 --- a/packages/next/build/webpack-config.ts +++ b/packages/next/build/webpack-config.ts @@ -38,6 +38,7 @@ import BuildStatsPlugin from './webpack/plugins/build-stats-plugin' import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin' import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin' import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin' +import { TraceEntryPointsPlugin } from './webpack/plugins/next-trace-entrypoints-plugin' import NextJsSsrImportPlugin from './webpack/plugins/nextjs-ssr-import' import NextJsSSRModuleCachePlugin from './webpack/plugins/nextjs-ssr-module-cache' import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin' @@ -1245,6 +1246,12 @@ export default async function getBaseWebpackConfig( pagesDir, }), !isServer && new DropClientPage(), + config.experimental.nftTracing && + !isLikeServerless && + isServer && + !dev && + isWebpack5 && + new TraceEntryPointsPlugin({ appDir: dir }), // Moment.js is an extremely popular library that bundles large locale files // by default due to how Webpack interprets its code. This is a practical // solution that requires the user to opt into importing specific locales. diff --git a/packages/next/build/webpack/plugins/next-trace-entrypoints-plugin.ts b/packages/next/build/webpack/plugins/next-trace-entrypoints-plugin.ts new file mode 100644 index 000000000000000..d8b8447ce3bb2a4 --- /dev/null +++ b/packages/next/build/webpack/plugins/next-trace-entrypoints-plugin.ts @@ -0,0 +1,261 @@ +import nodePath from 'path' +import { nodeFileTrace } from 'next/dist/compiled/@vercel/nft' +import { + webpack, + isWebpack5, + sources, +} from 'next/dist/compiled/webpack/webpack' +import { TRACE_OUTPUT_VERSION } from '../../../shared/lib/constants' + +const PLUGIN_NAME = 'TraceEntryPointsPlugin' +const TRACE_IGNORES = [ + '**/*/node_modules/react/**/*.development.js', + '**/*/node_modules/react-dom/**/*.development.js', +] + +function getModuleFromDependency( + compilation: any, + dep: any +): webpack.Module & { resource?: string } { + if (isWebpack5) { + return compilation.moduleGraph.getModule(dep) + } + + return dep.module +} + +export class TraceEntryPointsPlugin implements webpack.Plugin { + private appDir: string + private entryTraces: Map + private excludeFiles: string[] + + constructor({ + appDir, + excludeFiles, + }: { + appDir: string + excludeFiles?: string[] + }) { + this.appDir = appDir + this.entryTraces = new Map() + this.excludeFiles = excludeFiles || [] + } + + // Here we output all traced assets and webpack chunks to a + // ${page}.js.nft.json file + createTraceAssets(compilation: any, assets: any) { + const outputPath = compilation.outputOptions.path + + for (const entrypoint of compilation.entrypoints.values()) { + const entryFiles = new Set() + + for (const chunk of entrypoint + .getEntrypointChunk() + .getAllReferencedChunks()) { + for (const file of chunk.files) { + entryFiles.add(nodePath.join(outputPath, file)) + } + for (const file of chunk.auxiliaryFiles) { + entryFiles.add(nodePath.join(outputPath, file)) + } + } + // don't include the entry itself in the trace + entryFiles.delete( + nodePath.join( + outputPath, + `${isWebpack5 ? '../' : ''}${entrypoint.name}.js` + ) + ) + const traceOutputName = `${isWebpack5 ? '../' : ''}${ + entrypoint.name + }.js.nft.json` + const traceOutputPath = nodePath.join(outputPath, traceOutputName) + + assets[traceOutputName] = new sources.RawSource( + JSON.stringify({ + version: TRACE_OUTPUT_VERSION, + files: [...entryFiles, ...this.entryTraces.get(entrypoint.name)!].map( + (file) => { + return nodePath + .relative(traceOutputPath, file) + .replace(/\\/g, '/') + } + ), + }) + ) + } + } + + apply(compiler: webpack.Compiler) { + if (isWebpack5) { + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + // @ts-ignore TODO: Remove ignore when webpack 5 is stable + compilation.hooks.processAssets.tap( + { + name: PLUGIN_NAME, + // @ts-ignore TODO: Remove ignore when webpack 5 is stable + stage: webpack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE, + }, + (assets: any) => { + this.createTraceAssets(compilation, assets) + } + ) + }) + } else { + compiler.hooks.emit.tap(PLUGIN_NAME, (compilation: any) => { + this.createTraceAssets(compilation, compilation.assets) + }) + } + + compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => { + compilation.hooks.finishModules.tapAsync( + PLUGIN_NAME, + async (_stats: any, callback: any) => { + // we create entry -> module maps so that we can + // look them up faster instead of having to iterate + // over the compilation modules list + const entryNameMap = new Map() + const entryModMap = new Map() + + try { + const depModMap = new Map() + + compilation.entries.forEach((entry) => { + const name = entry.name || entry.options?.name + + if (name?.startsWith('pages/') && entry.dependencies[0]) { + const entryMod = getModuleFromDependency( + compilation, + entry.dependencies[0] + ) + + if (entryMod.resource) { + entryNameMap.set(entryMod.resource, name) + entryModMap.set(entryMod.resource, entryMod) + } + } + }) + + // TODO: investigate allowing non-sync fs calls in node-file-trace + // for better performance + const readFile = (path: string) => { + const mod = depModMap.get(path) || entryModMap.get(path) + + // map the transpiled source when available to avoid + // parse errors in node-file-trace + const source = mod?.originalSource?.() + + if (source) { + return source.buffer() + } + + try { + return compilation.inputFileSystem.readFileSync(path) + } catch (e) { + if (e.code === 'ENOENT' || e.code === 'EISDIR') { + return null + } + throw e + } + } + const readlink = (path: string) => { + try { + return compilation.inputFileSystem.readlinkSync(path) + } catch (e) { + if ( + e.code !== 'EINVAL' && + e.code !== 'ENOENT' && + e.code !== 'UNKNOWN' + ) { + throw e + } + return null + } + } + const stat = (path: string) => { + try { + return compilation.inputFileSystem.statSync(path) + } catch (e) { + if (e.code === 'ENOENT') { + return null + } + throw e + } + } + + const nftCache = {} + const entryPaths = Array.from(entryModMap.keys()) + + for (const entry of entryPaths) { + depModMap.clear() + const entryMod = entryModMap.get(entry) + // TODO: investigate caching, will require ensuring no traced + // files in the cache have changed, we could potentially hash + // all traced files and only leverage the cache if the hashes + // match + // const cachedTraces = entryMod.buildInfo?.cachedNextEntryTrace + + // Use cached trace if available and trace version matches + // if ( + // isWebpack5 && + // cachedTraces && + // cachedTraces.version === TRACE_OUTPUT_VERSION + // ) { + // this.entryTraces.set( + // entryNameMap.get(entry)!, + // cachedTraces.tracedDeps + // ) + // continue + // } + const collectDependencies = (mod: any) => { + if (!mod || !mod.dependencies) return + + for (const dep of mod.dependencies) { + const depMod = getModuleFromDependency(compilation, dep) + + if (depMod?.resource && !depModMap.get(depMod.resource)) { + depModMap.set(depMod.resource, depMod) + collectDependencies(depMod) + } + } + } + collectDependencies(entryMod) + + const toTrace: string[] = [entry, ...depModMap.keys()] + + const root = nodePath.parse(process.cwd()).root + const result = await nodeFileTrace(toTrace, { + base: root, + cache: nftCache, + processCwd: this.appDir, + readFile, + readlink, + stat, + ignore: [...TRACE_IGNORES, ...this.excludeFiles], + }) + + const tracedDeps: string[] = [] + + for (const file of result.fileList) { + if (result.reasons[file].type === 'initial') { + continue + } + tracedDeps.push(nodePath.join(root, file)) + } + + // entryMod.buildInfo.cachedNextEntryTrace = { + // version: TRACE_OUTPUT_VERSION, + // tracedDeps, + // } + this.entryTraces.set(entryNameMap.get(entry)!, tracedDeps) + } + + callback() + } catch (err) { + callback(err) + } + } + ) + }) + } +} diff --git a/packages/next/compiled/@vercel/nft/LICENSE b/packages/next/compiled/@vercel/nft/LICENSE new file mode 100644 index 000000000000000..682f390ba4bc038 --- /dev/null +++ b/packages/next/compiled/@vercel/nft/LICENSE @@ -0,0 +1,7 @@ +Copyright 2019 Vercel, Inc. + +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. \ No newline at end of file diff --git a/packages/next/compiled/@vercel/nft/index.js b/packages/next/compiled/@vercel/nft/index.js new file mode 100644 index 000000000000000..d132671e6468a85 --- /dev/null +++ b/packages/next/compiled/@vercel/nft/index.js @@ -0,0 +1 @@ +module.exports=(()=>{var __webpack_modules__={3380:e=>{"use strict";e.exports=JSON.parse('{"0.1.14":{"node_abi":null,"v8":"1.3"},"0.1.15":{"node_abi":null,"v8":"1.3"},"0.1.16":{"node_abi":null,"v8":"1.3"},"0.1.17":{"node_abi":null,"v8":"1.3"},"0.1.18":{"node_abi":null,"v8":"1.3"},"0.1.19":{"node_abi":null,"v8":"2.0"},"0.1.20":{"node_abi":null,"v8":"2.0"},"0.1.21":{"node_abi":null,"v8":"2.0"},"0.1.22":{"node_abi":null,"v8":"2.0"},"0.1.23":{"node_abi":null,"v8":"2.0"},"0.1.24":{"node_abi":null,"v8":"2.0"},"0.1.25":{"node_abi":null,"v8":"2.0"},"0.1.26":{"node_abi":null,"v8":"2.0"},"0.1.27":{"node_abi":null,"v8":"2.1"},"0.1.28":{"node_abi":null,"v8":"2.1"},"0.1.29":{"node_abi":null,"v8":"2.1"},"0.1.30":{"node_abi":null,"v8":"2.1"},"0.1.31":{"node_abi":null,"v8":"2.1"},"0.1.32":{"node_abi":null,"v8":"2.1"},"0.1.33":{"node_abi":null,"v8":"2.1"},"0.1.90":{"node_abi":null,"v8":"2.2"},"0.1.91":{"node_abi":null,"v8":"2.2"},"0.1.92":{"node_abi":null,"v8":"2.2"},"0.1.93":{"node_abi":null,"v8":"2.2"},"0.1.94":{"node_abi":null,"v8":"2.2"},"0.1.95":{"node_abi":null,"v8":"2.2"},"0.1.96":{"node_abi":null,"v8":"2.2"},"0.1.97":{"node_abi":null,"v8":"2.2"},"0.1.98":{"node_abi":null,"v8":"2.2"},"0.1.99":{"node_abi":null,"v8":"2.2"},"0.1.100":{"node_abi":null,"v8":"2.2"},"0.1.101":{"node_abi":null,"v8":"2.3"},"0.1.102":{"node_abi":null,"v8":"2.3"},"0.1.103":{"node_abi":null,"v8":"2.3"},"0.1.104":{"node_abi":null,"v8":"2.3"},"0.2.0":{"node_abi":1,"v8":"2.3"},"0.2.1":{"node_abi":1,"v8":"2.3"},"0.2.2":{"node_abi":1,"v8":"2.3"},"0.2.3":{"node_abi":1,"v8":"2.3"},"0.2.4":{"node_abi":1,"v8":"2.3"},"0.2.5":{"node_abi":1,"v8":"2.3"},"0.2.6":{"node_abi":1,"v8":"2.3"},"0.3.0":{"node_abi":1,"v8":"2.5"},"0.3.1":{"node_abi":1,"v8":"2.5"},"0.3.2":{"node_abi":1,"v8":"3.0"},"0.3.3":{"node_abi":1,"v8":"3.0"},"0.3.4":{"node_abi":1,"v8":"3.0"},"0.3.5":{"node_abi":1,"v8":"3.0"},"0.3.6":{"node_abi":1,"v8":"3.0"},"0.3.7":{"node_abi":1,"v8":"3.0"},"0.3.8":{"node_abi":1,"v8":"3.1"},"0.4.0":{"node_abi":1,"v8":"3.1"},"0.4.1":{"node_abi":1,"v8":"3.1"},"0.4.2":{"node_abi":1,"v8":"3.1"},"0.4.3":{"node_abi":1,"v8":"3.1"},"0.4.4":{"node_abi":1,"v8":"3.1"},"0.4.5":{"node_abi":1,"v8":"3.1"},"0.4.6":{"node_abi":1,"v8":"3.1"},"0.4.7":{"node_abi":1,"v8":"3.1"},"0.4.8":{"node_abi":1,"v8":"3.1"},"0.4.9":{"node_abi":1,"v8":"3.1"},"0.4.10":{"node_abi":1,"v8":"3.1"},"0.4.11":{"node_abi":1,"v8":"3.1"},"0.4.12":{"node_abi":1,"v8":"3.1"},"0.5.0":{"node_abi":1,"v8":"3.1"},"0.5.1":{"node_abi":1,"v8":"3.4"},"0.5.2":{"node_abi":1,"v8":"3.4"},"0.5.3":{"node_abi":1,"v8":"3.4"},"0.5.4":{"node_abi":1,"v8":"3.5"},"0.5.5":{"node_abi":1,"v8":"3.5"},"0.5.6":{"node_abi":1,"v8":"3.6"},"0.5.7":{"node_abi":1,"v8":"3.6"},"0.5.8":{"node_abi":1,"v8":"3.6"},"0.5.9":{"node_abi":1,"v8":"3.6"},"0.5.10":{"node_abi":1,"v8":"3.7"},"0.6.0":{"node_abi":1,"v8":"3.6"},"0.6.1":{"node_abi":1,"v8":"3.6"},"0.6.2":{"node_abi":1,"v8":"3.6"},"0.6.3":{"node_abi":1,"v8":"3.6"},"0.6.4":{"node_abi":1,"v8":"3.6"},"0.6.5":{"node_abi":1,"v8":"3.6"},"0.6.6":{"node_abi":1,"v8":"3.6"},"0.6.7":{"node_abi":1,"v8":"3.6"},"0.6.8":{"node_abi":1,"v8":"3.6"},"0.6.9":{"node_abi":1,"v8":"3.6"},"0.6.10":{"node_abi":1,"v8":"3.6"},"0.6.11":{"node_abi":1,"v8":"3.6"},"0.6.12":{"node_abi":1,"v8":"3.6"},"0.6.13":{"node_abi":1,"v8":"3.6"},"0.6.14":{"node_abi":1,"v8":"3.6"},"0.6.15":{"node_abi":1,"v8":"3.6"},"0.6.16":{"node_abi":1,"v8":"3.6"},"0.6.17":{"node_abi":1,"v8":"3.6"},"0.6.18":{"node_abi":1,"v8":"3.6"},"0.6.19":{"node_abi":1,"v8":"3.6"},"0.6.20":{"node_abi":1,"v8":"3.6"},"0.6.21":{"node_abi":1,"v8":"3.6"},"0.7.0":{"node_abi":1,"v8":"3.8"},"0.7.1":{"node_abi":1,"v8":"3.8"},"0.7.2":{"node_abi":1,"v8":"3.8"},"0.7.3":{"node_abi":1,"v8":"3.9"},"0.7.4":{"node_abi":1,"v8":"3.9"},"0.7.5":{"node_abi":1,"v8":"3.9"},"0.7.6":{"node_abi":1,"v8":"3.9"},"0.7.7":{"node_abi":1,"v8":"3.9"},"0.7.8":{"node_abi":1,"v8":"3.9"},"0.7.9":{"node_abi":1,"v8":"3.11"},"0.7.10":{"node_abi":1,"v8":"3.9"},"0.7.11":{"node_abi":1,"v8":"3.11"},"0.7.12":{"node_abi":1,"v8":"3.11"},"0.8.0":{"node_abi":1,"v8":"3.11"},"0.8.1":{"node_abi":1,"v8":"3.11"},"0.8.2":{"node_abi":1,"v8":"3.11"},"0.8.3":{"node_abi":1,"v8":"3.11"},"0.8.4":{"node_abi":1,"v8":"3.11"},"0.8.5":{"node_abi":1,"v8":"3.11"},"0.8.6":{"node_abi":1,"v8":"3.11"},"0.8.7":{"node_abi":1,"v8":"3.11"},"0.8.8":{"node_abi":1,"v8":"3.11"},"0.8.9":{"node_abi":1,"v8":"3.11"},"0.8.10":{"node_abi":1,"v8":"3.11"},"0.8.11":{"node_abi":1,"v8":"3.11"},"0.8.12":{"node_abi":1,"v8":"3.11"},"0.8.13":{"node_abi":1,"v8":"3.11"},"0.8.14":{"node_abi":1,"v8":"3.11"},"0.8.15":{"node_abi":1,"v8":"3.11"},"0.8.16":{"node_abi":1,"v8":"3.11"},"0.8.17":{"node_abi":1,"v8":"3.11"},"0.8.18":{"node_abi":1,"v8":"3.11"},"0.8.19":{"node_abi":1,"v8":"3.11"},"0.8.20":{"node_abi":1,"v8":"3.11"},"0.8.21":{"node_abi":1,"v8":"3.11"},"0.8.22":{"node_abi":1,"v8":"3.11"},"0.8.23":{"node_abi":1,"v8":"3.11"},"0.8.24":{"node_abi":1,"v8":"3.11"},"0.8.25":{"node_abi":1,"v8":"3.11"},"0.8.26":{"node_abi":1,"v8":"3.11"},"0.8.27":{"node_abi":1,"v8":"3.11"},"0.8.28":{"node_abi":1,"v8":"3.11"},"0.9.0":{"node_abi":1,"v8":"3.11"},"0.9.1":{"node_abi":10,"v8":"3.11"},"0.9.2":{"node_abi":10,"v8":"3.11"},"0.9.3":{"node_abi":10,"v8":"3.13"},"0.9.4":{"node_abi":10,"v8":"3.13"},"0.9.5":{"node_abi":10,"v8":"3.13"},"0.9.6":{"node_abi":10,"v8":"3.15"},"0.9.7":{"node_abi":10,"v8":"3.15"},"0.9.8":{"node_abi":10,"v8":"3.15"},"0.9.9":{"node_abi":11,"v8":"3.15"},"0.9.10":{"node_abi":11,"v8":"3.15"},"0.9.11":{"node_abi":11,"v8":"3.14"},"0.9.12":{"node_abi":11,"v8":"3.14"},"0.10.0":{"node_abi":11,"v8":"3.14"},"0.10.1":{"node_abi":11,"v8":"3.14"},"0.10.2":{"node_abi":11,"v8":"3.14"},"0.10.3":{"node_abi":11,"v8":"3.14"},"0.10.4":{"node_abi":11,"v8":"3.14"},"0.10.5":{"node_abi":11,"v8":"3.14"},"0.10.6":{"node_abi":11,"v8":"3.14"},"0.10.7":{"node_abi":11,"v8":"3.14"},"0.10.8":{"node_abi":11,"v8":"3.14"},"0.10.9":{"node_abi":11,"v8":"3.14"},"0.10.10":{"node_abi":11,"v8":"3.14"},"0.10.11":{"node_abi":11,"v8":"3.14"},"0.10.12":{"node_abi":11,"v8":"3.14"},"0.10.13":{"node_abi":11,"v8":"3.14"},"0.10.14":{"node_abi":11,"v8":"3.14"},"0.10.15":{"node_abi":11,"v8":"3.14"},"0.10.16":{"node_abi":11,"v8":"3.14"},"0.10.17":{"node_abi":11,"v8":"3.14"},"0.10.18":{"node_abi":11,"v8":"3.14"},"0.10.19":{"node_abi":11,"v8":"3.14"},"0.10.20":{"node_abi":11,"v8":"3.14"},"0.10.21":{"node_abi":11,"v8":"3.14"},"0.10.22":{"node_abi":11,"v8":"3.14"},"0.10.23":{"node_abi":11,"v8":"3.14"},"0.10.24":{"node_abi":11,"v8":"3.14"},"0.10.25":{"node_abi":11,"v8":"3.14"},"0.10.26":{"node_abi":11,"v8":"3.14"},"0.10.27":{"node_abi":11,"v8":"3.14"},"0.10.28":{"node_abi":11,"v8":"3.14"},"0.10.29":{"node_abi":11,"v8":"3.14"},"0.10.30":{"node_abi":11,"v8":"3.14"},"0.10.31":{"node_abi":11,"v8":"3.14"},"0.10.32":{"node_abi":11,"v8":"3.14"},"0.10.33":{"node_abi":11,"v8":"3.14"},"0.10.34":{"node_abi":11,"v8":"3.14"},"0.10.35":{"node_abi":11,"v8":"3.14"},"0.10.36":{"node_abi":11,"v8":"3.14"},"0.10.37":{"node_abi":11,"v8":"3.14"},"0.10.38":{"node_abi":11,"v8":"3.14"},"0.10.39":{"node_abi":11,"v8":"3.14"},"0.10.40":{"node_abi":11,"v8":"3.14"},"0.10.41":{"node_abi":11,"v8":"3.14"},"0.10.42":{"node_abi":11,"v8":"3.14"},"0.10.43":{"node_abi":11,"v8":"3.14"},"0.10.44":{"node_abi":11,"v8":"3.14"},"0.10.45":{"node_abi":11,"v8":"3.14"},"0.10.46":{"node_abi":11,"v8":"3.14"},"0.10.47":{"node_abi":11,"v8":"3.14"},"0.10.48":{"node_abi":11,"v8":"3.14"},"0.11.0":{"node_abi":12,"v8":"3.17"},"0.11.1":{"node_abi":12,"v8":"3.18"},"0.11.2":{"node_abi":12,"v8":"3.19"},"0.11.3":{"node_abi":12,"v8":"3.19"},"0.11.4":{"node_abi":12,"v8":"3.20"},"0.11.5":{"node_abi":12,"v8":"3.20"},"0.11.6":{"node_abi":12,"v8":"3.20"},"0.11.7":{"node_abi":12,"v8":"3.20"},"0.11.8":{"node_abi":13,"v8":"3.21"},"0.11.9":{"node_abi":13,"v8":"3.22"},"0.11.10":{"node_abi":13,"v8":"3.22"},"0.11.11":{"node_abi":14,"v8":"3.22"},"0.11.12":{"node_abi":14,"v8":"3.22"},"0.11.13":{"node_abi":14,"v8":"3.25"},"0.11.14":{"node_abi":14,"v8":"3.26"},"0.11.15":{"node_abi":14,"v8":"3.28"},"0.11.16":{"node_abi":14,"v8":"3.28"},"0.12.0":{"node_abi":14,"v8":"3.28"},"0.12.1":{"node_abi":14,"v8":"3.28"},"0.12.2":{"node_abi":14,"v8":"3.28"},"0.12.3":{"node_abi":14,"v8":"3.28"},"0.12.4":{"node_abi":14,"v8":"3.28"},"0.12.5":{"node_abi":14,"v8":"3.28"},"0.12.6":{"node_abi":14,"v8":"3.28"},"0.12.7":{"node_abi":14,"v8":"3.28"},"0.12.8":{"node_abi":14,"v8":"3.28"},"0.12.9":{"node_abi":14,"v8":"3.28"},"0.12.10":{"node_abi":14,"v8":"3.28"},"0.12.11":{"node_abi":14,"v8":"3.28"},"0.12.12":{"node_abi":14,"v8":"3.28"},"0.12.13":{"node_abi":14,"v8":"3.28"},"0.12.14":{"node_abi":14,"v8":"3.28"},"0.12.15":{"node_abi":14,"v8":"3.28"},"0.12.16":{"node_abi":14,"v8":"3.28"},"0.12.17":{"node_abi":14,"v8":"3.28"},"0.12.18":{"node_abi":14,"v8":"3.28"},"1.0.0":{"node_abi":42,"v8":"3.31"},"1.0.1":{"node_abi":42,"v8":"3.31"},"1.0.2":{"node_abi":42,"v8":"3.31"},"1.0.3":{"node_abi":42,"v8":"4.1"},"1.0.4":{"node_abi":42,"v8":"4.1"},"1.1.0":{"node_abi":43,"v8":"4.1"},"1.2.0":{"node_abi":43,"v8":"4.1"},"1.3.0":{"node_abi":43,"v8":"4.1"},"1.4.1":{"node_abi":43,"v8":"4.1"},"1.4.2":{"node_abi":43,"v8":"4.1"},"1.4.3":{"node_abi":43,"v8":"4.1"},"1.5.0":{"node_abi":43,"v8":"4.1"},"1.5.1":{"node_abi":43,"v8":"4.1"},"1.6.0":{"node_abi":43,"v8":"4.1"},"1.6.1":{"node_abi":43,"v8":"4.1"},"1.6.2":{"node_abi":43,"v8":"4.1"},"1.6.3":{"node_abi":43,"v8":"4.1"},"1.6.4":{"node_abi":43,"v8":"4.1"},"1.7.1":{"node_abi":43,"v8":"4.1"},"1.8.1":{"node_abi":43,"v8":"4.1"},"1.8.2":{"node_abi":43,"v8":"4.1"},"1.8.3":{"node_abi":43,"v8":"4.1"},"1.8.4":{"node_abi":43,"v8":"4.1"},"2.0.0":{"node_abi":44,"v8":"4.2"},"2.0.1":{"node_abi":44,"v8":"4.2"},"2.0.2":{"node_abi":44,"v8":"4.2"},"2.1.0":{"node_abi":44,"v8":"4.2"},"2.2.0":{"node_abi":44,"v8":"4.2"},"2.2.1":{"node_abi":44,"v8":"4.2"},"2.3.0":{"node_abi":44,"v8":"4.2"},"2.3.1":{"node_abi":44,"v8":"4.2"},"2.3.2":{"node_abi":44,"v8":"4.2"},"2.3.3":{"node_abi":44,"v8":"4.2"},"2.3.4":{"node_abi":44,"v8":"4.2"},"2.4.0":{"node_abi":44,"v8":"4.2"},"2.5.0":{"node_abi":44,"v8":"4.2"},"3.0.0":{"node_abi":45,"v8":"4.4"},"3.1.0":{"node_abi":45,"v8":"4.4"},"3.2.0":{"node_abi":45,"v8":"4.4"},"3.3.0":{"node_abi":45,"v8":"4.4"},"3.3.1":{"node_abi":45,"v8":"4.4"},"4.0.0":{"node_abi":46,"v8":"4.5"},"4.1.0":{"node_abi":46,"v8":"4.5"},"4.1.1":{"node_abi":46,"v8":"4.5"},"4.1.2":{"node_abi":46,"v8":"4.5"},"4.2.0":{"node_abi":46,"v8":"4.5"},"4.2.1":{"node_abi":46,"v8":"4.5"},"4.2.2":{"node_abi":46,"v8":"4.5"},"4.2.3":{"node_abi":46,"v8":"4.5"},"4.2.4":{"node_abi":46,"v8":"4.5"},"4.2.5":{"node_abi":46,"v8":"4.5"},"4.2.6":{"node_abi":46,"v8":"4.5"},"4.3.0":{"node_abi":46,"v8":"4.5"},"4.3.1":{"node_abi":46,"v8":"4.5"},"4.3.2":{"node_abi":46,"v8":"4.5"},"4.4.0":{"node_abi":46,"v8":"4.5"},"4.4.1":{"node_abi":46,"v8":"4.5"},"4.4.2":{"node_abi":46,"v8":"4.5"},"4.4.3":{"node_abi":46,"v8":"4.5"},"4.4.4":{"node_abi":46,"v8":"4.5"},"4.4.5":{"node_abi":46,"v8":"4.5"},"4.4.6":{"node_abi":46,"v8":"4.5"},"4.4.7":{"node_abi":46,"v8":"4.5"},"4.5.0":{"node_abi":46,"v8":"4.5"},"4.6.0":{"node_abi":46,"v8":"4.5"},"4.6.1":{"node_abi":46,"v8":"4.5"},"4.6.2":{"node_abi":46,"v8":"4.5"},"4.7.0":{"node_abi":46,"v8":"4.5"},"4.7.1":{"node_abi":46,"v8":"4.5"},"4.7.2":{"node_abi":46,"v8":"4.5"},"4.7.3":{"node_abi":46,"v8":"4.5"},"4.8.0":{"node_abi":46,"v8":"4.5"},"4.8.1":{"node_abi":46,"v8":"4.5"},"4.8.2":{"node_abi":46,"v8":"4.5"},"4.8.3":{"node_abi":46,"v8":"4.5"},"4.8.4":{"node_abi":46,"v8":"4.5"},"4.8.5":{"node_abi":46,"v8":"4.5"},"4.8.6":{"node_abi":46,"v8":"4.5"},"4.8.7":{"node_abi":46,"v8":"4.5"},"4.9.0":{"node_abi":46,"v8":"4.5"},"4.9.1":{"node_abi":46,"v8":"4.5"},"5.0.0":{"node_abi":47,"v8":"4.6"},"5.1.0":{"node_abi":47,"v8":"4.6"},"5.1.1":{"node_abi":47,"v8":"4.6"},"5.2.0":{"node_abi":47,"v8":"4.6"},"5.3.0":{"node_abi":47,"v8":"4.6"},"5.4.0":{"node_abi":47,"v8":"4.6"},"5.4.1":{"node_abi":47,"v8":"4.6"},"5.5.0":{"node_abi":47,"v8":"4.6"},"5.6.0":{"node_abi":47,"v8":"4.6"},"5.7.0":{"node_abi":47,"v8":"4.6"},"5.7.1":{"node_abi":47,"v8":"4.6"},"5.8.0":{"node_abi":47,"v8":"4.6"},"5.9.0":{"node_abi":47,"v8":"4.6"},"5.9.1":{"node_abi":47,"v8":"4.6"},"5.10.0":{"node_abi":47,"v8":"4.6"},"5.10.1":{"node_abi":47,"v8":"4.6"},"5.11.0":{"node_abi":47,"v8":"4.6"},"5.11.1":{"node_abi":47,"v8":"4.6"},"5.12.0":{"node_abi":47,"v8":"4.6"},"6.0.0":{"node_abi":48,"v8":"5.0"},"6.1.0":{"node_abi":48,"v8":"5.0"},"6.2.0":{"node_abi":48,"v8":"5.0"},"6.2.1":{"node_abi":48,"v8":"5.0"},"6.2.2":{"node_abi":48,"v8":"5.0"},"6.3.0":{"node_abi":48,"v8":"5.0"},"6.3.1":{"node_abi":48,"v8":"5.0"},"6.4.0":{"node_abi":48,"v8":"5.0"},"6.5.0":{"node_abi":48,"v8":"5.1"},"6.6.0":{"node_abi":48,"v8":"5.1"},"6.7.0":{"node_abi":48,"v8":"5.1"},"6.8.0":{"node_abi":48,"v8":"5.1"},"6.8.1":{"node_abi":48,"v8":"5.1"},"6.9.0":{"node_abi":48,"v8":"5.1"},"6.9.1":{"node_abi":48,"v8":"5.1"},"6.9.2":{"node_abi":48,"v8":"5.1"},"6.9.3":{"node_abi":48,"v8":"5.1"},"6.9.4":{"node_abi":48,"v8":"5.1"},"6.9.5":{"node_abi":48,"v8":"5.1"},"6.10.0":{"node_abi":48,"v8":"5.1"},"6.10.1":{"node_abi":48,"v8":"5.1"},"6.10.2":{"node_abi":48,"v8":"5.1"},"6.10.3":{"node_abi":48,"v8":"5.1"},"6.11.0":{"node_abi":48,"v8":"5.1"},"6.11.1":{"node_abi":48,"v8":"5.1"},"6.11.2":{"node_abi":48,"v8":"5.1"},"6.11.3":{"node_abi":48,"v8":"5.1"},"6.11.4":{"node_abi":48,"v8":"5.1"},"6.11.5":{"node_abi":48,"v8":"5.1"},"6.12.0":{"node_abi":48,"v8":"5.1"},"6.12.1":{"node_abi":48,"v8":"5.1"},"6.12.2":{"node_abi":48,"v8":"5.1"},"6.12.3":{"node_abi":48,"v8":"5.1"},"6.13.0":{"node_abi":48,"v8":"5.1"},"6.13.1":{"node_abi":48,"v8":"5.1"},"6.14.0":{"node_abi":48,"v8":"5.1"},"6.14.1":{"node_abi":48,"v8":"5.1"},"6.14.2":{"node_abi":48,"v8":"5.1"},"6.14.3":{"node_abi":48,"v8":"5.1"},"6.14.4":{"node_abi":48,"v8":"5.1"},"6.15.0":{"node_abi":48,"v8":"5.1"},"6.15.1":{"node_abi":48,"v8":"5.1"},"6.16.0":{"node_abi":48,"v8":"5.1"},"6.17.0":{"node_abi":48,"v8":"5.1"},"6.17.1":{"node_abi":48,"v8":"5.1"},"7.0.0":{"node_abi":51,"v8":"5.4"},"7.1.0":{"node_abi":51,"v8":"5.4"},"7.2.0":{"node_abi":51,"v8":"5.4"},"7.2.1":{"node_abi":51,"v8":"5.4"},"7.3.0":{"node_abi":51,"v8":"5.4"},"7.4.0":{"node_abi":51,"v8":"5.4"},"7.5.0":{"node_abi":51,"v8":"5.4"},"7.6.0":{"node_abi":51,"v8":"5.5"},"7.7.0":{"node_abi":51,"v8":"5.5"},"7.7.1":{"node_abi":51,"v8":"5.5"},"7.7.2":{"node_abi":51,"v8":"5.5"},"7.7.3":{"node_abi":51,"v8":"5.5"},"7.7.4":{"node_abi":51,"v8":"5.5"},"7.8.0":{"node_abi":51,"v8":"5.5"},"7.9.0":{"node_abi":51,"v8":"5.5"},"7.10.0":{"node_abi":51,"v8":"5.5"},"7.10.1":{"node_abi":51,"v8":"5.5"},"8.0.0":{"node_abi":57,"v8":"5.8"},"8.1.0":{"node_abi":57,"v8":"5.8"},"8.1.1":{"node_abi":57,"v8":"5.8"},"8.1.2":{"node_abi":57,"v8":"5.8"},"8.1.3":{"node_abi":57,"v8":"5.8"},"8.1.4":{"node_abi":57,"v8":"5.8"},"8.2.0":{"node_abi":57,"v8":"5.8"},"8.2.1":{"node_abi":57,"v8":"5.8"},"8.3.0":{"node_abi":57,"v8":"6.0"},"8.4.0":{"node_abi":57,"v8":"6.0"},"8.5.0":{"node_abi":57,"v8":"6.0"},"8.6.0":{"node_abi":57,"v8":"6.0"},"8.7.0":{"node_abi":57,"v8":"6.1"},"8.8.0":{"node_abi":57,"v8":"6.1"},"8.8.1":{"node_abi":57,"v8":"6.1"},"8.9.0":{"node_abi":57,"v8":"6.1"},"8.9.1":{"node_abi":57,"v8":"6.1"},"8.9.2":{"node_abi":57,"v8":"6.1"},"8.9.3":{"node_abi":57,"v8":"6.1"},"8.9.4":{"node_abi":57,"v8":"6.1"},"8.10.0":{"node_abi":57,"v8":"6.2"},"8.11.0":{"node_abi":57,"v8":"6.2"},"8.11.1":{"node_abi":57,"v8":"6.2"},"8.11.2":{"node_abi":57,"v8":"6.2"},"8.11.3":{"node_abi":57,"v8":"6.2"},"8.11.4":{"node_abi":57,"v8":"6.2"},"8.12.0":{"node_abi":57,"v8":"6.2"},"8.13.0":{"node_abi":57,"v8":"6.2"},"8.14.0":{"node_abi":57,"v8":"6.2"},"8.14.1":{"node_abi":57,"v8":"6.2"},"8.15.0":{"node_abi":57,"v8":"6.2"},"8.15.1":{"node_abi":57,"v8":"6.2"},"8.16.0":{"node_abi":57,"v8":"6.2"},"8.16.1":{"node_abi":57,"v8":"6.2"},"8.16.2":{"node_abi":57,"v8":"6.2"},"8.17.0":{"node_abi":57,"v8":"6.2"},"9.0.0":{"node_abi":59,"v8":"6.2"},"9.1.0":{"node_abi":59,"v8":"6.2"},"9.2.0":{"node_abi":59,"v8":"6.2"},"9.2.1":{"node_abi":59,"v8":"6.2"},"9.3.0":{"node_abi":59,"v8":"6.2"},"9.4.0":{"node_abi":59,"v8":"6.2"},"9.5.0":{"node_abi":59,"v8":"6.2"},"9.6.0":{"node_abi":59,"v8":"6.2"},"9.6.1":{"node_abi":59,"v8":"6.2"},"9.7.0":{"node_abi":59,"v8":"6.2"},"9.7.1":{"node_abi":59,"v8":"6.2"},"9.8.0":{"node_abi":59,"v8":"6.2"},"9.9.0":{"node_abi":59,"v8":"6.2"},"9.10.0":{"node_abi":59,"v8":"6.2"},"9.10.1":{"node_abi":59,"v8":"6.2"},"9.11.0":{"node_abi":59,"v8":"6.2"},"9.11.1":{"node_abi":59,"v8":"6.2"},"9.11.2":{"node_abi":59,"v8":"6.2"},"10.0.0":{"node_abi":64,"v8":"6.6"},"10.1.0":{"node_abi":64,"v8":"6.6"},"10.2.0":{"node_abi":64,"v8":"6.6"},"10.2.1":{"node_abi":64,"v8":"6.6"},"10.3.0":{"node_abi":64,"v8":"6.6"},"10.4.0":{"node_abi":64,"v8":"6.7"},"10.4.1":{"node_abi":64,"v8":"6.7"},"10.5.0":{"node_abi":64,"v8":"6.7"},"10.6.0":{"node_abi":64,"v8":"6.7"},"10.7.0":{"node_abi":64,"v8":"6.7"},"10.8.0":{"node_abi":64,"v8":"6.7"},"10.9.0":{"node_abi":64,"v8":"6.8"},"10.10.0":{"node_abi":64,"v8":"6.8"},"10.11.0":{"node_abi":64,"v8":"6.8"},"10.12.0":{"node_abi":64,"v8":"6.8"},"10.13.0":{"node_abi":64,"v8":"6.8"},"10.14.0":{"node_abi":64,"v8":"6.8"},"10.14.1":{"node_abi":64,"v8":"6.8"},"10.14.2":{"node_abi":64,"v8":"6.8"},"10.15.0":{"node_abi":64,"v8":"6.8"},"10.15.1":{"node_abi":64,"v8":"6.8"},"10.15.2":{"node_abi":64,"v8":"6.8"},"10.15.3":{"node_abi":64,"v8":"6.8"},"10.16.0":{"node_abi":64,"v8":"6.8"},"10.16.1":{"node_abi":64,"v8":"6.8"},"10.16.2":{"node_abi":64,"v8":"6.8"},"10.16.3":{"node_abi":64,"v8":"6.8"},"10.17.0":{"node_abi":64,"v8":"6.8"},"10.18.0":{"node_abi":64,"v8":"6.8"},"10.18.1":{"node_abi":64,"v8":"6.8"},"10.19.0":{"node_abi":64,"v8":"6.8"},"10.20.0":{"node_abi":64,"v8":"6.8"},"10.20.1":{"node_abi":64,"v8":"6.8"},"10.21.0":{"node_abi":64,"v8":"6.8"},"10.22.0":{"node_abi":64,"v8":"6.8"},"10.22.1":{"node_abi":64,"v8":"6.8"},"10.23.0":{"node_abi":64,"v8":"6.8"},"10.23.1":{"node_abi":64,"v8":"6.8"},"10.23.2":{"node_abi":64,"v8":"6.8"},"10.23.3":{"node_abi":64,"v8":"6.8"},"10.24.0":{"node_abi":64,"v8":"6.8"},"10.24.1":{"node_abi":64,"v8":"6.8"},"11.0.0":{"node_abi":67,"v8":"7.0"},"11.1.0":{"node_abi":67,"v8":"7.0"},"11.2.0":{"node_abi":67,"v8":"7.0"},"11.3.0":{"node_abi":67,"v8":"7.0"},"11.4.0":{"node_abi":67,"v8":"7.0"},"11.5.0":{"node_abi":67,"v8":"7.0"},"11.6.0":{"node_abi":67,"v8":"7.0"},"11.7.0":{"node_abi":67,"v8":"7.0"},"11.8.0":{"node_abi":67,"v8":"7.0"},"11.9.0":{"node_abi":67,"v8":"7.0"},"11.10.0":{"node_abi":67,"v8":"7.0"},"11.10.1":{"node_abi":67,"v8":"7.0"},"11.11.0":{"node_abi":67,"v8":"7.0"},"11.12.0":{"node_abi":67,"v8":"7.0"},"11.13.0":{"node_abi":67,"v8":"7.0"},"11.14.0":{"node_abi":67,"v8":"7.0"},"11.15.0":{"node_abi":67,"v8":"7.0"},"12.0.0":{"node_abi":72,"v8":"7.4"},"12.1.0":{"node_abi":72,"v8":"7.4"},"12.2.0":{"node_abi":72,"v8":"7.4"},"12.3.0":{"node_abi":72,"v8":"7.4"},"12.3.1":{"node_abi":72,"v8":"7.4"},"12.4.0":{"node_abi":72,"v8":"7.4"},"12.5.0":{"node_abi":72,"v8":"7.5"},"12.6.0":{"node_abi":72,"v8":"7.5"},"12.7.0":{"node_abi":72,"v8":"7.5"},"12.8.0":{"node_abi":72,"v8":"7.5"},"12.8.1":{"node_abi":72,"v8":"7.5"},"12.9.0":{"node_abi":72,"v8":"7.6"},"12.9.1":{"node_abi":72,"v8":"7.6"},"12.10.0":{"node_abi":72,"v8":"7.6"},"12.11.0":{"node_abi":72,"v8":"7.7"},"12.11.1":{"node_abi":72,"v8":"7.7"},"12.12.0":{"node_abi":72,"v8":"7.7"},"12.13.0":{"node_abi":72,"v8":"7.7"},"12.13.1":{"node_abi":72,"v8":"7.7"},"12.14.0":{"node_abi":72,"v8":"7.7"},"12.14.1":{"node_abi":72,"v8":"7.7"},"12.15.0":{"node_abi":72,"v8":"7.7"},"12.16.0":{"node_abi":72,"v8":"7.8"},"12.16.1":{"node_abi":72,"v8":"7.8"},"12.16.2":{"node_abi":72,"v8":"7.8"},"12.16.3":{"node_abi":72,"v8":"7.8"},"12.17.0":{"node_abi":72,"v8":"7.8"},"12.18.0":{"node_abi":72,"v8":"7.8"},"12.18.1":{"node_abi":72,"v8":"7.8"},"12.18.2":{"node_abi":72,"v8":"7.8"},"12.18.3":{"node_abi":72,"v8":"7.8"},"12.18.4":{"node_abi":72,"v8":"7.8"},"12.19.0":{"node_abi":72,"v8":"7.8"},"12.19.1":{"node_abi":72,"v8":"7.8"},"12.20.0":{"node_abi":72,"v8":"7.8"},"12.20.1":{"node_abi":72,"v8":"7.8"},"12.20.2":{"node_abi":72,"v8":"7.8"},"12.21.0":{"node_abi":72,"v8":"7.8"},"12.22.0":{"node_abi":72,"v8":"7.8"},"12.22.1":{"node_abi":72,"v8":"7.8"},"13.0.0":{"node_abi":79,"v8":"7.8"},"13.0.1":{"node_abi":79,"v8":"7.8"},"13.1.0":{"node_abi":79,"v8":"7.8"},"13.2.0":{"node_abi":79,"v8":"7.9"},"13.3.0":{"node_abi":79,"v8":"7.9"},"13.4.0":{"node_abi":79,"v8":"7.9"},"13.5.0":{"node_abi":79,"v8":"7.9"},"13.6.0":{"node_abi":79,"v8":"7.9"},"13.7.0":{"node_abi":79,"v8":"7.9"},"13.8.0":{"node_abi":79,"v8":"7.9"},"13.9.0":{"node_abi":79,"v8":"7.9"},"13.10.0":{"node_abi":79,"v8":"7.9"},"13.10.1":{"node_abi":79,"v8":"7.9"},"13.11.0":{"node_abi":79,"v8":"7.9"},"13.12.0":{"node_abi":79,"v8":"7.9"},"13.13.0":{"node_abi":79,"v8":"7.9"},"13.14.0":{"node_abi":79,"v8":"7.9"},"14.0.0":{"node_abi":83,"v8":"8.1"},"14.1.0":{"node_abi":83,"v8":"8.1"},"14.2.0":{"node_abi":83,"v8":"8.1"},"14.3.0":{"node_abi":83,"v8":"8.1"},"14.4.0":{"node_abi":83,"v8":"8.1"},"14.5.0":{"node_abi":83,"v8":"8.3"},"14.6.0":{"node_abi":83,"v8":"8.4"},"14.7.0":{"node_abi":83,"v8":"8.4"},"14.8.0":{"node_abi":83,"v8":"8.4"},"14.9.0":{"node_abi":83,"v8":"8.4"},"14.10.0":{"node_abi":83,"v8":"8.4"},"14.10.1":{"node_abi":83,"v8":"8.4"},"14.11.0":{"node_abi":83,"v8":"8.4"},"14.12.0":{"node_abi":83,"v8":"8.4"},"14.13.0":{"node_abi":83,"v8":"8.4"},"14.13.1":{"node_abi":83,"v8":"8.4"},"14.14.0":{"node_abi":83,"v8":"8.4"},"14.15.0":{"node_abi":83,"v8":"8.4"},"14.15.1":{"node_abi":83,"v8":"8.4"},"14.15.2":{"node_abi":83,"v8":"8.4"},"14.15.3":{"node_abi":83,"v8":"8.4"},"14.15.4":{"node_abi":83,"v8":"8.4"},"14.15.5":{"node_abi":83,"v8":"8.4"},"14.16.0":{"node_abi":83,"v8":"8.4"},"14.16.1":{"node_abi":83,"v8":"8.4"},"15.0.0":{"node_abi":88,"v8":"8.6"},"15.0.1":{"node_abi":88,"v8":"8.6"},"15.1.0":{"node_abi":88,"v8":"8.6"},"15.2.0":{"node_abi":88,"v8":"8.6"},"15.2.1":{"node_abi":88,"v8":"8.6"},"15.3.0":{"node_abi":88,"v8":"8.6"},"15.4.0":{"node_abi":88,"v8":"8.6"},"15.5.0":{"node_abi":88,"v8":"8.6"},"15.5.1":{"node_abi":88,"v8":"8.6"},"15.6.0":{"node_abi":88,"v8":"8.6"},"15.7.0":{"node_abi":88,"v8":"8.6"},"15.8.0":{"node_abi":88,"v8":"8.6"},"15.9.0":{"node_abi":88,"v8":"8.6"},"15.10.0":{"node_abi":88,"v8":"8.6"},"15.11.0":{"node_abi":88,"v8":"8.6"},"15.12.0":{"node_abi":88,"v8":"8.6"},"15.13.0":{"node_abi":88,"v8":"8.6"},"15.14.0":{"node_abi":88,"v8":"8.6"},"16.0.0":{"node_abi":93,"v8":"9.0"}}')},5381:e=>{"use strict";e.exports=JSON.parse('{"name":"@mapbox/node-pre-gyp","description":"Node.js native addon binary install tool","version":"1.0.5","keywords":["native","addon","module","c","c++","bindings","binary"],"license":"BSD-3-Clause","author":"Dane Springmeyer ","repository":{"type":"git","url":"git://github.com/mapbox/node-pre-gyp.git"},"bin":"./bin/node-pre-gyp","main":"./lib/node-pre-gyp.js","dependencies":{"detect-libc":"^1.0.3","https-proxy-agent":"^5.0.0","make-dir":"^3.1.0","node-fetch":"^2.6.1","nopt":"^5.0.0","npmlog":"^4.1.2","rimraf":"^3.0.2","semver":"^7.3.4","tar":"^6.1.0"},"devDependencies":{"@mapbox/cloudfriend":"^4.6.0","@mapbox/eslint-config-mapbox":"^3.0.0","action-walk":"^2.2.0","aws-sdk":"^2.840.0","codecov":"^3.8.1","eslint":"^7.18.0","eslint-plugin-node":"^11.1.0","mock-aws-s3":"^4.0.1","nock":"^12.0.3","node-addon-api":"^3.1.0","nyc":"^15.1.0","tape":"^5.2.2","tar-fs":"^2.1.1"},"nyc":{"all":true,"skip-full":false,"exclude":["test/**"]},"scripts":{"coverage":"nyc --all --include index.js --include lib/ npm test","upload-coverage":"nyc report --reporter json && codecov --clear --flags=unit --file=./coverage/coverage-final.json","lint":"eslint bin/node-pre-gyp lib/*js lib/util/*js test/*js scripts/*js","fix":"npm run lint -- --fix","update-crosswalk":"node scripts/abi_crosswalk.js","test":"tape test/*test.js"}}')},7277:e=>{"use strict";e.exports=JSON.parse('{"0.1.14":{"node_abi":null,"v8":"1.3"},"0.1.15":{"node_abi":null,"v8":"1.3"},"0.1.16":{"node_abi":null,"v8":"1.3"},"0.1.17":{"node_abi":null,"v8":"1.3"},"0.1.18":{"node_abi":null,"v8":"1.3"},"0.1.19":{"node_abi":null,"v8":"2.0"},"0.1.20":{"node_abi":null,"v8":"2.0"},"0.1.21":{"node_abi":null,"v8":"2.0"},"0.1.22":{"node_abi":null,"v8":"2.0"},"0.1.23":{"node_abi":null,"v8":"2.0"},"0.1.24":{"node_abi":null,"v8":"2.0"},"0.1.25":{"node_abi":null,"v8":"2.0"},"0.1.26":{"node_abi":null,"v8":"2.0"},"0.1.27":{"node_abi":null,"v8":"2.1"},"0.1.28":{"node_abi":null,"v8":"2.1"},"0.1.29":{"node_abi":null,"v8":"2.1"},"0.1.30":{"node_abi":null,"v8":"2.1"},"0.1.31":{"node_abi":null,"v8":"2.1"},"0.1.32":{"node_abi":null,"v8":"2.1"},"0.1.33":{"node_abi":null,"v8":"2.1"},"0.1.90":{"node_abi":null,"v8":"2.2"},"0.1.91":{"node_abi":null,"v8":"2.2"},"0.1.92":{"node_abi":null,"v8":"2.2"},"0.1.93":{"node_abi":null,"v8":"2.2"},"0.1.94":{"node_abi":null,"v8":"2.2"},"0.1.95":{"node_abi":null,"v8":"2.2"},"0.1.96":{"node_abi":null,"v8":"2.2"},"0.1.97":{"node_abi":null,"v8":"2.2"},"0.1.98":{"node_abi":null,"v8":"2.2"},"0.1.99":{"node_abi":null,"v8":"2.2"},"0.1.100":{"node_abi":null,"v8":"2.2"},"0.1.101":{"node_abi":null,"v8":"2.3"},"0.1.102":{"node_abi":null,"v8":"2.3"},"0.1.103":{"node_abi":null,"v8":"2.3"},"0.1.104":{"node_abi":null,"v8":"2.3"},"0.2.0":{"node_abi":1,"v8":"2.3"},"0.2.1":{"node_abi":1,"v8":"2.3"},"0.2.2":{"node_abi":1,"v8":"2.3"},"0.2.3":{"node_abi":1,"v8":"2.3"},"0.2.4":{"node_abi":1,"v8":"2.3"},"0.2.5":{"node_abi":1,"v8":"2.3"},"0.2.6":{"node_abi":1,"v8":"2.3"},"0.3.0":{"node_abi":1,"v8":"2.5"},"0.3.1":{"node_abi":1,"v8":"2.5"},"0.3.2":{"node_abi":1,"v8":"3.0"},"0.3.3":{"node_abi":1,"v8":"3.0"},"0.3.4":{"node_abi":1,"v8":"3.0"},"0.3.5":{"node_abi":1,"v8":"3.0"},"0.3.6":{"node_abi":1,"v8":"3.0"},"0.3.7":{"node_abi":1,"v8":"3.0"},"0.3.8":{"node_abi":1,"v8":"3.1"},"0.4.0":{"node_abi":1,"v8":"3.1"},"0.4.1":{"node_abi":1,"v8":"3.1"},"0.4.2":{"node_abi":1,"v8":"3.1"},"0.4.3":{"node_abi":1,"v8":"3.1"},"0.4.4":{"node_abi":1,"v8":"3.1"},"0.4.5":{"node_abi":1,"v8":"3.1"},"0.4.6":{"node_abi":1,"v8":"3.1"},"0.4.7":{"node_abi":1,"v8":"3.1"},"0.4.8":{"node_abi":1,"v8":"3.1"},"0.4.9":{"node_abi":1,"v8":"3.1"},"0.4.10":{"node_abi":1,"v8":"3.1"},"0.4.11":{"node_abi":1,"v8":"3.1"},"0.4.12":{"node_abi":1,"v8":"3.1"},"0.5.0":{"node_abi":1,"v8":"3.1"},"0.5.1":{"node_abi":1,"v8":"3.4"},"0.5.2":{"node_abi":1,"v8":"3.4"},"0.5.3":{"node_abi":1,"v8":"3.4"},"0.5.4":{"node_abi":1,"v8":"3.5"},"0.5.5":{"node_abi":1,"v8":"3.5"},"0.5.6":{"node_abi":1,"v8":"3.6"},"0.5.7":{"node_abi":1,"v8":"3.6"},"0.5.8":{"node_abi":1,"v8":"3.6"},"0.5.9":{"node_abi":1,"v8":"3.6"},"0.5.10":{"node_abi":1,"v8":"3.7"},"0.6.0":{"node_abi":1,"v8":"3.6"},"0.6.1":{"node_abi":1,"v8":"3.6"},"0.6.2":{"node_abi":1,"v8":"3.6"},"0.6.3":{"node_abi":1,"v8":"3.6"},"0.6.4":{"node_abi":1,"v8":"3.6"},"0.6.5":{"node_abi":1,"v8":"3.6"},"0.6.6":{"node_abi":1,"v8":"3.6"},"0.6.7":{"node_abi":1,"v8":"3.6"},"0.6.8":{"node_abi":1,"v8":"3.6"},"0.6.9":{"node_abi":1,"v8":"3.6"},"0.6.10":{"node_abi":1,"v8":"3.6"},"0.6.11":{"node_abi":1,"v8":"3.6"},"0.6.12":{"node_abi":1,"v8":"3.6"},"0.6.13":{"node_abi":1,"v8":"3.6"},"0.6.14":{"node_abi":1,"v8":"3.6"},"0.6.15":{"node_abi":1,"v8":"3.6"},"0.6.16":{"node_abi":1,"v8":"3.6"},"0.6.17":{"node_abi":1,"v8":"3.6"},"0.6.18":{"node_abi":1,"v8":"3.6"},"0.6.19":{"node_abi":1,"v8":"3.6"},"0.6.20":{"node_abi":1,"v8":"3.6"},"0.6.21":{"node_abi":1,"v8":"3.6"},"0.7.0":{"node_abi":1,"v8":"3.8"},"0.7.1":{"node_abi":1,"v8":"3.8"},"0.7.2":{"node_abi":1,"v8":"3.8"},"0.7.3":{"node_abi":1,"v8":"3.9"},"0.7.4":{"node_abi":1,"v8":"3.9"},"0.7.5":{"node_abi":1,"v8":"3.9"},"0.7.6":{"node_abi":1,"v8":"3.9"},"0.7.7":{"node_abi":1,"v8":"3.9"},"0.7.8":{"node_abi":1,"v8":"3.9"},"0.7.9":{"node_abi":1,"v8":"3.11"},"0.7.10":{"node_abi":1,"v8":"3.9"},"0.7.11":{"node_abi":1,"v8":"3.11"},"0.7.12":{"node_abi":1,"v8":"3.11"},"0.8.0":{"node_abi":1,"v8":"3.11"},"0.8.1":{"node_abi":1,"v8":"3.11"},"0.8.2":{"node_abi":1,"v8":"3.11"},"0.8.3":{"node_abi":1,"v8":"3.11"},"0.8.4":{"node_abi":1,"v8":"3.11"},"0.8.5":{"node_abi":1,"v8":"3.11"},"0.8.6":{"node_abi":1,"v8":"3.11"},"0.8.7":{"node_abi":1,"v8":"3.11"},"0.8.8":{"node_abi":1,"v8":"3.11"},"0.8.9":{"node_abi":1,"v8":"3.11"},"0.8.10":{"node_abi":1,"v8":"3.11"},"0.8.11":{"node_abi":1,"v8":"3.11"},"0.8.12":{"node_abi":1,"v8":"3.11"},"0.8.13":{"node_abi":1,"v8":"3.11"},"0.8.14":{"node_abi":1,"v8":"3.11"},"0.8.15":{"node_abi":1,"v8":"3.11"},"0.8.16":{"node_abi":1,"v8":"3.11"},"0.8.17":{"node_abi":1,"v8":"3.11"},"0.8.18":{"node_abi":1,"v8":"3.11"},"0.8.19":{"node_abi":1,"v8":"3.11"},"0.8.20":{"node_abi":1,"v8":"3.11"},"0.8.21":{"node_abi":1,"v8":"3.11"},"0.8.22":{"node_abi":1,"v8":"3.11"},"0.8.23":{"node_abi":1,"v8":"3.11"},"0.8.24":{"node_abi":1,"v8":"3.11"},"0.8.25":{"node_abi":1,"v8":"3.11"},"0.8.26":{"node_abi":1,"v8":"3.11"},"0.8.27":{"node_abi":1,"v8":"3.11"},"0.8.28":{"node_abi":1,"v8":"3.11"},"0.9.0":{"node_abi":1,"v8":"3.11"},"0.9.1":{"node_abi":10,"v8":"3.11"},"0.9.2":{"node_abi":10,"v8":"3.11"},"0.9.3":{"node_abi":10,"v8":"3.13"},"0.9.4":{"node_abi":10,"v8":"3.13"},"0.9.5":{"node_abi":10,"v8":"3.13"},"0.9.6":{"node_abi":10,"v8":"3.15"},"0.9.7":{"node_abi":10,"v8":"3.15"},"0.9.8":{"node_abi":10,"v8":"3.15"},"0.9.9":{"node_abi":11,"v8":"3.15"},"0.9.10":{"node_abi":11,"v8":"3.15"},"0.9.11":{"node_abi":11,"v8":"3.14"},"0.9.12":{"node_abi":11,"v8":"3.14"},"0.10.0":{"node_abi":11,"v8":"3.14"},"0.10.1":{"node_abi":11,"v8":"3.14"},"0.10.2":{"node_abi":11,"v8":"3.14"},"0.10.3":{"node_abi":11,"v8":"3.14"},"0.10.4":{"node_abi":11,"v8":"3.14"},"0.10.5":{"node_abi":11,"v8":"3.14"},"0.10.6":{"node_abi":11,"v8":"3.14"},"0.10.7":{"node_abi":11,"v8":"3.14"},"0.10.8":{"node_abi":11,"v8":"3.14"},"0.10.9":{"node_abi":11,"v8":"3.14"},"0.10.10":{"node_abi":11,"v8":"3.14"},"0.10.11":{"node_abi":11,"v8":"3.14"},"0.10.12":{"node_abi":11,"v8":"3.14"},"0.10.13":{"node_abi":11,"v8":"3.14"},"0.10.14":{"node_abi":11,"v8":"3.14"},"0.10.15":{"node_abi":11,"v8":"3.14"},"0.10.16":{"node_abi":11,"v8":"3.14"},"0.10.17":{"node_abi":11,"v8":"3.14"},"0.10.18":{"node_abi":11,"v8":"3.14"},"0.10.19":{"node_abi":11,"v8":"3.14"},"0.10.20":{"node_abi":11,"v8":"3.14"},"0.10.21":{"node_abi":11,"v8":"3.14"},"0.10.22":{"node_abi":11,"v8":"3.14"},"0.10.23":{"node_abi":11,"v8":"3.14"},"0.10.24":{"node_abi":11,"v8":"3.14"},"0.10.25":{"node_abi":11,"v8":"3.14"},"0.10.26":{"node_abi":11,"v8":"3.14"},"0.10.27":{"node_abi":11,"v8":"3.14"},"0.10.28":{"node_abi":11,"v8":"3.14"},"0.10.29":{"node_abi":11,"v8":"3.14"},"0.10.30":{"node_abi":11,"v8":"3.14"},"0.10.31":{"node_abi":11,"v8":"3.14"},"0.10.32":{"node_abi":11,"v8":"3.14"},"0.10.33":{"node_abi":11,"v8":"3.14"},"0.10.34":{"node_abi":11,"v8":"3.14"},"0.10.35":{"node_abi":11,"v8":"3.14"},"0.10.36":{"node_abi":11,"v8":"3.14"},"0.10.37":{"node_abi":11,"v8":"3.14"},"0.10.38":{"node_abi":11,"v8":"3.14"},"0.10.39":{"node_abi":11,"v8":"3.14"},"0.10.40":{"node_abi":11,"v8":"3.14"},"0.10.41":{"node_abi":11,"v8":"3.14"},"0.10.42":{"node_abi":11,"v8":"3.14"},"0.10.43":{"node_abi":11,"v8":"3.14"},"0.10.44":{"node_abi":11,"v8":"3.14"},"0.10.45":{"node_abi":11,"v8":"3.14"},"0.10.46":{"node_abi":11,"v8":"3.14"},"0.10.47":{"node_abi":11,"v8":"3.14"},"0.10.48":{"node_abi":11,"v8":"3.14"},"0.11.0":{"node_abi":12,"v8":"3.17"},"0.11.1":{"node_abi":12,"v8":"3.18"},"0.11.2":{"node_abi":12,"v8":"3.19"},"0.11.3":{"node_abi":12,"v8":"3.19"},"0.11.4":{"node_abi":12,"v8":"3.20"},"0.11.5":{"node_abi":12,"v8":"3.20"},"0.11.6":{"node_abi":12,"v8":"3.20"},"0.11.7":{"node_abi":12,"v8":"3.20"},"0.11.8":{"node_abi":13,"v8":"3.21"},"0.11.9":{"node_abi":13,"v8":"3.22"},"0.11.10":{"node_abi":13,"v8":"3.22"},"0.11.11":{"node_abi":14,"v8":"3.22"},"0.11.12":{"node_abi":14,"v8":"3.22"},"0.11.13":{"node_abi":14,"v8":"3.25"},"0.11.14":{"node_abi":14,"v8":"3.26"},"0.11.15":{"node_abi":14,"v8":"3.28"},"0.11.16":{"node_abi":14,"v8":"3.28"},"0.12.0":{"node_abi":14,"v8":"3.28"},"0.12.1":{"node_abi":14,"v8":"3.28"},"0.12.2":{"node_abi":14,"v8":"3.28"},"0.12.3":{"node_abi":14,"v8":"3.28"},"0.12.4":{"node_abi":14,"v8":"3.28"},"0.12.5":{"node_abi":14,"v8":"3.28"},"0.12.6":{"node_abi":14,"v8":"3.28"},"0.12.7":{"node_abi":14,"v8":"3.28"},"0.12.8":{"node_abi":14,"v8":"3.28"},"0.12.9":{"node_abi":14,"v8":"3.28"},"0.12.10":{"node_abi":14,"v8":"3.28"},"0.12.11":{"node_abi":14,"v8":"3.28"},"0.12.12":{"node_abi":14,"v8":"3.28"},"0.12.13":{"node_abi":14,"v8":"3.28"},"0.12.14":{"node_abi":14,"v8":"3.28"},"0.12.15":{"node_abi":14,"v8":"3.28"},"0.12.16":{"node_abi":14,"v8":"3.28"},"0.12.17":{"node_abi":14,"v8":"3.28"},"0.12.18":{"node_abi":14,"v8":"3.28"},"1.0.0":{"node_abi":42,"v8":"3.31"},"1.0.1":{"node_abi":42,"v8":"3.31"},"1.0.2":{"node_abi":42,"v8":"3.31"},"1.0.3":{"node_abi":42,"v8":"4.1"},"1.0.4":{"node_abi":42,"v8":"4.1"},"1.1.0":{"node_abi":43,"v8":"4.1"},"1.2.0":{"node_abi":43,"v8":"4.1"},"1.3.0":{"node_abi":43,"v8":"4.1"},"1.4.1":{"node_abi":43,"v8":"4.1"},"1.4.2":{"node_abi":43,"v8":"4.1"},"1.4.3":{"node_abi":43,"v8":"4.1"},"1.5.0":{"node_abi":43,"v8":"4.1"},"1.5.1":{"node_abi":43,"v8":"4.1"},"1.6.0":{"node_abi":43,"v8":"4.1"},"1.6.1":{"node_abi":43,"v8":"4.1"},"1.6.2":{"node_abi":43,"v8":"4.1"},"1.6.3":{"node_abi":43,"v8":"4.1"},"1.6.4":{"node_abi":43,"v8":"4.1"},"1.7.1":{"node_abi":43,"v8":"4.1"},"1.8.1":{"node_abi":43,"v8":"4.1"},"1.8.2":{"node_abi":43,"v8":"4.1"},"1.8.3":{"node_abi":43,"v8":"4.1"},"1.8.4":{"node_abi":43,"v8":"4.1"},"2.0.0":{"node_abi":44,"v8":"4.2"},"2.0.1":{"node_abi":44,"v8":"4.2"},"2.0.2":{"node_abi":44,"v8":"4.2"},"2.1.0":{"node_abi":44,"v8":"4.2"},"2.2.0":{"node_abi":44,"v8":"4.2"},"2.2.1":{"node_abi":44,"v8":"4.2"},"2.3.0":{"node_abi":44,"v8":"4.2"},"2.3.1":{"node_abi":44,"v8":"4.2"},"2.3.2":{"node_abi":44,"v8":"4.2"},"2.3.3":{"node_abi":44,"v8":"4.2"},"2.3.4":{"node_abi":44,"v8":"4.2"},"2.4.0":{"node_abi":44,"v8":"4.2"},"2.5.0":{"node_abi":44,"v8":"4.2"},"3.0.0":{"node_abi":45,"v8":"4.4"},"3.1.0":{"node_abi":45,"v8":"4.4"},"3.2.0":{"node_abi":45,"v8":"4.4"},"3.3.0":{"node_abi":45,"v8":"4.4"},"3.3.1":{"node_abi":45,"v8":"4.4"},"4.0.0":{"node_abi":46,"v8":"4.5"},"4.1.0":{"node_abi":46,"v8":"4.5"},"4.1.1":{"node_abi":46,"v8":"4.5"},"4.1.2":{"node_abi":46,"v8":"4.5"},"4.2.0":{"node_abi":46,"v8":"4.5"},"4.2.1":{"node_abi":46,"v8":"4.5"},"4.2.2":{"node_abi":46,"v8":"4.5"},"4.2.3":{"node_abi":46,"v8":"4.5"},"4.2.4":{"node_abi":46,"v8":"4.5"},"4.2.5":{"node_abi":46,"v8":"4.5"},"4.2.6":{"node_abi":46,"v8":"4.5"},"4.3.0":{"node_abi":46,"v8":"4.5"},"4.3.1":{"node_abi":46,"v8":"4.5"},"4.3.2":{"node_abi":46,"v8":"4.5"},"4.4.0":{"node_abi":46,"v8":"4.5"},"4.4.1":{"node_abi":46,"v8":"4.5"},"4.4.2":{"node_abi":46,"v8":"4.5"},"4.4.3":{"node_abi":46,"v8":"4.5"},"4.4.4":{"node_abi":46,"v8":"4.5"},"4.4.5":{"node_abi":46,"v8":"4.5"},"4.4.6":{"node_abi":46,"v8":"4.5"},"4.4.7":{"node_abi":46,"v8":"4.5"},"4.5.0":{"node_abi":46,"v8":"4.5"},"4.6.0":{"node_abi":46,"v8":"4.5"},"4.6.1":{"node_abi":46,"v8":"4.5"},"4.6.2":{"node_abi":46,"v8":"4.5"},"4.7.0":{"node_abi":46,"v8":"4.5"},"4.7.1":{"node_abi":46,"v8":"4.5"},"4.7.2":{"node_abi":46,"v8":"4.5"},"4.7.3":{"node_abi":46,"v8":"4.5"},"4.8.0":{"node_abi":46,"v8":"4.5"},"4.8.1":{"node_abi":46,"v8":"4.5"},"4.8.2":{"node_abi":46,"v8":"4.5"},"4.8.3":{"node_abi":46,"v8":"4.5"},"4.8.4":{"node_abi":46,"v8":"4.5"},"4.8.5":{"node_abi":46,"v8":"4.5"},"4.8.6":{"node_abi":46,"v8":"4.5"},"4.8.7":{"node_abi":46,"v8":"4.5"},"4.9.0":{"node_abi":46,"v8":"4.5"},"4.9.1":{"node_abi":46,"v8":"4.5"},"5.0.0":{"node_abi":47,"v8":"4.6"},"5.1.0":{"node_abi":47,"v8":"4.6"},"5.1.1":{"node_abi":47,"v8":"4.6"},"5.2.0":{"node_abi":47,"v8":"4.6"},"5.3.0":{"node_abi":47,"v8":"4.6"},"5.4.0":{"node_abi":47,"v8":"4.6"},"5.4.1":{"node_abi":47,"v8":"4.6"},"5.5.0":{"node_abi":47,"v8":"4.6"},"5.6.0":{"node_abi":47,"v8":"4.6"},"5.7.0":{"node_abi":47,"v8":"4.6"},"5.7.1":{"node_abi":47,"v8":"4.6"},"5.8.0":{"node_abi":47,"v8":"4.6"},"5.9.0":{"node_abi":47,"v8":"4.6"},"5.9.1":{"node_abi":47,"v8":"4.6"},"5.10.0":{"node_abi":47,"v8":"4.6"},"5.10.1":{"node_abi":47,"v8":"4.6"},"5.11.0":{"node_abi":47,"v8":"4.6"},"5.11.1":{"node_abi":47,"v8":"4.6"},"5.12.0":{"node_abi":47,"v8":"4.6"},"6.0.0":{"node_abi":48,"v8":"5.0"},"6.1.0":{"node_abi":48,"v8":"5.0"},"6.2.0":{"node_abi":48,"v8":"5.0"},"6.2.1":{"node_abi":48,"v8":"5.0"},"6.2.2":{"node_abi":48,"v8":"5.0"},"6.3.0":{"node_abi":48,"v8":"5.0"},"6.3.1":{"node_abi":48,"v8":"5.0"},"6.4.0":{"node_abi":48,"v8":"5.0"},"6.5.0":{"node_abi":48,"v8":"5.1"},"6.6.0":{"node_abi":48,"v8":"5.1"},"6.7.0":{"node_abi":48,"v8":"5.1"},"6.8.0":{"node_abi":48,"v8":"5.1"},"6.8.1":{"node_abi":48,"v8":"5.1"},"6.9.0":{"node_abi":48,"v8":"5.1"},"6.9.1":{"node_abi":48,"v8":"5.1"},"6.9.2":{"node_abi":48,"v8":"5.1"},"6.9.3":{"node_abi":48,"v8":"5.1"},"6.9.4":{"node_abi":48,"v8":"5.1"},"6.9.5":{"node_abi":48,"v8":"5.1"},"6.10.0":{"node_abi":48,"v8":"5.1"},"6.10.1":{"node_abi":48,"v8":"5.1"},"6.10.2":{"node_abi":48,"v8":"5.1"},"6.10.3":{"node_abi":48,"v8":"5.1"},"6.11.0":{"node_abi":48,"v8":"5.1"},"6.11.1":{"node_abi":48,"v8":"5.1"},"6.11.2":{"node_abi":48,"v8":"5.1"},"6.11.3":{"node_abi":48,"v8":"5.1"},"6.11.4":{"node_abi":48,"v8":"5.1"},"6.11.5":{"node_abi":48,"v8":"5.1"},"6.12.0":{"node_abi":48,"v8":"5.1"},"6.12.1":{"node_abi":48,"v8":"5.1"},"6.12.2":{"node_abi":48,"v8":"5.1"},"6.12.3":{"node_abi":48,"v8":"5.1"},"6.13.0":{"node_abi":48,"v8":"5.1"},"6.13.1":{"node_abi":48,"v8":"5.1"},"6.14.0":{"node_abi":48,"v8":"5.1"},"6.14.1":{"node_abi":48,"v8":"5.1"},"6.14.2":{"node_abi":48,"v8":"5.1"},"6.14.3":{"node_abi":48,"v8":"5.1"},"6.14.4":{"node_abi":48,"v8":"5.1"},"6.15.0":{"node_abi":48,"v8":"5.1"},"6.15.1":{"node_abi":48,"v8":"5.1"},"6.16.0":{"node_abi":48,"v8":"5.1"},"6.17.0":{"node_abi":48,"v8":"5.1"},"6.17.1":{"node_abi":48,"v8":"5.1"},"7.0.0":{"node_abi":51,"v8":"5.4"},"7.1.0":{"node_abi":51,"v8":"5.4"},"7.2.0":{"node_abi":51,"v8":"5.4"},"7.2.1":{"node_abi":51,"v8":"5.4"},"7.3.0":{"node_abi":51,"v8":"5.4"},"7.4.0":{"node_abi":51,"v8":"5.4"},"7.5.0":{"node_abi":51,"v8":"5.4"},"7.6.0":{"node_abi":51,"v8":"5.5"},"7.7.0":{"node_abi":51,"v8":"5.5"},"7.7.1":{"node_abi":51,"v8":"5.5"},"7.7.2":{"node_abi":51,"v8":"5.5"},"7.7.3":{"node_abi":51,"v8":"5.5"},"7.7.4":{"node_abi":51,"v8":"5.5"},"7.8.0":{"node_abi":51,"v8":"5.5"},"7.9.0":{"node_abi":51,"v8":"5.5"},"7.10.0":{"node_abi":51,"v8":"5.5"},"7.10.1":{"node_abi":51,"v8":"5.5"},"8.0.0":{"node_abi":57,"v8":"5.8"},"8.1.0":{"node_abi":57,"v8":"5.8"},"8.1.1":{"node_abi":57,"v8":"5.8"},"8.1.2":{"node_abi":57,"v8":"5.8"},"8.1.3":{"node_abi":57,"v8":"5.8"},"8.1.4":{"node_abi":57,"v8":"5.8"},"8.2.0":{"node_abi":57,"v8":"5.8"},"8.2.1":{"node_abi":57,"v8":"5.8"},"8.3.0":{"node_abi":57,"v8":"6.0"},"8.4.0":{"node_abi":57,"v8":"6.0"},"8.5.0":{"node_abi":57,"v8":"6.0"},"8.6.0":{"node_abi":57,"v8":"6.0"},"8.7.0":{"node_abi":57,"v8":"6.1"},"8.8.0":{"node_abi":57,"v8":"6.1"},"8.8.1":{"node_abi":57,"v8":"6.1"},"8.9.0":{"node_abi":57,"v8":"6.1"},"8.9.1":{"node_abi":57,"v8":"6.1"},"8.9.2":{"node_abi":57,"v8":"6.1"},"8.9.3":{"node_abi":57,"v8":"6.1"},"8.9.4":{"node_abi":57,"v8":"6.1"},"8.10.0":{"node_abi":57,"v8":"6.2"},"8.11.0":{"node_abi":57,"v8":"6.2"},"8.11.1":{"node_abi":57,"v8":"6.2"},"8.11.2":{"node_abi":57,"v8":"6.2"},"8.11.3":{"node_abi":57,"v8":"6.2"},"8.11.4":{"node_abi":57,"v8":"6.2"},"8.12.0":{"node_abi":57,"v8":"6.2"},"8.13.0":{"node_abi":57,"v8":"6.2"},"8.14.0":{"node_abi":57,"v8":"6.2"},"8.14.1":{"node_abi":57,"v8":"6.2"},"8.15.0":{"node_abi":57,"v8":"6.2"},"8.15.1":{"node_abi":57,"v8":"6.2"},"8.16.0":{"node_abi":57,"v8":"6.2"},"9.0.0":{"node_abi":59,"v8":"6.2"},"9.1.0":{"node_abi":59,"v8":"6.2"},"9.2.0":{"node_abi":59,"v8":"6.2"},"9.2.1":{"node_abi":59,"v8":"6.2"},"9.3.0":{"node_abi":59,"v8":"6.2"},"9.4.0":{"node_abi":59,"v8":"6.2"},"9.5.0":{"node_abi":59,"v8":"6.2"},"9.6.0":{"node_abi":59,"v8":"6.2"},"9.6.1":{"node_abi":59,"v8":"6.2"},"9.7.0":{"node_abi":59,"v8":"6.2"},"9.7.1":{"node_abi":59,"v8":"6.2"},"9.8.0":{"node_abi":59,"v8":"6.2"},"9.9.0":{"node_abi":59,"v8":"6.2"},"9.10.0":{"node_abi":59,"v8":"6.2"},"9.10.1":{"node_abi":59,"v8":"6.2"},"9.11.0":{"node_abi":59,"v8":"6.2"},"9.11.1":{"node_abi":59,"v8":"6.2"},"9.11.2":{"node_abi":59,"v8":"6.2"},"10.0.0":{"node_abi":64,"v8":"6.6"},"10.1.0":{"node_abi":64,"v8":"6.6"},"10.2.0":{"node_abi":64,"v8":"6.6"},"10.2.1":{"node_abi":64,"v8":"6.6"},"10.3.0":{"node_abi":64,"v8":"6.6"},"10.4.0":{"node_abi":64,"v8":"6.7"},"10.4.1":{"node_abi":64,"v8":"6.7"},"10.5.0":{"node_abi":64,"v8":"6.7"},"10.6.0":{"node_abi":64,"v8":"6.7"},"10.7.0":{"node_abi":64,"v8":"6.7"},"10.8.0":{"node_abi":64,"v8":"6.7"},"10.9.0":{"node_abi":64,"v8":"6.8"},"10.10.0":{"node_abi":64,"v8":"6.8"},"10.11.0":{"node_abi":64,"v8":"6.8"},"10.12.0":{"node_abi":64,"v8":"6.8"},"10.13.0":{"node_abi":64,"v8":"6.8"},"10.14.0":{"node_abi":64,"v8":"6.8"},"10.14.1":{"node_abi":64,"v8":"6.8"},"10.14.2":{"node_abi":64,"v8":"6.8"},"10.15.0":{"node_abi":64,"v8":"6.8"},"10.15.1":{"node_abi":64,"v8":"6.8"},"10.15.2":{"node_abi":64,"v8":"6.8"},"10.15.3":{"node_abi":64,"v8":"6.8"},"11.0.0":{"node_abi":67,"v8":"7.0"},"11.1.0":{"node_abi":67,"v8":"7.0"},"11.2.0":{"node_abi":67,"v8":"7.0"},"11.3.0":{"node_abi":67,"v8":"7.0"},"11.4.0":{"node_abi":67,"v8":"7.0"},"11.5.0":{"node_abi":67,"v8":"7.0"},"11.6.0":{"node_abi":67,"v8":"7.0"},"11.7.0":{"node_abi":67,"v8":"7.0"},"11.8.0":{"node_abi":67,"v8":"7.0"},"11.9.0":{"node_abi":67,"v8":"7.0"},"11.10.0":{"node_abi":67,"v8":"7.0"},"11.10.1":{"node_abi":67,"v8":"7.0"},"11.11.0":{"node_abi":67,"v8":"7.0"},"11.12.0":{"node_abi":67,"v8":"7.0"},"11.13.0":{"node_abi":67,"v8":"7.0"},"11.14.0":{"node_abi":67,"v8":"7.0"},"12.0.0":{"node_abi":72,"v8":"7.4"}}')},2914:(e,t,i)=>{"use strict";e.exports=t;t.mockS3Http=i(3008).get_mockS3Http();t.mockS3Http("on");const n=t.mockS3Http("get");const r=i(5747);const s=i(5622);const a=i(9253);const o=i(496);o.disableProgress();const u=i(8145);const l=i(8614).EventEmitter;const f=i(1669).inherits;const c=["clean","install","reinstall","build","rebuild","package","testpackage","publish","unpublish","info","testbinary","reveal","configure"];const h={};o.heading="node-pre-gyp";if(n){o.warn(`mocking s3 to ${process.env.node_pre_gyp_mock_s3}`)}Object.defineProperty(t,"find",{get:function(){return i(4865).find},enumerable:true});function Run({package_json_path:e="./package.json",argv:t}){this.package_json_path=e;this.commands={};const i=this;c.forEach(e=>{i.commands[e]=function(t,n){o.verbose("command",e,t);return require("./"+e)(i,t,n)}});this.parseArgv(t);this.binaryHostSet=false}f(Run,l);t.Run=Run;const p=Run.prototype;p.package=i(5381);p.configDefs={help:Boolean,arch:String,debug:Boolean,directory:String,proxy:String,loglevel:String};p.shorthands={release:"--no-debug",C:"--directory",debug:"--debug",j:"--jobs",silent:"--loglevel=silent",silly:"--loglevel=silly",verbose:"--loglevel=verbose"};p.aliases=h;p.parseArgv=function parseOpts(e){this.opts=a(this.configDefs,this.shorthands,e);this.argv=this.opts.argv.remain.slice();const t=this.todo=[];e=this.argv.map(e=>{if(e in this.aliases){e=this.aliases[e]}return e});e.slice().forEach(i=>{if(i in this.commands){const n=e.splice(0,e.indexOf(i));e.shift();if(t.length>0){t[t.length-1].args=n}t.push({name:i,args:[]})}});if(t.length>0){t[t.length-1].args=e.splice(0)}let i=this.package_json_path;if(this.opts.directory){i=s.join(this.opts.directory,i)}this.package_json=JSON.parse(r.readFileSync(i));this.todo=u.expand_commands(this.package_json,this.opts,t);const n="npm_config_";Object.keys(process.env).forEach(e=>{if(e.indexOf(n)!==0)return;const t=process.env[e];if(e===n+"loglevel"){o.level=t}else{e=e.substring(n.length);if(e==="argv"){if(this.opts.argv&&this.opts.argv.remain&&this.opts.argv.remain.length){}else{this.opts[e]=t}}else{this.opts[e]=t}}});if(this.opts.loglevel){o.level=this.opts.loglevel}o.resume()};p.setBinaryHostProperty=function(e){if(this.binaryHostSet){return this.package_json.binary.host}const t=this.package_json;if(!t||!t.binary||t.binary.host){return""}if(!t.binary.staging_host||!t.binary.production_host){return""}let i="production_host";if(e==="publish"){i="staging_host"}const n=process.env.node_pre_gyp_s3_host;if(n==="staging"||n==="production"){i=`${n}_host`}else if(this.opts["s3_host"]==="staging"||this.opts["s3_host"]==="production"){i=`${this.opts["s3_host"]}_host`}else if(this.opts["s3_host"]||n){throw new Error(`invalid s3_host ${this.opts["s3_host"]||n}`)}t.binary.host=t.binary[i];this.binaryHostSet=true;return t.binary.host};p.usage=function usage(){const e=[""," Usage: node-pre-gyp [options]",""," where is one of:",c.map(e=>{return" - "+e+" - "+require("./"+e).usage}).join("\n"),"","node-pre-gyp@"+this.version+" "+s.resolve(__dirname,".."),"node@"+process.versions.node].join("\n");return e};Object.defineProperty(p,"version",{get:function(){return this.package.version},enumerable:true})},4865:(e,t,i)=>{"use strict";const n=i(2914);const r=i(4112);const s=i(8145);const a=i(5747).existsSync||i(5622).existsSync;const o=i(5622);e.exports=t;t.usage="Finds the require path for the node-pre-gyp installed module";t.validate=function(e,t){r.validate_config(e,t)};t.find=function(e,t){if(!a(e)){throw new Error(e+"does not exist")}const i=new n.Run({package_json_path:e,argv:process.argv});i.setBinaryHostProperty();const u=i.package_json;r.validate_config(u,t);let l;if(s.get_napi_build_versions(u,t)){l=s.get_best_napi_build_version(u,t)}t=t||{};if(!t.module_root)t.module_root=o.dirname(e);const f=r.evaluate(u,t,l);return f.module}},8145:(e,t,i)=>{"use strict";const n=i(5747);e.exports=t;const r=process.version.substr(1).replace(/-.*$/,"").split(".").map(e=>{return+e});const s=["build","clean","configure","package","publish","reveal","testbinary","testpackage","unpublish"];const a="napi_build_version=";e.exports.get_napi_version=function(){let e=process.versions.napi;if(!e){if(r[0]===9&&r[1]>=3)e=2;else if(r[0]===8)e=1}return e};e.exports.get_napi_version_as_string=function(t){const i=e.exports.get_napi_version(t);return i?""+i:""};e.exports.validate_package_json=function(t,i){const n=t.binary;const r=pathOK(n.module_path);const s=pathOK(n.remote_path);const a=pathOK(n.package_name);const o=e.exports.get_napi_build_versions(t,i,true);const u=e.exports.get_napi_build_versions_raw(t);if(o){o.forEach(e=>{if(!(parseInt(e,10)===e&&e>0)){throw new Error("All values specified in napi_versions must be positive integers.")}})}if(o&&(!r||!s&&!a)){throw new Error("When napi_versions is specified; module_path and either remote_path or "+"package_name must contain the substitution string '{napi_build_version}`.")}if((r||s||a)&&!u){throw new Error("When the substitution string '{napi_build_version}` is specified in "+"module_path, remote_path, or package_name; napi_versions must also be specified.")}if(o&&!e.exports.get_best_napi_build_version(t,i)&&e.exports.build_napi_only(t)){throw new Error("The Node-API version of this Node instance is "+e.exports.get_napi_version(i?i.target:undefined)+". "+"This module supports Node-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}if(u&&!o&&e.exports.build_napi_only(t)){throw new Error("The Node-API version of this Node instance is "+e.exports.get_napi_version(i?i.target:undefined)+". "+"This module supports Node-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}};function pathOK(e){return e&&(e.indexOf("{napi_build_version}")!==-1||e.indexOf("{node_napi_label}")!==-1)}e.exports.expand_commands=function(t,i,n){const r=[];const o=e.exports.get_napi_build_versions(t,i);n.forEach(n=>{if(o&&n.name==="install"){const s=e.exports.get_best_napi_build_version(t,i);const o=s?[a+s]:[];r.push({name:n.name,args:o})}else if(o&&s.indexOf(n.name)!==-1){o.forEach(e=>{const t=n.args.slice();t.push(a+e);r.push({name:n.name,args:t})})}else{r.push(n)}});return r};e.exports.get_napi_build_versions=function(t,n,r){const s=i(496);let a=[];const o=e.exports.get_napi_version(n?n.target:undefined);if(t.binary&&t.binary.napi_versions){t.binary.napi_versions.forEach(e=>{const t=a.indexOf(e)!==-1;if(!t&&o&&e<=o){a.push(e)}else if(r&&!t&&o){s.info("This Node instance does not support builds for Node-API version",e)}})}if(n&&n["build-latest-napi-version-only"]){let e=0;a.forEach(t=>{if(t>e)e=t});a=e?[e]:[]}return a.length?a:undefined};e.exports.get_napi_build_versions_raw=function(e){const t=[];if(e.binary&&e.binary.napi_versions){e.binary.napi_versions.forEach(e=>{if(t.indexOf(e)===-1){t.push(e)}})}return t.length?t:undefined};e.exports.get_command_arg=function(e){return a+e};e.exports.get_napi_build_version_from_command_args=function(e){for(let t=0;t{if(e>n&&e<=t){n=e}})}return n===0?undefined:n};e.exports.build_napi_only=function(e){return e.binary&&e.binary.package_name&&e.binary.package_name.indexOf("{node_napi_label}")===-1}},3008:(e,t,i)=>{"use strict";e.exports=t;const n=i(8835);const r=i(5747);const s=i(5622);e.exports.detect=function(e,t){const i=e.hosted_path;const r=n.parse(i);t.prefix=!r.pathname||r.pathname==="/"?"":r.pathname.replace("/","");if(e.bucket&&e.region){t.bucket=e.bucket;t.region=e.region;t.endpoint=e.host;t.s3ForcePathStyle=e.s3ForcePathStyle}else{const e=r.hostname.split(".s3");const i=e[0];if(!i){return}if(!t.bucket){t.bucket=i}if(!t.region){const i=e[1].slice(1).split(".")[0];if(i==="amazonaws"){t.region="us-east-1"}else{t.region=i}}}};e.exports.get_s3=function(e){if(process.env.node_pre_gyp_mock_s3){const e=i(8263);const t=i(2087);e.config.basePath=`${t.tmpdir()}/mock`;const n=e.S3();const r=e=>(t,...i)=>{if(t&&t.code==="ENOENT"){t.code="NotFound"}return e(t,...i)};return{listObjects(e,t){return n.listObjects(e,r(t))},headObject(e,t){return n.headObject(e,r(t))},deleteObject(e,t){return n.deleteObject(e,r(t))},putObject(e,t){return n.putObject(e,r(t))}}}const t=i(159);t.config.update(e);const n=new t.S3;return{listObjects(e,t){return n.listObjects(e,t)},headObject(e,t){return n.headObject(e,t)},deleteObject(e,t){return n.deleteObject(e,t)},putObject(e,t){return n.putObject(e,t)}}};e.exports.get_mockS3Http=function(){let e=false;if(!process.env.node_pre_gyp_mock_s3){return()=>e}const t=i(1301);const n="https://mapbox-node-pre-gyp-public-testing-bucket.s3.us-east-1.amazonaws.com";const a=process.env.node_pre_gyp_mock_s3+"/mapbox-node-pre-gyp-public-testing-bucket";const o=()=>{function get(e,t){const i=s.join(a,e.replace("%2B","+"));try{r.accessSync(i,r.constants.R_OK)}catch(e){return[404,"not found\n"]}return[200,r.createReadStream(i)]}return t(n).persist().get(()=>e).reply(get)};o(t,n,a);const u=t=>{const i=e;if(t==="off"){e=false}else if(t==="on"){e=true}else if(t!=="get"){throw new Error(`illegal action for setMockHttp ${t}`)}return i};return u}},4112:(e,t,i)=>{"use strict";e.exports=t;const n=i(5622);const r=i(2519);const s=i(8835);const a=i(2226);const o=i(8145);let u;if(process.env.NODE_PRE_GYP_ABI_CROSSWALK){u=require(process.env.NODE_PRE_GYP_ABI_CROSSWALK)}else{u=i(3380)}const l={};Object.keys(u).forEach(e=>{const t=e.split(".")[0];if(!l[t]){l[t]=e}});function get_electron_abi(e,t){if(!e){throw new Error("get_electron_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if electron is the target.")}const i=r.parse(t);return e+"-v"+i.major+"."+i.minor}e.exports.get_electron_abi=get_electron_abi;function get_node_webkit_abi(e,t){if(!e){throw new Error("get_node_webkit_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if node-webkit is the target.")}return e+"-v"+t}e.exports.get_node_webkit_abi=get_node_webkit_abi;function get_node_abi(e,t){if(!e){throw new Error("get_node_abi requires valid runtime arg")}if(!t){throw new Error("get_node_abi requires valid process.versions object")}const i=r.parse(t.node);if(i.major===0&&i.minor%2){return e+"-v"+t.node}else{return t.modules?e+"-v"+ +t.modules:"v8-"+t.v8.split(".").slice(0,2).join(".")}}e.exports.get_node_abi=get_node_abi;function get_runtime_abi(e,t){if(!e){throw new Error("get_runtime_abi requires valid runtime arg")}if(e==="node-webkit"){return get_node_webkit_abi(e,t||process.versions["node-webkit"])}else if(e==="electron"){return get_electron_abi(e,t||process.versions.electron)}else{if(e!=="node"){throw new Error("Unknown Runtime: '"+e+"'")}if(!t){return get_node_abi(e,process.versions)}else{let i;if(u[t]){i=u[t]}else{const e=t.split(".").map(e=>{return+e});if(e.length!==3){throw new Error("Unknown target version: "+t)}const n=e[0];let r=e[1];let s=e[2];if(n===1){while(true){if(r>0)--r;if(s>0)--s;const e=""+n+"."+r+"."+s;if(u[e]){i=u[e];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+e+" as ABI compatible target");break}if(r===0&&s===0){break}}}else if(n>=2){if(l[n]){i=u[l[n]];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+l[n]+" as ABI compatible target")}}else if(n===0){if(e[1]%2===0){while(--s>0){const e=""+n+"."+r+"."+s;if(u[e]){i=u[e];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+e+" as ABI compatible target");break}}}}}if(!i){throw new Error("Unsupported target version: "+t)}const n={node:t,v8:i.v8+".0",modules:i.node_abi>1?i.node_abi:undefined};return get_node_abi(e,n)}}}e.exports.get_runtime_abi=get_runtime_abi;const f=["module_name","module_path","host"];function validate_config(e,t){const i=e.name+" package.json is not node-pre-gyp ready:\n";const n=[];if(!e.main){n.push("main")}if(!e.version){n.push("version")}if(!e.name){n.push("name")}if(!e.binary){n.push("binary")}const r=e.binary;if(r){f.forEach(e=>{if(!r[e]||typeof r[e]!=="string"){n.push("binary."+e)}})}if(n.length>=1){throw new Error(i+"package.json must declare these properties: \n"+n.join("\n"))}if(r){const e=s.parse(r.host).protocol;if(e==="http:"){throw new Error("'host' protocol ("+e+") is invalid - only 'https:' is accepted")}}o.validate_package_json(e,t)}e.exports.validate_config=validate_config;function eval_template(e,t){Object.keys(t).forEach(i=>{const n="{"+i+"}";while(e.indexOf(n)>-1){e=e.replace(n,t[i])}});return e}function fix_slashes(e){if(e.slice(-1)!=="/"){return e+"/"}return e}function drop_double_slashes(e){return e.replace(/\/\//g,"/")}function get_process_runtime(e){let t="node";if(e["node-webkit"]){t="node-webkit"}else if(e.electron){t="electron"}return t}e.exports.get_process_runtime=get_process_runtime;const c="{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz";const h="";e.exports.evaluate=function(e,t,i){t=t||{};validate_config(e,t);const u=e.version;const l=r.parse(u);const f=t.runtime||get_process_runtime(process.versions);const p={name:e.name,configuration:t.debug?"Debug":"Release",debug:t.debug,module_name:e.binary.module_name,version:l.version,prerelease:l.prerelease.length?l.prerelease.join("."):"",build:l.build.length?l.build.join("."):"",major:l.major,minor:l.minor,patch:l.patch,runtime:f,node_abi:get_runtime_abi(f,t.target),node_abi_napi:o.get_napi_version(t.target)?"napi":get_runtime_abi(f,t.target),napi_version:o.get_napi_version(t.target),napi_build_version:i||"",node_napi_label:i?"napi-v"+i:get_runtime_abi(f,t.target),target:t.target||"",platform:t.target_platform||process.platform,target_platform:t.target_platform||process.platform,arch:t.target_arch||process.arch,target_arch:t.target_arch||process.arch,libc:t.target_libc||a.family||"unknown",module_main:e.main,toolset:t.toolset||"",bucket:e.binary.bucket,region:e.binary.region,s3ForcePathStyle:e.binary.s3ForcePathStyle||false};const d=p.module_name.replace("-","_");const b=process.env["npm_config_"+d+"_binary_host_mirror"]||e.binary.host;p.host=fix_slashes(eval_template(b,p));p.module_path=eval_template(e.binary.module_path,p);if(t.module_root){p.module_path=n.join(t.module_root,p.module_path)}else{p.module_path=n.resolve(p.module_path)}p.module=n.join(p.module_path,p.module_name+".node");p.remote_path=e.binary.remote_path?drop_double_slashes(fix_slashes(eval_template(e.binary.remote_path,p))):h;const v=e.binary.package_name?e.binary.package_name:c;p.package_name=eval_template(v,p);p.staged_tarball=n.join("build/stage",p.remote_path,p.package_name);p.hosted_path=s.resolve(p.host,p.remote_path);p.hosted_tarball=s.resolve(p.hosted_path,p.package_name);return p}},9253:(e,t,i)=>{var n=process.env.DEBUG_NOPT||process.env.NOPT_DEBUG?function(){console.error.apply(console,arguments)}:function(){};var r=i(8835),s=i(5622),a=i(2413).Stream,o=i(1289),u=i(2087);e.exports=t=nopt;t.clean=clean;t.typeDefs={String:{type:String,validate:validateString},Boolean:{type:Boolean,validate:validateBoolean},url:{type:r,validate:validateUrl},Number:{type:Number,validate:validateNumber},path:{type:s,validate:validatePath},Stream:{type:a,validate:validateStream},Date:{type:Date,validate:validateDate}};function nopt(e,i,r,s){r=r||process.argv;e=e||{};i=i||{};if(typeof s!=="number")s=2;n(e,i,r,s);r=r.slice(s);var a={},o,u={remain:[],cooked:r,original:r.slice(0)};parse(r,a,u.remain,e,i);clean(a,e,t.typeDefs);a.argv=u;Object.defineProperty(a.argv,"toString",{value:function(){return this.original.map(JSON.stringify).join(" ")},enumerable:false});return a}function clean(e,i,r){r=r||t.typeDefs;var s={},a=[false,true,null,String,Array];Object.keys(e).forEach(function(o){if(o==="argv")return;var u=e[o],l=Array.isArray(u),f=i[o];if(!l)u=[u];if(!f)f=a;if(f===Array)f=a.concat(Array);if(!Array.isArray(f))f=[f];n("val=%j",u);n("types=",f);u=u.map(function(a){if(typeof a==="string"){n("string %j",a);a=a.trim();if(a==="null"&&~f.indexOf(null)||a==="true"&&(~f.indexOf(true)||~f.indexOf(Boolean))||a==="false"&&(~f.indexOf(false)||~f.indexOf(Boolean))){a=JSON.parse(a);n("jsonable %j",a)}else if(~f.indexOf(Number)&&!isNaN(a)){n("convert to number",a);a=+a}else if(~f.indexOf(Date)&&!isNaN(Date.parse(a))){n("convert to date",a);a=new Date(a)}}if(!i.hasOwnProperty(o)){return a}if(a===false&&~f.indexOf(null)&&!(~f.indexOf(false)||~f.indexOf(Boolean))){a=null}var u={};u[o]=a;n("prevalidated val",u,a,i[o]);if(!validate(u,o,a,i[o],r)){if(t.invalidHandler){t.invalidHandler(o,a,i[o],e)}else if(t.invalidHandler!==false){n("invalid: "+o+"="+a,i[o])}return s}n("validated val",u,a,i[o]);return u[o]}).filter(function(e){return e!==s});if(!u.length&&f.indexOf(Array)===-1){n("VAL HAS NO LENGTH, DELETE IT",u,o,f.indexOf(Array));delete e[o]}else if(l){n(l,e[o],u);e[o]=u}else e[o]=u[0];n("k=%s val=%j",o,u,e[o])})}function validateString(e,t,i){e[t]=String(i)}function validatePath(e,t,i){if(i===true)return false;if(i===null)return true;i=String(i);var n=process.platform==="win32",r=n?/^~(\/|\\)/:/^~\//,a=u.homedir();if(a&&i.match(r)){e[t]=s.resolve(a,i.substr(2))}else{e[t]=s.resolve(i)}return true}function validateNumber(e,t,i){n("validate Number %j %j %j",t,i,isNaN(i));if(isNaN(i))return false;e[t]=+i}function validateDate(e,t,i){var r=Date.parse(i);n("validate Date %j %j %j",t,i,r);if(isNaN(r))return false;e[t]=new Date(i)}function validateBoolean(e,t,i){if(i instanceof Boolean)i=i.valueOf();else if(typeof i==="string"){if(!isNaN(i))i=!!+i;else if(i==="null"||i==="false")i=false;else i=true}else i=!!i;e[t]=i}function validateUrl(e,t,i){i=r.parse(String(i));if(!i.host)return false;e[t]=i.href}function validateStream(e,t,i){if(!(i instanceof a))return false;e[t]=i}function validate(e,t,i,r,s){if(Array.isArray(r)){for(var a=0,o=r.length;a1){var p=c.indexOf("=");if(p>-1){h=true;var d=c.substr(p+1);c=c.substr(0,p);e.splice(f,1,c,d)}var b=resolveShort(c,s,l,u);n("arg=%j shRes=%j",c,b);if(b){n(c,b);e.splice.apply(e,[f,1].concat(b));if(c!==b[0]){f--;continue}}c=c.replace(/^-+/,"");var v=null;while(c.toLowerCase().indexOf("no-")===0){v=!v;c=c.substr(3)}if(u[c])c=u[c];var g=r[c];var _=Array.isArray(g);if(_&&g.length===1){_=false;g=g[0]}var y=g===Array||_&&g.indexOf(Array)!==-1;if(!r.hasOwnProperty(c)&&t.hasOwnProperty(c)){if(!Array.isArray(t[c]))t[c]=[t[c]];y=true}var m,x=e[f+1];var E=typeof v==="boolean"||g===Boolean||_&&g.indexOf(Boolean)!==-1||typeof g==="undefined"&&!h||x==="false"&&(g===null||_&&~g.indexOf(null));if(E){m=!v;if(x==="true"||x==="false"){m=JSON.parse(x);x=null;if(v)m=!m;f++}if(_&&x){if(~g.indexOf(x)){m=x;f++}else if(x==="null"&&~g.indexOf(null)){m=null;f++}else if(!x.match(/^-{2,}[^-]/)&&!isNaN(x)&&~g.indexOf(Number)){m=+x;f++}else if(!x.match(/^-[^-]/)&&~g.indexOf(String)){m=x;f++}}if(y)(t[c]=t[c]||[]).push(m);else t[c]=m;continue}if(g===String){if(x===undefined){x=""}else if(x.match(/^-{1,2}[^-]+/)){x="";f--}}if(x&&x.match(/^-{2,}$/)){x=undefined;f--}m=x===undefined?true:x;if(y)(t[c]=t[c]||[]).push(m);else t[c]=m;f++;continue}i.push(c)}}function resolveShort(e,t,i,r){e=e.replace(/^-+/,"");if(r[e]===e)return null;if(t[e]){if(t[e]&&!Array.isArray(t[e]))t[e]=t[e].split(/\s+/);return t[e]}var s=t.___singles;if(!s){s=Object.keys(t).filter(function(e){return e.length===1}).reduce(function(e,t){e[t]=true;return e},{});t.___singles=s;n("shorthand singles",s)}var a=e.split("").filter(function(e){return s[e]});if(a.join("")===e)return a.map(function(e){return t[e]}).reduce(function(e,t){return e.concat(t)},[]);if(r[e]&&!t[e])return null;if(i[e])e=i[e];if(t[e]&&!Array.isArray(t[e]))t[e]=t[e].split(/\s+/);return t[e]}},6692:(e,t,i)=>{const n=i(2357);const r=i(5622);const s=i(5747);let a=undefined;try{a=i(4993)}catch(e){}const o={nosort:true,silent:true};let u=0;const l=process.platform==="win32";const f=e=>{const t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach(t=>{e[t]=e[t]||s[t];t=t+"Sync";e[t]=e[t]||s[t]});e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&a===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||o};const c=(e,t,i)=>{if(typeof t==="function"){i=t;t={}}n(e,"rimraf: missing path");n.equal(typeof e,"string","rimraf: path should be a string");n.equal(typeof i,"function","rimraf: callback function required");n(t,"rimraf: invalid options argument provided");n.equal(typeof t,"object","rimraf: options should be object");f(t);let r=0;let s=null;let o=0;const l=e=>{s=s||e;if(--o===0)i(s)};const c=(e,n)=>{if(e)return i(e);o=n.length;if(o===0)return i();n.forEach(e=>{const i=n=>{if(n){if((n.code==="EBUSY"||n.code==="ENOTEMPTY"||n.code==="EPERM")&&rh(e,t,i),r*100)}if(n.code==="EMFILE"&&uh(e,t,i),u++)}if(n.code==="ENOENT")n=null}u=0;l(n)};h(e,t,i)})};if(t.disableGlob||!a.hasMagic(e))return c(null,[e]);t.lstat(e,(i,n)=>{if(!i)return c(null,[e]);a(e,t.glob,c)})};const h=(e,t,i)=>{n(e);n(t);n(typeof i==="function");t.lstat(e,(n,r)=>{if(n&&n.code==="ENOENT")return i(null);if(n&&n.code==="EPERM"&&l)p(e,t,n,i);if(r&&r.isDirectory())return b(e,t,n,i);t.unlink(e,n=>{if(n){if(n.code==="ENOENT")return i(null);if(n.code==="EPERM")return l?p(e,t,n,i):b(e,t,n,i);if(n.code==="EISDIR")return b(e,t,n,i)}return i(n)})})};const p=(e,t,i,r)=>{n(e);n(t);n(typeof r==="function");t.chmod(e,438,n=>{if(n)r(n.code==="ENOENT"?null:i);else t.stat(e,(n,s)=>{if(n)r(n.code==="ENOENT"?null:i);else if(s.isDirectory())b(e,t,i,r);else t.unlink(e,r)})})};const d=(e,t,i)=>{n(e);n(t);try{t.chmodSync(e,438)}catch(e){if(e.code==="ENOENT")return;else throw i}let r;try{r=t.statSync(e)}catch(e){if(e.code==="ENOENT")return;else throw i}if(r.isDirectory())_(e,t,i);else t.unlinkSync(e)};const b=(e,t,i,r)=>{n(e);n(t);n(typeof r==="function");t.rmdir(e,n=>{if(n&&(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM"))v(e,t,r);else if(n&&n.code==="ENOTDIR")r(i);else r(n)})};const v=(e,t,i)=>{n(e);n(t);n(typeof i==="function");t.readdir(e,(n,s)=>{if(n)return i(n);let a=s.length;if(a===0)return t.rmdir(e,i);let o;s.forEach(n=>{c(r.join(e,n),t,n=>{if(o)return;if(n)return i(o=n);if(--a===0)t.rmdir(e,i)})})})};const g=(e,t)=>{t=t||{};f(t);n(e,"rimraf: missing path");n.equal(typeof e,"string","rimraf: path should be a string");n(t,"rimraf: missing options");n.equal(typeof t,"object","rimraf: options should be object");let i;if(t.disableGlob||!a.hasMagic(e)){i=[e]}else{try{t.lstatSync(e);i=[e]}catch(n){i=a.sync(e,t.glob)}}if(!i.length)return;for(let e=0;e{n(e);n(t);try{t.rmdirSync(e)}catch(n){if(n.code==="ENOENT")return;if(n.code==="ENOTDIR")throw i;if(n.code==="ENOTEMPTY"||n.code==="EEXIST"||n.code==="EPERM")y(e,t)}};const y=(e,t)=>{n(e);n(t);t.readdirSync(e).forEach(i=>g(r.join(e,i),t));const i=l?100:1;let s=0;do{let n=true;try{const r=t.rmdirSync(e,t);n=false;return r}finally{if(++s{"use strict";var n=i(5747);var r=i(8890);var s=i(496);e.exports=t;var a=process.version.substr(1).replace(/-.*$/,"").split(".").map(function(e){return+e});var o=["build","clean","configure","package","publish","reveal","testbinary","testpackage","unpublish"];var u="napi_build_version=";e.exports.get_napi_version=function(e){var t=process.versions.napi;if(!t){if(a[0]===9&&a[1]>=3)t=2;else if(a[0]===8)t=1}return t};e.exports.get_napi_version_as_string=function(t){var i=e.exports.get_napi_version(t);return i?""+i:""};e.exports.validate_package_json=function(t,i){var n=t.binary;var r=pathOK(n.module_path);var s=pathOK(n.remote_path);var a=pathOK(n.package_name);var o=e.exports.get_napi_build_versions(t,i,true);var u=e.exports.get_napi_build_versions_raw(t);if(o){o.forEach(function(e){if(!(parseInt(e,10)===e&&e>0)){throw new Error("All values specified in napi_versions must be positive integers.")}})}if(o&&(!r||!s&&!a)){throw new Error("When napi_versions is specified; module_path and either remote_path or "+"package_name must contain the substitution string '{napi_build_version}`.")}if((r||s||a)&&!u){throw new Error("When the substitution string '{napi_build_version}` is specified in "+"module_path, remote_path, or package_name; napi_versions must also be specified.")}if(o&&!e.exports.get_best_napi_build_version(t,i)&&e.exports.build_napi_only(t)){throw new Error("The N-API version of this Node instance is "+e.exports.get_napi_version(i?i.target:undefined)+". "+"This module supports N-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}if(u&&!o&&e.exports.build_napi_only(t)){throw new Error("The N-API version of this Node instance is "+e.exports.get_napi_version(i?i.target:undefined)+". "+"This module supports N-API version(s) "+e.exports.get_napi_build_versions_raw(t)+". "+"This Node instance cannot run this module.")}};function pathOK(e){return e&&(e.indexOf("{napi_build_version}")!==-1||e.indexOf("{node_napi_label}")!==-1)}e.exports.expand_commands=function(t,i,n){var r=[];var s=e.exports.get_napi_build_versions(t,i);n.forEach(function(n){if(s&&n.name==="install"){var a=e.exports.get_best_napi_build_version(t,i);var l=a?[u+a]:[];r.push({name:n.name,args:l})}else if(s&&o.indexOf(n.name)!==-1){s.forEach(function(e){var t=n.args.slice();t.push(u+e);r.push({name:n.name,args:t})})}else{r.push(n)}});return r};e.exports.get_napi_build_versions=function(t,i,n){var r=[];var a=e.exports.get_napi_version(i?i.target:undefined);if(t.binary&&t.binary.napi_versions){t.binary.napi_versions.forEach(function(e){var t=r.indexOf(e)!==-1;if(!t&&a&&e<=a){r.push(e)}else if(n&&!t&&a){s.info("This Node instance does not support builds for N-API version",e)}})}if(i&&i["build-latest-napi-version-only"]){var o=0;r.forEach(function(e){if(e>o)o=e});r=o?[o]:[]}return r.length?r:undefined};e.exports.get_napi_build_versions_raw=function(e){var t=[];if(e.binary&&e.binary.napi_versions){e.binary.napi_versions.forEach(function(e){if(t.indexOf(e)===-1){t.push(e)}})}return t.length?t:undefined};e.exports.get_command_arg=function(e){return u+e};e.exports.get_napi_build_version_from_command_args=function(e){for(var t=0;tn&&e<=s){n=e}})}return n===0?undefined:n};e.exports.build_napi_only=function(e){return e.binary&&e.binary.package_name&&e.binary.package_name.indexOf("{node_napi_label}")===-1}},2463:(e,t,i)=>{"use strict";e.exports=t;var n=i(5622);var r=i(2519);var s=i(8835);var a=i(2226);var o=i(6500);var u;if(process.env.NODE_PRE_GYP_ABI_CROSSWALK){u=require(process.env.NODE_PRE_GYP_ABI_CROSSWALK)}else{u=i(7277)}var l={};Object.keys(u).forEach(function(e){var t=e.split(".")[0];if(!l[t]){l[t]=e}});function get_electron_abi(e,t){if(!e){throw new Error("get_electron_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if electron is the target.")}var i=r.parse(t);return e+"-v"+i.major+"."+i.minor}e.exports.get_electron_abi=get_electron_abi;function get_node_webkit_abi(e,t){if(!e){throw new Error("get_node_webkit_abi requires valid runtime arg")}if(typeof t==="undefined"){throw new Error("Empty target version is not supported if node-webkit is the target.")}return e+"-v"+t}e.exports.get_node_webkit_abi=get_node_webkit_abi;function get_node_abi(e,t){if(!e){throw new Error("get_node_abi requires valid runtime arg")}if(!t){throw new Error("get_node_abi requires valid process.versions object")}var i=r.parse(t.node);if(i.major===0&&i.minor%2){return e+"-v"+t.node}else{return t.modules?e+"-v"+ +t.modules:"v8-"+t.v8.split(".").slice(0,2).join(".")}}e.exports.get_node_abi=get_node_abi;function get_runtime_abi(e,t){if(!e){throw new Error("get_runtime_abi requires valid runtime arg")}if(e==="node-webkit"){return get_node_webkit_abi(e,t||process.versions["node-webkit"])}else if(e==="electron"){return get_electron_abi(e,t||process.versions.electron)}else{if(e!="node"){throw new Error("Unknown Runtime: '"+e+"'")}if(!t){return get_node_abi(e,process.versions)}else{var i;if(u[t]){i=u[t]}else{var n=t.split(".").map(function(e){return+e});if(n.length!=3){throw new Error("Unknown target version: "+t)}var r=n[0];var s=n[1];var a=n[2];if(r===1){while(true){if(s>0)--s;if(a>0)--a;var o=""+r+"."+s+"."+a;if(u[o]){i=u[o];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+o+" as ABI compatible target");break}if(s===0&&a===0){break}}}else if(r>=2){if(l[r]){i=u[l[r]];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+l[r]+" as ABI compatible target")}}else if(r===0){if(n[1]%2===0){while(--a>0){var f=""+r+"."+s+"."+a;if(u[f]){i=u[f];console.log("Warning: node-pre-gyp could not find exact match for "+t);console.log("Warning: but node-pre-gyp successfully choose "+f+" as ABI compatible target");break}}}}}if(!i){throw new Error("Unsupported target version: "+t)}var c={node:t,v8:i.v8+".0",modules:i.node_abi>1?i.node_abi:undefined};return get_node_abi(e,c)}}}e.exports.get_runtime_abi=get_runtime_abi;var f=["module_name","module_path","host"];function validate_config(e,t){var i=e.name+" package.json is not node-pre-gyp ready:\n";var n=[];if(!e.main){n.push("main")}if(!e.version){n.push("version")}if(!e.name){n.push("name")}if(!e.binary){n.push("binary")}var r=e.binary;f.forEach(function(e){if(n.indexOf("binary")>-1){n.pop("binary")}if(!r||r[e]===undefined||r[e]===""){n.push("binary."+e)}});if(n.length>=1){throw new Error(i+"package.json must declare these properties: \n"+n.join("\n"))}if(r){var a=s.parse(r.host).protocol;if(a==="http:"){throw new Error("'host' protocol ("+a+") is invalid - only 'https:' is accepted")}}o.validate_package_json(e,t)}e.exports.validate_config=validate_config;function eval_template(e,t){Object.keys(t).forEach(function(i){var n="{"+i+"}";while(e.indexOf(n)>-1){e=e.replace(n,t[i])}});return e}function fix_slashes(e){if(e.slice(-1)!="/"){return e+"/"}return e}function drop_double_slashes(e){return e.replace(/\/\//g,"/")}function get_process_runtime(e){var t="node";if(e["node-webkit"]){t="node-webkit"}else if(e.electron){t="electron"}return t}e.exports.get_process_runtime=get_process_runtime;var c="{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz";var h="";e.exports.evaluate=function(e,t,i){t=t||{};validate_config(e,t);var u=e.version;var l=r.parse(u);var f=t.runtime||get_process_runtime(process.versions);var p={name:e.name,configuration:Boolean(t.debug)?"Debug":"Release",debug:t.debug,module_name:e.binary.module_name,version:l.version,prerelease:l.prerelease.length?l.prerelease.join("."):"",build:l.build.length?l.build.join("."):"",major:l.major,minor:l.minor,patch:l.patch,runtime:f,node_abi:get_runtime_abi(f,t.target),node_abi_napi:o.get_napi_version(t.target)?"napi":get_runtime_abi(f,t.target),napi_version:o.get_napi_version(t.target),napi_build_version:i||"",node_napi_label:i?"napi-v"+i:get_runtime_abi(f,t.target),target:t.target||"",platform:t.target_platform||process.platform,target_platform:t.target_platform||process.platform,arch:t.target_arch||process.arch,target_arch:t.target_arch||process.arch,libc:t.target_libc||a.family||"unknown",module_main:e.main,toolset:t.toolset||""};var d=process.env["npm_config_"+p.module_name+"_binary_host_mirror"]||e.binary.host;p.host=fix_slashes(eval_template(d,p));p.module_path=eval_template(e.binary.module_path,p);if(t.module_root){p.module_path=n.join(t.module_root,p.module_path)}else{p.module_path=n.resolve(p.module_path)}p.module=n.join(p.module_path,p.module_name+".node");p.remote_path=e.binary.remote_path?drop_double_slashes(fix_slashes(eval_template(e.binary.remote_path,p))):h;var b=e.binary.package_name?e.binary.package_name:c;p.package_name=eval_template(b,p);p.staged_tarball=n.join("build/stage",p.remote_path,p.package_name);p.hosted_path=s.resolve(p.host,p.remote_path);p.hosted_tarball=s.resolve(p.hosted_path,p.package_name);return p}},8890:(e,t,i)=>{e.exports=rimraf;rimraf.sync=rimrafSync;var n=i(2357);var r=i(5622);var s=i(5747);var a=undefined;try{a=i(4993)}catch(e){}var o=parseInt("666",8);var u={nosort:true,silent:true};var l=0;var f=process.platform==="win32";function defaults(e){var t=["unlink","chmod","stat","lstat","rmdir","readdir"];t.forEach(function(t){e[t]=e[t]||s[t];t=t+"Sync";e[t]=e[t]||s[t]});e.maxBusyTries=e.maxBusyTries||3;e.emfileWait=e.emfileWait||1e3;if(e.glob===false){e.disableGlob=true}if(e.disableGlob!==true&&a===undefined){throw Error("glob dependency not found, set `options.disableGlob = true` if intentional")}e.disableGlob=e.disableGlob||false;e.glob=e.glob||u}function rimraf(e,t,i){if(typeof t==="function"){i=t;t={}}n(e,"rimraf: missing path");n.equal(typeof e,"string","rimraf: path should be a string");n.equal(typeof i,"function","rimraf: callback function required");n(t,"rimraf: invalid options argument provided");n.equal(typeof t,"object","rimraf: options should be object");defaults(t);var r=0;var s=null;var o=0;if(t.disableGlob||!a.hasMagic(e))return afterGlob(null,[e]);t.lstat(e,function(i,n){if(!i)return afterGlob(null,[e]);a(e,t.glob,afterGlob)});function next(e){s=s||e;if(--o===0)i(s)}function afterGlob(e,n){if(e)return i(e);o=n.length;if(o===0)return i();n.forEach(function(e){rimraf_(e,t,function CB(i){if(i){if((i.code==="EBUSY"||i.code==="ENOTEMPTY"||i.code==="EPERM")&&r{return W},env:{NODE_ENV:u.UNKNOWN,[u.UNKNOWN]:true},[u.UNKNOWN]:true};const R=Symbol();const k=Symbol();const C=Symbol();const T=Symbol();const O=Symbol();const N=Symbol();const I=Symbol();const L=Symbol();const P={access:N,accessSync:N,createReadStream:N,exists:N,existsSync:N,fstat:N,fstatSync:N,lstat:N,lstatSync:N,open:N,readFile:N,readFileSync:N,stat:N,statSync:N};const M=Object.assign(Object.create(null),{bindings:{default:I},express:{default:function(){return{[u.UNKNOWN]:true,set:R,engine:k}}},fs:Object.assign({default:P},P),process:Object.assign({default:A},A),path:{default:{}},os:Object.assign({default:E.default},E.default),"@mapbox/node-pre-gyp":Object.assign({default:y.default},y.default),"node-pre-gyp":d.pregyp,"node-pre-gyp/lib/pre-binding":d.pregyp,"node-pre-gyp/lib/pre-binding.js":d.pregyp,"node-gyp-build":{default:L},nbind:{init:C,default:{init:C}},"resolve-from":{default:S.default},"strong-globalize":{default:{SetRootDir:T},SetRootDir:T},pkginfo:{default:O}});const H={_interopRequireDefault:b.normalizeDefaultRequire,_interopRequireWildcard:b.normalizeWildcardRequire,__importDefault:b.normalizeDefaultRequire,__importStar:b.normalizeWildcardRequire,MONGOOSE_DRIVER_PATH:undefined,URL:m.URL,Object:{assign:Object.assign}};H.global=H.GLOBAL=H.globalThis=H;const F=Symbol();d.pregyp.find[F]=true;const B=M.path;Object.keys(r.default).forEach(e=>{const t=r.default[e];if(typeof t==="function"){const i=function mockPath(){return t.apply(mockPath,arguments)};i[F]=true;B[e]=B.default[e]=i}else{B[e]=B.default[e]=t}});B.resolve=B.default.resolve=function(...e){return r.default.resolve.apply(this,[W,...e])};B.resolve[F]=true;const D=new Set([".h",".cmake",".c",".cpp"]);const $=new Set(["CHANGELOG.md","README.md","readme.md","changelog.md"]);let W;const U=/^\/[^\/]+|^[a-z]:[\\/][^\\/]+/i;function isAbsolutePathOrUrl(e){if(e instanceof m.URL)return e.protocol==="file:";if(typeof e==="string"){if(e.startsWith("file:")){try{new m.URL(e);return true}catch(e){return false}}return U.test(e)}return false}const j=Symbol();const q=/([\/\\]\*\*[\/\\]\*)+/g;async function analyze(e,t,i){const n=new Set;const l=new Set;const b=new Set;const y=r.default.dirname(e);W=i.cwd;const E=p.getPackageBase(e);const S=e=>{if(!i.analysis.emitGlobs)return;const t=e.indexOf(u.WILDCARD);const s=t===-1?e.length:e.lastIndexOf(r.default.sep,t);const a=e.substr(0,s);const o=e.substr(s);const l=o.replace(u.wildcardRegEx,(e,t)=>{return o[t-1]===r.default.sep?"**/*":"*"}).replace(q,"/**/*")||"/**/*";if(i.ignoreFn(r.default.relative(i.base,a+l)))return;P=P.then(async()=>{if(i.log)console.log("Globbing "+a+l);const e=await new Promise((e,t)=>h.default(a+l,{mark:true,ignore:a+"/**/node_modules/**/*"},(i,n)=>i?t(i):e(n)));e.filter(e=>!D.has(r.default.extname(e))&&!$.has(r.default.basename(e))&&!e.endsWith("/")).forEach(e=>n.add(e))})};let P=Promise.resolve();t=t.replace(/^#![^\n\r]*[\r\n]/,"");let B;let G=false;try{B=x.parse(t,{ecmaVersion:2020,allowReturnOutsideFunction:true});G=false}catch(t){const n=t&&t.message&&t.message.includes("sourceType: module");if(!n){i.warnings.add(new Error(`Failed to parse ${e} as script:\n${t&&t.message}`))}}if(!B){try{B=x.parse(t,{ecmaVersion:2020,sourceType:"module",allowAwaitOutsideFunction:true});G=true}catch(t){i.warnings.add(new Error(`Failed to parse ${e} as module:\n${t&&t.message}`));return{assets:n,deps:l,imports:b,isESM:false}}}const V=m.pathToFileURL(e).href;const K=Object.assign(Object.create(null),{__dirname:{shadowDepth:0,value:{value:r.default.resolve(e,"..")}},__filename:{shadowDepth:0,value:{value:e}},process:{shadowDepth:0,value:{value:A}}});if(!G||i.mixedModules){K.require={shadowDepth:0,value:{value:{[u.FUNCTION](e){l.add(e);const t=M[e];return t.default},resolve(t){return g.default(t,e,i)}}}};K.require.value.value.resolve[F]=true}function setKnownBinding(e,t){if(e==="require")return;K[e]={shadowDepth:0,value:t}}function getKnownBinding(e){const t=K[e];if(t){if(t.shadowDepth===0){return t.value}}return undefined}function hasKnownBindingValue(e){const t=K[e];return t&&t.shadowDepth===0}if(G||i.mixedModules){for(const e of B.body){if(e.type==="ImportDeclaration"){const t=e.source.value;l.add(t);const i=M[t];if(i){for(const t of e.specifiers){if(t.type==="ImportNamespaceSpecifier")setKnownBinding(t.local.name,{value:i});else if(t.type==="ImportDefaultSpecifier"&&"default"in i)setKnownBinding(t.local.name,{value:i.default});else if(t.type==="ImportSpecifier"&&t.imported.name in i)setKnownBinding(t.local.name,{value:i[t.imported.name]})}}}else if(e.type==="ExportNamedDeclaration"||e.type==="ExportAllDeclaration"){if(e.source)l.add(e.source.value)}}}function computePureStaticValue(e,t=true){const i=Object.create(null);Object.keys(H).forEach(e=>{i[e]={value:H[e]}});Object.keys(K).forEach(e=>{i[e]=getKnownBinding(e)});i["import.meta"]={url:V};const n=u.evaluate(e,i,t);return n}let z;let Q;let Z=false;function emitWildcardRequire(e){if(!i.analysis.emitGlobs||!e.startsWith("./")&&!e.startsWith("../"))return;e=r.default.resolve(y,e);const t=e.indexOf(u.WILDCARD);const s=t===-1?e.length:e.lastIndexOf(r.default.sep,t);const a=e.substr(0,s);const o=e.substr(s);let l=o.replace(u.wildcardRegEx,(e,t)=>{return o[t-1]===r.default.sep?"**/*":"*"})||"/**/*";if(!l.endsWith("*"))l+="?("+(i.ts?".ts|.tsx|":"")+".js|.json|.node)";if(i.ignoreFn(r.default.relative(i.base,a+l)))return;P=P.then(async()=>{if(i.log)console.log("Globbing "+a+l);const e=await new Promise((e,t)=>h.default(a+l,{mark:true,ignore:a+"/**/node_modules/**/*"},(i,n)=>i?t(i):e(n)));e.filter(e=>!D.has(r.default.extname(e))&&!$.has(r.default.basename(e))&&!e.endsWith("/")).forEach(e=>n.add(e))})}function processRequireArg(e,t=false){if(e.type==="ConditionalExpression"){processRequireArg(e.consequent,t);processRequireArg(e.alternate,t);return}if(e.type==="LogicalExpression"){processRequireArg(e.left,t);processRequireArg(e.right,t);return}let i=computePureStaticValue(e,true);if(!i)return;if("value"in i&&typeof i.value==="string"){if(!i.wildcards)(t?b:l).add(i.value);else if(i.wildcards.length>=1)emitWildcardRequire(i.value)}else{if("then"in i&&typeof i.then==="string")(t?b:l).add(i.then);if("else"in i&&typeof i.else==="string")(t?b:l).add(i.else)}}let X=o.attachScopes(B,"scope");w.handleWrappers(B);v.default({id:e,ast:B,emitAsset:e=>n.add(e),emitAssetDirectory:S,job:i});function backtrack(e,t){if(!z)throw new Error("Internal error: No staticChildNode for backtrack.");const i=computePureStaticValue(e,true);if(i){if("value"in i&&typeof i.value!=="symbol"||"then"in i&&typeof i.then!=="symbol"&&typeof i.else!=="symbol"){Q=i;z=e;if(t)t.skip();return}}emitStaticChildAsset()}a.walk(B,{enter(t,a){var o;if(t.scope){X=t.scope;for(const e in t.scope.declarations){if(e in K)K[e].shadowDepth++}}if(z)return;if(!a)return;if(t.type==="Identifier"){if(c.isIdentifierRead(t,a)&&i.analysis.computeFileReferences){let e;if(typeof(e=(o=getKnownBinding(t.name))===null||o===void 0?void 0:o.value)==="string"&&e.match(U)||e&&(typeof e==="function"||typeof e==="object")&&e[F]){Q={value:typeof e==="string"?e:undefined};z=t;backtrack(a,this)}}}else if(i.analysis.computeFileReferences&&t.type==="MemberExpression"&&t.object.type==="MetaProperty"&&t.object.meta.name==="import"&&t.object.property.name==="meta"&&(t.property.computed?t.property.value:t.property.name)==="url"){Q={value:V};z=t;backtrack(a,this)}else if(t.type==="ImportExpression"){processRequireArg(t.source,true);return}else if(t.type==="CallExpression"){if((!G||i.mixedModules)&&t.callee.type==="Identifier"&&t.arguments.length){if(t.callee.name==="require"&&K.require.shadowDepth===0){processRequireArg(t.arguments[0]);return}}else if((!G||i.mixedModules)&&t.callee.type==="MemberExpression"&&t.callee.object.type==="Identifier"&&t.callee.object.name==="module"&&"module"in K===false&&t.callee.property.type==="Identifier"&&!t.callee.computed&&t.callee.property.name==="require"&&t.arguments.length){processRequireArg(t.arguments[0]);return}const o=i.analysis.evaluatePureExpressions&&computePureStaticValue(t.callee,false);if(o&&"value"in o&&typeof o.value==="function"&&o.value[F]&&i.analysis.computeFileReferences){Q=computePureStaticValue(t,true);if(Q&&a){z=t;backtrack(a,this)}}else if(o&&"value"in o&&typeof o.value==="symbol"){switch(o.value){case j:if(t.arguments.length===1&&t.arguments[0].type==="Literal"&&t.callee.type==="Identifier"&&K.require.shadowDepth===0){processRequireArg(t.arguments[0])}break;case I:if(t.arguments.length){const e=computePureStaticValue(t.arguments[0],false);if(e&&"value"in e&&e.value){let i;if(typeof e.value==="object")i=e.value;else if(typeof e.value==="string")i={bindings:e.value};if(!i.path){i.path=true}i.module_root=E;let n;try{n=f.default(i)}catch(e){}if(n){Q={value:n};z=t;emitStaticChildAsset()}}}break;case L:if(t.arguments.length===1&&t.arguments[0].type==="Identifier"&&t.arguments[0].name==="__dirname"&&K.__dirname.shadowDepth===0){let e;try{e=_.default.path(y)}catch(e){}if(e){Q={value:e};z=t;emitStaticChildAsset()}}break;case C:if(t.arguments.length){const e=computePureStaticValue(t.arguments[0],false);if(e&&"value"in e&&(typeof e.value==="string"||typeof e.value==="undefined")){const t=d.nbind(e.value);if(t&&t.path){l.add(r.default.relative(y,t.path).replace(/\\/g,"/"));return this.skip()}}}break;case R:if(t.arguments.length===2&&t.arguments[0].type==="Literal"&&t.arguments[0].value==="view engine"&&!Z){processRequireArg(t.arguments[1]);return this.skip()}break;case k:Z=true;break;case N:if(t.arguments[0]&&i.analysis.computeFileReferences){Q=computePureStaticValue(t.arguments[0],true);if(Q){z=t.arguments[0];backtrack(a,this);return this.skip()}}break;case T:if(t.arguments[0]){const e=computePureStaticValue(t.arguments[0],false);if(e&&"value"in e&&e.value)S(e.value+"/intl");return this.skip()}break;case O:let u=r.default.resolve(e,"../package.json");const c=r.default.resolve("/package.json");while(u!==c&&!s.existsSync(u))u=r.default.resolve(u,"../../package.json");if(u!==c)n.add(u);break}}}else if(t.type==="VariableDeclaration"&&a&&!c.isVarLoop(a)&&i.analysis.evaluatePureExpressions){for(const e of t.declarations){if(!e.init)continue;const t=computePureStaticValue(e.init,true);if(t){if(e.id.type==="Identifier"){setKnownBinding(e.id.name,t)}else if(e.id.type==="ObjectPattern"&&"value"in t){for(const i of e.id.properties){if(i.type!=="Property"||i.key.type!=="Identifier"||i.value.type!=="Identifier"||typeof t.value!=="object"||t.value===null||!(i.key.name in t.value))continue;setKnownBinding(i.value.name,{value:t.value[i.key.name]})}}if(!("value"in t)&&isAbsolutePathOrUrl(t.then)&&isAbsolutePathOrUrl(t.else)){Q=t;z=e.init;emitStaticChildAsset()}}}}else if(t.type==="AssignmentExpression"&&a&&!c.isLoop(a)&&i.analysis.evaluatePureExpressions){if(!hasKnownBindingValue(t.left.name)){const e=computePureStaticValue(t.right,false);if(e&&"value"in e){if(t.left.type==="Identifier"){setKnownBinding(t.left.name,e)}else if(t.left.type==="ObjectPattern"){for(const i of t.left.properties){if(i.type!=="Property"||i.key.type!=="Identifier"||i.value.type!=="Identifier"||typeof e.value!=="object"||e.value===null||!(i.key.name in e.value))continue;setKnownBinding(i.value.name,{value:e.value[i.key.name]})}}if(isAbsolutePathOrUrl(e.value)){Q=e;z=t.right;emitStaticChildAsset()}}}}else if((!G||i.mixedModules)&&(t.type==="FunctionDeclaration"||t.type==="FunctionExpression"||t.type==="ArrowFunctionExpression")&&(t.arguments||t.params)[0]&&(t.arguments||t.params)[0].type==="Identifier"){let e;let i;if((t.type==="ArrowFunctionExpression"||t.type==="FunctionExpression")&&a&&a.type==="VariableDeclarator"&&a.id.type==="Identifier"){e=a.id;i=t.arguments||t.params}else if(t.id){e=t.id;i=t.arguments||t.params}if(e&&t.body.body){let n,r=false;for(let e=0;ee&&e.id&&e.id.type==="Identifier"&&e.init&&e.init.type==="CallExpression"&&e.init.callee.type==="Identifier"&&e.init.callee.name==="require"&&K.require.shadowDepth===0&&e.init.arguments[0]&&e.init.arguments[0].type==="Identifier"&&e.init.arguments[0].name===i[0].name)}if(n&&t.body.body[e].type==="ReturnStatement"&&t.body.body[e].argument&&t.body.body[e].argument.type==="Identifier"&&t.body.body[e].argument.name===n.id.name){r=true;break}}if(r)setKnownBinding(e.name,{value:j})}}},leave(e,t){if(e.scope){if(X.parent){X=X.parent}for(const t in e.scope.declarations){if(t in K){if(K[t].shadowDepth>0)K[t].shadowDepth--;else delete K[t]}}}if(z&&t)backtrack(t,this)}});await P;return{assets:n,deps:l,imports:b,isESM:G};function emitAssetPath(e){const t=e.indexOf(u.WILDCARD);const i=t===-1?e.length:e.lastIndexOf(r.default.sep,t);const a=e.substr(0,i);try{var o=s.statSync(a)}catch(e){return}if(t!==-1&&o.isFile())return;if(o.isFile()){n.add(e)}else if(o.isDirectory()){if(validWildcard(e))S(e)}}function validWildcard(t){let n="";if(t.endsWith(r.default.sep))n=r.default.sep;else if(t.endsWith(r.default.sep+u.WILDCARD))n=r.default.sep+u.WILDCARD;else if(t.endsWith(u.WILDCARD))n=u.WILDCARD;if(t===y+n)return false;if(t===W+n)return false;if(t.endsWith(r.default.sep+"node_modules"+n))return false;if(y.startsWith(t.substr(0,t.length-n.length)+r.default.sep))return false;if(E){const n=e.substr(0,e.indexOf(r.default.sep+"node_modules"))+r.default.sep+"node_modules"+r.default.sep;if(!t.startsWith(n)){if(i.log)console.log("Skipping asset emission of "+t.replace(u.wildcardRegEx,"*")+" for "+e+" as it is outside the package base "+E);return false}}return true}function resolveAbsolutePathOrUrl(e){return e instanceof m.URL?m.fileURLToPath(e):e.startsWith("file:")?m.fileURLToPath(new m.URL(e)):r.default.resolve(e)}function emitStaticChildAsset(){if(!Q){return}if("value"in Q&&isAbsolutePathOrUrl(Q.value)){try{const e=resolveAbsolutePathOrUrl(Q.value);emitAssetPath(e)}catch(e){}}else if("then"in Q&&"else"in Q&&isAbsolutePathOrUrl(Q.then)&&isAbsolutePathOrUrl(Q.else)){let e;try{e=resolveAbsolutePathOrUrl(Q.then)}catch(e){}let t;try{t=resolveAbsolutePathOrUrl(Q.else)}catch(e){}if(e)emitAssetPath(e);if(t)emitAssetPath(t)}else if(z&&z.type==="ArrayExpression"&&"value"in Q&&Q.value instanceof Array){for(const e of Q.value){try{const t=resolveAbsolutePathOrUrl(e);emitAssetPath(t)}catch(e){}}}z=Q=undefined}}t.default=analyze},1652:function(e,t,i){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){if(n===undefined)n=i;Object.defineProperty(e,n,{enumerable:true,get:function(){return t[i]}})}:function(e,t,i,n){if(n===undefined)n=i;e[n]=t[i]});var r=this&&this.__exportStar||function(e,t){for(var i in e)if(i!=="default"&&!t.hasOwnProperty(i))n(t,e,i)};Object.defineProperty(t,"__esModule",{value:true});r(i(6121),t);var s=i(209);Object.defineProperty(t,"nodeFileTrace",{enumerable:true,get:function(){return s.nodeFileTrace}})},209:function(e,t,i){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.Job=t.nodeFileTrace=void 0;const r=i(5622);const s=n(i(5747));const a=n(i(9551));const o=n(i(7126));const u=i(3024);const l=i(6413);const f=i(5622);const{gracefulify:c}=i(2161);c(s.default);function inPath(e,t){const i=f.join(t,r.sep);return e.startsWith(i)&&e!==i}async function nodeFileTrace(e,t={}){const i=new Job(t);if(t.readFile)i.readFile=t.readFile;if(t.stat)i.stat=t.stat;if(t.readlink)i.readlink=t.readlink;if(t.resolve)i.resolve=t.resolve;i.ts=true;await Promise.all(e.map(e=>{const t=r.resolve(e);i.emitFile(t,"initial");if(t.endsWith(".js")||t.endsWith(".cjs")||t.endsWith(".mjs")||t.endsWith(".node")||i.ts&&(t.endsWith(".ts")||t.endsWith(".tsx"))){return i.emitDependency(t)}return undefined}));const n={fileList:[...i.fileList].sort(),esmFileList:[...i.esmFileList].sort(),reasons:i.reasons,warnings:[...i.warnings]};return n}t.nodeFileTrace=nodeFileTrace;class Job{constructor({base:e=process.cwd(),processCwd:t,exports:i,conditions:n=i||["node"],exportsOnly:s=false,paths:a={},ignore:o,log:l=false,mixedModules:f=false,ts:c=true,analysis:h={},cache:p}){this.reasons=Object.create(null);this.ts=c;e=r.resolve(e);this.ignoreFn=(e=>{if(e.startsWith(".."+r.sep))return true;return false});if(typeof o==="string")o=[o];if(typeof o==="function"){const e=o;this.ignoreFn=(t=>{if(t.startsWith(".."+r.sep))return true;if(e(t))return true;return false})}else if(Array.isArray(o)){const t=o.map(t=>r.relative(e,r.resolve(e||process.cwd(),t)));this.ignoreFn=(e=>{if(e.startsWith(".."+r.sep))return true;if(u.isMatch(e,t))return true;return false})}this.base=e;this.cwd=r.resolve(t||e);this.conditions=n;this.exportsOnly=s;const d={};for(const t of Object.keys(a)){const i=a[t].endsWith("/");const n=r.resolve(e,a[t]);d[t]=n+(i?"/":"")}this.paths=d;this.log=l;this.mixedModules=f;this.analysis={};if(h!==false){Object.assign(this.analysis,{emitGlobs:true,computeFileReferences:true,evaluatePureExpressions:true},h===true?{}:h)}this.fileCache=p&&p.fileCache||new Map;this.statCache=p&&p.statCache||new Map;this.symlinkCache=p&&p.symlinkCache||new Map;this.analysisCache=p&&p.analysisCache||new Map;if(p){p.fileCache=this.fileCache;p.statCache=this.statCache;p.symlinkCache=this.symlinkCache;p.analysisCache=this.analysisCache}this.fileList=new Set;this.esmFileList=new Set;this.processed=new Set;this.warnings=new Set}readlink(e){const t=this.symlinkCache.get(e);if(t!==undefined)return t;try{const t=s.default.readlinkSync(e);const i=this.statCache.get(e);if(i)this.statCache.set(r.resolve(e,t),i);this.symlinkCache.set(e,t);return t}catch(t){if(t.code!=="EINVAL"&&t.code!=="ENOENT"&&t.code!=="UNKNOWN")throw t;this.symlinkCache.set(e,null);return null}}isFile(e){const t=this.stat(e);if(t)return t.isFile();return false}isDir(e){const t=this.stat(e);if(t)return t.isDirectory();return false}stat(e){const t=this.statCache.get(e);if(t)return t;try{const t=s.default.statSync(e);this.statCache.set(e,t);return t}catch(t){if(t.code==="ENOENT"){this.statCache.set(e,null);return null}throw t}}resolve(e,t,i,n){return o.default(e,t,i,n)}readFile(e){const t=this.fileCache.get(e);if(t!==undefined)return t;try{const t=s.default.readFileSync(e).toString();this.fileCache.set(e,t);return t}catch(t){if(t.code==="ENOENT"||t.code==="EISDIR"){this.fileCache.set(e,null);return null}throw t}}realpath(e,t,i=new Set){if(i.has(e))throw new Error("Recursive symlink detected resolving "+e);i.add(e);const n=this.readlink(e);if(n){const s=r.dirname(e);const a=r.resolve(s,n);const o=this.realpath(s,t);if(inPath(e,o))this.emitFile(e,"resolve",t,true);return this.realpath(a,t,i)}if(!inPath(e,this.base))return e;return f.join(this.realpath(r.dirname(e),t,i),r.basename(e))}emitFile(e,t,i,n=false){if(!n)e=this.realpath(e,i);if(this.fileList.has(e))return;e=r.relative(this.base,e);if(i)i=r.relative(this.base,i);const s=this.reasons[e]||(this.reasons[e]={type:t,ignored:false,parents:[]});if(i&&s.parents.indexOf(i)===-1)s.parents.push(i);if(i&&this.ignoreFn(e,i)){if(s)s.ignored=true;return false}this.fileList.add(e);return true}getPjsonBoundary(e){const t=e.indexOf(r.sep);let i;while((i=e.lastIndexOf(r.sep))>t){e=e.substr(0,i);if(this.isFile(e+r.sep+"package.json"))return e}return undefined}async emitDependency(e,t){if(this.processed.has(e))return;this.processed.add(e);const i=this.emitFile(e,"dependency",t);if(!i)return;if(e.endsWith(".json"))return;if(e.endsWith(".node"))return await l.sharedLibEmit(e,this);if(e.endsWith(".js")){const t=this.getPjsonBoundary(e);if(t)this.emitFile(t+r.sep+"package.json","resolve",e)}let n;const s=this.analysisCache.get(e);if(s){n=s}else{const t=this.readFile(e);if(t===null)throw new Error("File "+e+" does not exist.");n=await a.default(e,t.toString(),this);this.analysisCache.set(e,n)}const{deps:o,imports:u,assets:f,isESM:c}=n;if(c)this.esmFileList.add(r.relative(this.base,e));await Promise.all([...[...f].map(async t=>{const i=r.extname(t);if(i===".js"||i===".mjs"||i===".node"||i===""||this.ts&&(i===".ts"||i===".tsx")&&t.startsWith(this.base)&&t.substr(this.base.length).indexOf(r.sep+"node_modules"+r.sep)===-1)await this.emitDependency(t,e);else this.emitFile(t,"asset",e)}),...[...o].map(async t=>{try{var i=this.resolve(t,e,this,!c)}catch(e){this.warnings.add(new Error(`Failed to resolve dependency ${t}:\n${e&&e.message}`));return}if(Array.isArray(i)){for(const t of i){if(t.startsWith("node:"))return;await this.emitDependency(t,e)}}else{if(i.startsWith("node:"))return;await this.emitDependency(i,e)}}),...[...u].map(async t=>{try{var i=this.resolve(t,e,this,false)}catch(e){this.warnings.add(new Error(`Failed to resolve dependency ${t}:\n${e&&e.message}`));return}if(Array.isArray(i)){for(const t of i){if(t.startsWith("node:"))return;await this.emitDependency(t,e)}}else{if(i.startsWith("node:"))return;await this.emitDependency(i,e)}})])}}t.Job=Job},7126:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});const n=i(5622);function resolveDependency(e,t,i,r=true){let s;if(n.isAbsolute(e)||e==="."||e===".."||e.startsWith("./")||e.startsWith("../")){const r=e.endsWith("/");s=resolvePath(n.resolve(t,"..",e)+(r?"/":""),t,i)}else if(e[0]==="#"){s=packageImportsResolve(e,t,i,r)}else{s=resolvePackage(e,t,i,r)}if(Array.isArray(s)){return s.map(e=>i.realpath(e,t))}else if(s.startsWith("node:")){return s}else{return i.realpath(s,t)}}t.default=resolveDependency;function resolvePath(e,t,i){const n=resolveFile(e,t,i)||resolveDir(e,t,i);if(!n){throw new NotFoundError(e,t)}return n}function resolveFile(e,t,i){if(e.endsWith("/"))return undefined;e=i.realpath(e,t);if(i.isFile(e))return e;if(i.ts&&e.startsWith(i.base)&&e.substr(i.base.length).indexOf(n.sep+"node_modules"+n.sep)===-1&&i.isFile(e+".ts"))return e+".ts";if(i.ts&&e.startsWith(i.base)&&e.substr(i.base.length).indexOf(n.sep+"node_modules"+n.sep)===-1&&i.isFile(e+".tsx"))return e+".tsx";if(i.isFile(e+".js"))return e+".js";if(i.isFile(e+".json"))return e+".json";if(i.isFile(e+".node"))return e+".node";return undefined}function resolveDir(e,t,i){if(e.endsWith("/"))e=e.slice(0,-1);if(!i.isDir(e))return;const r=getPkgCfg(e,i);if(r&&typeof r.main==="string"){const s=resolveFile(n.resolve(e,r.main),t,i)||resolveFile(n.resolve(e,r.main,"index"),t,i);if(s){i.emitFile(e+n.sep+"package.json","resolve",t);return s}}return resolveFile(n.resolve(e,"index"),t,i)}class NotFoundError extends Error{constructor(e,t){super("Cannot find module '"+e+"' loaded from "+t);this.code="MODULE_NOT_FOUND"}}const r=new Set([...i(8027)._builtinLibs,"constants","module","timers","console","_stream_writable","_stream_readable","_stream_duplex","process","sys"]);function getPkgName(e){const t=e.split("/");if(e[0]==="@"&&t.length>1)return t.length>1?t.slice(0,2).join("/"):null;return t.length?t[0]:null}function getPkgCfg(e,t){const i=t.readFile(e+n.sep+"package.json");if(i){try{return JSON.parse(i.toString())}catch(e){}}return undefined}function getExportsTarget(e,t,i){if(typeof e==="string"){return e}else if(e===null){return e}else if(Array.isArray(e)){for(const n of e){const e=getExportsTarget(n,t,i);if(e===null||typeof e==="string"&&e.startsWith("./"))return e}}else if(typeof e==="object"){for(const n of Object.keys(e)){if(n==="default"||n==="require"&&i||n==="import"&&!i||t.includes(n)){const r=getExportsTarget(e[n],t,i);if(r!==undefined)return r}}}return undefined}function resolveExportsImports(e,t,i,n,r,s){let a;if(r){if(!(typeof t==="object"&&!Array.isArray(t)&&t!==null))return undefined;a=t}else if(typeof t==="string"||Array.isArray(t)||t===null||typeof t==="object"&&Object.keys(t).length&&Object.keys(t)[0][0]!=="."){a={".":t}}else{a=t}if(i in a){const t=getExportsTarget(a[i],n.conditions,s);if(typeof t==="string"&&t.startsWith("./"))return e+t.slice(1)}for(const t of Object.keys(a).sort((e,t)=>t.length-e.length)){if(t.endsWith("*")&&i.startsWith(t.slice(0,-1))){const r=getExportsTarget(a[t],n.conditions,s);if(typeof r==="string"&&r.startsWith("./"))return e+r.slice(1).replace(/\*/g,i.slice(t.length-1))}if(!t.endsWith("/"))continue;if(i.startsWith(t)){const r=getExportsTarget(a[t],n.conditions,s);if(typeof r==="string"&&r.endsWith("/")&&r.startsWith("./"))return e+r.slice(1)+i.slice(t.length)}}return undefined}function packageImportsResolve(e,t,i,r){if(e!=="#"&&!e.startsWith("#/")&&i.conditions){const s=i.getPjsonBoundary(t);if(s){const a=getPkgCfg(s,i);const{imports:o}=a||{};if(a&&o!==null&&o!==undefined){let a=resolveExportsImports(s,o,e,i,true,r);if(a){if(r)a=resolveFile(a,t,i)||resolveDir(a,t,i);else if(!i.isFile(a))throw new NotFoundError(a,t);if(a){i.emitFile(s+n.sep+"package.json","resolve",t);return a}}}}}throw new NotFoundError(e,t)}function resolvePackage(e,t,i,s){let a=t;if(r.has(e))return"node:"+e;const o=getPkgName(e)||"";let u;if(i.conditions){const r=i.getPjsonBoundary(t);if(r){const a=getPkgCfg(r,i);const{exports:l}=a||{};if(a&&a.name&&a.name===o&&l!==null&&l!==undefined){u=resolveExportsImports(r,l,"."+e.slice(o.length),i,false,s);if(u){if(s)u=resolveFile(u,t,i)||resolveDir(u,t,i);else if(!i.isFile(u))throw new NotFoundError(u,t)}if(u)i.emitFile(r+n.sep+"package.json","resolve",t)}}}let l;const f=a.indexOf(n.sep);while((l=a.lastIndexOf(n.sep))>f){a=a.substr(0,l);const r=a+n.sep+"node_modules";const f=i.stat(r);if(!f||!f.isDirectory())continue;const c=getPkgCfg(r+n.sep+o,i);const{exports:h}=c||{};if(i.conditions&&h!==undefined&&h!==null&&!u){let a;if(!i.exportsOnly)a=resolveFile(r+n.sep+e,t,i)||resolveDir(r+n.sep+e,t,i);let u=resolveExportsImports(r+n.sep+o,h,"."+e.slice(o.length),i,false,s);if(u){if(s)u=resolveFile(u,t,i)||resolveDir(u,t,i);else if(!i.isFile(u))throw new NotFoundError(u,t)}if(u){i.emitFile(r+n.sep+o+n.sep+"package.json","resolve",t);if(a&&a!==u)return[u,a];return u}if(a)return a}else{const s=resolveFile(r+n.sep+e,t,i)||resolveDir(r+n.sep+e,t,i);if(s){if(u&&u!==s)return[s,u];return s}}}if(u)return u;if(Object.hasOwnProperty.call(i.paths,e)){return i.paths[e]}for(const n of Object.keys(i.paths)){if(n.endsWith("/")&&e.startsWith(n)){const r=i.paths[n]+e.slice(n.length);const s=resolveFile(r,t,i)||resolveDir(r,t,i);if(!s){throw new NotFoundError(e,t)}return s}}throw new NotFoundError(e,t)}},6121:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true})},2947:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.isLoop=t.isVarLoop=t.isIdentifierRead=void 0;function isIdentifierRead(e,t){switch(t.type){case"ObjectPattern":case"ArrayPattern":return false;case"AssignmentExpression":return t.right===e;case"MemberExpression":return t.computed||e===t.object;case"Property":return e===t.value;case"MethodDefinition":return false;case"VariableDeclarator":return t.id!==e;case"ExportSpecifier":return false;case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":return false;default:return true}}t.isIdentifierRead=isIdentifierRead;function isVarLoop(e){return e.type==="ForStatement"||e.type==="ForInStatement"||e.type==="ForOfStatement"}t.isVarLoop=isVarLoop;function isLoop(e){return e.type==="ForStatement"||e.type==="ForInStatement"||e.type==="ForOfStatement"||e.type==="WhileStatement"||e.type==="DoWhileStatement"}t.isLoop=isLoop},4612:function(__unused_webpack_module,exports,__nccwpck_require__){"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:true});exports.nbind=exports.pregyp=void 0;const path_1=__importDefault(__nccwpck_require__(5622));const fs_1=__importDefault(__nccwpck_require__(5747));const versioning=__nccwpck_require__(2463);const napi=__nccwpck_require__(6500);const pregypFind=(e,t)=>{const i=JSON.parse(fs_1.default.readFileSync(e).toString());versioning.validate_config(i,t);var n;if(napi.get_napi_build_versions(i,t)){n=napi.get_best_napi_build_version(i,t)}t=t||{};if(!t.module_root)t.module_root=path_1.default.dirname(e);var r=versioning.evaluate(i,t,n);return r.module};exports.pregyp={default:{find:pregypFind},find:pregypFind};function makeModulePathList(e,t){return[[e,t],[e,"build",t],[e,"build","Debug",t],[e,"build","Release",t],[e,"out","Debug",t],[e,"Debug",t],[e,"out","Release",t],[e,"Release",t],[e,"build","default",t],[e,process.env["NODE_BINDINGS_COMPILED_DIR"]||"compiled",process.versions.node,process.platform,process.arch,t]]}function findCompiledModule(basePath,specList){var resolvedList=[];var ext=path_1.default.extname(basePath);for(var _i=0,specList_1=specList;_i{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.getPackageName=t.getPackageBase=void 0;const i=/^(@[^\\\/]+[\\\/])?[^\\\/]+/;function getPackageBase(e){const t=e.lastIndexOf("node_modules");if(t!==-1&&(e[t-1]==="/"||e[t-1]==="\\")&&(e[t+12]==="/"||e[t+12]==="\\")){const n=e.substr(t+13).match(i);if(n)return e.substr(0,t+13+n[0].length)}return undefined}t.getPackageBase=getPackageBase;function getPackageName(e){const t=e.lastIndexOf("node_modules");if(t!==-1&&(e[t-1]==="/"||e[t-1]==="\\")&&(e[t+12]==="/"||e[t+12]==="\\")){const n=e.substr(t+13).match(i);if(n&&n.length>0){return n[0].replace(/\\/g,"/")}}return undefined}t.getPackageName=getPackageName},1551:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.normalizeWildcardRequire=t.normalizeDefaultRequire=void 0;function normalizeDefaultRequire(e){if(e&&e.__esModule)return e;return{default:e}}t.normalizeDefaultRequire=normalizeDefaultRequire;const i=Object.prototype.hasOwnProperty;function normalizeWildcardRequire(e){if(e&&e.__esModule)return e;const t={};for(const n in e){if(!i.call(e,n))continue;t[n]=e[n]}t["default"]=e;return t}t.normalizeWildcardRequire=normalizeWildcardRequire},6413:function(e,t,i){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});t.sharedLibEmit=void 0;const r=n(i(2087));const s=n(i(4993));const a=i(3584);let o="";switch(r.default.platform()){case"darwin":o="/**/*.@(dylib|so?(.*))";break;case"win32":o="/**/*.dll";break;default:o="/**/*.so?(.*)"}async function sharedLibEmit(e,t){const i=a.getPackageBase(e);if(!i)return;const n=await new Promise((e,t)=>s.default(i+o,{ignore:i+"/**/node_modules/**/*"},(i,n)=>i?t(i):e(n)));n.forEach(i=>t.emitFile(i,"sharedlib",e))}t.sharedLibEmit=sharedLibEmit},3877:function(e,t,i){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:true});const r=i(5622);const s=n(i(7126));const a=i(3584);const o=i(5747);const u={"@generated/photon"({id:e,emitAssetDirectory:t}){if(e.endsWith("@generated/photon/index.js")){t(r.resolve(r.dirname(e),"runtime/"))}},argon2({id:e,emitAssetDirectory:t}){if(e.endsWith("argon2/argon2.js")){t(r.resolve(r.dirname(e),"build","Release"));t(r.resolve(r.dirname(e),"prebuilds"));t(r.resolve(r.dirname(e),"lib","binding"))}},bull({id:e,emitAssetDirectory:t}){if(e.endsWith("bull/lib/commands/index.js")){t(r.resolve(r.dirname(e)))}},camaro({id:e,emitAsset:t}){if(e.endsWith("camaro/dist/camaro.js")){t(r.resolve(r.dirname(e),"camaro.wasm"))}},"google-gax"({id:e,ast:t,emitAssetDirectory:i}){if(e.endsWith("google-gax/build/src/grpc.js")){for(const n of t.body){if(n.type==="VariableDeclaration"&&n.declarations[0].id.type==="Identifier"&&n.declarations[0].id.name==="googleProtoFilesDir"){i(r.resolve(r.dirname(e),"../../../google-proto-files"))}}}},oracledb({id:e,ast:t,emitAsset:i}){if(e.endsWith("oracledb/lib/oracledb.js")){for(const n of t.body){if(n.type==="ForStatement"&&n.body.body&&n.body.body[0]&&n.body.body[0].type==="TryStatement"&&n.body.body[0].block.body[0]&&n.body.body[0].block.body[0].type==="ExpressionStatement"&&n.body.body[0].block.body[0].expression.type==="AssignmentExpression"&&n.body.body[0].block.body[0].expression.operator==="="&&n.body.body[0].block.body[0].expression.left.type==="Identifier"&&n.body.body[0].block.body[0].expression.left.name==="oracledbCLib"&&n.body.body[0].block.body[0].expression.right.type==="CallExpression"&&n.body.body[0].block.body[0].expression.right.callee.type==="Identifier"&&n.body.body[0].block.body[0].expression.right.callee.name==="require"&&n.body.body[0].block.body[0].expression.right.arguments.length===1&&n.body.body[0].block.body[0].expression.right.arguments[0].type==="MemberExpression"&&n.body.body[0].block.body[0].expression.right.arguments[0].computed===true&&n.body.body[0].block.body[0].expression.right.arguments[0].object.type==="Identifier"&&n.body.body[0].block.body[0].expression.right.arguments[0].object.name==="binaryLocations"&&n.body.body[0].block.body[0].expression.right.arguments[0].property.type==="Identifier"&&n.body.body[0].block.body[0].expression.right.arguments[0].property.name==="i"){n.body.body[0].block.body[0].expression.right.arguments=[{type:"Literal",value:"_"}];const t=global._unit?"3.0.0":JSON.parse(o.readFileSync(e.slice(0,-15)+"package.json","utf8")).version;const s=Number(t.slice(0,t.indexOf(".")))>=4;const a="oracledb-"+(s?t:"abi"+process.versions.modules)+"-"+process.platform+"-"+process.arch+".node";i(r.resolve(e,"../../build/Release/"+a))}}}},"phantomjs-prebuilt"({id:e,emitAssetDirectory:t}){if(e.endsWith("phantomjs-prebuilt/lib/phantomjs.js")){t(r.resolve(r.dirname(e),"..","bin"))}},semver({id:e,emitAsset:t}){if(e.endsWith("semver/index.js")){t(r.resolve(e.replace("index.js","preload.js")))}},"socket.io"({id:e,ast:t,job:i}){if(e.endsWith("socket.io/lib/index.js")){function replaceResolvePathStatement(t){if(t.type==="ExpressionStatement"&&t.expression.type==="AssignmentExpression"&&t.expression.operator==="="&&t.expression.right.type==="CallExpression"&&t.expression.right.callee.type==="Identifier"&&t.expression.right.callee.name==="read"&&t.expression.right.arguments.length>=1&&t.expression.right.arguments[0].type==="CallExpression"&&t.expression.right.arguments[0].callee.type==="Identifier"&&t.expression.right.arguments[0].callee.name==="resolvePath"&&t.expression.right.arguments[0].arguments.length===1&&t.expression.right.arguments[0].arguments[0].type==="Literal"){const n=t.expression.right.arguments[0].arguments[0].value;let a;try{const t=s.default(n,e,i);if(typeof t==="string"){a=t}else{return undefined}}catch(e){return undefined}const o="/"+r.relative(r.dirname(e),a);t.expression.right.arguments[0]={type:"BinaryExpression",start:t.expression.right.arguments[0].start,end:t.expression.right.arguments[0].end,operator:"+",left:{type:"Identifier",name:"__dirname"},right:{type:"Literal",value:o,raw:JSON.stringify(o)}}}return undefined}for(const e of t.body){if(e.type==="ExpressionStatement"&&e.expression.type==="AssignmentExpression"&&e.expression.operator==="="&&e.expression.left.type==="MemberExpression"&&e.expression.left.object.type==="MemberExpression"&&e.expression.left.object.object.type==="Identifier"&&e.expression.left.object.object.name==="Server"&&e.expression.left.object.property.type==="Identifier"&&e.expression.left.object.property.name==="prototype"&&e.expression.left.property.type==="Identifier"&&e.expression.left.property.name==="serveClient"&&e.expression.right.type==="FunctionExpression"){let t;for(const i of e.expression.right.body.body)if(i.type==="IfStatement")t=i;const i=t&&t.consequent.body;let n=false;if(i&&i[0]&&i[0].type==="ExpressionStatement")n=replaceResolvePathStatement(i[0]);const r=i&&i[1]&&i[1].type==="TryStatement"&&i[1].block.body;if(r&&r[0])n=replaceResolvePathStatement(r[0])||n;return}}}},typescript({id:e,emitAssetDirectory:t}){if(e.endsWith("typescript/lib/tsc.js")){t(r.resolve(e,"../"))}},"uglify-es"({id:e,emitAsset:t}){if(e.endsWith("uglify-es/tools/node.js")){t(r.resolve(e,"../../lib/utils.js"));t(r.resolve(e,"../../lib/ast.js"));t(r.resolve(e,"../../lib/parse.js"));t(r.resolve(e,"../../lib/transform.js"));t(r.resolve(e,"../../lib/scope.js"));t(r.resolve(e,"../../lib/output.js"));t(r.resolve(e,"../../lib/compress.js"));t(r.resolve(e,"../../lib/sourcemap.js"));t(r.resolve(e,"../../lib/mozilla-ast.js"));t(r.resolve(e,"../../lib/propmangle.js"));t(r.resolve(e,"../../lib/minify.js"));t(r.resolve(e,"../exports.js"))}},"uglify-js"({id:e,emitAsset:t,emitAssetDirectory:i}){if(e.endsWith("uglify-js/tools/node.js")){i(r.resolve(e,"../../lib"));t(r.resolve(e,"../exports.js"))}},"playwright-core"({id:e,emitAsset:t}){if(e.endsWith("playwright-core/index.js")){t(r.resolve(r.dirname(e),"browsers.json"))}}};function handleSpecialCases({id:e,ast:t,emitAsset:i,emitAssetDirectory:n,job:r}){const s=a.getPackageName(e);const o=u[s||""];e=e.replace(/\\/g,"/");if(o)o({id:e,ast:t,emitAsset:i,emitAssetDirectory:n,job:r})}t.default=handleSpecialCases},8652:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.wildcardRegEx=t.WILDCARD=t.FUNCTION=t.UNKNOWN=t.evaluate=void 0;const n=i(8835);function evaluate(e,t={},i=true){const n={computeBranches:i,vars:t};return walk(e);function walk(e){const t=r[e.type];if(t){return t.call(n,e,walk)}return undefined}}t.evaluate=evaluate;t.UNKNOWN=Symbol();t.FUNCTION=Symbol();t.WILDCARD="";t.wildcardRegEx=/\x1a/g;function countWildcards(e){t.wildcardRegEx.lastIndex=0;let i=0;while(t.wildcardRegEx.exec(e))i++;return i}const r={ArrayExpression:function ArrayExpression(e,t){const i=[];for(let n=0,r=e.elements.length;nn.value}}}return undefined},BinaryExpression:function BinaryExpression(e,i){const n=e.operator;let r=i(e.left);if(!r&&n!=="+")return;let s=i(e.right);if(!r&&!s)return;if(!r){if(this.computeBranches&&s&&"value"in s&&typeof s.value==="string")return{value:t.WILDCARD+s.value,wildcards:[e.left,...s.wildcards||[]]};return}if(!s){if(this.computeBranches&&n==="+"){if(r&&"value"in r&&typeof r.value==="string")return{value:r.value+t.WILDCARD,wildcards:[...r.wildcards||[],e.right]}}if(!("test"in r)&&n==="||"&&r.value)return r;return}if("test"in r&&"value"in s){const e=s.value;if(n==="==")return{test:r.test,then:r.then==e,else:r.else==e};if(n==="===")return{test:r.test,then:r.then===e,else:r.else===e};if(n==="!=")return{test:r.test,then:r.then!=e,else:r.else!=e};if(n==="!==")return{test:r.test,then:r.then!==e,else:r.else!==e};if(n==="+")return{test:r.test,then:r.then+e,else:r.else+e};if(n==="-")return{test:r.test,then:r.then-e,else:r.else-e};if(n==="*")return{test:r.test,then:r.then*e,else:r.else*e};if(n==="/")return{test:r.test,then:r.then/e,else:r.else/e};if(n==="%")return{test:r.test,then:r.then%e,else:r.else%e};if(n==="<")return{test:r.test,then:r.then")return{test:r.test,then:r.then>e,else:r.else>e};if(n===">=")return{test:r.test,then:r.then>=e,else:r.else>=e};if(n==="|")return{test:r.test,then:r.then|e,else:r.else|e};if(n==="&")return{test:r.test,then:r.then&e,else:r.else&e};if(n==="^")return{test:r.test,then:r.then^e,else:r.else^e};if(n==="&&")return{test:r.test,then:r.then&&e,else:r.else&&e};if(n==="||")return{test:r.test,then:r.then||e,else:r.else||e}}else if("test"in s&&"value"in r){const e=r.value;if(n==="==")return{test:s.test,then:e==s.then,else:e==s.else};if(n==="===")return{test:s.test,then:e===s.then,else:e===s.else};if(n==="!=")return{test:s.test,then:e!=s.then,else:e!=s.else};if(n==="!==")return{test:s.test,then:e!==s.then,else:e!==s.else};if(n==="+")return{test:s.test,then:e+s.then,else:e+s.else};if(n==="-")return{test:s.test,then:e-s.then,else:e-s.else};if(n==="*")return{test:s.test,then:e*s.then,else:e*s.else};if(n==="/")return{test:s.test,then:e/s.then,else:e/s.else};if(n==="%")return{test:s.test,then:e%s.then,else:e%s.else};if(n==="<")return{test:s.test,then:e")return{test:s.test,then:e>s.then,else:e>s.else};if(n===">=")return{test:s.test,then:e>=s.then,else:e>=s.else};if(n==="|")return{test:s.test,then:e|s.then,else:e|s.else};if(n==="&")return{test:s.test,then:e&s.then,else:e&s.else};if(n==="^")return{test:s.test,then:e^s.then,else:e^s.else};if(n==="&&")return{test:s.test,then:e&&s.then,else:r&&s.else};if(n==="||")return{test:s.test,then:e||s.then,else:r||s.else}}else if("value"in r&&"value"in s){if(n==="==")return{value:r.value==s.value};if(n==="===")return{value:r.value===s.value};if(n==="!=")return{value:r.value!=s.value};if(n==="!==")return{value:r.value!==s.value};if(n==="+"){const e={value:r.value+s.value};let t=[];if("wildcards"in r&&r.wildcards){t=t.concat(r.wildcards)}if("wildcards"in s&&s.wildcards){t=t.concat(s.wildcards)}if(t.length>0){e.wildcards=t}return e}if(n==="-")return{value:r.value-s.value};if(n==="*")return{value:r.value*s.value};if(n==="/")return{value:r.value/s.value};if(n==="%")return{value:r.value%s.value};if(n==="<")return{value:r.value")return{value:r.value>s.value};if(n===">=")return{value:r.value>=s.value};if(n==="|")return{value:r.value|s.value};if(n==="&")return{value:r.value&s.value};if(n==="^")return{value:r.value^s.value};if(n==="&&")return{value:r.value&&s.value};if(n==="||")return{value:r.value||s.value}}return},CallExpression:function CallExpression(e,i){var n;const r=i(e.callee);if(!r||"test"in r)return;let s=r.value;if(typeof s==="object"&&s!==null)s=s[t.FUNCTION];if(typeof s!=="function")return;let a=null;if(e.callee.object){a=i(e.callee.object);a=a&&"value"in a&&a.value?a.value:null}let o;let u=[];let l;let f=e.arguments.length>0&&((n=e.callee.property)===null||n===void 0?void 0:n.name)!=="concat";const c=[];for(let n=0,r=e.arguments.length;nc.push(e))}else{if(!this.computeBranches)return;r={value:t.WILDCARD};c.push(e.arguments[n])}if("test"in r){if(c.length)return;if(o)return;o=r.test;l=u.concat([]);u.push(r.then);l.push(r.else)}else{u.push(r.value);if(l)l.push(r.value)}}if(f)return;try{const e=s.apply(a,u);if(e===t.UNKNOWN)return;if(!o){if(c.length){if(typeof e!=="string"||countWildcards(e)!==c.length)return;return{value:e,wildcards:c}}return{value:e}}const i=s.apply(a,l);if(e===t.UNKNOWN)return;return{test:o,then:e,else:i}}catch(e){return}},ConditionalExpression:function ConditionalExpression(e,t){const i=t(e.test);if(i&&"value"in i)return i.value?t(e.consequent):t(e.alternate);if(!this.computeBranches)return;const n=t(e.consequent);if(!n||"wildcards"in n||"test"in n)return;const r=t(e.alternate);if(!r||"wildcards"in r||"test"in r)return;return{test:e.test,then:n.value,else:r.value}},ExpressionStatement:function ExpressionStatement(e,t){return t(e.expression)},Identifier:function Identifier(e,t){if(Object.hasOwnProperty.call(this.vars,e.name))return this.vars[e.name];return undefined},Literal:function Literal(e,t){return{value:e.value}},MemberExpression:function MemberExpression(e,i){const n=i(e.object);if(!n||"test"in n||typeof n.value==="function"){return undefined}if(e.property.type==="Identifier"){if(typeof n.value==="string"&&e.property.name==="concat"){return{value:{[t.FUNCTION]:(...e)=>n.value.concat(e)}}}if(typeof n.value==="object"&&n.value!==null){const r=n.value;if(e.computed){const s=i(e.property);if(s&&"value"in s&&s.value){const e=r[s.value];if(e===t.UNKNOWN)return undefined;return{value:e}}if(!r[t.UNKNOWN]&&Object.keys(n).length===0){return{value:undefined}}}else if(e.property.name in r){const i=r[e.property.name];if(i===t.UNKNOWN)return undefined;return{value:i}}else if(r[t.UNKNOWN])return undefined}else{return{value:undefined}}}const r=i(e.property);if(!r||"test"in r)return undefined;if(typeof n.value==="object"&&n.value!==null){if(r.value in n.value){const e=n.value[r.value];if(e===t.UNKNOWN)return undefined;return{value:e}}else if(n.value[t.UNKNOWN]){return undefined}}else{return{value:undefined}}return undefined},MetaProperty:function MetaProperty(e){if(e.meta.name==="import"&&e.property.name==="meta")return{value:this.vars["import.meta"]};return undefined},NewExpression:function NewExpression(e,t){const i=t(e.callee);if(i&&"value"in i&&i.value===n.URL&&e.arguments.length){const i=t(e.arguments[0]);if(!i)return undefined;let r=null;if(e.arguments[1]){r=t(e.arguments[1]);if(!r||!("value"in r))return undefined}if("value"in i){if(r){try{return{value:new n.URL(i.value,r.value)}}catch(e){return undefined}}try{return{value:new n.URL(i.value)}}catch(e){return undefined}}else{const e=i.test;if(r){try{return{test:e,then:new n.URL(i.then,r.value),else:new n.URL(i.else,r.value)}}catch(e){return undefined}}try{return{test:e,then:new n.URL(i.then),else:new n.URL(i.else)}}catch(e){return undefined}}}return undefined},ObjectExpression:function ObjectExpression(e,i){const n={};for(let r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:true});t.handleWrappers=void 0;const n=i(4855);function isUndefinedOrVoid(e){return e.type==="Identifier"&&e.name==="undefined"||e.type==="UnaryExpression"&&e.operator==="void"&&e.argument.type==="Literal"&&e.argument.value===0}function handleWrappers(e){let t;if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="UnaryExpression"&&e.body[0].expression.operator==="!"&&e.body[0].expression.argument.type==="CallExpression"&&e.body[0].expression.argument.callee.type==="FunctionExpression"&&e.body[0].expression.argument.arguments.length===1)t=e.body[0].expression.argument;else if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="CallExpression"&&e.body[0].expression.callee.type==="FunctionExpression"&&(e.body[0].expression.arguments.length===1||e.body[0].expression.arguments.length===0))t=e.body[0].expression;else if(e.body.length===1&&e.body[0].type==="ExpressionStatement"&&e.body[0].expression.type==="AssignmentExpression"&&e.body[0].expression.left.type==="MemberExpression"&&e.body[0].expression.left.object.type==="Identifier"&&e.body[0].expression.left.object.name==="module"&&e.body[0].expression.left.property.type==="Identifier"&&e.body[0].expression.left.property.name==="exports"&&e.body[0].expression.right.type==="CallExpression"&&e.body[0].expression.right.callee.type==="FunctionExpression"&&e.body[0].expression.right.arguments.length===1)t=e.body[0].expression.right;if(t){if(t.arguments[0]&&t.arguments[0].type==="ConditionalExpression"&&t.arguments[0].test.type==="LogicalExpression"&&t.arguments[0].test.operator==="&&"&&t.arguments[0].test.left.type==="BinaryExpression"&&t.arguments[0].test.left.operator==="==="&&t.arguments[0].test.left.left.type==="UnaryExpression"&&t.arguments[0].test.left.left.operator==="typeof"&&t.arguments[0].test.left.left.argument.name==="define"&&t.arguments[0].test.left.right.type==="Literal"&&t.arguments[0].test.left.right.value==="function"&&t.arguments[0].test.right.type==="MemberExpression"&&t.arguments[0].test.right.object.type==="Identifier"&&t.arguments[0].test.right.property.type==="Identifier"&&t.arguments[0].test.right.property.name==="amd"&&t.arguments[0].test.right.computed===false&&t.arguments[0].alternate.type==="FunctionExpression"&&t.arguments[0].alternate.params.length===1&&t.arguments[0].alternate.params[0].type==="Identifier"&&t.arguments[0].alternate.body.body.length===1&&t.arguments[0].alternate.body.body[0].type==="ExpressionStatement"&&t.arguments[0].alternate.body.body[0].expression.type==="AssignmentExpression"&&t.arguments[0].alternate.body.body[0].expression.left.type==="MemberExpression"&&t.arguments[0].alternate.body.body[0].expression.left.object.type==="Identifier"&&t.arguments[0].alternate.body.body[0].expression.left.object.name==="module"&&t.arguments[0].alternate.body.body[0].expression.left.property.type==="Identifier"&&t.arguments[0].alternate.body.body[0].expression.left.property.name==="exports"&&t.arguments[0].alternate.body.body[0].expression.left.computed===false&&t.arguments[0].alternate.body.body[0].expression.right.type==="CallExpression"&&t.arguments[0].alternate.body.body[0].expression.right.callee.type==="Identifier"&&t.arguments[0].alternate.body.body[0].expression.right.callee.name===t.arguments[0].alternate.params[0].name&&t.arguments[0].alternate.body.body[0].expression.right.arguments.length===1&&t.arguments[0].alternate.body.body[0].expression.right.arguments[0].type==="Identifier"&&t.arguments[0].alternate.body.body[0].expression.right.arguments[0].name==="require"){let e=t.callee.body.body;if(e[0].type==="ExpressionStatement"&&e[0].expression.type==="Literal"&&e[0].expression.value==="use strict"){e=e.slice(1)}if(e.length===1&&e[0].type==="ExpressionStatement"&&e[0].expression.type==="CallExpression"&&e[0].expression.callee.type==="Identifier"&&e[0].expression.callee.name===t.arguments[0].test.right.object.name&&e[0].expression.arguments.length===1&&e[0].expression.arguments[0].type==="FunctionExpression"&&e[0].expression.arguments[0].params.length===1&&e[0].expression.arguments[0].params[0].type==="Identifier"&&e[0].expression.arguments[0].params[0].name==="require"){delete e[0].expression.arguments[0].scope.declarations.require;e[0].expression.arguments[0].params=[]}}else if(t.arguments[0]&&t.arguments[0].type==="FunctionExpression"&&t.arguments[0].params.length===0&&(t.arguments[0].body.body.length===1||t.arguments[0].body.body.length===2&&t.arguments[0].body.body[0].type==="VariableDeclaration"&&t.arguments[0].body.body[0].declarations.length===3&&t.arguments[0].body.body[0].declarations.every(e=>e.init===null&&e.id.type==="Identifier"))&&t.arguments[0].body.body[t.arguments[0].body.body.length-1].type==="ReturnStatement"&&t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.type==="CallExpression"&&t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.callee.type==="CallExpression"&&t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.arguments.length&&t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.arguments.every(e=>e&&e.type==="Literal"&&typeof e.value==="number")&&(t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.callee.callee.type==="FunctionExpression"||t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.callee.callee.type==="CallExpression"&&t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.callee.callee.callee.type==="FunctionExpression"&&t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.callee.callee.arguments.length===0)&&t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.callee.arguments.length===3&&t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.callee.arguments[0].type==="ObjectExpression"&&t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.callee.arguments[1].type==="ObjectExpression"&&t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.callee.arguments[2].type==="ArrayExpression"){const e=t.arguments[0].body.body[t.arguments[0].body.body.length-1].argument.callee.arguments[0].properties;const i={};if(e.every(e=>{if(e.type!=="Property"||e.computed!==false||e.key.type!=="Literal"||typeof e.key.value!=="number"||e.value.type!=="ArrayExpression"||e.value.elements.length!==2||e.value.elements[0].type!=="FunctionExpression"||e.value.elements[1].type!=="ObjectExpression"){return false}const t=e.value.elements[1].properties;for(const e of t){if(e.type!=="Property"||e.value.type!=="Identifier"&&e.value.type!=="Literal"&&!isUndefinedOrVoid(e.value)||!(e.key.type==="Literal"&&typeof e.key.value==="string"||e.key.type==="Identifier")||e.computed){return false}if(isUndefinedOrVoid(e.value)){if(e.key.type==="Identifier")i[e.key.name]={type:"Literal",start:e.key.start,end:e.key.end,value:e.key.name,raw:JSON.stringify(e.key.name)};else if(e.key.type==="Literal")i[e.key.value]=e.key}}return true})){const e=Object.keys(i);if(e.length){const n=(t.arguments[0].body.body[1]||t.arguments[0].body.body[0]).argument.callee.arguments[1];n.properties=e.map(e=>{return{type:"Property",kind:"init",key:i[e],value:{type:"ObjectExpression",properties:[{type:"Property",kind:"init",key:{type:"Identifier",name:"exports"},value:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[i[e]]}}]}}})}}}else if(t.arguments[0]&&t.arguments[0].type==="FunctionExpression"&&t.arguments[0].params.length===2&&t.arguments[0].params[0].type==="Identifier"&&t.arguments[0].params[1].type==="Identifier"&&t.callee.body.body.length===1){const e=t.callee.body.body[0];if(e.type==="IfStatement"&&e.test.type==="LogicalExpression"&&e.test.operator==="&&"&&e.test.left.type==="BinaryExpression"&&e.test.left.left.type==="UnaryExpression"&&e.test.left.left.operator==="typeof"&&e.test.left.left.argument.type==="Identifier"&&e.test.left.left.argument.name==="module"&&e.test.left.right.type==="Literal"&&e.test.left.right.value==="object"&&e.test.right.type==="BinaryExpression"&&e.test.right.left.type==="UnaryExpression"&&e.test.right.left.operator==="typeof"&&e.test.right.left.argument.type==="MemberExpression"&&e.test.right.left.argument.object.type==="Identifier"&&e.test.right.left.argument.object.name==="module"&&e.test.right.left.argument.property.type==="Identifier"&&e.test.right.left.argument.property.name==="exports"&&e.test.right.right.type==="Literal"&&e.test.right.right.value==="object"&&e.consequent.type==="BlockStatement"&&e.consequent.body.length>0){let i;if(e.consequent.body[0].type==="VariableDeclaration"&&e.consequent.body[0].declarations[0].init&&e.consequent.body[0].declarations[0].init.type==="CallExpression")i=e.consequent.body[0].declarations[0].init;else if(e.consequent.body[0].type==="ExpressionStatement"&&e.consequent.body[0].expression.type==="CallExpression")i=e.consequent.body[0].expression;else if(e.consequent.body[0].type==="ExpressionStatement"&&e.consequent.body[0].expression.type==="AssignmentExpression"&&e.consequent.body[0].expression.operator==="="&&e.consequent.body[0].expression.right.type==="CallExpression")i=e.consequent.body[0].expression.right;if(i&&i.callee.type==="Identifier"&&t.callee.params.length>0&&i.callee.name===t.callee.params[0].name&&i.arguments.length===2&&i.arguments[0].type==="Identifier"&&i.arguments[0].name==="require"&&i.arguments[1].type==="Identifier"&&i.arguments[1].name==="exports"){delete t.arguments[0].scope.declarations.require;delete t.arguments[0].scope.declarations.exports;t.arguments[0].params=[]}}}else if(t.callee.type==="FunctionExpression"&&t.callee.body.body.length>2&&t.callee.body.body[0].type==="VariableDeclaration"&&t.callee.body.body[0].declarations.length===1&&t.callee.body.body[0].declarations[0].type==="VariableDeclarator"&&t.callee.body.body[0].declarations[0].id.type==="Identifier"&&t.callee.body.body[0].declarations[0].init&&(t.callee.body.body[0].declarations[0].init.type==="ObjectExpression"&&t.callee.body.body[0].declarations[0].init.properties.length===0||t.callee.body.body[0].declarations[0].init.type==="CallExpression"&&t.callee.body.body[0].declarations[0].init.arguments.length===1)&&(t.callee.body.body[1]&&t.callee.body.body[1].type==="FunctionDeclaration"&&t.callee.body.body[1].params.length===1&&t.callee.body.body[1].body.body.length>=3||t.callee.body.body[2]&&t.callee.body.body[2].type==="FunctionDeclaration"&&t.callee.body.body[2].params.length===1&&t.callee.body.body[2].body.body.length>=3)&&(t.arguments[0]&&(t.arguments[0].type==="ArrayExpression"&&t.arguments[0].elements.length>0&&t.arguments[0].elements.every(e=>e&&e.type==="FunctionExpression")||t.arguments[0].type==="ObjectExpression"&&t.arguments[0].properties&&t.arguments[0].properties.length>0&&t.arguments[0].properties.every(e=>e&&e.key&&e.key.type==="Literal"&&e.value&&e.value.type==="FunctionExpression")))||t.arguments.length===0&&t.callee.type==="FunctionExpression"&&t.callee.params.length===0&&t.callee.body.type==="BlockStatement"&&t.callee.body.body.length>5&&t.callee.body.body[0].type==="VariableDeclaration"&&t.callee.body.body[0].declarations.length===1&&t.callee.body.body[0].declarations[0].id.type==="Identifier"&&t.callee.body.body[1].type==="ExpressionStatement"&&t.callee.body.body[1].expression.type==="AssignmentExpression"&&t.callee.body.body[2].type==="ExpressionStatement"&&t.callee.body.body[2].expression.type==="AssignmentExpression"&&t.callee.body.body[3].type==="ExpressionStatement"&&t.callee.body.body[3].expression.type==="AssignmentExpression"&&t.callee.body.body[3].expression.left.type==="MemberExpression"&&t.callee.body.body[3].expression.left.object.type==="Identifier"&&t.callee.body.body[3].expression.left.object.name===t.callee.body.body[0].declarations[0].id.name&&t.callee.body.body[3].expression.left.property.type==="Identifier"&&t.callee.body.body[3].expression.left.property.name==="modules"&&t.callee.body.body[3].expression.right.type==="ObjectExpression"&&(t.callee.body.body[4].type==="VariableDeclaration"&&t.callee.body.body[4].declarations.length===1&&t.callee.body.body[4].declarations[0].init.type==="CallExpression"&&t.callee.body.body[4].declarations[0].init.callee.type==="Identifier"&&t.callee.body.body[4].declarations[0].init.callee.name==="require"||t.callee.body.body[5].type==="VariableDeclaration"&&t.callee.body.body[5].declarations.length===1&&t.callee.body.body[5].declarations[0].init.type==="CallExpression"&&t.callee.body.body[5].declarations[0].init.callee.type==="Identifier"&&t.callee.body.body[5].declarations[0].init.callee.name==="require")){const e=new Map;const i=t.callee.params.length?t.arguments[0]:t.callee.body.body[3].expression.right;let r;if(i.type==="ArrayExpression")r=i.elements.map((e,t)=>[t,e]);else r=i.properties.map(e=>[e.key.value,e.value]);for(const[t,i]of r){const n=i.body.body.length===1?i.body.body[0]:(i.body.body.length===2||i.body.body.length===3&&i.body.body[2].type==="EmptyStatement")&&i.body.body[0].type==="ExpressionStatement"&&i.body.body[0].expression.type==="Literal"&&i.body.body[0].expression.value==="use strict"?i.body.body[1]:null;if(n&&n.type==="ExpressionStatement"&&n.expression.type==="AssignmentExpression"&&n.expression.operator==="="&&n.expression.left.type==="MemberExpression"&&n.expression.left.object.type==="Identifier"&&i.params.length>0&&n.expression.left.object.name===i.params[0].name&&n.expression.left.property.type==="Identifier"&&n.expression.left.property.name==="exports"&&n.expression.right.type==="CallExpression"&&n.expression.right.callee.type==="Identifier"&&n.expression.right.callee.name==="require"&&n.expression.right.arguments.length===1&&n.expression.right.arguments[0].type==="Literal"){e.set(t,n.expression.right.arguments[0].value)}}for(const[,t]of r){if(t.params.length===3&&t.params[2].type==="Identifier"){const i=new Map;n.walk(t.body,{enter(n,r){if(n.type==="CallExpression"&&n.callee.type==="Identifier"&&n.callee.name===t.params[2].name&&n.arguments.length===1&&n.arguments[0].type==="Literal"){const t=e.get(n.arguments[0].value);if(t){const e={type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Literal",value:t}]};const s=r;if(s.right===n){s.right=e}else if(s.left===n){s.left=e}else if(s.object===n){s.object=e}else if(s.callee===n){s.callee=e}else if(s.arguments&&s.arguments.some(e=>e===n)){s.arguments=s.arguments.map(t=>t===n?e:t)}else if(s.init===n){if(s.type==="VariableDeclarator"&&s.id.type==="Identifier")i.set(s.id.name,t);s.init=e}}}else if(n.type==="CallExpression"&&n.callee.type==="MemberExpression"&&n.callee.object.type==="Identifier"&&n.callee.object.name===t.params[2].name&&n.callee.property.type==="Identifier"&&n.callee.property.name==="n"&&n.arguments.length===1&&n.arguments[0].type==="Identifier"){if(r&&r.init===n){const e=n.arguments[0];r.init={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"assign"}},arguments:[{type:"ArrowFunctionExpression",expression:true,params:[],body:e},{type:"ObjectExpression",properties:[{type:"ObjectProperty",method:false,computed:false,shorthand:false,key:{type:"Identifier",name:"a"},value:e}]}]}}}}})}}}}}t.handleWrappers=handleWrappers},1289:(e,t)=>{e.exports=t=abbrev.abbrev=abbrev;abbrev.monkeyPatch=monkeyPatch;function monkeyPatch(){Object.defineProperty(Array.prototype,"abbrev",{value:function(){return abbrev(this)},enumerable:false,configurable:true,writable:true});Object.defineProperty(Object.prototype,"abbrev",{value:function(){return abbrev(Object.keys(this))},enumerable:false,configurable:true,writable:true})}function abbrev(e){if(arguments.length!==1||!Array.isArray(e)){e=Array.prototype.slice.call(arguments,0)}for(var t=0,i=e.length,n=[];tt?1:-1}},8363:(e,t,i)=>{"use strict";const n=i(3485);e.exports=function(e){const t=e.acorn||i(9089);const r=t.tokTypes;e=n(e);return class extends e{_maybeParseFieldValue(e){if(this.eat(r.eq)){const t=this._inFieldValue;this._inFieldValue=true;if(this.type===r.name&&this.value==="await"&&(this.inAsync||this.options.allowAwaitOutsideFunction)){e.value=this.parseAwait()}else e.value=this.parseExpression();this._inFieldValue=t}else e.value=null}parseClassElement(e){if(this.options.ecmaVersion>=8&&(this.type==r.name||this.type.keyword||this.type==this.privateIdentifierToken||this.type==r.bracketL||this.type==r.string||this.type==r.num)){const e=this._branch();if(e.type==r.bracketL){let t=0;do{if(e.eat(r.bracketL))++t;else if(e.eat(r.bracketR))--t;else e.next()}while(t>0)}else e.next(true);let t=e.type==r.eq||e.type==r.semi;if(!t&&e.canInsertSemicolon()){t=e.type!=r.parenL}if(t){const e=this.startNode();if(this.type==this.privateIdentifierToken){this.parsePrivateClassElementName(e)}else{this.parsePropertyName(e)}if(e.key.type==="Identifier"&&e.key.name==="constructor"||e.key.type==="Literal"&&e.key.value==="constructor"){this.raise(e.key.start,"Classes may not have a field called constructor")}this.enterScope(64|2|1);this._maybeParseFieldValue(e);this.exitScope();this.finishNode(e,"PropertyDefinition");this.semicolon();return e}}return super.parseClassElement.apply(this,arguments)}parseIdent(e,t){const i=super.parseIdent(e,t);if(this._inFieldValue&&i.name=="arguments")this.raise(i.start,"A class field initializer may not contain arguments");return i}}}},3485:(e,t,i)=>{"use strict";const n=Object.getPrototypeOf||(e=>e.__proto__);const r=e=>{if(e.acorn)return e.acorn;const t=i(9089);if(t.version.indexOf("6.")!=0&&t.version.indexOf("6.0.")==0&&t.version.indexOf("7.")!=0){throw new Error(`acorn-private-class-elements requires acorn@^6.1.0 or acorn@7.0.0, not ${t.version}`)}for(let i=e;i&&i!==t.Parser;i=n(i)){if(i!==t.Parser){throw new Error("acorn-private-class-elements does not support mixing different acorn copies")}}return t};e.exports=function(e){if(e.prototype.parsePrivateName){return e}const t=r(e);e=class extends e{_branch(){this.__branch=this.__branch||new e({ecmaVersion:this.options.ecmaVersion},this.input);this.__branch.end=this.end;this.__branch.pos=this.pos;this.__branch.type=this.type;this.__branch.value=this.value;this.__branch.containsEsc=this.containsEsc;return this.__branch}parsePrivateClassElementName(e){e.computed=false;e.key=this.parsePrivateName();if(e.key.name=="constructor")this.raise(e.key.start,"Classes may not have a private element named constructor");const t={get:"set",set:"get"}[e.kind];const i=this._privateBoundNames;if(Object.prototype.hasOwnProperty.call(i,e.key.name)&&i[e.key.name]!==t){this.raise(e.start,"Duplicate private element")}i[e.key.name]=e.kind||true;delete this._unresolvedPrivateNames[e.key.name];return e.key}parsePrivateName(){const e=this.startNode();e.name=this.value;this.next();this.finishNode(e,"PrivateIdentifier");if(this.options.allowReserved=="never")this.checkUnreserved(e);return e}getTokenFromCode(e){if(e===35){++this.pos;const e=this.readWord1();return this.finishToken(this.privateIdentifierToken,e)}return super.getTokenFromCode(e)}parseClass(e,t){const i=this._outerPrivateBoundNames;this._outerPrivateBoundNames=this._privateBoundNames;this._privateBoundNames=Object.create(this._privateBoundNames||null);const n=this._outerUnresolvedPrivateNames;this._outerUnresolvedPrivateNames=this._unresolvedPrivateNames;this._unresolvedPrivateNames=Object.create(null);const r=super.parseClass(e,t);const s=this._unresolvedPrivateNames;this._privateBoundNames=this._outerPrivateBoundNames;this._outerPrivateBoundNames=i;this._unresolvedPrivateNames=this._outerUnresolvedPrivateNames;this._outerUnresolvedPrivateNames=n;if(!this._unresolvedPrivateNames){const e=Object.keys(s);if(e.length){e.sort((e,t)=>s[e]-s[t]);this.raise(s[e[0]],"Usage of undeclared private name")}}else Object.assign(this._unresolvedPrivateNames,s);return r}parseClassSuper(e){const t=this._privateBoundNames;this._privateBoundNames=this._outerPrivateBoundNames;const i=this._unresolvedPrivateNames;this._unresolvedPrivateNames=this._outerUnresolvedPrivateNames;const n=super.parseClassSuper(e);this._privateBoundNames=t;this._unresolvedPrivateNames=i;return n}parseSubscript(e,i,n,r,s,a){const o=this.options.ecmaVersion>=11&&t.tokTypes.questionDot;const u=this._branch();if(!((u.eat(t.tokTypes.dot)||o&&u.eat(t.tokTypes.questionDot))&&u.type==this.privateIdentifierToken)){return super.parseSubscript.apply(this,arguments)}let l=false;if(!this.eat(t.tokTypes.dot)){this.expect(t.tokTypes.questionDot);l=true}let f=this.startNodeAt(i,n);f.object=e;f.computed=false;if(o){f.optional=l}if(this.type==this.privateIdentifierToken){if(e.type=="Super"){this.raise(this.start,"Cannot access private element on super")}f.property=this.parsePrivateName();if(!this._privateBoundNames||!this._privateBoundNames[f.property.name]){if(!this._unresolvedPrivateNames){this.raise(f.property.start,"Usage of undeclared private name")}this._unresolvedPrivateNames[f.property.name]=f.property.start}}else{f.property=this.parseIdent(true)}return this.finishNode(f,"MemberExpression")}parseMaybeUnary(e,t){const i=super.parseMaybeUnary(e,t);if(i.operator=="delete"){if(i.argument.type=="MemberExpression"&&i.argument.property.type=="PrivateIdentifier"){this.raise(i.start,"Private elements may not be deleted")}}return i}};e.prototype.privateIdentifierToken=new t.TokenType("privateIdentifier");return e}},2484:(e,t,i)=>{"use strict";const n=i(3485);e.exports=function(e){const t=n(e);const r=e.acorn||i(9089);const s=r.tokTypes;return class extends t{_maybeParseFieldValue(e){if(this.eat(s.eq)){const t=this._inStaticFieldScope;this._inStaticFieldScope=this.currentThisScope();e.value=this.parseExpression();this._inStaticFieldScope=t}else e.value=null}parseClassElement(e){if(this.options.ecmaVersion<8||!this.isContextual("static")){return super.parseClassElement.apply(this,arguments)}const t=this._branch();t.next();if([s.name,s.bracketL,s.string,s.num,this.privateIdentifierToken].indexOf(t.type)==-1&&!t.type.keyword){return super.parseClassElement.apply(this,arguments)}if(t.type==s.bracketL){let e=0;do{if(t.eat(s.bracketL))++e;else if(t.eat(s.bracketR))--e;else t.next()}while(e>0)}else t.next();if(t.type!=s.eq&&!t.canInsertSemicolon()&&t.type!=s.semi){return super.parseClassElement.apply(this,arguments)}const i=this.startNode();i.static=this.eatContextual("static");if(this.type==this.privateIdentifierToken){this.parsePrivateClassElementName(i)}else{this.parsePropertyName(i)}if(i.key.type==="Identifier"&&i.key.name==="constructor"||i.key.type==="Literal"&&!i.computed&&i.key.value==="constructor"){this.raise(i.key.start,"Classes may not have a field called constructor")}if((i.key.name||i.key.value)==="prototype"&&!i.computed){this.raise(i.key.start,"Classes may not have a static property named prototype")}this.enterScope(64|2|1);this._maybeParseFieldValue(i);this.exitScope();this.finishNode(i,"PropertyDefinition");this.semicolon();return i}parsePropertyName(e){if(e.static&&this.type==this.privateIdentifierToken){this.parsePrivateClassElementName(e)}else{super.parsePropertyName(e)}}parseIdent(e,t){const i=super.parseIdent(e,t);if(this._inStaticFieldScope&&this.currentThisScope()===this._inStaticFieldScope&&i.name=="arguments"){this.raise(i.start,"A static class field initializer may not contain arguments")}return i}}}},9089:function(e,t){(function(e,i){true?i(t):0})(this,function(e){"use strict";var t={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"};var i="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 n={5:i,"5module":i+" export import",6:i+" const class extends export import super"};var r=/^in(stanceof)?$/;var s="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var a="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var o=new RegExp("["+s+"]");var u=new RegExp("["+s+a+"]");s=a=null;var l=[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];var f=[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];function isInAstralSet(e,t){var i=65536;for(var n=0;ne){return false}i+=t[n+1];if(i>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&o.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,l)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&u.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,l)||isInAstralSet(e,f)}var c=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new c(e,{beforeExpr:true,binop:t})}var h={beforeExpr:true},p={startsExpr:true};var d={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return d[e]=new c(e,t)}var b={num:new c("num",p),regexp:new c("regexp",p),string:new c("string",p),name:new c("name",p),privateId:new c("privateId",p),eof:new c("eof"),bracketL:new c("[",{beforeExpr:true,startsExpr:true}),bracketR:new c("]"),braceL:new c("{",{beforeExpr:true,startsExpr:true}),braceR:new c("}"),parenL:new c("(",{beforeExpr:true,startsExpr:true}),parenR:new c(")"),comma:new c(",",h),semi:new c(";",h),colon:new c(":",h),dot:new c("."),question:new c("?",h),questionDot:new c("?."),arrow:new c("=>",h),template:new c("template"),invalidTemplate:new c("invalidTemplate"),ellipsis:new c("...",h),backQuote:new c("`",p),dollarBraceL:new c("${",{beforeExpr:true,startsExpr:true}),eq:new c("=",{beforeExpr:true,isAssign:true}),assign:new c("_=",{beforeExpr:true,isAssign:true}),incDec:new c("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new c("!/~",{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 c("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new c("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",h),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",h),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",h),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",p),_if:kw("if"),_return:kw("return",h),_switch:kw("switch"),_throw:kw("throw",h),_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",p),_super:kw("super",p),_class:kw("class",p),_extends:kw("extends",h),_export:kw("export"),_import:kw("import",p),_null:kw("null",p),_true:kw("true",p),_false:kw("false",p),_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})};var v=/\r\n?|\n|\u2028|\u2029/;var g=new RegExp(v.source,"g");function isNewLine(e,t){return e===10||e===13||!t&&(e===8232||e===8233)}var _=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var y=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var m=Object.prototype;var x=m.hasOwnProperty;var E=m.toString;function has(e,t){return x.call(e,t)}var w=Array.isArray||function(e){return E.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var S=function Position(e,t){this.line=e;this.column=t};S.prototype.offset=function offset(e){return new S(this.line,this.column+e)};var A=function SourceLocation(e,t,i){this.start=t;this.end=i;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var i=1,n=0;;){g.lastIndex=n;var r=g.exec(e);if(r&&r.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(w(t.onToken)){var n=t.onToken;t.onToken=function(e){return n.push(e)}}if(w(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(i,n,r,s,a,o){var u={type:i?"Block":"Line",value:n,start:r,end:s};if(e.locations){u.loc=new A(this,a,o)}if(e.ranges){u.range=[r,s]}t.push(u)}}var C=1,T=2,O=C|T,N=4,I=8,L=16,P=32,M=64,H=128;function functionFlags(e,t){return T|(e?N:0)|(t?I:0)}var F=0,B=1,D=2,$=3,W=4,U=5;var j=function Parser(e,i,r){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(n[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var s="";if(e.allowReserved!==true){s=t[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3];if(e.sourceType==="module"){s+=" await"}}this.reservedWords=wordsRegexp(s);var a=(s?s+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(a);this.reservedWordsStrictBind=wordsRegexp(a+" "+t.strictBind);this.input=String(i);this.containsEsc=false;if(r){this.pos=r;this.lineStart=this.input.lastIndexOf("\n",r-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(v).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=b.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.potentialArrowInForAwait=false;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports=Object.create(null);if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(C);this.regexpState=null;this.privateNameStack=[]};var q={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true},inNonArrowFunction:{configurable:true}};j.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};q.inFunction.get=function(){return(this.currentVarScope().flags&T)>0};q.inGenerator.get=function(){return(this.currentVarScope().flags&I)>0&&!this.currentVarScope().inClassFieldInit};q.inAsync.get=function(){return(this.currentVarScope().flags&N)>0&&!this.currentVarScope().inClassFieldInit};q.allowSuper.get=function(){var e=this.currentThisScope();var t=e.flags;var i=e.inClassFieldInit;return(t&M)>0||i};q.allowDirectSuper.get=function(){return(this.currentThisScope().flags&H)>0};q.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};q.inNonArrowFunction.get=function(){var e=this.currentThisScope();var t=e.flags;var i=e.inClassFieldInit;return(t&T)>0||i};j.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var i=this;for(var n=0;n=,?^&]/.test(r)||r==="!"&&this.input.charAt(n+1)==="=")}e+=t[0].length;y.lastIndex=e;e+=y.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};G.eat=function(e){if(this.type===e){this.next();return true}else{return false}};G.isContextual=function(e){return this.type===b.name&&this.value===e&&!this.containsEsc};G.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};G.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};G.canInsertSemicolon=function(){return this.type===b.eof||this.type===b.braceR||v.test(this.input.slice(this.lastTokEnd,this.start))};G.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};G.semicolon=function(){if(!this.eat(b.semi)&&!this.insertSemicolon()){this.unexpected()}};G.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};G.expect=function(e){this.eat(e)||this.unexpected()};G.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}G.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var i=t?e.parenthesizedAssign:e.parenthesizedBind;if(i>-1){this.raiseRecoverable(i,"Parenthesized pattern")}};G.checkExpressionErrors=function(e,t){if(!e){return false}var i=e.shorthandAssign;var n=e.doubleProto;if(!t){return i>=0||n>=0}if(i>=0){this.raise(i,"Shorthand property assignments are valid only in destructuring patterns")}if(n>=0){this.raiseRecoverable(n,"Redefinition of __proto__ property")}};G.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(r,false,!e);case b._class:if(e){this.unexpected()}return this.parseClass(r,true);case b._if:return this.parseIfStatement(r);case b._return:return this.parseReturnStatement(r);case b._switch:return this.parseSwitchStatement(r);case b._throw:return this.parseThrowStatement(r);case b._try:return this.parseTryStatement(r);case b._const:case b._var:s=s||this.value;if(e&&s!=="var"){this.unexpected()}return this.parseVarStatement(r,s);case b._while:return this.parseWhileStatement(r);case b._with:return this.parseWithStatement(r);case b.braceL:return this.parseBlock(true,r);case b.semi:return this.parseEmptyStatement(r);case b._export:case b._import:if(this.options.ecmaVersion>10&&n===b._import){y.lastIndex=this.pos;var a=y.exec(this.input);var o=this.pos+a[0].length,u=this.input.charCodeAt(o);if(u===40||u===46){return this.parseExpressionStatement(r,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){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 n===b._import?this.parseImport(r):this.parseExport(r,i);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(r,true,!e)}var l=this.value,f=this.parseExpression();if(n===b.name&&f.type==="Identifier"&&this.eat(b.colon)){return this.parseLabeledStatement(r,l,f,e)}else{return this.parseExpressionStatement(r,f)}}};K.parseBreakContinueStatement=function(e,t){var i=t==="break";this.next();if(this.eat(b.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==b.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var n=0;for(;n=6){this.eat(b.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};K.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(z);this.enterScope(0);this.expect(b.parenL);if(this.type===b.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var i=this.isLet();if(this.type===b._var||this.type===b._const||i){var n=this.startNode(),r=i?"let":this.value;this.next();this.parseVar(n,true,r);this.finishNode(n,"VariableDeclaration");if((this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&n.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===b._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,n)}if(t>-1){this.unexpected(t)}return this.parseFor(e,n)}var s=new DestructuringErrors;var a=this.parseExpression(t>-1?"await":true,s);if(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===b._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}this.toAssignable(a,false,s);this.checkLValPattern(a);return this.parseForIn(e,a)}else{this.checkExpressionErrors(s,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,a)};K.parseFunctionStatement=function(e,t,i){this.next();return this.parseFunction(e,X|(i?0:Y),false,t)};K.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(b._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};K.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(b.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};K.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(b.braceL);this.labels.push(Q);this.enterScope(0);var t;for(var i=false;this.type!==b.braceR;){if(this.type===b._case||this.type===b._default){var n=this.type===b._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(n){t.test=this.parseExpression()}else{if(i){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}i=true;t.test=null}this.expect(b.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};K.parseThrowStatement=function(e){this.next();if(v.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var Z=[];K.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===b._catch){var t=this.startNode();this.next();if(this.eat(b.parenL)){t.param=this.parseBindingAtom();var i=t.param.type==="Identifier";this.enterScope(i?P:0);this.checkLValPattern(t.param,i?W:D);this.expect(b.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(b._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};K.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};K.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(z);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};K.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};K.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};K.parseLabeledStatement=function(e,t,i,n){for(var r=0,s=this.labels;r=0;u--){var l=this.labels[u];if(l.statementStart===e.start){l.statementStart=this.start;l.kind=o}else{break}}this.labels.push({name:t,kind:o,statementStart:this.start});e.body=this.parseStatement(n?n.indexOf("label")===-1?n+"label":n:"label");this.labels.pop();e.label=i;return this.finishNode(e,"LabeledStatement")};K.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};K.parseBlock=function(e,t,i){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(b.braceL);if(e){this.enterScope(0)}while(this.type!==b.braceR){var n=this.parseStatement(null);t.body.push(n)}if(i){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};K.parseFor=function(e,t){e.init=t;this.expect(b.semi);e.test=this.type===b.semi?null:this.parseExpression();this.expect(b.semi);e.update=this.type===b.parenR?null:this.parseExpression();this.expect(b.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};K.parseForIn=function(e,t){var i=this.type===b._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!i||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(i?"for-in":"for-of")+" loop variable declaration may not have an initializer")}e.left=t;e.right=i?this.parseExpression():this.parseMaybeAssign();this.expect(b.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,i?"ForInStatement":"ForOfStatement")};K.parseVar=function(e,t,i){e.declarations=[];e.kind=i;for(;;){var n=this.startNode();this.parseVarId(n,i);if(this.eat(b.eq)){n.init=this.parseMaybeAssign(t)}else if(i==="const"&&!(this.type===b._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(n.id.type!=="Identifier"&&!(t&&(this.type===b._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{n.init=null}e.declarations.push(this.finishNode(n,"VariableDeclarator"));if(!this.eat(b.comma)){break}}return e};K.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLValPattern(e.id,t==="var"?B:D,false)};var X=1,Y=2,J=4;K.parseFunction=function(e,t,i,n){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!n){if(this.type===b.star&&t&Y){this.unexpected()}e.generator=this.eat(b.star)}if(this.options.ecmaVersion>=8){e.async=!!n}if(t&X){e.id=t&J&&this.type!==b.name?null:this.parseIdent();if(e.id&&!(t&Y)){this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?B:D:$)}}var r=this.yieldPos,s=this.awaitPos,a=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&X)){e.id=this.type===b.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,i,false);this.yieldPos=r;this.awaitPos=s;this.awaitIdentPos=a;return this.finishNode(e,t&X?"FunctionDeclaration":"FunctionExpression")};K.parseFunctionParams=function(e){this.expect(b.parenL);e.params=this.parseBindingList(b.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};K.parseClass=function(e,t){this.next();var i=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var n=this.enterClassBody();var r=this.startNode();var s=false;r.body=[];this.expect(b.braceL);while(this.type!==b.braceR){var a=this.parseClassElement(e.superClass!==null);if(a){r.body.push(a);if(a.type==="MethodDefinition"&&a.kind==="constructor"){if(s){this.raise(a.start,"Duplicate constructor in the same class")}s=true}else if(a.key.type==="PrivateIdentifier"&&isPrivateNameConflicted(n,a)){this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared")}}}this.strict=i;this.next();e.body=this.finishNode(r,"ClassBody");this.exitClassBody();return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};K.parseClassElement=function(e){if(this.eat(b.semi)){return null}var t=this.options.ecmaVersion;var i=this.startNode();var n="";var r=false;var s=false;var a="method";i.static=false;if(this.eatContextual("static")){if(this.isClassElementNameStart()||this.type===b.star){i.static=true}else{n="static"}}if(!n&&t>=8&&this.eatContextual("async")){if((this.isClassElementNameStart()||this.type===b.star)&&!this.canInsertSemicolon()){s=true}else{n="async"}}if(!n&&(t>=9||!s)&&this.eat(b.star)){r=true}if(!n&&!s&&!r){var o=this.value;if(this.eatContextual("get")||this.eatContextual("set")){if(this.isClassElementNameStart()){a=o}else{n=o}}}if(n){i.computed=false;i.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc);i.key.name=n;this.finishNode(i.key,"Identifier")}else{this.parseClassElementName(i)}if(t<13||this.type===b.parenL||a!=="method"||r||s){var u=!i.static&&checkKeyName(i,"constructor");var l=u&&e;if(u&&a!=="method"){this.raise(i.key.start,"Constructor can't have get/set modifier")}i.kind=u?"constructor":a;this.parseClassMethod(i,r,s,l)}else{this.parseClassField(i)}return i};K.isClassElementNameStart=function(){return this.type===b.name||this.type===b.privateId||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword};K.parseClassElementName=function(e){if(this.type===b.privateId){if(this.value==="constructor"){this.raise(this.start,"Classes can't have an element named '#constructor'")}e.computed=false;e.key=this.parsePrivateIdent()}else{this.parsePropertyName(e)}};K.parseClassMethod=function(e,t,i,n){var r=e.key;if(e.kind==="constructor"){if(t){this.raise(r.start,"Constructor can't be a generator")}if(i){this.raise(r.start,"Constructor can't be an async method")}}else if(e.static&&checkKeyName(e,"prototype")){this.raise(r.start,"Classes may not have a static property named prototype")}var s=e.value=this.parseMethod(t,i,n);if(e.kind==="get"&&s.params.length!==0){this.raiseRecoverable(s.start,"getter should have no params")}if(e.kind==="set"&&s.params.length!==1){this.raiseRecoverable(s.start,"setter should have exactly one param")}if(e.kind==="set"&&s.params[0].type==="RestElement"){this.raiseRecoverable(s.params[0].start,"Setter cannot use rest params")}return this.finishNode(e,"MethodDefinition")};K.parseClassField=function(e){if(checkKeyName(e,"constructor")){this.raise(e.key.start,"Classes can't have a field named 'constructor'")}else if(e.static&&checkKeyName(e,"prototype")){this.raise(e.key.start,"Classes can't have a static field named 'prototype'")}if(this.eat(b.eq)){var t=this.currentThisScope();var i=t.inClassFieldInit;t.inClassFieldInit=true;e.value=this.parseMaybeAssign();t.inClassFieldInit=i}else{e.value=null}this.semicolon();return this.finishNode(e,"PropertyDefinition")};K.parseClassId=function(e,t){if(this.type===b.name){e.id=this.parseIdent();if(t){this.checkLValSimple(e.id,D,false)}}else{if(t===true){this.unexpected()}e.id=null}};K.parseClassSuper=function(e){e.superClass=this.eat(b._extends)?this.parseExprSubscripts():null};K.enterClassBody=function(){var e={declared:Object.create(null),used:[]};this.privateNameStack.push(e);return e.declared};K.exitClassBody=function(){var e=this.privateNameStack.pop();var t=e.declared;var i=e.used;var n=this.privateNameStack.length;var r=n===0?null:this.privateNameStack[n-1];for(var s=0;s=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==b.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(b._default)){this.checkExport(t,"default",this.lastTokStart);var i;if(this.type===b._function||(i=this.isAsyncFunction())){var n=this.startNode();this.next();if(i){this.next()}e.declaration=this.parseFunction(n,X|J,false,i)}else if(this.type===b._class){var r=this.startNode();e.declaration=this.parseClass(r,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==b.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var s=0,a=e.specifiers;s=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(i){this.checkPatternErrors(i,true)}for(var n=0,r=e.properties;n=8&&!s&&a.name==="async"&&!this.canInsertSemicolon()&&this.eat(b._function)){return this.parseFunction(this.startNodeAt(n,r),0,false,true)}if(i&&!this.canInsertSemicolon()){if(this.eat(b.arrow)){return this.parseArrowExpression(this.startNodeAt(n,r),[a],false)}if(this.options.ecmaVersion>=8&&a.name==="async"&&this.type===b.name&&!s&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc)){a=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(b.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(n,r),[a],true)}}return a;case b.regexp:var o=this.value;t=this.parseLiteral(o.value);t.regex={pattern:o.pattern,flags:o.flags};return t;case b.num:case b.string:return this.parseLiteral(this.value);case b._null:case b._true:case b._false:t=this.startNode();t.value=this.type===b._null?null:this.type===b._true;t.raw=this.type.keyword;this.next();return this.finishNode(t,"Literal");case b.parenL:var u=this.start,l=this.parseParenAndDistinguishExpression(i);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(l)){e.parenthesizedAssign=u}if(e.parenthesizedBind<0){e.parenthesizedBind=u}}return l;case b.bracketL:t=this.startNode();this.next();t.elements=this.parseExprList(b.bracketR,true,true,e);return this.finishNode(t,"ArrayExpression");case b.braceL:return this.parseObj(false,e);case b._function:t=this.startNode();this.next();return this.parseFunction(t,0);case b._class:return this.parseClass(this.startNode(),false);case b._new:return this.parseNew();case b.backQuote:return this.parseTemplate();case b._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};te.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case b.parenL:return this.parseDynamicImport(e);case b.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};te.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(b.parenR)){var t=this.start;if(this.eat(b.comma)&&this.eat(b.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};te.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};te.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};te.parseParenExpression=function(){this.expect(b.parenL);var e=this.parseExpression();this.expect(b.parenR);return e};te.parseParenAndDistinguishExpression=function(e){var t=this.start,i=this.startLoc,n,r=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var s=this.start,a=this.startLoc;var o=[],u=true,l=false;var f=new DestructuringErrors,c=this.yieldPos,h=this.awaitPos,p;this.yieldPos=0;this.awaitPos=0;while(this.type!==b.parenR){u?u=false:this.expect(b.comma);if(r&&this.afterTrailingComma(b.parenR,true)){l=true;break}else if(this.type===b.ellipsis){p=this.start;o.push(this.parseParenItem(this.parseRestBinding()));if(this.type===b.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{o.push(this.parseMaybeAssign(false,f,this.parseParenItem))}}var d=this.start,v=this.startLoc;this.expect(b.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(b.arrow)){this.checkPatternErrors(f,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=c;this.awaitPos=h;return this.parseParenArrowList(t,i,o)}if(!o.length||l){this.unexpected(this.lastTokStart)}if(p){this.unexpected(p)}this.checkExpressionErrors(f,true);this.yieldPos=c||this.yieldPos;this.awaitPos=h||this.awaitPos;if(o.length>1){n=this.startNodeAt(s,a);n.expressions=o;this.finishNodeAt(n,"SequenceExpression",d,v)}else{n=o[0]}}else{n=this.parseParenExpression()}if(this.options.preserveParens){var g=this.startNodeAt(t,i);g.expression=n;return this.finishNode(g,"ParenthesizedExpression")}else{return n}};te.parseParenItem=function(e){return e};te.parseParenArrowList=function(e,t,i){return this.parseArrowExpression(this.startNodeAt(e,t),i)};var ie=[];te.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(b.dot)){e.meta=t;var i=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(i){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.inNonArrowFunction){this.raiseRecoverable(e.start,"'new.target' can only be used in functions")}return this.finishNode(e,"MetaProperty")}var n=this.start,r=this.startLoc,s=this.type===b._import;e.callee=this.parseSubscripts(this.parseExprAtom(),n,r,true);if(s&&e.callee.type==="ImportExpression"){this.raise(n,"Cannot use new with import()")}if(this.eat(b.parenL)){e.arguments=this.parseExprList(b.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=ie}return this.finishNode(e,"NewExpression")};te.parseTemplateElement=function(e){var t=e.isTagged;var i=this.startNode();if(this.type===b.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}i.value={raw:this.value,cooked:null}}else{i.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();i.tail=this.type===b.backQuote;return this.finishNode(i,"TemplateElement")};te.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var i=this.startNode();this.next();i.expressions=[];var n=this.parseTemplateElement({isTagged:t});i.quasis=[n];while(!n.tail){if(this.type===b.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(b.dollarBraceL);i.expressions.push(this.parseExpression());this.expect(b.braceR);i.quasis.push(n=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(i,"TemplateLiteral")};te.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===b.name||this.type===b.num||this.type===b.string||this.type===b.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===b.star)&&!v.test(this.input.slice(this.lastTokEnd,this.start))};te.parseObj=function(e,t){var i=this.startNode(),n=true,r={};i.properties=[];this.next();while(!this.eat(b.braceR)){if(!n){this.expect(b.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(b.braceR)){break}}else{n=false}var s=this.parseProperty(e,t);if(!e){this.checkPropClash(s,r,t)}i.properties.push(s)}return this.finishNode(i,e?"ObjectPattern":"ObjectExpression")};te.parseProperty=function(e,t){var i=this.startNode(),n,r,s,a;if(this.options.ecmaVersion>=9&&this.eat(b.ellipsis)){if(e){i.argument=this.parseIdent(false);if(this.type===b.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(i,"RestElement")}if(this.type===b.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}i.argument=this.parseMaybeAssign(false,t);if(this.type===b.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(i,"SpreadElement")}if(this.options.ecmaVersion>=6){i.method=false;i.shorthand=false;if(e||t){s=this.start;a=this.startLoc}if(!e){n=this.eat(b.star)}}var o=this.containsEsc;this.parsePropertyName(i);if(!e&&!o&&this.options.ecmaVersion>=8&&!n&&this.isAsyncProp(i)){r=true;n=this.options.ecmaVersion>=9&&this.eat(b.star);this.parsePropertyName(i,t)}else{r=false}this.parsePropertyValue(i,e,n,r,s,a,t,o);return this.finishNode(i,"Property")};te.parsePropertyValue=function(e,t,i,n,r,s,a,o){if((i||n)&&this.type===b.colon){this.unexpected()}if(this.eat(b.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,a);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===b.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(i,n)}else if(!t&&!o&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==b.comma&&this.type!==b.braceR&&this.type!==b.eq)){if(i||n){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var u=e.kind==="get"?0:1;if(e.value.params.length!==u){var l=e.value.start;if(e.kind==="get"){this.raiseRecoverable(l,"getter should have no params")}else{this.raiseRecoverable(l,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(i||n){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=r}e.kind="init";if(t){e.value=this.parseMaybeDefault(r,s,this.copyNode(e.key))}else if(this.type===b.eq&&a){if(a.shorthandAssign<0){a.shorthandAssign=this.start}e.value=this.parseMaybeDefault(r,s,this.copyNode(e.key))}else{e.value=this.copyNode(e.key)}e.shorthand=true}else{this.unexpected()}};te.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(b.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(b.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===b.num||this.type===b.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};te.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};te.parseMethod=function(e,t,i){var n=this.startNode(),r=this.yieldPos,s=this.awaitPos,a=this.awaitIdentPos;this.initFunction(n);if(this.options.ecmaVersion>=6){n.generator=e}if(this.options.ecmaVersion>=8){n.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,n.generator)|M|(i?H:0));this.expect(b.parenL);n.params=this.parseBindingList(b.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(n,false,true);this.yieldPos=r;this.awaitPos=s;this.awaitIdentPos=a;return this.finishNode(n,"FunctionExpression")};te.parseArrowExpression=function(e,t,i){var n=this.yieldPos,r=this.awaitPos,s=this.awaitIdentPos;this.enterScope(functionFlags(i,false)|L);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!i}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false);this.yieldPos=n;this.awaitPos=r;this.awaitIdentPos=s;return this.finishNode(e,"ArrowFunctionExpression")};te.parseFunctionBody=function(e,t,i){var n=t&&this.type!==b.braceL;var r=this.strict,s=false;if(n){e.body=this.parseMaybeAssign();e.expression=true;this.checkParams(e,false)}else{var a=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!r||a){s=this.strictDirective(this.end);if(s&&a){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var o=this.labels;this.labels=[];if(s){this.strict=true}this.checkParams(e,!r&&!s&&!t&&!i&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLValSimple(e.id,U)}e.body=this.parseBlock(false,undefined,s&&!r);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=o}this.exitScope()};te.isSimpleParamList=function(e){for(var t=0,i=e;t-1||r.functions.indexOf(e)>-1||r.var.indexOf(e)>-1;r.lexical.push(e);if(this.inModule&&r.flags&C){delete this.undefinedExports[e]}}else if(t===W){var s=this.currentScope();s.lexical.push(e)}else if(t===$){var a=this.currentScope();if(this.treatFunctionsAsVar){n=a.lexical.indexOf(e)>-1}else{n=a.lexical.indexOf(e)>-1||a.var.indexOf(e)>-1}a.functions.push(e)}else{for(var o=this.scopeStack.length-1;o>=0;--o){var u=this.scopeStack[o];if(u.lexical.indexOf(e)>-1&&!(u.flags&P&&u.lexical[0]===e)||!this.treatFunctionsAsVarInScope(u)&&u.functions.indexOf(e)>-1){n=true;break}u.var.push(e);if(this.inModule&&u.flags&C){delete this.undefinedExports[e]}if(u.flags&O){break}}}if(n){this.raiseRecoverable(i,"Identifier '"+e+"' has already been declared")}};re.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};re.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};re.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&O){return t}}};re.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&O&&!(t.flags&L)){return t}}};var ae=function Node(e,t,i){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new A(e,i)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var oe=j.prototype;oe.startNode=function(){return new ae(this,this.start,this.startLoc)};oe.startNodeAt=function(e,t){return new ae(this,e,t)};function finishNodeAt(e,t,i,n){e.type=t;e.end=i;if(this.options.locations){e.loc.end=n}if(this.options.ranges){e.range[1]=i}return e}oe.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};oe.finishNodeAt=function(e,t,i,n){return finishNodeAt.call(this,e,t,i,n)};oe.copyNode=function(e){var t=new ae(this,e.start,this.startLoc);for(var i in e){t[i]=e[i]}return t};var ue=function TokContext(e,t,i,n,r){this.token=e;this.isExpr=!!t;this.preserveSpace=!!i;this.override=n;this.generator=!!r};var le={b_stat:new ue("{",false),b_expr:new ue("{",true),b_tmpl:new ue("${",false),p_stat:new ue("(",false),p_expr:new ue("(",true),q_tmpl:new ue("`",true,true,function(e){return e.tryReadTemplateToken()}),f_stat:new ue("function",false),f_expr:new ue("function",true),f_expr_gen:new ue("function",true,false,null,true),f_gen:new ue("function",false,false,null,true)};var fe=j.prototype;fe.initialContext=function(){return[le.b_stat]};fe.braceIsBlock=function(e){var t=this.curContext();if(t===le.f_expr||t===le.f_stat){return true}if(e===b.colon&&(t===le.b_stat||t===le.b_expr)){return!t.isExpr}if(e===b._return||e===b.name&&this.exprAllowed){return v.test(this.input.slice(this.lastTokEnd,this.start))}if(e===b._else||e===b.semi||e===b.eof||e===b.parenR||e===b.arrow){return true}if(e===b.braceL){return t===le.b_stat}if(e===b._var||e===b._const||e===b.name){return false}return!this.exprAllowed};fe.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if(t.token==="function"){return t.generator}}return false};fe.updateContext=function(e){var t,i=this.type;if(i.keyword&&e===b.dot){this.exprAllowed=false}else if(t=i.updateContext){t.call(this,e)}else{this.exprAllowed=i.beforeExpr}};b.parenR.updateContext=b.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var e=this.context.pop();if(e===le.b_stat&&this.curContext().token==="function"){e=this.context.pop()}this.exprAllowed=!e.isExpr};b.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?le.b_stat:le.b_expr);this.exprAllowed=true};b.dollarBraceL.updateContext=function(){this.context.push(le.b_tmpl);this.exprAllowed=true};b.parenL.updateContext=function(e){var t=e===b._if||e===b._for||e===b._with||e===b._while;this.context.push(t?le.p_stat:le.p_expr);this.exprAllowed=true};b.incDec.updateContext=function(){};b._function.updateContext=b._class.updateContext=function(e){if(e.beforeExpr&&e!==b._else&&!(e===b.semi&&this.curContext()!==le.p_stat)&&!(e===b._return&&v.test(this.input.slice(this.lastTokEnd,this.start)))&&!((e===b.colon||e===b.braceL)&&this.curContext()===le.b_stat)){this.context.push(le.f_expr)}else{this.context.push(le.f_stat)}this.exprAllowed=false};b.backQuote.updateContext=function(){if(this.curContext()===le.q_tmpl){this.context.pop()}else{this.context.push(le.q_tmpl)}this.exprAllowed=false};b.star.updateContext=function(e){if(e===b._function){var t=this.context.length-1;if(this.context[t]===le.f_expr){this.context[t]=le.f_expr_gen}else{this.context[t]=le.f_gen}}this.exprAllowed=true};b.name.updateContext=function(e){var t=false;if(this.options.ecmaVersion>=6&&e!==b.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){t=true}}this.exprAllowed=t};var ce="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 he=ce+" Extended_Pictographic";var pe=he;var de=pe+" EBase EComp EMod EPres ExtPict";var be={9:ce,10:he,11:pe,12:de};var ve="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";var ge="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 _e=ge+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ye=_e+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var me=ye+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";var xe={9:ge,10:_e,11:ye,12:me};var Ee={};function buildUnicodeData(e){var t=Ee[e]={binary:wordsRegexp(be[e]+" "+ve),nonBinary:{General_Category:wordsRegexp(ve),Script:wordsRegexp(xe[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);buildUnicodeData(12);var we=j.prototype;var Se=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"");this.unicodeProperties=Ee[e.options.ecmaVersion>=12?12:e.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=[]};Se.prototype.reset=function reset(e,t,i){var n=i.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=i;this.switchU=n&&this.parser.options.ecmaVersion>=6;this.switchN=n&&this.parser.options.ecmaVersion>=9};Se.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};Se.prototype.at=function at(e,t){if(t===void 0)t=false;var i=this.source;var n=i.length;if(e>=n){return-1}var r=i.charCodeAt(e);if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=n){return r}var s=i.charCodeAt(e+1);return s>=56320&&s<=57343?(r<<10)+s-56613888:r};Se.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var i=this.source;var n=i.length;if(e>=n){return n}var r=i.charCodeAt(e),s;if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=n||(s=i.charCodeAt(e+1))<56320||s>57343){return e+1}return e+2};Se.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};Se.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};Se.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};Se.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}we.validateRegExpFlags=function(e){var t=e.validFlags;var i=e.flags;for(var n=0;n-1){this.raise(e.start,"Duplicate regular expression flag")}}};we.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};we.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,i=e.backReferenceNames;t=9){i=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!i;return true}}e.pos=t;return false};we.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};we.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};we.regexp_eatBracedQuantifier=function(e,t){var i=e.pos;if(e.eat(123)){var n=0,r=-1;if(this.regexp_eatDecimalDigits(e)){n=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){r=e.lastIntValue}if(e.eat(125)){if(r!==-1&&r=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};we.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};we.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};we.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}we.regexp_eatPatternCharacters=function(e){var t=e.pos;var i=0;while((i=e.current())!==-1&&!isSyntaxCharacter(i)){e.advance()}return e.pos!==t};we.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};we.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};we.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};we.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString(e.lastIntValue)}return true}return false};we.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var i=this.options.ecmaVersion>=11;var n=e.current(i);e.advance(i);if(n===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)){n=e.lastIntValue}if(isRegExpIdentifierStart(n)){e.lastIntValue=n;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}we.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var i=this.options.ecmaVersion>=11;var n=e.current(i);e.advance(i);if(n===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)){n=e.lastIntValue}if(isRegExpIdentifierPart(n)){e.lastIntValue=n;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}we.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};we.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var i=e.lastIntValue;if(e.switchU){if(i>e.maxBackReference){e.maxBackReference=i}return true}if(i<=e.numCapturingParens){return true}e.pos=t}return false};we.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};we.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};we.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};we.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};we.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};we.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}we.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var i=e.pos;var n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var r=e.lastIntValue;if(n&&r>=55296&&r<=56319){var s=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var a=e.lastIntValue;if(a>=56320&&a<=57343){e.lastIntValue=(r-55296)*1024+(a-56320)+65536;return true}}e.pos=s;e.lastIntValue=r}return true}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(n){e.raise("Invalid unicode escape")}e.pos=i}return false};function isValidUnicode(e){return e>=0&&e<=1114111}we.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};we.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};we.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}we.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var i=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var n=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,i,n);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var r=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,r);return true}return false};we.regexp_validateUnicodePropertyNameAndValue=function(e,t,i){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(i)){e.raise("Invalid property value")}};we.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};we.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}we.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}we.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};we.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};we.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var i=e.lastIntValue;if(e.switchU&&(t===-1||i===-1)){e.raise("Invalid character class")}if(t!==-1&&i!==-1&&t>i){e.raise("Range out of order in character class")}}}};we.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var i=e.current();if(i===99||isOctalDigit(i)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var n=e.current();if(n!==93){e.lastIntValue=n;e.advance();return true}return false};we.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};we.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};we.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};we.regexp_eatDecimalDigits=function(e){var t=e.pos;var i=0;e.lastIntValue=0;while(isDecimalDigit(i=e.current())){e.lastIntValue=10*e.lastIntValue+(i-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}we.regexp_eatHexDigits=function(e){var t=e.pos;var i=0;e.lastIntValue=0;while(isHexDigit(i=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(i);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}we.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var i=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+i*8+e.lastIntValue}else{e.lastIntValue=t*8+i}}else{e.lastIntValue=t}return true}return false};we.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}we.regexp_eatFixedHexDigits=function(e,t){var i=e.pos;e.lastIntValue=0;for(var n=0;n=this.input.length){return this.finishToken(b.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};Re.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};Re.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320){return e}var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888};Re.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,i=this.input.indexOf("*/",this.pos+=2);if(i===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=i+2;if(this.options.locations){g.lastIndex=t;var n;while((n=g.exec(this.input))&&n.index8&&e<14||e>=5760&&_.test(String.fromCharCode(e))){++this.pos}else{break e}}}};Re.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var i=this.type;this.type=e;this.value=t;this.updateContext(i)};Re.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(b.ellipsis)}else{++this.pos;return this.finishToken(b.dot)}};Re.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(b.assign,2)}return this.finishOp(b.slash,1)};Re.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var i=1;var n=e===42?b.star:b.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++i;n=b.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(b.assign,i+1)}return this.finishOp(n,i)};Re.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var i=this.input.charCodeAt(this.pos+2);if(i===61){return this.finishOp(b.assign,3)}}return this.finishOp(e===124?b.logicalOR:b.logicalAND,2)}if(t===61){return this.finishOp(b.assign,2)}return this.finishOp(e===124?b.bitwiseOR:b.bitwiseAND,1)};Re.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(b.assign,2)}return this.finishOp(b.bitwiseXOR,1)};Re.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||v.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(b.incDec,2)}if(t===61){return this.finishOp(b.assign,2)}return this.finishOp(b.plusMin,1)};Re.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var i=1;if(t===e){i=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+i)===61){return this.finishOp(b.assign,i+1)}return this.finishOp(b.bitShift,i)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){i=2}return this.finishOp(b.relational,i)};Re.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(b.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(b.arrow)}return this.finishOp(e===61?b.eq:b.prefix,1)};Re.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var i=this.input.charCodeAt(this.pos+2);if(i<48||i>57){return this.finishOp(b.questionDot,2)}}if(t===63){if(e>=12){var n=this.input.charCodeAt(this.pos+2);if(n===61){return this.finishOp(b.assign,3)}}return this.finishOp(b.coalesce,2)}}return this.finishOp(b.question,1)};Re.readToken_numberSign=function(){var e=this.options.ecmaVersion;var t=35;if(e>=13){++this.pos;t=this.fullCharCodeAtPos();if(isIdentifierStart(t,true)||t===92){return this.finishToken(b.privateId,this.readWord1())}}this.raise(this.pos,"Unexpected character '"+codePointToString$1(t)+"'")};Re.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(b.parenL);case 41:++this.pos;return this.finishToken(b.parenR);case 59:++this.pos;return this.finishToken(b.semi);case 44:++this.pos;return this.finishToken(b.comma);case 91:++this.pos;return this.finishToken(b.bracketL);case 93:++this.pos;return this.finishToken(b.bracketR);case 123:++this.pos;return this.finishToken(b.braceL);case 125:++this.pos;return this.finishToken(b.braceR);case 58:++this.pos;return this.finishToken(b.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(b.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(b.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+codePointToString$1(e)+"'")};Re.finishOp=function(e,t){var i=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,i)};Re.readRegexp=function(){var e,t,i=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(i,"Unterminated regular expression")}var n=this.input.charAt(this.pos);if(v.test(n)){this.raise(i,"Unterminated regular expression")}if(!e){if(n==="["){t=true}else if(n==="]"&&t){t=false}else if(n==="/"&&!t){break}e=n==="\\"}else{e=false}++this.pos}var r=this.input.slice(i,this.pos);++this.pos;var s=this.pos;var a=this.readWord1();if(this.containsEsc){this.unexpected(s)}var o=this.regexpState||(this.regexpState=new Se(this));o.reset(i,r,a);this.validateRegExpFlags(o);this.validateRegExpPattern(o);var u=null;try{u=new RegExp(r,a)}catch(e){}return this.finishToken(b.regexp,{pattern:r,flags:a,value:u})};Re.readInt=function(e,t,i){var n=this.options.ecmaVersion>=12&&t===undefined;var r=i&&this.input.charCodeAt(this.pos)===48;var s=this.pos,a=0,o=0;for(var u=0,l=t==null?Infinity:t;u=97){c=f-97+10}else if(f>=65){c=f-65+10}else if(f>=48&&f<=57){c=f-48}else{c=Infinity}if(c>=e){break}o=f;a=a*e+c}if(n&&o===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===s||t!=null&&this.pos-s!==t){return null}return a};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}Re.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var i=this.readInt(e);if(i==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){i=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(b.num,i)};Re.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var i=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(i&&this.strict){this.raise(t,"Invalid number")}var n=this.input.charCodeAt(this.pos);if(!i&&!e&&this.options.ecmaVersion>=11&&n===110){var r=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(b.num,r)}if(i&&/[89]/.test(this.input.slice(t,this.pos))){i=false}if(n===46&&!i){++this.pos;this.readInt(10);n=this.input.charCodeAt(this.pos)}if((n===69||n===101)&&!i){n=this.input.charCodeAt(++this.pos);if(n===43||n===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var s=stringToNumber(this.input.slice(t,this.pos),i);return this.finishToken(b.num,s)};Re.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var i=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(i,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Re.readString=function(e){var t="",i=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var n=this.input.charCodeAt(this.pos);if(n===e){break}if(n===92){t+=this.input.slice(i,this.pos);t+=this.readEscapedChar(false);i=this.pos}else{if(isNewLine(n,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(i,this.pos++);return this.finishToken(b.string,t)};var ke={};Re.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===ke){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};Re.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw ke}else{this.raise(e,t)}};Re.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var i=this.input.charCodeAt(this.pos);if(i===96||i===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===b.template||this.type===b.invalidTemplate)){if(i===36){this.pos+=2;return this.finishToken(b.dollarBraceL)}else{++this.pos;return this.finishToken(b.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(b.template,e)}if(i===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(i)){e+=this.input.slice(t,this.pos);++this.pos;switch(i){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(i);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};Re.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var n=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var r=parseInt(n,8);if(r>255){n=n.slice(0,-1);r=parseInt(n,8)}this.pos+=n.length-1;t=this.input.charCodeAt(this.pos);if((n!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-n.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(r)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};Re.readHexChar=function(e){var t=this.pos;var i=this.readInt(16,e);if(i===null){this.invalidStringToken(t,"Bad character escape sequence")}return i};Re.readWord1=function(){this.containsEsc=false;var e="",t=true,i=this.pos;var n=this.options.ecmaVersion>=6;while(this.pos{"use strict";function isArguments(e){return e!=null&&typeof e==="object"&&e.hasOwnProperty("callee")}var t={"*":{label:"any",check:function(){return true}},A:{label:"array",check:function(e){return Array.isArray(e)||isArguments(e)}},S:{label:"string",check:function(e){return typeof e==="string"}},N:{label:"number",check:function(e){return typeof e==="number"}},F:{label:"function",check:function(e){return typeof e==="function"}},O:{label:"object",check:function(e){return typeof e==="object"&&e!=null&&!t.A.check(e)&&!t.E.check(e)}},B:{label:"boolean",check:function(e){return typeof e==="boolean"}},E:{label:"error",check:function(e){return e instanceof Error}},Z:{label:"null",check:function(e){return e==null}}};function addSchema(e,t){var i=t[e.length]=t[e.length]||[];if(i.indexOf(e)===-1)i.push(e)}var i=e.exports=function(e,i){if(arguments.length!==2)throw wrongNumberOfArgs(["SA"],arguments.length);if(!e)throw missingRequiredArg(0,"rawSchemas");if(!i)throw missingRequiredArg(1,"args");if(!t.S.check(e))throw invalidType(0,["string"],e);if(!t.A.check(i))throw invalidType(1,["array"],i);var n=e.split("|");var r={};n.forEach(function(e){for(var i=0;i{"use strict";t.TrackerGroup=i(5383);t.Tracker=i(3267);t.TrackerStream=i(4754)},122:(e,t,i)=>{"use strict";var n=i(8614).EventEmitter;var r=i(1669);var s=0;var a=e.exports=function(e){n.call(this);this.id=++s;this.name=e};r.inherits(a,n)},5383:(e,t,i)=>{"use strict";var n=i(1669);var r=i(122);var s=i(3267);var a=i(4754);var o=e.exports=function(e){r.call(this,e);this.parentGroup=null;this.trackers=[];this.completion={};this.weight={};this.totalWeight=0;this.finished=false;this.bubbleChange=bubbleChange(this)};n.inherits(o,r);function bubbleChange(e){return function(t,i,n){e.completion[n.id]=i;if(e.finished)return;e.emit("change",t||e.name,e.completed(),e)}}o.prototype.nameInTree=function(){var e=[];var t=this;while(t){e.unshift(t.name);t=t.parentGroup}return e.join("/")};o.prototype.addUnit=function(e,t){if(e.addUnit){var i=this;while(i){if(e===i){throw new Error("Attempted to add tracker group "+e.name+" to tree that already includes it "+this.nameInTree(this))}i=i.parentGroup}e.parentGroup=this}this.weight[e.id]=t||1;this.totalWeight+=this.weight[e.id];this.trackers.push(e);this.completion[e.id]=e.completed();e.on("change",this.bubbleChange);if(!this.finished)this.emit("change",e.name,this.completion[e.id],e);return e};o.prototype.completed=function(){if(this.trackers.length===0)return 0;var e=1/this.totalWeight;var t=0;for(var i=0;i{"use strict";var n=i(1669);var r=i(8193);var s=i(5458);var a=i(3267);var o=e.exports=function(e,t,i){r.Transform.call(this,i);this.tracker=new a(e,t);this.name=e;this.id=this.tracker.id;this.tracker.on("change",delegateChange(this))};n.inherits(o,r.Transform);function delegateChange(e){return function(t,i,n){e.emit("change",t,i,e)}}o.prototype._transform=function(e,t,i){this.tracker.completeWork(e.length?e.length:1);this.push(e);i()};o.prototype._flush=function(e){this.tracker.finish();e()};s(o.prototype,"tracker").method("completed").method("addWork").method("finish")},3267:(e,t,i)=>{"use strict";var n=i(1669);var r=i(122);var s=e.exports=function(e,t){r.call(this,e);this.workDone=0;this.workTodo=t||0};n.inherits(s,r);s.prototype.completed=function(){return this.workTodo===0?0:this.workDone/this.workTodo};s.prototype.addWork=function(e){this.workTodo+=e;this.emit("change",this.name,this.completed(),this)};s.prototype.completeWork=function(e){this.workDone+=e;if(this.workDone>this.workTodo)this.workDone=this.workTodo;this.emit("change",this.name,this.completed(),this)};s.prototype.finish=function(){this.workTodo=this.workDone=1;this.emit("change",this.name,1,this)}},9341:(module,exports,__nccwpck_require__)=>{var fs=__nccwpck_require__(5747),path=__nccwpck_require__(5622),fileURLToPath=__nccwpck_require__(7986),join=path.join,dirname=path.dirname,exists=fs.accessSync&&function(e){try{fs.accessSync(e)}catch(e){return false}return true}||fs.existsSync||path.existsSync,defaults={arrow:process.env.NODE_BINDINGS_ARROW||" → ",compiled:process.env.NODE_BINDINGS_COMPILED_DIR||"compiled",platform:process.platform,arch:process.arch,nodePreGyp:"node-v"+process.versions.modules+"-"+process.platform+"-"+process.arch,version:process.versions.node,bindings:"bindings.node",try:[["module_root","build","bindings"],["module_root","build","Debug","bindings"],["module_root","build","Release","bindings"],["module_root","out","Debug","bindings"],["module_root","Debug","bindings"],["module_root","out","Release","bindings"],["module_root","Release","bindings"],["module_root","build","default","bindings"],["module_root","compiled","version","platform","arch","bindings"],["module_root","addon-build","release","install-root","bindings"],["module_root","addon-build","debug","install-root","bindings"],["module_root","addon-build","default","install-root","bindings"],["module_root","lib","binding","nodePreGyp","bindings"]]};function bindings(opts){if(typeof opts=="string"){opts={bindings:opts}}else if(!opts){opts={}}Object.keys(defaults).map(function(e){if(!(e in opts))opts[e]=defaults[e]});if(!opts.module_root){opts.module_root=exports.getRoot(exports.getFileName())}if(path.extname(opts.bindings)!=".node"){opts.bindings+=".node"}var requireFunc=true?eval("require"):0;var tries=[],i=0,l=opts.try.length,n,b,err;for(;i{"use strict";const n=i(2698);const r=i(3047);const s=i(2482);const a=i(5900);const o=(e,t={})=>{let i=[];if(Array.isArray(e)){for(let n of e){let e=o.create(n,t);if(Array.isArray(e)){i.push(...e)}else{i.push(e)}}}else{i=[].concat(o.create(e,t))}if(t&&t.expand===true&&t.nodupes===true){i=[...new Set(i)]}return i};o.parse=((e,t={})=>a(e,t));o.stringify=((e,t={})=>{if(typeof e==="string"){return n(o.parse(e,t),t)}return n(e,t)});o.compile=((e,t={})=>{if(typeof e==="string"){e=o.parse(e,t)}return r(e,t)});o.expand=((e,t={})=>{if(typeof e==="string"){e=o.parse(e,t)}let i=s(e,t);if(t.noempty===true){i=i.filter(Boolean)}if(t.nodupes===true){i=[...new Set(i)]}return i});o.create=((e,t={})=>{if(e===""||e.length<3){return[e]}return t.expand!==true?o.compile(e,t):o.expand(e,t)});e.exports=o},3047:(e,t,i)=>{"use strict";const n=i(5955);const r=i(8130);const s=(e,t={})=>{let i=(e,s={})=>{let a=r.isInvalidBrace(s);let o=e.invalid===true&&t.escapeInvalid===true;let u=a===true||o===true;let l=t.escapeInvalid===true?"\\":"";let f="";if(e.isOpen===true){return l+e.value}if(e.isClose===true){return l+e.value}if(e.type==="open"){return u?l+e.value:"("}if(e.type==="close"){return u?l+e.value:")"}if(e.type==="comma"){return e.prev.type==="comma"?"":u?e.value:"|"}if(e.value){return e.value}if(e.nodes&&e.ranges>0){let i=r.reduce(e.nodes);let s=n(...i,{...t,wrap:false,toRegex:true});if(s.length!==0){return i.length>1&&s.length>1?`(${s})`:s}}if(e.nodes){for(let t of e.nodes){f+=i(t,e)}}return f};return i(e)};e.exports=s},9552:e=>{"use strict";e.exports={MAX_LENGTH:1024*64,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:"\n",CHAR_NO_BREAK_SPACE:" ",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:"\t",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\ufeff"}},2482:(e,t,i)=>{"use strict";const n=i(5955);const r=i(2698);const s=i(8130);const a=(e="",t="",i=false)=>{let n=[];e=[].concat(e);t=[].concat(t);if(!t.length)return e;if(!e.length){return i?s.flatten(t).map(e=>`{${e}}`):t}for(let r of e){if(Array.isArray(r)){for(let e of r){n.push(a(e,t,i))}}else{for(let e of t){if(i===true&&typeof e==="string")e=`{${e}}`;n.push(Array.isArray(e)?a(r,e,i):r+e)}}}return s.flatten(n)};const o=(e,t={})=>{let i=t.rangeLimit===void 0?1e3:t.rangeLimit;let o=(e,u={})=>{e.queue=[];let l=u;let f=u.queue;while(l.type!=="brace"&&l.type!=="root"&&l.parent){l=l.parent;f=l.queue}if(e.invalid||e.dollar){f.push(a(f.pop(),r(e,t)));return}if(e.type==="brace"&&e.invalid!==true&&e.nodes.length===2){f.push(a(f.pop(),["{}"]));return}if(e.nodes&&e.ranges>0){let o=s.reduce(e.nodes);if(s.exceedsLimit(...o,t.step,i)){throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.")}let u=n(...o,t);if(u.length===0){u=r(e,t)}f.push(a(f.pop(),u));e.nodes=[];return}let c=s.encloseBrace(e);let h=e.queue;let p=e;while(p.type!=="brace"&&p.type!=="root"&&p.parent){p=p.parent;h=p.queue}for(let t=0;t{"use strict";const n=i(2698);const{MAX_LENGTH:r,CHAR_BACKSLASH:s,CHAR_BACKTICK:a,CHAR_COMMA:o,CHAR_DOT:u,CHAR_LEFT_PARENTHESES:l,CHAR_RIGHT_PARENTHESES:f,CHAR_LEFT_CURLY_BRACE:c,CHAR_RIGHT_CURLY_BRACE:h,CHAR_LEFT_SQUARE_BRACKET:p,CHAR_RIGHT_SQUARE_BRACKET:d,CHAR_DOUBLE_QUOTE:b,CHAR_SINGLE_QUOTE:v,CHAR_NO_BREAK_SPACE:g,CHAR_ZERO_WIDTH_NOBREAK_SPACE:_}=i(9552);const y=(e,t={})=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}let i=t||{};let y=typeof i.maxLength==="number"?Math.min(r,i.maxLength):r;if(e.length>y){throw new SyntaxError(`Input length (${e.length}), exceeds max characters (${y})`)}let m={type:"root",input:e,nodes:[]};let x=[m];let E=m;let w=m;let S=0;let A=e.length;let R=0;let k=0;let C;let T={};const O=()=>e[R++];const N=e=>{if(e.type==="text"&&w.type==="dot"){w.type="text"}if(w&&w.type==="text"&&e.type==="text"){w.value+=e.value;return}E.nodes.push(e);e.parent=E;e.prev=w;w=e;return e};N({type:"bos"});while(R0){if(E.ranges>0){E.ranges=0;let e=E.nodes.shift();E.nodes=[e,{type:"text",value:n(E)}]}N({type:"comma",value:C});E.commas++;continue}if(C===u&&k>0&&E.commas===0){let e=E.nodes;if(k===0||e.length===0){N({type:"text",value:C});continue}if(w.type==="dot"){E.range=[];w.value+=C;w.type="range";if(E.nodes.length!==3&&E.nodes.length!==5){E.invalid=true;E.ranges=0;w.type="text";continue}E.ranges++;E.args=[];continue}if(w.type==="range"){e.pop();let t=e[e.length-1];t.value+=w.value+C;w=t;E.ranges--;continue}N({type:"dot",value:C});continue}N({type:"text",value:C})}do{E=x.pop();if(E.type!=="root"){E.nodes.forEach(e=>{if(!e.nodes){if(e.type==="open")e.isOpen=true;if(e.type==="close")e.isClose=true;if(!e.nodes)e.type="text";e.invalid=true}});let e=x[x.length-1];let t=e.nodes.indexOf(E);e.nodes.splice(t,1,...E.nodes)}}while(x.length>0);N({type:"eos"});return m};e.exports=y},2698:(e,t,i)=>{"use strict";const n=i(8130);e.exports=((e,t={})=>{let i=(e,r={})=>{let s=t.escapeInvalid&&n.isInvalidBrace(r);let a=e.invalid===true&&t.escapeInvalid===true;let o="";if(e.value){if((s||a)&&n.isOpenOrClose(e)){return"\\"+e.value}return e.value}if(e.value){return e.value}if(e.nodes){for(let t of e.nodes){o+=i(t)}}return o};return i(e)})},8130:(e,t)=>{"use strict";t.isInteger=(e=>{if(typeof e==="number"){return Number.isInteger(e)}if(typeof e==="string"&&e.trim()!==""){return Number.isInteger(Number(e))}return false});t.find=((e,t)=>e.nodes.find(e=>e.type===t));t.exceedsLimit=((e,i,n=1,r)=>{if(r===false)return false;if(!t.isInteger(e)||!t.isInteger(i))return false;return(Number(i)-Number(e))/Number(n)>=r});t.escapeNode=((e,t=0,i)=>{let n=e.nodes[t];if(!n)return;if(i&&n.type===i||n.type==="open"||n.type==="close"){if(n.escaped!==true){n.value="\\"+n.value;n.escaped=true}}});t.encloseBrace=(e=>{if(e.type!=="brace")return false;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}return false});t.isInvalidBrace=(e=>{if(e.type!=="brace")return false;if(e.invalid===true||e.dollar)return true;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}if(e.open!==true||e.close!==true){e.invalid=true;return true}return false});t.isOpenOrClose=(e=>{if(e.type==="open"||e.type==="close"){return true}return e.open===true||e.close===true});t.reduce=(e=>e.reduce((e,t)=>{if(t.type==="text")e.push(t.value);if(t.type==="range")t.type="text";return e},[]));t.flatten=((...e)=>{const t=[];const i=e=>{for(let n=0;n{"use strict";e.exports=function(e,t){if(e===null||e===undefined){throw TypeError()}e=String(e);var i=e.length;var n=t?Number(t):0;if(Number.isNaN(n)){n=0}if(n<0||n>=i){return undefined}var r=e.charCodeAt(n);if(r>=55296&&r<=56319&&i>n+1){var s=e.charCodeAt(n+1);if(s>=56320&&s<=57343){return(r-55296)*1024+s-56320+65536}}return r}},3645:(e,t)=>{"use strict";var i="[";t.up=function up(e){return i+(e||"")+"A"};t.down=function down(e){return i+(e||"")+"B"};t.forward=function forward(e){return i+(e||"")+"C"};t.back=function back(e){return i+(e||"")+"D"};t.nextLine=function nextLine(e){return i+(e||"")+"E"};t.previousLine=function previousLine(e){return i+(e||"")+"F"};t.horizontalAbsolute=function horizontalAbsolute(e){if(e==null)throw new Error("horizontalAboslute requires a column to position to");return i+e+"G"};t.eraseData=function eraseData(){return i+"J"};t.eraseLine=function eraseLine(){return i+"K"};t.goto=function(e,t){return i+t+";"+e+"H"};t.gotoSOL=function(){return"\r"};t.beep=function(){return""};t.hideCursor=function hideCursor(){return i+"?25l"};t.showCursor=function showCursor(){return i+"?25h"};var n={reset:0,bold:1,italic:3,underline:4,inverse:7,stopBold:22,stopItalic:23,stopUnderline:24,stopInverse:27,white:37,black:30,blue:34,cyan:36,green:32,magenta:35,red:31,yellow:33,bgWhite:47,bgBlack:40,bgBlue:44,bgCyan:46,bgGreen:42,bgMagenta:45,bgRed:41,bgYellow:43,grey:90,brightBlack:90,brightRed:91,brightGreen:92,brightYellow:93,brightBlue:94,brightMagenta:95,brightCyan:96,brightWhite:97,bgGrey:100,bgBrightBlack:100,bgBrightRed:101,bgBrightGreen:102,bgBrightYellow:103,bgBrightBlue:104,bgBrightMagenta:105,bgBrightCyan:106,bgBrightWhite:107};t.color=function color(e){if(arguments.length!==1||!Array.isArray(e)){e=Array.prototype.slice.call(arguments)}return i+e.map(colorNameToCode).join(";")+"m"};function colorNameToCode(e){if(n[e]!=null)return n[e];throw new Error("Unknown color or style name: "+e)}},8334:(e,t)=>{function isArray(e){if(Array.isArray){return Array.isArray(e)}return objectToString(e)==="[object Array]"}t.isArray=isArray;function isBoolean(e){return typeof e==="boolean"}t.isBoolean=isBoolean;function isNull(e){return e===null}t.isNull=isNull;function isNullOrUndefined(e){return e==null}t.isNullOrUndefined=isNullOrUndefined;function isNumber(e){return typeof e==="number"}t.isNumber=isNumber;function isString(e){return typeof e==="string"}t.isString=isString;function isSymbol(e){return typeof e==="symbol"}t.isSymbol=isSymbol;function isUndefined(e){return e===void 0}t.isUndefined=isUndefined;function isRegExp(e){return objectToString(e)==="[object RegExp]"}t.isRegExp=isRegExp;function isObject(e){return typeof e==="object"&&e!==null}t.isObject=isObject;function isDate(e){return objectToString(e)==="[object Date]"}t.isDate=isDate;function isError(e){return objectToString(e)==="[object Error]"||e instanceof Error}t.isError=isError;function isFunction(e){return typeof e==="function"}t.isFunction=isFunction;function isPrimitive(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}t.isPrimitive=isPrimitive;t.isBuffer=Buffer.isBuffer;function objectToString(e){return Object.prototype.toString.call(e)}},5458:e=>{e.exports=Delegator;function Delegator(e,t){if(!(this instanceof Delegator))return new Delegator(e,t);this.proto=e;this.target=t;this.methods=[];this.getters=[];this.setters=[];this.fluents=[]}Delegator.prototype.method=function(e){var t=this.proto;var i=this.target;this.methods.push(e);t[e]=function(){return this[i][e].apply(this[i],arguments)};return this};Delegator.prototype.access=function(e){return this.getter(e).setter(e)};Delegator.prototype.getter=function(e){var t=this.proto;var i=this.target;this.getters.push(e);t.__defineGetter__(e,function(){return this[i][e]});return this};Delegator.prototype.setter=function(e){var t=this.proto;var i=this.target;this.setters.push(e);t.__defineSetter__(e,function(t){return this[i][e]=t});return this};Delegator.prototype.fluent=function(e){var t=this.proto;var i=this.target;this.fluents.push(e);t[e]=function(t){if("undefined"!=typeof t){this[i][e]=t;return this}else{return this[i][e]}};return this}},2226:(e,t,i)=>{"use strict";var n=i(2087).platform();var r=i(3129).spawnSync;var s=i(5747).readdirSync;var a="glibc";var o="musl";var u={encoding:"utf8",env:process.env};if(!r){r=function(){return{status:126,stdout:"",stderr:""}}}function contains(e){return function(t){return t.indexOf(e)!==-1}}function versionFromMuslLdd(e){return e.split(/[\r\n]+/)[1].trim().split(/\s/)[1]}function safeReaddirSync(e){try{return s(e)}catch(e){}return[]}var l="";var f="";var c="";if(n==="linux"){var h=r("getconf",["GNU_LIBC_VERSION"],u);if(h.status===0){l=a;f=h.stdout.trim().split(" ")[1];c="getconf"}else{var p=r("ldd",["--version"],u);if(p.status===0&&p.stdout.indexOf(o)!==-1){l=o;f=versionFromMuslLdd(p.stdout);c="ldd"}else if(p.status===1&&p.stderr.indexOf(o)!==-1){l=o;f=versionFromMuslLdd(p.stderr);c="ldd"}else{var d=safeReaddirSync("/lib");if(d.some(contains("-linux-gnu"))){l=a;c="filesystem"}else if(d.some(contains("libc.musl-"))){l=o;c="filesystem"}else if(d.some(contains("ld-musl-"))){l=o;c="filesystem"}else{var b=safeReaddirSync("/usr/sbin");if(b.some(contains("glibc"))){l=a;c="filesystem"}}}}}var v=l!==""&&l!==a;e.exports={GLIBC:a,MUSL:o,family:l,version:f,method:c,isNonGlibcLinux:v}},4855:function(e,t){(function(e,i){true?i(t):0})(this,function(e){"use strict";function walk(e,{enter:t,leave:i}){visit(e,null,t,i)}let t=false;const i={skip:()=>t=true};const n={};const r=Object.prototype.toString;function isArray(e){return r.call(e)==="[object Array]"}function visit(e,r,s,a,o,u){if(!e)return;if(s){const n=t;t=false;s.call(i,e,r,o,u);const a=t;t=n;if(a)return}const l=e.type&&n[e.type]||(n[e.type]=Object.keys(e).filter(t=>typeof e[t]==="object"));for(let t=0;t{var n=i(5622).sep||"/";e.exports=fileUriToPath;function fileUriToPath(e){if("string"!=typeof e||e.length<=7||"file://"!=e.substring(0,7)){throw new TypeError("must pass in a file:// URI to convert to a file path")}var t=decodeURI(e.substring(7));var i=t.indexOf("/");var r=t.substring(0,i);var s=t.substring(i+1);if("localhost"==r)r="";if(r){r=n+n+r}s=s.replace(/^(.+)\|/,"$1:");if(n=="\\"){s=s.replace(/\//g,"\\")}if(/^.+\:/.test(s)){}else{s=n+s}return r+s}},5955:(e,t,i)=>{"use strict";const n=i(1669);const r=i(1353);const s=e=>e!==null&&typeof e==="object"&&!Array.isArray(e);const a=e=>{return t=>e===true?Number(t):String(t)};const o=e=>{return typeof e==="number"||typeof e==="string"&&e!==""};const u=e=>Number.isInteger(+e);const l=e=>{let t=`${e}`;let i=-1;if(t[0]==="-")t=t.slice(1);if(t==="0")return false;while(t[++i]==="0");return i>0};const f=(e,t,i)=>{if(typeof e==="string"||typeof t==="string"){return true}return i.stringify===true};const c=(e,t,i)=>{if(t>0){let i=e[0]==="-"?"-":"";if(i)e=e.slice(1);e=i+e.padStart(i?t-1:t,"0")}if(i===false){return String(e)}return e};const h=(e,t)=>{let i=e[0]==="-"?"-":"";if(i){e=e.slice(1);t--}while(e.length{e.negatives.sort((e,t)=>et?1:0);e.positives.sort((e,t)=>et?1:0);let i=t.capture?"":"?:";let n="";let r="";let s;if(e.positives.length){n=e.positives.join("|")}if(e.negatives.length){r=`-(${i}${e.negatives.join("|")})`}if(n&&r){s=`${n}|${r}`}else{s=n||r}if(t.wrap){return`(${i}${s})`}return s};const d=(e,t,i,n)=>{if(i){return r(e,t,{wrap:false,...n})}let s=String.fromCharCode(e);if(e===t)return s;let a=String.fromCharCode(t);return`[${s}-${a}]`};const b=(e,t,i)=>{if(Array.isArray(e)){let t=i.wrap===true;let n=i.capture?"":"?:";return t?`(${n}${e.join("|")})`:e.join("|")}return r(e,t,i)};const v=(...e)=>{return new RangeError("Invalid range arguments: "+n.inspect(...e))};const g=(e,t,i)=>{if(i.strictRanges===true)throw v([e,t]);return[]};const _=(e,t)=>{if(t.strictRanges===true){throw new TypeError(`Expected step "${e}" to be a number`)}return[]};const y=(e,t,i=1,n={})=>{let r=Number(e);let s=Number(t);if(!Number.isInteger(r)||!Number.isInteger(s)){if(n.strictRanges===true)throw v([e,t]);return[]}if(r===0)r=0;if(s===0)s=0;let o=r>s;let u=String(e);let g=String(t);let _=String(i);i=Math.max(Math.abs(i),1);let y=l(u)||l(g)||l(_);let m=y?Math.max(u.length,g.length,_.length):0;let x=y===false&&f(e,t,n)===false;let E=n.transform||a(x);if(n.toRegex&&i===1){return d(h(e,m),h(t,m),true,n)}let w={negatives:[],positives:[]};let S=e=>w[e<0?"negatives":"positives"].push(Math.abs(e));let A=[];let R=0;while(o?r>=s:r<=s){if(n.toRegex===true&&i>1){S(r)}else{A.push(c(E(r,R),m,x))}r=o?r-i:r+i;R++}if(n.toRegex===true){return i>1?p(w,n):b(A,null,{wrap:false,...n})}return A};const m=(e,t,i=1,n={})=>{if(!u(e)&&e.length>1||!u(t)&&t.length>1){return g(e,t,n)}let r=n.transform||(e=>String.fromCharCode(e));let s=`${e}`.charCodeAt(0);let a=`${t}`.charCodeAt(0);let o=s>a;let l=Math.min(s,a);let f=Math.max(s,a);if(n.toRegex&&i===1){return d(l,f,false,n)}let c=[];let h=0;while(o?s>=a:s<=a){c.push(r(s,h));s=o?s-i:s+i;h++}if(n.toRegex===true){return b(c,null,{wrap:false,options:n})}return c};const x=(e,t,i,n={})=>{if(t==null&&o(e)){return[e]}if(!o(e)||!o(t)){return g(e,t,n)}if(typeof i==="function"){return x(e,t,1,{transform:i})}if(s(i)){return x(e,t,0,i)}let r={...n};if(r.capture===true)r.wrap=true;i=i||r.step||1;if(!u(i)){if(i!=null&&!s(i))return _(i,r);return x(e,t,1,i)}if(u(e)&&u(t)){return y(e,t,i,r)}return m(e,t,Math.max(Math.abs(i),1),r)};e.exports=x},3073:(e,t,i)=>{"use strict";var n=i(8054);var r=i(6412);e.exports={activityIndicator:function(e,t,i){if(e.spun==null)return;return n(t,e.spun)},progressbar:function(e,t,i){if(e.completed==null)return;return r(t,i,e.completed)}}},2411:(e,t,i)=>{"use strict";var n=i(1669);var r=t.User=function User(e){var t=new Error(e);Error.captureStackTrace(t,User);t.code="EGAUGE";return t};t.MissingTemplateValue=function MissingTemplateValue(e,t){var i=new r(n.format('Missing template value "%s"',e.type));Error.captureStackTrace(i,MissingTemplateValue);i.template=e;i.values=t;return i};t.Internal=function Internal(e){var t=new Error(e);Error.captureStackTrace(t,Internal);t.code="EGAUGEINTERNAL";return t}},561:e=>{"use strict";e.exports=isWin32()||isColorTerm();function isWin32(){return process.platform==="win32"}function isColorTerm(){var e=/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i;return!!process.env.COLORTERM||e.test(process.env.TERM)}},7249:(e,t,i)=>{"use strict";var n=i(8065);var r=i(2022);var s=i(561);var a=i(2317);var o=i(8875);var u=i(5953);var l=i(6593);var f=i(9615);e.exports=Gauge;function callWith(e,t){return function(){return t.call(e)}}function Gauge(e,t){var i,r;if(e&&e.write){r=e;i=t||{}}else if(t&&t.write){r=t;i=e||{}}else{r=l.stderr;i=e||t||{}}this._status={spun:0,section:"",subsection:""};this._paused=false;this._disabled=true;this._showing=false;this._onScreen=false;this._needsRedraw=false;this._hideCursor=i.hideCursor==null?true:i.hideCursor;this._fixedFramerate=i.fixedFramerate==null?!/^v0\.8\./.test(l.version):i.fixedFramerate;this._lastUpdateAt=null;this._updateInterval=i.updateInterval==null?50:i.updateInterval;this._themes=i.themes||o;this._theme=i.theme;var s=this._computeTheme(i.theme);var a=i.template||[{type:"progressbar",length:20},{type:"activityIndicator",kerning:1,length:1},{type:"section",kerning:1,default:""},{type:"subsection",kerning:1,default:""}];this.setWriteTo(r,i.tty);var u=i.Plumbing||n;this._gauge=new u(s,a,this.getWidth());this._$$doRedraw=callWith(this,this._doRedraw);this._$$handleSizeChange=callWith(this,this._handleSizeChange);this._cleanupOnExit=i.cleanupOnExit==null||i.cleanupOnExit;this._removeOnExit=null;if(i.enabled||i.enabled==null&&this._tty&&this._tty.isTTY){this.enable()}else{this.disable()}}Gauge.prototype={};Gauge.prototype.isEnabled=function(){return!this._disabled};Gauge.prototype.setTemplate=function(e){this._gauge.setTemplate(e);if(this._showing)this._requestRedraw()};Gauge.prototype._computeTheme=function(e){if(!e)e={};if(typeof e==="string"){e=this._themes.getTheme(e)}else if(e&&(Object.keys(e).length===0||e.hasUnicode!=null||e.hasColor!=null)){var t=e.hasUnicode==null?r():e.hasUnicode;var i=e.hasColor==null?s:e.hasColor;e=this._themes.getDefault({hasUnicode:t,hasColor:i,platform:e.platform})}return e};Gauge.prototype.setThemeset=function(e){this._themes=e;this.setTheme(this._theme)};Gauge.prototype.setTheme=function(e){this._gauge.setTheme(this._computeTheme(e));if(this._showing)this._requestRedraw();this._theme=e};Gauge.prototype._requestRedraw=function(){this._needsRedraw=true;if(!this._fixedFramerate)this._doRedraw()};Gauge.prototype.getWidth=function(){return(this._tty&&this._tty.columns||80)-1};Gauge.prototype.setWriteTo=function(e,t){var i=!this._disabled;if(i)this.disable();this._writeTo=e;this._tty=t||e===l.stderr&&l.stdout.isTTY&&l.stdout||e.isTTY&&e||this._tty;if(this._gauge)this._gauge.setWidth(this.getWidth());if(i)this.enable()};Gauge.prototype.enable=function(){if(!this._disabled)return;this._disabled=false;if(this._tty)this._enableEvents();if(this._showing)this.show()};Gauge.prototype.disable=function(){if(this._disabled)return;if(this._showing){this._lastUpdateAt=null;this._showing=false;this._doRedraw();this._showing=true}this._disabled=true;if(this._tty)this._disableEvents()};Gauge.prototype._enableEvents=function(){if(this._cleanupOnExit){this._removeOnExit=a(callWith(this,this.disable))}this._tty.on("resize",this._$$handleSizeChange);if(this._fixedFramerate){this.redrawTracker=u(this._$$doRedraw,this._updateInterval);if(this.redrawTracker.unref)this.redrawTracker.unref()}};Gauge.prototype._disableEvents=function(){this._tty.removeListener("resize",this._$$handleSizeChange);if(this._fixedFramerate)clearInterval(this.redrawTracker);if(this._removeOnExit)this._removeOnExit()};Gauge.prototype.hide=function(e){if(this._disabled)return e&&l.nextTick(e);if(!this._showing)return e&&l.nextTick(e);this._showing=false;this._doRedraw();e&&f(e)};Gauge.prototype.show=function(e,t){this._showing=true;if(typeof e==="string"){this._status.section=e}else if(typeof e==="object"){var i=Object.keys(e);for(var n=0;n{"use strict";var n=i(5079);e.exports=function(e){if(n(e)){return false}if(e>=4352&&(e<=4447||9001===e||9002===e||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141)){return true}return false}},5346:(e,t,i)=>{"use strict";var n=i(148);var r=i(8525);var s=i(3991);e.exports=function(e){if(typeof e!=="string"||e.length===0){return 0}var t=0;e=n(e);for(var i=0;i=127&&a<=159){continue}if(a>=65536){i++}if(s(a)){t+=2}else{t++}}return t}},8065:(e,t,i)=>{"use strict";var n=i(3645);var r=i(7966);var s=i(4394);var a=e.exports=function(e,t,i){if(!i)i=80;s("OAN",[e,t,i]);this.showing=false;this.theme=e;this.width=i;this.template=t};a.prototype={};a.prototype.setTheme=function(e){s("O",[e]);this.theme=e};a.prototype.setTemplate=function(e){s("A",[e]);this.template=e};a.prototype.setWidth=function(e){s("N",[e]);this.width=e};a.prototype.hide=function(){return n.gotoSOL()+n.eraseLine()};a.prototype.hideCursor=n.hideCursor;a.prototype.showCursor=n.showCursor;a.prototype.show=function(e){var t=Object.create(this.theme);for(var i in e){t[i]=e[i]}return r(this.width,this.template,t).trim()+n.color("reset")+n.eraseLine()+n.gotoSOL()}},6593:e=>{"use strict";e.exports=process},6412:(e,t,i)=>{"use strict";var n=i(4394);var r=i(7966);var s=i(3638);var a=i(5346);e.exports=function(e,t,i){n("ONN",[e,t,i]);if(i<0)i=0;if(i>1)i=1;if(t<=0)return"";var s=Math.round(t*i);var a=t-s;var o=[{type:"complete",value:repeat(e.complete,s),length:s},{type:"remaining",value:repeat(e.remaining,a),length:a}];return r(t,o,e)};function repeat(e,t){var i="";var n=t;do{if(n%2){i+=e}n=Math.floor(n/2);e+=e}while(n&&a(i){"use strict";var n=i(7378);var r=i(4394);var s=i(4594);var a=i(3638);var o=i(2411);var u=i(4184);function renderValueWithValues(e){return function(t){return renderValue(t,e)}}var l=e.exports=function(e,t,i){var r=prepareItems(e,t,i);var s=r.map(renderValueWithValues(i)).join("");return n.left(a(s,e),e)};function preType(e){var t=e.type[0].toUpperCase()+e.type.slice(1);return"pre"+t}function postType(e){var t=e.type[0].toUpperCase()+e.type.slice(1);return"post"+t}function hasPreOrPost(e,t){if(!e.type)return;return t[preType(e)]||t[postType(e)]}function generatePreAndPost(e,t){var i=s({},e);var n=Object.create(t);var r=[];var a=preType(i);var o=postType(i);if(n[a]){r.push({value:n[a]});n[a]=null}i.minLength=null;i.length=null;i.maxLength=null;r.push(i);n[i.type]=n[i.type];if(n[o]){r.push({value:n[o]});n[o]=null}return function(e,t,i){return l(i,r,n)}}function prepareItems(e,t,i){function cloneAndObjectify(t,n,r){var s=new u(t,e);var a=s.type;if(s.value==null){if(!(a in i)){if(s.default==null){throw new o.MissingTemplateValue(s,i)}else{s.value=s.default}}else{s.value=i[a]}}if(s.value==null||s.value==="")return null;s.index=n;s.first=n===0;s.last=n===r.length-1;if(hasPreOrPost(s,i))s.value=generatePreAndPost(s,i);return s}var n=t.map(cloneAndObjectify).filter(function(e){return e!=null});var r=0;var s=e;var a=n.length;function consumeSpace(e){if(e>s)e=s;r+=e;s-=e}function finishSizing(e,t){if(e.finished)throw new o.Internal("Tried to finish template item that was already finished");if(t===Infinity)throw new o.Internal("Length of template item cannot be infinity");if(t!=null)e.length=t;e.minLength=null;e.maxLength=null;--a;e.finished=true;if(e.length==null)e.length=e.getBaseLength();if(e.length==null)throw new o.Internal("Finished template items must have a length");consumeSpace(e.getLength())}n.forEach(function(e){if(!e.kerning)return;var t=e.first?0:n[e.index-1].padRight;if(!e.first&&t=c){finishSizing(e,e.minLength);f=true}})}while(f&&l++{"use strict";var n=i(6593);try{e.exports=setImmediate}catch(t){e.exports=n.nextTick}},5953:e=>{"use strict";e.exports=setInterval},8054:e=>{"use strict";e.exports=function spin(e,t){return e[t%e.length]}},4184:(e,t,i)=>{"use strict";var n=i(5346);e.exports=TemplateItem;function isPercent(e){if(typeof e!=="string")return false;return e.slice(-1)==="%"}function percent(e){return Number(e.slice(0,-1))/100}function TemplateItem(e,t){this.overallOutputLength=t;this.finished=false;this.type=null;this.value=null;this.length=null;this.maxLength=null;this.minLength=null;this.kerning=null;this.align="left";this.padLeft=0;this.padRight=0;this.index=null;this.first=null;this.last=null;if(typeof e==="string"){this.value=e}else{for(var i in e)this[i]=e[i]}if(isPercent(this.length)){this.length=Math.round(this.overallOutputLength*percent(this.length))}if(isPercent(this.minLength)){this.minLength=Math.round(this.overallOutputLength*percent(this.minLength))}if(isPercent(this.maxLength)){this.maxLength=Math.round(this.overallOutputLength*percent(this.maxLength))}return this}TemplateItem.prototype={};TemplateItem.prototype.getBaseLength=function(){var e=this.length;if(e==null&&typeof this.value==="string"&&this.maxLength==null&&this.minLength==null){e=n(this.value)}return e};TemplateItem.prototype.getLength=function(){var e=this.getBaseLength();if(e==null)return null;return e+this.padLeft+this.padRight};TemplateItem.prototype.getMaxLength=function(){if(this.maxLength==null)return null;return this.maxLength+this.padLeft+this.padRight};TemplateItem.prototype.getMinLength=function(){if(this.minLength==null)return null;return this.minLength+this.padLeft+this.padRight}},8607:(e,t,i)=>{"use strict";var n=i(4594);e.exports=function(){return r.newThemeSet()};var r={};r.baseTheme=i(3073);r.newTheme=function(e,t){if(!t){t=e;e=this.baseTheme}return n({},e,t)};r.getThemeNames=function(){return Object.keys(this.themes)};r.addTheme=function(e,t,i){this.themes[e]=this.newTheme(t,i)};r.addToAllThemes=function(e){var t=this.themes;Object.keys(t).forEach(function(i){n(t[i],e)});n(this.baseTheme,e)};r.getTheme=function(e){if(!this.themes[e])throw this.newMissingThemeError(e);return this.themes[e]};r.setDefault=function(e,t){if(t==null){t=e;e={}}var i=e.platform==null?"fallback":e.platform;var n=!!e.hasUnicode;var r=!!e.hasColor;if(!this.defaults[i])this.defaults[i]={true:{},false:{}};this.defaults[i][n][r]=t};r.getDefault=function(e){if(!e)e={};var t=e.platform||process.platform;var i=this.defaults[t]||this.defaults.fallback;var r=!!e.hasUnicode;var s=!!e.hasColor;if(!i)throw this.newMissingDefaultThemeError(t,r,s);if(!i[r][s]){if(r&&s&&i[!r][s]){r=false}else if(r&&s&&i[r][!s]){s=false}else if(r&&s&&i[!r][!s]){r=false;s=false}else if(r&&!s&&i[!r][s]){r=false}else if(!r&&s&&i[r][!s]){s=false}else if(i===this.defaults.fallback){throw this.newMissingDefaultThemeError(t,r,s)}}if(i[r][s]){return this.getTheme(i[r][s])}else{return this.getDefault(n({},e,{platform:"fallback"}))}};r.newMissingThemeError=function newMissingThemeError(e){var t=new Error('Could not find a gauge theme named "'+e+'"');Error.captureStackTrace.call(t,newMissingThemeError);t.theme=e;t.code="EMISSINGTHEME";return t};r.newMissingDefaultThemeError=function newMissingDefaultThemeError(e,t,i){var n=new Error("Could not find a gauge theme for your platform/unicode/color use combo:\n"+" platform = "+e+"\n"+" hasUnicode = "+t+"\n"+" hasColor = "+i);Error.captureStackTrace.call(n,newMissingDefaultThemeError);n.platform=e;n.hasUnicode=t;n.hasColor=i;n.code="EMISSINGTHEME";return n};r.newThemeSet=function(){var e=function(t){return e.getDefault(t)};return n(e,r,{themes:n({},this.themes),baseTheme:n({},this.baseTheme),defaults:JSON.parse(JSON.stringify(this.defaults||{}))})}},8875:(e,t,i)=>{"use strict";var n=i(3645);var r=i(8607);var s=e.exports=new r;s.addTheme("ASCII",{preProgressbar:"[",postProgressbar:"]",progressbarTheme:{complete:"#",remaining:"."},activityIndicatorTheme:"-\\|/",preSubsection:">"});s.addTheme("colorASCII",s.getTheme("ASCII"),{progressbarTheme:{preComplete:n.color("inverse"),complete:" ",postComplete:n.color("stopInverse"),preRemaining:n.color("brightBlack"),remaining:".",postRemaining:n.color("reset")}});s.addTheme("brailleSpinner",{preProgressbar:"⸨",postProgressbar:"⸩",progressbarTheme:{complete:"░",remaining:"⠂"},activityIndicatorTheme:"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏",preSubsection:">"});s.addTheme("colorBrailleSpinner",s.getTheme("brailleSpinner"),{progressbarTheme:{preComplete:n.color("inverse"),complete:" ",postComplete:n.color("stopInverse"),preRemaining:n.color("brightBlack"),remaining:"░",postRemaining:n.color("reset")}});s.setDefault({},"ASCII");s.setDefault({hasColor:true},"colorASCII");s.setDefault({platform:"darwin",hasUnicode:true},"brailleSpinner");s.setDefault({platform:"darwin",hasUnicode:true,hasColor:true},"colorBrailleSpinner")},3638:(e,t,i)=>{"use strict";var n=i(5346);var r=i(148);e.exports=wideTruncate;function wideTruncate(e,t){if(n(e)===0)return e;if(t<=0)return"";if(n(e)<=t)return e;var i=r(e);var s=e.length+i.length;var a=e.slice(0,t+s);while(n(a)>t){a=a.slice(0,-1)}return a}},5581:e=>{"use strict";e.exports=clone;function clone(e){if(e===null||typeof e!=="object")return e;if(e instanceof Object)var t={__proto__:e.__proto__};else var t=Object.create(null);Object.getOwnPropertyNames(e).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(e,i))});return t}},2161:(e,t,i)=>{var n=i(5747);var r=i(34);var s=i(7077);var a=i(5581);var o=i(1669);var u;var l;if(typeof Symbol==="function"&&typeof Symbol.for==="function"){u=Symbol.for("graceful-fs.queue");l=Symbol.for("graceful-fs.previous")}else{u="___graceful-fs.queue";l="___graceful-fs.previous"}function noop(){}function publishQueue(e,t){Object.defineProperty(e,u,{get:function(){return t}})}var f=noop;if(o.debuglog)f=o.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))f=function(){var e=o.format.apply(o,arguments);e="GFS4: "+e.split(/\n/).join("\nGFS4: ");console.error(e)};if(!n[u]){var c=global[u]||[];publishQueue(n,c);n.close=function(e){function close(t,i){return e.call(n,t,function(e){if(!e){retry()}if(typeof i==="function")i.apply(this,arguments)})}Object.defineProperty(close,l,{value:e});return close}(n.close);n.closeSync=function(e){function closeSync(t){e.apply(n,arguments);retry()}Object.defineProperty(closeSync,l,{value:e});return closeSync}(n.closeSync);if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")){process.on("exit",function(){f(n[u]);i(2357).equal(n[u].length,0)})}}if(!global[u]){publishQueue(global,n[u])}e.exports=patch(a(n));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!n.__patched){e.exports=patch(n);n.__patched=true}function patch(e){r(e);e.gracefulify=patch;e.createReadStream=createReadStream;e.createWriteStream=createWriteStream;var t=e.readFile;e.readFile=readFile;function readFile(e,i,n){if(typeof i==="function")n=i,i=null;return go$readFile(e,i,n);function go$readFile(e,i,n){return t(e,i,function(t){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))enqueue([go$readFile,[e,i,n]]);else{if(typeof n==="function")n.apply(this,arguments);retry()}})}}var i=e.writeFile;e.writeFile=writeFile;function writeFile(e,t,n,r){if(typeof n==="function")r=n,n=null;return go$writeFile(e,t,n,r);function go$writeFile(e,t,n,r){return i(e,t,n,function(i){if(i&&(i.code==="EMFILE"||i.code==="ENFILE"))enqueue([go$writeFile,[e,t,n,r]]);else{if(typeof r==="function")r.apply(this,arguments);retry()}})}}var n=e.appendFile;if(n)e.appendFile=appendFile;function appendFile(e,t,i,r){if(typeof i==="function")r=i,i=null;return go$appendFile(e,t,i,r);function go$appendFile(e,t,i,r){return n(e,t,i,function(n){if(n&&(n.code==="EMFILE"||n.code==="ENFILE"))enqueue([go$appendFile,[e,t,i,r]]);else{if(typeof r==="function")r.apply(this,arguments);retry()}})}}var a=e.readdir;e.readdir=readdir;function readdir(e,t,i){var n=[e];if(typeof t!=="function"){n.push(t)}else{i=t}n.push(go$readdir$cb);return go$readdir(n);function go$readdir$cb(e,t){if(t&&t.sort)t.sort();if(e&&(e.code==="EMFILE"||e.code==="ENFILE"))enqueue([go$readdir,[n]]);else{if(typeof i==="function")i.apply(this,arguments);retry()}}}function go$readdir(t){return a.apply(e,t)}if(process.version.substr(0,4)==="v0.8"){var o=s(e);ReadStream=o.ReadStream;WriteStream=o.WriteStream}var u=e.ReadStream;if(u){ReadStream.prototype=Object.create(u.prototype);ReadStream.prototype.open=ReadStream$open}var l=e.WriteStream;if(l){WriteStream.prototype=Object.create(l.prototype);WriteStream.prototype.open=WriteStream$open}Object.defineProperty(e,"ReadStream",{get:function(){return ReadStream},set:function(e){ReadStream=e},enumerable:true,configurable:true});Object.defineProperty(e,"WriteStream",{get:function(){return WriteStream},set:function(e){WriteStream=e},enumerable:true,configurable:true});var f=ReadStream;Object.defineProperty(e,"FileReadStream",{get:function(){return f},set:function(e){f=e},enumerable:true,configurable:true});var c=WriteStream;Object.defineProperty(e,"FileWriteStream",{get:function(){return c},set:function(e){c=e},enumerable:true,configurable:true});function ReadStream(e,t){if(this instanceof ReadStream)return u.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var e=this;open(e.path,e.flags,e.mode,function(t,i){if(t){if(e.autoClose)e.destroy();e.emit("error",t)}else{e.fd=i;e.emit("open",i);e.read()}})}function WriteStream(e,t){if(this instanceof WriteStream)return l.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var e=this;open(e.path,e.flags,e.mode,function(t,i){if(t){e.destroy();e.emit("error",t)}else{e.fd=i;e.emit("open",i)}})}function createReadStream(t,i){return new e.ReadStream(t,i)}function createWriteStream(t,i){return new e.WriteStream(t,i)}var h=e.open;e.open=open;function open(e,t,i,n){if(typeof i==="function")n=i,i=null;return go$open(e,t,i,n);function go$open(e,t,i,n){return h(e,t,i,function(r,s){if(r&&(r.code==="EMFILE"||r.code==="ENFILE"))enqueue([go$open,[e,t,i,n]]);else{if(typeof n==="function")n.apply(this,arguments);retry()}})}}return e}function enqueue(e){f("ENQUEUE",e[0].name,e[1]);n[u].push(e)}function retry(){var e=n[u].shift();if(e){f("RETRY",e[0].name,e[1]);e[0].apply(null,e[1])}}},7077:(e,t,i)=>{var n=i(2413).Stream;e.exports=legacy;function legacy(e){return{ReadStream:ReadStream,WriteStream:WriteStream};function ReadStream(t,i){if(!(this instanceof ReadStream))return new ReadStream(t,i);n.call(this);var r=this;this.path=t;this.fd=null;this.readable=true;this.paused=false;this.flags="r";this.mode=438;this.bufferSize=64*1024;i=i||{};var s=Object.keys(i);for(var a=0,o=s.length;athis.end){throw new Error("start must be <= end")}this.pos=this.start}if(this.fd!==null){process.nextTick(function(){r._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){r.emit("error",e);r.readable=false;return}r.fd=t;r.emit("open",t);r._read()})}function WriteStream(t,i){if(!(this instanceof WriteStream))return new WriteStream(t,i);n.call(this);this.path=t;this.fd=null;this.writable=true;this.flags="w";this.encoding="binary";this.mode=438;this.bytesWritten=0;i=i||{};var r=Object.keys(i);for(var s=0,a=r.length;s= zero")}this.pos=this.start}this.busy=false;this._queue=[];if(this.fd===null){this._open=e.open;this._queue.push([this._open,this.path,this.flags,this.mode,undefined]);this.flush()}}}},34:(e,t,i)=>{var n=i(7619);var r=process.cwd;var s=null;var a=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!s)s=r.call(process);return s};try{process.cwd()}catch(e){}var o=process.chdir;process.chdir=function(e){s=null;o.call(process,e)};e.exports=patch;function patch(e){if(n.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)){patchLchmod(e)}if(!e.lutimes){patchLutimes(e)}e.chown=chownFix(e.chown);e.fchown=chownFix(e.fchown);e.lchown=chownFix(e.lchown);e.chmod=chmodFix(e.chmod);e.fchmod=chmodFix(e.fchmod);e.lchmod=chmodFix(e.lchmod);e.chownSync=chownFixSync(e.chownSync);e.fchownSync=chownFixSync(e.fchownSync);e.lchownSync=chownFixSync(e.lchownSync);e.chmodSync=chmodFixSync(e.chmodSync);e.fchmodSync=chmodFixSync(e.fchmodSync);e.lchmodSync=chmodFixSync(e.lchmodSync);e.stat=statFix(e.stat);e.fstat=statFix(e.fstat);e.lstat=statFix(e.lstat);e.statSync=statFixSync(e.statSync);e.fstatSync=statFixSync(e.fstatSync);e.lstatSync=statFixSync(e.lstatSync);if(!e.lchmod){e.lchmod=function(e,t,i){if(i)process.nextTick(i)};e.lchmodSync=function(){}}if(!e.lchown){e.lchown=function(e,t,i,n){if(n)process.nextTick(n)};e.lchownSync=function(){}}if(a==="win32"){e.rename=function(t){return function(i,n,r){var s=Date.now();var a=0;t(i,n,function CB(o){if(o&&(o.code==="EACCES"||o.code==="EPERM")&&Date.now()-s<6e4){setTimeout(function(){e.stat(n,function(e,s){if(e&&e.code==="ENOENT")t(i,n,CB);else r(o)})},a);if(a<100)a+=10;return}if(r)r(o)})}}(e.rename)}e.read=function(t){function read(i,n,r,s,a,o){var u;if(o&&typeof o==="function"){var l=0;u=function(f,c,h){if(f&&f.code==="EAGAIN"&&l<10){l++;return t.call(e,i,n,r,s,a,u)}o.apply(this,arguments)}}return t.call(e,i,n,r,s,a,u)}read.__proto__=t;return read}(e.read);e.readSync=function(t){return function(i,n,r,s,a){var o=0;while(true){try{return t.call(e,i,n,r,s,a)}catch(e){if(e.code==="EAGAIN"&&o<10){o++;continue}throw e}}}}(e.readSync);function patchLchmod(e){e.lchmod=function(t,i,r){e.open(t,n.O_WRONLY|n.O_SYMLINK,i,function(t,n){if(t){if(r)r(t);return}e.fchmod(n,i,function(t){e.close(n,function(e){if(r)r(t||e)})})})};e.lchmodSync=function(t,i){var r=e.openSync(t,n.O_WRONLY|n.O_SYMLINK,i);var s=true;var a;try{a=e.fchmodSync(r,i);s=false}finally{if(s){try{e.closeSync(r)}catch(e){}}else{e.closeSync(r)}}return a}}function patchLutimes(e){if(n.hasOwnProperty("O_SYMLINK")){e.lutimes=function(t,i,r,s){e.open(t,n.O_SYMLINK,function(t,n){if(t){if(s)s(t);return}e.futimes(n,i,r,function(t){e.close(n,function(e){if(s)s(t||e)})})})};e.lutimesSync=function(t,i,r){var s=e.openSync(t,n.O_SYMLINK);var a;var o=true;try{a=e.futimesSync(s,i,r);o=false}finally{if(o){try{e.closeSync(s)}catch(e){}}else{e.closeSync(s)}}return a}}else{e.lutimes=function(e,t,i,n){if(n)process.nextTick(n)};e.lutimesSync=function(){}}}function chmodFix(t){if(!t)return t;return function(i,n,r){return t.call(e,i,n,function(e){if(chownErOk(e))e=null;if(r)r.apply(this,arguments)})}}function chmodFixSync(t){if(!t)return t;return function(i,n){try{return t.call(e,i,n)}catch(e){if(!chownErOk(e))throw e}}}function chownFix(t){if(!t)return t;return function(i,n,r,s){return t.call(e,i,n,r,function(e){if(chownErOk(e))e=null;if(s)s.apply(this,arguments)})}}function chownFixSync(t){if(!t)return t;return function(i,n,r){try{return t.call(e,i,n,r)}catch(e){if(!chownErOk(e))throw e}}}function statFix(t){if(!t)return t;return function(i,n,r){if(typeof n==="function"){r=n;n=null}function callback(e,t){if(t){if(t.uid<0)t.uid+=4294967296;if(t.gid<0)t.gid+=4294967296}if(r)r.apply(this,arguments)}return n?t.call(e,i,n,callback):t.call(e,i,callback)}}function statFixSync(t){if(!t)return t;return function(i,n){var r=n?t.call(e,i,n):t.call(e,i);if(r.uid<0)r.uid+=4294967296;if(r.gid<0)r.gid+=4294967296;return r}}function chownErOk(e){if(!e)return true;if(e.code==="ENOSYS")return true;var t=!process.getuid||process.getuid()!==0;if(t){if(e.code==="EINVAL"||e.code==="EPERM")return true}return false}}},2022:(e,t,i)=>{"use strict";var n=i(2087);var r=e.exports=function(){if(n.type()=="Windows_NT"){return false}var e=/UTF-?8$/i;var t=process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG;return e.test(t)}},2989:(e,t,i)=>{try{var n=i(1669);if(typeof n.inherits!=="function")throw"";e.exports=n.inherits}catch(t){e.exports=i(7350)}},7350:e=>{if(typeof Object.create==="function"){e.exports=function inherits(e,t){if(t){e.super_=t;e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}}else{e.exports=function inherits(e,t){if(t){e.super_=t;var i=function(){};i.prototype=t.prototype;e.prototype=new i;e.prototype.constructor=e}}}},1352:e=>{var t={}.toString;e.exports=Array.isArray||function(e){return t.call(e)=="[object Array]"}},3024:(e,t,i)=>{"use strict";const n=i(1669);const r=i(2706);const s=i(5669);const a=i(6444);const o=e=>typeof e==="string"&&(e===""||e==="./");const u=(e,t,i)=>{t=[].concat(t);e=[].concat(e);let n=new Set;let r=new Set;let a=new Set;let o=0;let u=e=>{a.add(e.output);if(i&&i.onResult){i.onResult(e)}};for(let a=0;a!n.has(e));if(i&&f.length===0){if(i.failglob===true){throw new Error(`No matches found for "${t.join(", ")}"`)}if(i.nonull===true||i.nullglob===true){return i.unescape?t.map(e=>e.replace(/\\/g,"")):t}}return f};u.match=u;u.matcher=((e,t)=>s(e,t));u.isMatch=((e,t,i)=>s(t,i)(e));u.any=u.isMatch;u.not=((e,t,i={})=>{t=[].concat(t).map(String);let n=new Set;let r=[];let s=e=>{if(i.onResult)i.onResult(e);r.push(e.output)};let a=u(e,t,{...i,onResult:s});for(let e of r){if(!a.includes(e)){n.add(e)}}return[...n]});u.contains=((e,t,i)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${n.inspect(e)}"`)}if(Array.isArray(t)){return t.some(t=>u.contains(e,t,i))}if(typeof t==="string"){if(o(e)||o(t)){return false}if(e.includes(t)||e.startsWith("./")&&e.slice(2).includes(t)){return true}}return u.isMatch(e,t,{...i,contains:true})});u.matchKeys=((e,t,i)=>{if(!a.isObject(e)){throw new TypeError("Expected the first argument to be an object")}let n=u(Object.keys(e),t,i);let r={};for(let t of n)r[t]=e[t];return r});u.some=((e,t,i)=>{let n=[].concat(e);for(let e of[].concat(t)){let t=s(String(e),i);if(n.some(e=>t(e))){return true}}return false});u.every=((e,t,i)=>{let n=[].concat(e);for(let e of[].concat(t)){let t=s(String(e),i);if(!n.every(e=>t(e))){return false}}return true});u.all=((e,t,i)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${n.inspect(e)}"`)}return[].concat(t).every(t=>s(t,i)(e))});u.capture=((e,t,i)=>{let n=a.isWindows(i);let r=s.makeRe(String(e),{...i,capture:true});let o=r.exec(n?a.toPosixSlashes(t):t);if(o){return o.slice(1).map(e=>e===void 0?"":e)}});u.makeRe=((...e)=>s.makeRe(...e));u.scan=((...e)=>s.scan(...e));u.parse=((e,t)=>{let i=[];for(let n of[].concat(e||[])){for(let e of r(String(n),t)){i.push(s.parse(e,t))}}return i});u.braces=((e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");if(t&&t.nobrace===true||!/\{.*\}/.test(e)){return[e]}return r(e,t)});u.braceExpand=((e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");return u.braces(e,{...t,expand:true})});e.exports=u},1213:(module,__unused_webpack_exports,__nccwpck_require__)=>{var fs=__nccwpck_require__(5747);var path=__nccwpck_require__(5622);var os=__nccwpck_require__(2087);var runtimeRequire=true?eval("require"):0;var vars=process.config&&process.config.variables||{};var prebuildsOnly=!!process.env.PREBUILDS_ONLY;var abi=process.versions.modules;var runtime=isElectron()?"electron":"node";var arch=os.arch();var platform=os.platform();var libc=process.env.LIBC||(isAlpine(platform)?"musl":"glibc");var armv=process.env.ARM_VERSION||(arch==="arm64"?"8":vars.arm_version)||"";var uv=(process.versions.uv||"").split(".")[0];module.exports=load;function load(e){return runtimeRequire(load.path(e))}load.path=function(e){e=path.resolve(e||".");try{var t=runtimeRequire(path.join(e,"package.json")).name.toUpperCase().replace(/-/g,"_");if(process.env[t+"_PREBUILD"])e=process.env[t+"_PREBUILD"]}catch(e){}if(!prebuildsOnly){var i=getFirst(path.join(e,"build/Release"),matchBuild);if(i)return i;var n=getFirst(path.join(e,"build/Debug"),matchBuild);if(n)return n}var r=resolve(e);if(r)return r;var s=resolve(path.dirname(process.execPath));if(s)return s;var a=["platform="+platform,"arch="+arch,"runtime="+runtime,"abi="+abi,"uv="+uv,armv?"armv="+armv:"","libc="+libc,"node="+process.versions.node,process.versions&&process.versions.electron?"electron="+process.versions.electron:"",true?"webpack=true":0].filter(Boolean).join(" ");throw new Error("No native build was found for "+a+"\n loaded from: "+e+"\n");function resolve(e){var t=path.join(e,"prebuilds",platform+"-"+arch);var i=readdirSync(t).map(parseTags);var n=i.filter(matchTags(runtime,abi));var r=n.sort(compareTags(runtime))[0];if(r)return path.join(t,r.file)}};function readdirSync(e){try{return fs.readdirSync(e)}catch(e){return[]}}function getFirst(e,t){var i=readdirSync(e).filter(t);return i[0]&&path.join(e,i[0])}function matchBuild(e){return/\.node$/.test(e)}function parseTags(e){var t=e.split(".");var i=t.pop();var n={file:e,specificity:0};if(i!=="node")return;for(var r=0;ri.specificity?-1:1}else{return 0}}}function isElectron(){if(process.versions&&process.versions.electron)return true;if(process.env.ELECTRON_RUN_AS_NODE)return true;return typeof window!=="undefined"&&window.process&&window.process.type==="renderer"}function isAlpine(e){return e==="linux"&&fs.existsSync("/etc/alpine-release")}load.parseTags=parseTags;load.matchTags=matchTags;load.compareTags=compareTags},496:(e,t,i)=>{"use strict";var n=i(7709);var r=i(7249);var s=i(8614).EventEmitter;var a=t=e.exports=new s;var o=i(1669);var u=i(5324);var l=i(3645);u(true);var f=process.stderr;Object.defineProperty(a,"stream",{set:function(e){f=e;if(this.gauge)this.gauge.setWriteTo(f,f)},get:function(){return f}});var c;a.useColor=function(){return c!=null?c:f.isTTY};a.enableColor=function(){c=true;this.gauge.setTheme({hasColor:c,hasUnicode:h})};a.disableColor=function(){c=false;this.gauge.setTheme({hasColor:c,hasUnicode:h})};a.level="info";a.gauge=new r(f,{enabled:false,theme:{hasColor:a.useColor()},template:[{type:"progressbar",length:20},{type:"activityIndicator",kerning:1,length:1},{type:"section",default:""},":",{type:"logline",kerning:1,default:""}]});a.tracker=new n.TrackerGroup;a.progressEnabled=a.gauge.isEnabled();var h;a.enableUnicode=function(){h=true;this.gauge.setTheme({hasColor:this.useColor(),hasUnicode:h})};a.disableUnicode=function(){h=false;this.gauge.setTheme({hasColor:this.useColor(),hasUnicode:h})};a.setGaugeThemeset=function(e){this.gauge.setThemeset(e)};a.setGaugeTemplate=function(e){this.gauge.setTemplate(e)};a.enableProgress=function(){if(this.progressEnabled)return;this.progressEnabled=true;this.tracker.on("change",this.showProgress);if(this._pause)return;this.gauge.enable()};a.disableProgress=function(){if(!this.progressEnabled)return;this.progressEnabled=false;this.tracker.removeListener("change",this.showProgress);this.gauge.disable()};var p=["newGroup","newItem","newStream"];var d=function(e){Object.keys(a).forEach(function(t){if(t[0]==="_")return;if(p.filter(function(e){return e===t}).length)return;if(e[t])return;if(typeof a[t]!=="function")return;var i=a[t];e[t]=function(){return i.apply(a,arguments)}});if(e instanceof n.TrackerGroup){p.forEach(function(t){var i=e[t];e[t]=function(){return d(i.apply(e,arguments))}})}return e};p.forEach(function(e){a[e]=function(){return d(this.tracker[e].apply(this.tracker,arguments))}});a.clearProgress=function(e){if(!this.progressEnabled)return e&&process.nextTick(e);this.gauge.hide(e)};a.showProgress=function(e,t){if(!this.progressEnabled)return;var i={};if(e)i.section=e;var n=a.record[a.record.length-1];if(n){i.subsection=n.prefix;var r=a.disp[n.level]||n.level;var s=this._format(r,a.style[n.level]);if(n.prefix)s+=" "+this._format(n.prefix,this.prefixStyle);s+=" "+n.message.split(/\r?\n/)[0];i.logline=s}i.completed=t||this.tracker.completed();this.gauge.show(i)}.bind(a);a.pause=function(){this._paused=true;if(this.progressEnabled)this.gauge.disable()};a.resume=function(){if(!this._paused)return;this._paused=false;var e=this._buffer;this._buffer=[];e.forEach(function(e){this.emitLog(e)},this);if(this.progressEnabled)this.gauge.enable()};a._buffer=[];var b=0;a.record=[];a.maxRecordSize=1e4;a.log=function(e,t,i){var n=this.levels[e];if(n===undefined){return this.emit("error",new Error(o.format("Undefined log level: %j",e)))}var r=new Array(arguments.length-2);var s=null;for(var a=2;af/10){var h=Math.floor(f*.9);this.record=this.record.slice(-1*h)}this.emitLog(l)}.bind(a);a.emitLog=function(e){if(this._paused){this._buffer.push(e);return}if(this.progressEnabled)this.gauge.pulse(e.prefix);var t=this.levels[e.level];if(t===undefined)return;if(t0&&!isFinite(t))return;var i=a.disp[e.level]!=null?a.disp[e.level]:e.level;this.clearProgress();e.message.split(/\r?\n/).forEach(function(t){if(this.heading){this.write(this.heading,this.headingStyle);this.write(" ")}this.write(i,a.style[e.level]);var n=e.prefix||"";if(n)this.write(" ");this.write(n,this.prefixStyle);this.write(" "+t+"\n")},this);this.showProgress()};a._format=function(e,t){if(!f)return;var i="";if(this.useColor()){t=t||{};var n=[];if(t.fg)n.push(t.fg);if(t.bg)n.push("bg"+t.bg[0].toUpperCase()+t.bg.slice(1));if(t.bold)n.push("bold");if(t.underline)n.push("underline");if(t.inverse)n.push("inverse");if(n.length)i+=l.color(n);if(t.beep)i+=l.beep()}i+=e;if(this.useColor()){i+=l.color("reset")}return i};a.write=function(e,t){if(!f)return;f.write(this._format(e,t))};a.addLevel=function(e,t,i,n){if(n==null)n=e;this.levels[e]=t;this.style[e]=i;if(!this[e]){this[e]=function(){var t=new Array(arguments.length+1);t[0]=e;for(var i=0;i{"use strict";e.exports=Number.isNaN||function(e){return e!==e}},4594:e=>{"use strict";var t=Object.getOwnPropertySymbols;var i=Object.prototype.hasOwnProperty;var n=Object.prototype.propertyIsEnumerable;function toObject(e){if(e===null||e===undefined){throw new TypeError("Object.assign cannot be called with null or undefined")}return Object(e)}function shouldUseNative(){try{if(!Object.assign){return false}var e=new String("abc");e[5]="de";if(Object.getOwnPropertyNames(e)[0]==="5"){return false}var t={};for(var i=0;i<10;i++){t["_"+String.fromCharCode(i)]=i}var n=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if(n.join("")!=="0123456789"){return false}var r={};"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e});if(Object.keys(Object.assign({},r)).join("")!=="abcdefghijklmnopqrst"){return false}return true}catch(e){return false}}e.exports=shouldUseNative()?Object.assign:function(e,r){var s;var a=toObject(e);var o;for(var u=1;u{"use strict";e.exports=i(7188)},1259:(e,t,i)=>{"use strict";const n=i(5622);const r="\\\\/";const s=`[^${r}]`;const a="\\.";const o="\\+";const u="\\?";const l="\\/";const f="(?=.)";const c="[^/]";const h=`(?:${l}|$)`;const p=`(?:^|${l})`;const d=`${a}{1,2}${h}`;const b=`(?!${a})`;const v=`(?!${p}${d})`;const g=`(?!${a}{0,1}${h})`;const _=`(?!${d})`;const y=`[^.${l}]`;const m=`${c}*?`;const x={DOT_LITERAL:a,PLUS_LITERAL:o,QMARK_LITERAL:u,SLASH_LITERAL:l,ONE_CHAR:f,QMARK:c,END_ANCHOR:h,DOTS_SLASH:d,NO_DOT:b,NO_DOTS:v,NO_DOT_SLASH:g,NO_DOTS_SLASH:_,QMARK_NO_DOT:y,STAR:m,START_ANCHOR:p};const E={...x,SLASH_LITERAL:`[${r}]`,QMARK:s,STAR:`${s}*?`,DOTS_SLASH:`${a}{1,2}(?:[${r}]|$)`,NO_DOT:`(?!${a})`,NO_DOTS:`(?!(?:^|[${r}])${a}{1,2}(?:[${r}]|$))`,NO_DOT_SLASH:`(?!${a}{0,1}(?:[${r}]|$))`,NO_DOTS_SLASH:`(?!${a}{1,2}(?:[${r}]|$))`,QMARK_NO_DOT:`[^.${r}]`,START_ANCHOR:`(?:^|[${r}])`,END_ANCHOR:`(?:[${r}]|$)`};const w={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};e.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:w,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:n.sep,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?E:x}}},3155:(e,t,i)=>{"use strict";const n=i(1259);const r=i(6444);const{MAX_LENGTH:s,POSIX_REGEX_SOURCE:a,REGEX_NON_SPECIAL_CHARS:o,REGEX_SPECIAL_CHARS_BACKREF:u,REPLACEMENTS:l}=n;const f=(e,t)=>{if(typeof t.expandRange==="function"){return t.expandRange(...e,t)}e.sort();const i=`[${e.join("-")}]`;try{new RegExp(i)}catch(t){return e.map(e=>r.escapeRegex(e)).join("..")}return i};const c=(e,t)=>{return`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`};const h=(e,t)=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}e=l[e]||e;const i={...t};const h=typeof i.maxLength==="number"?Math.min(s,i.maxLength):s;let p=e.length;if(p>h){throw new SyntaxError(`Input length: ${p}, exceeds maximum allowed length: ${h}`)}const d={type:"bos",value:"",output:i.prepend||""};const b=[d];const v=i.capture?"":"?:";const g=r.isWindows(t);const _=n.globChars(g);const y=n.extglobChars(_);const{DOT_LITERAL:m,PLUS_LITERAL:x,SLASH_LITERAL:E,ONE_CHAR:w,DOTS_SLASH:S,NO_DOT:A,NO_DOT_SLASH:R,NO_DOTS_SLASH:k,QMARK:C,QMARK_NO_DOT:T,STAR:O,START_ANCHOR:N}=_;const I=e=>{return`(${v}(?:(?!${N}${e.dot?S:m}).)*?)`};const L=i.dot?"":A;const P=i.dot?C:T;let M=i.bash===true?I(i):O;if(i.capture){M=`(${M})`}if(typeof i.noext==="boolean"){i.noextglob=i.noext}const H={input:e,index:-1,start:0,dot:i.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:b};e=r.removePrefix(e,H);p=e.length;const F=[];const B=[];const D=[];let $=d;let W;const U=()=>H.index===p-1;const j=H.peek=((t=1)=>e[H.index+t]);const q=H.advance=(()=>e[++H.index]);const G=()=>e.slice(H.index+1);const V=(e="",t=0)=>{H.consumed+=e;H.index+=t};const K=e=>{H.output+=e.output!=null?e.output:e.value;V(e.value)};const z=()=>{let e=1;while(j()==="!"&&(j(2)!=="("||j(3)==="?")){q();H.start++;e++}if(e%2===0){return false}H.negated=true;H.start++;return true};const Q=e=>{H[e]++;D.push(e)};const Z=e=>{H[e]--;D.pop()};const X=e=>{if($.type==="globstar"){const t=H.braces>0&&(e.type==="comma"||e.type==="brace");const i=e.extglob===true||F.length&&(e.type==="pipe"||e.type==="paren");if(e.type!=="slash"&&e.type!=="paren"&&!t&&!i){H.output=H.output.slice(0,-$.output.length);$.type="star";$.value="*";$.output=M;H.output+=$.output}}if(F.length&&e.type!=="paren"&&!y[e.value]){F[F.length-1].inner+=e.value}if(e.value||e.output)K(e);if($&&$.type==="text"&&e.type==="text"){$.value+=e.value;$.output=($.output||"")+e.value;return}e.prev=$;b.push(e);$=e};const Y=(e,t)=>{const n={...y[t],conditions:1,inner:""};n.prev=$;n.parens=H.parens;n.output=H.output;const r=(i.capture?"(":"")+n.open;Q("parens");X({type:e,value:t,output:H.output?"":w});X({type:"paren",extglob:true,value:q(),output:r});F.push(n)};const J=e=>{let t=e.close+(i.capture?")":"");if(e.type==="negate"){let n=M;if(e.inner&&e.inner.length>1&&e.inner.includes("/")){n=I(i)}if(n!==M||U()||/^\)+$/.test(G())){t=e.close=`)$))${n}`}if(e.prev.type==="bos"&&U()){H.negatedExtglob=true}}X({type:"paren",extglob:true,value:W,output:t});Z("parens")};if(i.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let n=false;let s=e.replace(u,(e,t,i,r,s,a)=>{if(r==="\\"){n=true;return e}if(r==="?"){if(t){return t+r+(s?C.repeat(s.length):"")}if(a===0){return P+(s?C.repeat(s.length):"")}return C.repeat(i.length)}if(r==="."){return m.repeat(i.length)}if(r==="*"){if(t){return t+r+(s?M:"")}return M}return t?e:`\\${e}`});if(n===true){if(i.unescape===true){s=s.replace(/\\/g,"")}else{s=s.replace(/\\+/g,e=>{return e.length%2===0?"\\\\":e?"\\":""})}}if(s===e&&i.contains===true){H.output=e;return H}H.output=r.wrapOutput(s,H,t);return H}while(!U()){W=q();if(W==="\0"){continue}if(W==="\\"){const e=j();if(e==="/"&&i.bash!==true){continue}if(e==="."||e===";"){continue}if(!e){W+="\\";X({type:"text",value:W});continue}const t=/^\\+/.exec(G());let n=0;if(t&&t[0].length>2){n=t[0].length;H.index+=n;if(n%2!==0){W+="\\"}}if(i.unescape===true){W=q()||""}else{W+=q()||""}if(H.brackets===0){X({type:"text",value:W});continue}}if(H.brackets>0&&(W!=="]"||$.value==="["||$.value==="[^")){if(i.posix!==false&&W===":"){const e=$.value.slice(1);if(e.includes("[")){$.posix=true;if(e.includes(":")){const e=$.value.lastIndexOf("[");const t=$.value.slice(0,e);const i=$.value.slice(e+2);const n=a[i];if(n){$.value=t+n;H.backtrack=true;q();if(!d.output&&b.indexOf($)===1){d.output=w}continue}}}}if(W==="["&&j()!==":"||W==="-"&&j()==="]"){W=`\\${W}`}if(W==="]"&&($.value==="["||$.value==="[^")){W=`\\${W}`}if(i.posix===true&&W==="!"&&$.value==="["){W="^"}$.value+=W;K({value:W});continue}if(H.quotes===1&&W!=='"'){W=r.escapeRegex(W);$.value+=W;K({value:W});continue}if(W==='"'){H.quotes=H.quotes===1?0:1;if(i.keepQuotes===true){X({type:"text",value:W})}continue}if(W==="("){Q("parens");X({type:"paren",value:W});continue}if(W===")"){if(H.parens===0&&i.strictBrackets===true){throw new SyntaxError(c("opening","("))}const e=F[F.length-1];if(e&&H.parens===e.parens+1){J(F.pop());continue}X({type:"paren",value:W,output:H.parens?")":"\\)"});Z("parens");continue}if(W==="["){if(i.nobracket===true||!G().includes("]")){if(i.nobracket!==true&&i.strictBrackets===true){throw new SyntaxError(c("closing","]"))}W=`\\${W}`}else{Q("brackets")}X({type:"bracket",value:W});continue}if(W==="]"){if(i.nobracket===true||$&&$.type==="bracket"&&$.value.length===1){X({type:"text",value:W,output:`\\${W}`});continue}if(H.brackets===0){if(i.strictBrackets===true){throw new SyntaxError(c("opening","["))}X({type:"text",value:W,output:`\\${W}`});continue}Z("brackets");const e=$.value.slice(1);if($.posix!==true&&e[0]==="^"&&!e.includes("/")){W=`/${W}`}$.value+=W;K({value:W});if(i.literalBrackets===false||r.hasRegexChars(e)){continue}const t=r.escapeRegex($.value);H.output=H.output.slice(0,-$.value.length);if(i.literalBrackets===true){H.output+=t;$.value=t;continue}$.value=`(${v}${t}|${$.value})`;H.output+=$.value;continue}if(W==="{"&&i.nobrace!==true){Q("braces");const e={type:"brace",value:W,output:"(",outputIndex:H.output.length,tokensIndex:H.tokens.length};B.push(e);X(e);continue}if(W==="}"){const e=B[B.length-1];if(i.nobrace===true||!e){X({type:"text",value:W,output:W});continue}let t=")";if(e.dots===true){const e=b.slice();const n=[];for(let t=e.length-1;t>=0;t--){b.pop();if(e[t].type==="brace"){break}if(e[t].type!=="dots"){n.unshift(e[t].value)}}t=f(n,i);H.backtrack=true}if(e.comma!==true&&e.dots!==true){const i=H.output.slice(0,e.outputIndex);const n=H.tokens.slice(e.tokensIndex);e.value=e.output="\\{";W=t="\\}";H.output=i;for(const e of n){H.output+=e.output||e.value}}X({type:"brace",value:W,output:t});Z("braces");B.pop();continue}if(W==="|"){if(F.length>0){F[F.length-1].conditions++}X({type:"text",value:W});continue}if(W===","){let e=W;const t=B[B.length-1];if(t&&D[D.length-1]==="braces"){t.comma=true;e="|"}X({type:"comma",value:W,output:e});continue}if(W==="/"){if($.type==="dot"&&H.index===H.start+1){H.start=H.index+1;H.consumed="";H.output="";b.pop();$=d;continue}X({type:"slash",value:W,output:E});continue}if(W==="."){if(H.braces>0&&$.type==="dot"){if($.value===".")$.output=m;const e=B[B.length-1];$.type="dots";$.output+=W;$.value+=W;e.dots=true;continue}if(H.braces+H.parens===0&&$.type!=="bos"&&$.type!=="slash"){X({type:"text",value:W,output:m});continue}X({type:"dot",value:W,output:m});continue}if(W==="?"){const e=$&&$.value==="(";if(!e&&i.noextglob!==true&&j()==="("&&j(2)!=="?"){Y("qmark",W);continue}if($&&$.type==="paren"){const e=j();let t=W;if(e==="<"&&!r.supportsLookbehinds()){throw new Error("Node.js v10 or higher is required for regex lookbehinds")}if($.value==="("&&!/[!=<:]/.test(e)||e==="<"&&!/<([!=]|\w+>)/.test(G())){t=`\\${W}`}X({type:"text",value:W,output:t});continue}if(i.dot!==true&&($.type==="slash"||$.type==="bos")){X({type:"qmark",value:W,output:T});continue}X({type:"qmark",value:W,output:C});continue}if(W==="!"){if(i.noextglob!==true&&j()==="("){if(j(2)!=="?"||!/[!=<:]/.test(j(3))){Y("negate",W);continue}}if(i.nonegate!==true&&H.index===0){z();continue}}if(W==="+"){if(i.noextglob!==true&&j()==="("&&j(2)!=="?"){Y("plus",W);continue}if($&&$.value==="("||i.regex===false){X({type:"plus",value:W,output:x});continue}if($&&($.type==="bracket"||$.type==="paren"||$.type==="brace")||H.parens>0){X({type:"plus",value:W});continue}X({type:"plus",value:x});continue}if(W==="@"){if(i.noextglob!==true&&j()==="("&&j(2)!=="?"){X({type:"at",extglob:true,value:W,output:""});continue}X({type:"text",value:W});continue}if(W!=="*"){if(W==="$"||W==="^"){W=`\\${W}`}const e=o.exec(G());if(e){W+=e[0];H.index+=e[0].length}X({type:"text",value:W});continue}if($&&($.type==="globstar"||$.star===true)){$.type="star";$.star=true;$.value+=W;$.output=M;H.backtrack=true;H.globstar=true;V(W);continue}let t=G();if(i.noextglob!==true&&/^\([^?]/.test(t)){Y("star",W);continue}if($.type==="star"){if(i.noglobstar===true){V(W);continue}const n=$.prev;const r=n.prev;const s=n.type==="slash"||n.type==="bos";const a=r&&(r.type==="star"||r.type==="globstar");if(i.bash===true&&(!s||t[0]&&t[0]!=="/")){X({type:"star",value:W,output:""});continue}const o=H.braces>0&&(n.type==="comma"||n.type==="brace");const u=F.length&&(n.type==="pipe"||n.type==="paren");if(!s&&n.type!=="paren"&&!o&&!u){X({type:"star",value:W,output:""});continue}while(t.slice(0,3)==="/**"){const i=e[H.index+4];if(i&&i!=="/"){break}t=t.slice(3);V("/**",3)}if(n.type==="bos"&&U()){$.type="globstar";$.value+=W;$.output=I(i);H.output=$.output;H.globstar=true;V(W);continue}if(n.type==="slash"&&n.prev.type!=="bos"&&!a&&U()){H.output=H.output.slice(0,-(n.output+$.output).length);n.output=`(?:${n.output}`;$.type="globstar";$.output=I(i)+(i.strictSlashes?")":"|$)");$.value+=W;H.globstar=true;H.output+=n.output+$.output;V(W);continue}if(n.type==="slash"&&n.prev.type!=="bos"&&t[0]==="/"){const e=t[1]!==void 0?"|$":"";H.output=H.output.slice(0,-(n.output+$.output).length);n.output=`(?:${n.output}`;$.type="globstar";$.output=`${I(i)}${E}|${E}${e})`;$.value+=W;H.output+=n.output+$.output;H.globstar=true;V(W+q());X({type:"slash",value:"/",output:""});continue}if(n.type==="bos"&&t[0]==="/"){$.type="globstar";$.value+=W;$.output=`(?:^|${E}|${I(i)}${E})`;H.output=$.output;H.globstar=true;V(W+q());X({type:"slash",value:"/",output:""});continue}H.output=H.output.slice(0,-$.output.length);$.type="globstar";$.output=I(i);$.value+=W;H.output+=$.output;H.globstar=true;V(W);continue}const n={type:"star",value:W,output:M};if(i.bash===true){n.output=".*?";if($.type==="bos"||$.type==="slash"){n.output=L+n.output}X(n);continue}if($&&($.type==="bracket"||$.type==="paren")&&i.regex===true){n.output=W;X(n);continue}if(H.index===H.start||$.type==="slash"||$.type==="dot"){if($.type==="dot"){H.output+=R;$.output+=R}else if(i.dot===true){H.output+=k;$.output+=k}else{H.output+=L;$.output+=L}if(j()!=="*"){H.output+=w;$.output+=w}}X(n)}while(H.brackets>0){if(i.strictBrackets===true)throw new SyntaxError(c("closing","]"));H.output=r.escapeLast(H.output,"[");Z("brackets")}while(H.parens>0){if(i.strictBrackets===true)throw new SyntaxError(c("closing",")"));H.output=r.escapeLast(H.output,"(");Z("parens")}while(H.braces>0){if(i.strictBrackets===true)throw new SyntaxError(c("closing","}"));H.output=r.escapeLast(H.output,"{");Z("braces")}if(i.strictSlashes!==true&&($.type==="star"||$.type==="bracket")){X({type:"maybe_slash",value:"",output:`${E}?`})}if(H.backtrack===true){H.output="";for(const e of H.tokens){H.output+=e.output!=null?e.output:e.value;if(e.suffix){H.output+=e.suffix}}}return H};h.fastpaths=((e,t)=>{const i={...t};const a=typeof i.maxLength==="number"?Math.min(s,i.maxLength):s;const o=e.length;if(o>a){throw new SyntaxError(`Input length: ${o}, exceeds maximum allowed length: ${a}`)}e=l[e]||e;const u=r.isWindows(t);const{DOT_LITERAL:f,SLASH_LITERAL:c,ONE_CHAR:h,DOTS_SLASH:p,NO_DOT:d,NO_DOTS:b,NO_DOTS_SLASH:v,STAR:g,START_ANCHOR:_}=n.globChars(u);const y=i.dot?b:d;const m=i.dot?v:d;const x=i.capture?"":"?:";const E={negated:false,prefix:""};let w=i.bash===true?".*?":g;if(i.capture){w=`(${w})`}const S=e=>{if(e.noglobstar===true)return w;return`(${x}(?:(?!${_}${e.dot?p:f}).)*?)`};const A=e=>{switch(e){case"*":return`${y}${h}${w}`;case".*":return`${f}${h}${w}`;case"*.*":return`${y}${w}${f}${h}${w}`;case"*/*":return`${y}${w}${c}${h}${m}${w}`;case"**":return y+S(i);case"**/*":return`(?:${y}${S(i)}${c})?${m}${h}${w}`;case"**/*.*":return`(?:${y}${S(i)}${c})?${m}${w}${f}${h}${w}`;case"**/.*":return`(?:${y}${S(i)}${c})?${f}${h}${w}`;default:{const t=/^(.*?)\.(\w+)$/.exec(e);if(!t)return;const i=A(t[1]);if(!i)return;return i+f+t[2]}}};const R=r.removePrefix(e,E);let k=A(R);if(k&&i.strictSlashes!==true){k+=`${c}?`}return k});e.exports=h},7188:(e,t,i)=>{"use strict";const n=i(5622);const r=i(5715);const s=i(3155);const a=i(6444);const o=i(1259);const u=e=>e&&typeof e==="object"&&!Array.isArray(e);const l=(e,t,i=false)=>{if(Array.isArray(e)){const n=e.map(e=>l(e,t,i));const r=e=>{for(const t of n){const i=t(e);if(i)return i}return false};return r}const n=u(e)&&e.tokens&&e.input;if(e===""||typeof e!=="string"&&!n){throw new TypeError("Expected pattern to be a non-empty string")}const r=t||{};const s=a.isWindows(t);const o=n?l.compileRe(e,t):l.makeRe(e,t,false,true);const f=o.state;delete o.state;let c=()=>false;if(r.ignore){const e={...t,ignore:null,onMatch:null,onResult:null};c=l(r.ignore,e,i)}const h=(i,n=false)=>{const{isMatch:a,match:u,output:h}=l.test(i,o,t,{glob:e,posix:s});const p={glob:e,state:f,regex:o,posix:s,input:i,output:h,match:u,isMatch:a};if(typeof r.onResult==="function"){r.onResult(p)}if(a===false){p.isMatch=false;return n?p:false}if(c(i)){if(typeof r.onIgnore==="function"){r.onIgnore(p)}p.isMatch=false;return n?p:false}if(typeof r.onMatch==="function"){r.onMatch(p)}return n?p:true};if(i){h.state=f}return h};l.test=((e,t,i,{glob:n,posix:r}={})=>{if(typeof e!=="string"){throw new TypeError("Expected input to be a string")}if(e===""){return{isMatch:false,output:""}}const s=i||{};const o=s.format||(r?a.toPosixSlashes:null);let u=e===n;let f=u&&o?o(e):e;if(u===false){f=o?o(e):e;u=f===n}if(u===false||s.capture===true){if(s.matchBase===true||s.basename===true){u=l.matchBase(e,t,i,r)}else{u=t.exec(f)}}return{isMatch:Boolean(u),match:u,output:f}});l.matchBase=((e,t,i,r=a.isWindows(i))=>{const s=t instanceof RegExp?t:l.makeRe(t,i);return s.test(n.basename(e))});l.isMatch=((e,t,i)=>l(t,i)(e));l.parse=((e,t)=>{if(Array.isArray(e))return e.map(e=>l.parse(e,t));return s(e,{...t,fastpaths:false})});l.scan=((e,t)=>r(e,t));l.compileRe=((e,t,i=false,n=false)=>{if(i===true){return e.output}const r=t||{};const s=r.contains?"":"^";const a=r.contains?"":"$";let o=`${s}(?:${e.output})${a}`;if(e&&e.negated===true){o=`^(?!${o}).*$`}const u=l.toRegex(o,t);if(n===true){u.state=e}return u});l.makeRe=((e,t,i=false,n=false)=>{if(!e||typeof e!=="string"){throw new TypeError("Expected a non-empty string")}const r=t||{};let a={negated:false,fastpaths:true};let o="";let u;if(e.startsWith("./")){e=e.slice(2);o=a.prefix="./"}if(r.fastpaths!==false&&(e[0]==="."||e[0]==="*")){u=s.fastpaths(e,t)}if(u===undefined){a=s(e,t);a.prefix=o+(a.prefix||"")}else{a.output=u}return l.compileRe(a,t,i,n)});l.toRegex=((e,t)=>{try{const i=t||{};return new RegExp(e,i.flags||(i.nocase?"i":""))}catch(e){if(t&&t.debug===true)throw e;return/$^/}});l.constants=o;e.exports=l},5715:(e,t,i)=>{"use strict";const n=i(6444);const{CHAR_ASTERISK:r,CHAR_AT:s,CHAR_BACKWARD_SLASH:a,CHAR_COMMA:o,CHAR_DOT:u,CHAR_EXCLAMATION_MARK:l,CHAR_FORWARD_SLASH:f,CHAR_LEFT_CURLY_BRACE:c,CHAR_LEFT_PARENTHESES:h,CHAR_LEFT_SQUARE_BRACKET:p,CHAR_PLUS:d,CHAR_QUESTION_MARK:b,CHAR_RIGHT_CURLY_BRACE:v,CHAR_RIGHT_PARENTHESES:g,CHAR_RIGHT_SQUARE_BRACKET:_}=i(1259);const y=e=>{return e===f||e===a};const m=e=>{if(e.isPrefix!==true){e.depth=e.isGlobstar?Infinity:1}};const x=(e,t)=>{const i=t||{};const x=e.length-1;const E=i.parts===true||i.scanToEnd===true;const w=[];const S=[];const A=[];let R=e;let k=-1;let C=0;let T=0;let O=false;let N=false;let I=false;let L=false;let P=false;let M=false;let H=false;let F=false;let B=false;let D=0;let $;let W;let U={value:"",depth:0,isGlob:false};const j=()=>k>=x;const q=()=>R.charCodeAt(k+1);const G=()=>{$=W;return R.charCodeAt(++k)};while(k0){K=R.slice(0,C);R=R.slice(C);T-=C}if(V&&I===true&&T>0){V=R.slice(0,T);z=R.slice(T)}else if(I===true){V="";z=R}else{V=R}if(V&&V!==""&&V!=="/"&&V!==R){if(y(V.charCodeAt(V.length-1))){V=V.slice(0,-1)}}if(i.unescape===true){if(z)z=n.removeBackslashes(z);if(V&&H===true){V=n.removeBackslashes(V)}}const Q={prefix:K,input:e,start:C,base:V,glob:z,isBrace:O,isBracket:N,isGlob:I,isExtglob:L,isGlobstar:P,negated:F};if(i.tokens===true){Q.maxDepth=0;if(!y(W)){S.push(U)}Q.tokens=S}if(i.parts===true||i.tokens===true){let t;for(let n=0;n{"use strict";const n=i(5622);const r=process.platform==="win32";const{REGEX_BACKSLASH:s,REGEX_REMOVE_BACKSLASH:a,REGEX_SPECIAL_CHARS:o,REGEX_SPECIAL_CHARS_GLOBAL:u}=i(1259);t.isObject=(e=>e!==null&&typeof e==="object"&&!Array.isArray(e));t.hasRegexChars=(e=>o.test(e));t.isRegexChar=(e=>e.length===1&&t.hasRegexChars(e));t.escapeRegex=(e=>e.replace(u,"\\$1"));t.toPosixSlashes=(e=>e.replace(s,"/"));t.removeBackslashes=(e=>{return e.replace(a,e=>{return e==="\\"?"":e})});t.supportsLookbehinds=(()=>{const e=process.version.slice(1).split(".").map(Number);if(e.length===3&&e[0]>=9||e[0]===8&&e[1]>=10){return true}return false});t.isWindows=(e=>{if(e&&typeof e.windows==="boolean"){return e.windows}return r===true||n.sep==="\\"});t.escapeLast=((e,i,n)=>{const r=e.lastIndexOf(i,n);if(r===-1)return e;if(e[r-1]==="\\")return t.escapeLast(e,i,r-1);return`${e.slice(0,r)}\\${e.slice(r)}`});t.removePrefix=((e,t={})=>{let i=e;if(i.startsWith("./")){i=i.slice(2);t.prefix="./"}return i});t.wrapOutput=((e,t={},i={})=>{const n=i.contains?"":"^";const r=i.contains?"":"$";let s=`${n}(?:${e})${r}`;if(t.negated===true){s=`(?:^(?!${s}).*$)`}return s})},8404:e=>{"use strict";if(typeof process==="undefined"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0){e.exports={nextTick:nextTick}}else{e.exports=process}function nextTick(e,t,i,n){if(typeof e!=="function"){throw new TypeError('"callback" argument must be a function')}var r=arguments.length;var s,a;switch(r){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(function afterTickOne(){e.call(null,t)});case 3:return process.nextTick(function afterTickTwo(){e.call(null,t,i)});case 4:return process.nextTick(function afterTickThree(){e.call(null,t,i,n)});default:s=new Array(r-1);a=0;while(a{"use strict";var n=i(8404);var r=Object.keys||function(e){var t=[];for(var i in e){t.push(i)}return t};e.exports=Duplex;var s=Object.create(i(8334));s.inherits=i(2989);var a=i(1195);var o=i(8063);s.inherits(Duplex,a);{var u=r(o.prototype);for(var l=0;l{"use strict";e.exports=PassThrough;var n=i(2826);var r=Object.create(i(8334));r.inherits=i(2989);r.inherits(PassThrough,n);function PassThrough(e){if(!(this instanceof PassThrough))return new PassThrough(e);n.call(this,e)}PassThrough.prototype._transform=function(e,t,i){i(null,e)}},1195:(e,t,i)=>{"use strict";var n=i(8404);e.exports=Readable;var r=i(1352);var s;Readable.ReadableState=ReadableState;var a=i(8614).EventEmitter;var o=function(e,t){return e.listeners(t).length};var u=i(1065);var l=i(6788).Buffer;var f=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return l.from(e)}function _isUint8Array(e){return l.isBuffer(e)||e instanceof f}var c=Object.create(i(8334));c.inherits=i(2989);var h=i(1669);var p=void 0;if(h&&h.debuglog){p=h.debuglog("stream")}else{p=function(){}}var d=i(8878);var b=i(7915);var v;c.inherits(Readable,u);var g=["error","close","destroy","pause","resume"];function prependListener(e,t,i){if(typeof e.prependListener==="function")return e.prependListener(t,i);if(!e._events||!e._events[t])e.on(t,i);else if(r(e._events[t]))e._events[t].unshift(i);else e._events[t]=[i,e._events[t]]}function ReadableState(e,t){s=s||i(2770);e=e||{};var n=t instanceof s;this.objectMode=!!e.objectMode;if(n)this.objectMode=this.objectMode||!!e.readableObjectMode;var r=e.highWaterMark;var a=e.readableHighWaterMark;var o=this.objectMode?16:16*1024;if(r||r===0)this.highWaterMark=r;else if(n&&(a||a===0))this.highWaterMark=a;else this.highWaterMark=o;this.highWaterMark=Math.floor(this.highWaterMark);this.buffer=new d;this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=null;this.ended=false;this.endEmitted=false;this.reading=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.resumeScheduled=false;this.destroyed=false;this.defaultEncoding=e.defaultEncoding||"utf8";this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(e.encoding){if(!v)v=i(7395).s;this.decoder=new v(e.encoding);this.encoding=e.encoding}}function Readable(e){s=s||i(2770);if(!(this instanceof Readable))return new Readable(e);this._readableState=new ReadableState(e,this);this.readable=true;if(e){if(typeof e.read==="function")this._read=e.read;if(typeof e.destroy==="function")this._destroy=e.destroy}u.call(this)}Object.defineProperty(Readable.prototype,"destroyed",{get:function(){if(this._readableState===undefined){return false}return this._readableState.destroyed},set:function(e){if(!this._readableState){return}this._readableState.destroyed=e}});Readable.prototype.destroy=b.destroy;Readable.prototype._undestroy=b.undestroy;Readable.prototype._destroy=function(e,t){this.push(null);t(e)};Readable.prototype.push=function(e,t){var i=this._readableState;var n;if(!i.objectMode){if(typeof e==="string"){t=t||i.defaultEncoding;if(t!==i.encoding){e=l.from(e,t);t=""}n=true}}else{n=true}return readableAddChunk(this,e,t,false,n)};Readable.prototype.unshift=function(e){return readableAddChunk(this,e,null,true,false)};function readableAddChunk(e,t,i,n,r){var s=e._readableState;if(t===null){s.reading=false;onEofChunk(e,s)}else{var a;if(!r)a=chunkInvalid(s,t);if(a){e.emit("error",a)}else if(s.objectMode||t&&t.length>0){if(typeof t!=="string"&&!s.objectMode&&Object.getPrototypeOf(t)!==l.prototype){t=_uint8ArrayToBuffer(t)}if(n){if(s.endEmitted)e.emit("error",new Error("stream.unshift() after end event"));else addChunk(e,s,t,true)}else if(s.ended){e.emit("error",new Error("stream.push() after EOF"))}else{s.reading=false;if(s.decoder&&!i){t=s.decoder.write(t);if(s.objectMode||t.length!==0)addChunk(e,s,t,false);else maybeReadMore(e,s)}else{addChunk(e,s,t,false)}}}else if(!n){s.reading=false}}return needMoreData(s)}function addChunk(e,t,i,n){if(t.flowing&&t.length===0&&!t.sync){e.emit("data",i);e.read(0)}else{t.length+=t.objectMode?1:i.length;if(n)t.buffer.unshift(i);else t.buffer.push(i);if(t.needReadable)emitReadable(e)}maybeReadMore(e,t)}function chunkInvalid(e,t){var i;if(!_isUint8Array(t)&&typeof t!=="string"&&t!==undefined&&!e.objectMode){i=new TypeError("Invalid non-string/buffer chunk")}return i}function needMoreData(e){return!e.ended&&(e.needReadable||e.length=_){e=_}else{e--;e|=e>>>1;e|=e>>>2;e|=e>>>4;e|=e>>>8;e|=e>>>16;e++}return e}function howMuchToRead(e,t){if(e<=0||t.length===0&&t.ended)return 0;if(t.objectMode)return 1;if(e!==e){if(t.flowing&&t.length)return t.buffer.head.data.length;else return t.length}if(e>t.highWaterMark)t.highWaterMark=computeNewHighWaterMark(e);if(e<=t.length)return e;if(!t.ended){t.needReadable=true;return 0}return t.length}Readable.prototype.read=function(e){p("read",e);e=parseInt(e,10);var t=this._readableState;var i=e;if(e!==0)t.emittedReadable=false;if(e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended)){p("read: emitReadable",t.length,t.ended);if(t.length===0&&t.ended)endReadable(this);else emitReadable(this);return null}e=howMuchToRead(e,t);if(e===0&&t.ended){if(t.length===0)endReadable(this);return null}var n=t.needReadable;p("need readable",n);if(t.length===0||t.length-e0)r=fromList(e,t);else r=null;if(r===null){t.needReadable=true;e=0}else{t.length-=e}if(t.length===0){if(!t.ended)t.needReadable=true;if(i!==e&&t.ended)endReadable(this)}if(r!==null)this.emit("data",r);return r};function onEofChunk(e,t){if(t.ended)return;if(t.decoder){var i=t.decoder.end();if(i&&i.length){t.buffer.push(i);t.length+=t.objectMode?1:i.length}}t.ended=true;emitReadable(e)}function emitReadable(e){var t=e._readableState;t.needReadable=false;if(!t.emittedReadable){p("emitReadable",t.flowing);t.emittedReadable=true;if(t.sync)n.nextTick(emitReadable_,e);else emitReadable_(e)}}function emitReadable_(e){p("emit readable");e.emit("readable");flow(e)}function maybeReadMore(e,t){if(!t.readingMore){t.readingMore=true;n.nextTick(maybeReadMore_,e,t)}}function maybeReadMore_(e,t){var i=t.length;while(!t.reading&&!t.flowing&&!t.ended&&t.length1&&indexOf(r.pipes,e)!==-1)&&!l){p("false write response, pause",i._readableState.awaitDrain);i._readableState.awaitDrain++;f=true}i.pause()}}function onerror(t){p("onerror",t);unpipe();e.removeListener("error",onerror);if(o(e,"error")===0)e.emit("error",t)}prependListener(e,"error",onerror);function onclose(){e.removeListener("finish",onfinish);unpipe()}e.once("close",onclose);function onfinish(){p("onfinish");e.removeListener("close",onclose);unpipe()}e.once("finish",onfinish);function unpipe(){p("unpipe");i.unpipe(e)}e.emit("pipe",i);if(!r.flowing){p("pipe resume");i.resume()}return e};function pipeOnDrain(e){return function(){var t=e._readableState;p("pipeOnDrain",t.awaitDrain);if(t.awaitDrain)t.awaitDrain--;if(t.awaitDrain===0&&o(e,"data")){t.flowing=true;flow(e)}}}Readable.prototype.unpipe=function(e){var t=this._readableState;var i={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1){if(e&&e!==t.pipes)return this;if(!e)e=t.pipes;t.pipes=null;t.pipesCount=0;t.flowing=false;if(e)e.emit("unpipe",this,i);return this}if(!e){var n=t.pipes;var r=t.pipesCount;t.pipes=null;t.pipesCount=0;t.flowing=false;for(var s=0;s=t.length){if(t.decoder)i=t.buffer.join("");else if(t.buffer.length===1)i=t.buffer.head.data;else i=t.buffer.concat(t.length);t.buffer.clear()}else{i=fromListPartial(e,t.buffer,t.decoder)}return i}function fromListPartial(e,t,i){var n;if(es.length?s.length:e;if(a===s.length)r+=s;else r+=s.slice(0,e);e-=a;if(e===0){if(a===s.length){++n;if(i.next)t.head=i.next;else t.head=t.tail=null}else{t.head=i;i.data=s.slice(a)}break}++n}t.length-=n;return r}function copyFromBuffer(e,t){var i=l.allocUnsafe(e);var n=t.head;var r=1;n.data.copy(i);e-=n.data.length;while(n=n.next){var s=n.data;var a=e>s.length?s.length:e;s.copy(i,i.length-e,0,a);e-=a;if(e===0){if(a===s.length){++r;if(n.next)t.head=n.next;else t.head=t.tail=null}else{t.head=n;n.data=s.slice(a)}break}++r}t.length-=r;return i}function endReadable(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!t.endEmitted){t.ended=true;n.nextTick(endReadableNT,t,e)}}function endReadableNT(e,t){if(!e.endEmitted&&e.length===0){e.endEmitted=true;t.readable=false;t.emit("end")}}function indexOf(e,t){for(var i=0,n=e.length;i{"use strict";e.exports=Transform;var n=i(2770);var r=Object.create(i(8334));r.inherits=i(2989);r.inherits(Transform,n);function afterTransform(e,t){var i=this._transformState;i.transforming=false;var n=i.writecb;if(!n){return this.emit("error",new Error("write callback called multiple times"))}i.writechunk=null;i.writecb=null;if(t!=null)this.push(t);n(e);var r=this._readableState;r.reading=false;if(r.needReadable||r.length{"use strict";var n=i(8404);e.exports=Writable;function WriteReq(e,t,i){this.chunk=e;this.encoding=t;this.callback=i;this.next=null}function CorkedRequest(e){var t=this;this.next=null;this.entry=null;this.finish=function(){onCorkedFinish(t,e)}}var r=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:n.nextTick;var s;Writable.WritableState=WritableState;var a=Object.create(i(8334));a.inherits=i(2989);var o={deprecate:i(2262)};var u=i(1065);var l=i(6788).Buffer;var f=global.Uint8Array||function(){};function _uint8ArrayToBuffer(e){return l.from(e)}function _isUint8Array(e){return l.isBuffer(e)||e instanceof f}var c=i(7915);a.inherits(Writable,u);function nop(){}function WritableState(e,t){s=s||i(2770);e=e||{};var n=t instanceof s;this.objectMode=!!e.objectMode;if(n)this.objectMode=this.objectMode||!!e.writableObjectMode;var r=e.highWaterMark;var a=e.writableHighWaterMark;var o=this.objectMode?16:16*1024;if(r||r===0)this.highWaterMark=r;else if(n&&(a||a===0))this.highWaterMark=a;else this.highWaterMark=o;this.highWaterMark=Math.floor(this.highWaterMark);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var u=e.decodeStrings===false;this.decodeStrings=!u;this.defaultEncoding=e.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(e){onwrite(t,e)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var e=this.bufferedRequest;var t=[];while(e){t.push(e);e=e.next}return t};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:o.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(e){}})();var h;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){h=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(e){if(h.call(this,e))return true;if(this!==Writable)return false;return e&&e._writableState instanceof WritableState}})}else{h=function(e){return e instanceof this}}function Writable(e){s=s||i(2770);if(!h.call(Writable,this)&&!(this instanceof s)){return new Writable(e)}this._writableState=new WritableState(e,this);this.writable=true;if(e){if(typeof e.write==="function")this._write=e.write;if(typeof e.writev==="function")this._writev=e.writev;if(typeof e.destroy==="function")this._destroy=e.destroy;if(typeof e.final==="function")this._final=e.final}u.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(e,t){var i=new Error("write after end");e.emit("error",i);n.nextTick(t,i)}function validChunk(e,t,i,r){var s=true;var a=false;if(i===null){a=new TypeError("May not write null values to stream")}else if(typeof i!=="string"&&i!==undefined&&!t.objectMode){a=new TypeError("Invalid non-string/buffer chunk")}if(a){e.emit("error",a);n.nextTick(r,a);s=false}return s}Writable.prototype.write=function(e,t,i){var n=this._writableState;var r=false;var s=!n.objectMode&&_isUint8Array(e);if(s&&!l.isBuffer(e)){e=_uint8ArrayToBuffer(e)}if(typeof t==="function"){i=t;t=null}if(s)t="buffer";else if(!t)t=n.defaultEncoding;if(typeof i!=="function")i=nop;if(n.ended)writeAfterEnd(this,i);else if(s||validChunk(this,n,e,i)){n.pendingcb++;r=writeOrBuffer(this,n,s,e,t,i)}return r};Writable.prototype.cork=function(){var e=this._writableState;e.corked++};Writable.prototype.uncork=function(){var e=this._writableState;if(e.corked){e.corked--;if(!e.writing&&!e.corked&&!e.finished&&!e.bufferProcessing&&e.bufferedRequest)clearBuffer(this,e)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(e){if(typeof e==="string")e=e.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);this._writableState.defaultEncoding=e;return this};function decodeChunk(e,t,i){if(!e.objectMode&&e.decodeStrings!==false&&typeof t==="string"){t=l.from(t,i)}return t}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function writeOrBuffer(e,t,i,n,r,s){if(!i){var a=decodeChunk(t,n,r);if(n!==a){i=true;r="buffer";n=a}}var o=t.objectMode?1:n.length;t.length+=o;var u=t.length{"use strict";function _classCallCheck(e,t){if(!(e instanceof t)){throw new TypeError("Cannot call a class as a function")}}var n=i(6788).Buffer;var r=i(1669);function copyBuffer(e,t,i){e.copy(t,i)}e.exports=function(){function BufferList(){_classCallCheck(this,BufferList);this.head=null;this.tail=null;this.length=0}BufferList.prototype.push=function push(e){var t={data:e,next:null};if(this.length>0)this.tail.next=t;else this.head=t;this.tail=t;++this.length};BufferList.prototype.unshift=function unshift(e){var t={data:e,next:this.head};if(this.length===0)this.tail=t;this.head=t;++this.length};BufferList.prototype.shift=function shift(){if(this.length===0)return;var e=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return e};BufferList.prototype.clear=function clear(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=function join(e){if(this.length===0)return"";var t=this.head;var i=""+t.data;while(t=t.next){i+=e+t.data}return i};BufferList.prototype.concat=function concat(e){if(this.length===0)return n.alloc(0);if(this.length===1)return this.head.data;var t=n.allocUnsafe(e>>>0);var i=this.head;var r=0;while(i){copyBuffer(i.data,t,r);r+=i.data.length;i=i.next}return t};return BufferList}();if(r&&r.inspect&&r.inspect.custom){e.exports.prototype[r.inspect.custom]=function(){var e=r.inspect({length:this.length});return this.constructor.name+" "+e}}},7915:(e,t,i)=>{"use strict";var n=i(8404);function destroy(e,t){var i=this;var r=this._readableState&&this._readableState.destroyed;var s=this._writableState&&this._writableState.destroyed;if(r||s){if(t){t(e)}else if(e&&(!this._writableState||!this._writableState.errorEmitted)){n.nextTick(emitErrorNT,this,e)}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(e||null,function(e){if(!t&&e){n.nextTick(emitErrorNT,i,e);if(i._writableState){i._writableState.errorEmitted=true}}else if(t){t(e)}});return this}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(e,t){e.emit("error",t)}e.exports={destroy:destroy,undestroy:undestroy}},1065:(e,t,i)=>{e.exports=i(2413)},6788:(e,t,i)=>{var n=i(4293);var r=n.Buffer;function copyProps(e,t){for(var i in e){t[i]=e[i]}}if(r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow){e.exports=n}else{copyProps(n,t);t.Buffer=SafeBuffer}function SafeBuffer(e,t,i){return r(e,t,i)}copyProps(r,SafeBuffer);SafeBuffer.from=function(e,t,i){if(typeof e==="number"){throw new TypeError("Argument must not be a number")}return r(e,t,i)};SafeBuffer.alloc=function(e,t,i){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}var n=r(e);if(t!==undefined){if(typeof i==="string"){n.fill(t,i)}else{n.fill(t)}}else{n.fill(0)}return n};SafeBuffer.allocUnsafe=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return r(e)};SafeBuffer.allocUnsafeSlow=function(e){if(typeof e!=="number"){throw new TypeError("Argument must be a number")}return n.SlowBuffer(e)}},7395:(e,t,i)=>{"use strict";var n=i(6788).Buffer;var r=n.isEncoding||function(e){e=""+e;switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function _normalizeEncoding(e){if(!e)return"utf8";var t;while(true){switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase();t=true}}}function normalizeEncoding(e){var t=_normalizeEncoding(e);if(typeof t!=="string"&&(n.isEncoding===r||!r(e)))throw new Error("Unknown encoding: "+e);return t||e}t.s=StringDecoder;function StringDecoder(e){this.encoding=normalizeEncoding(e);var t;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;t=4;break;case"utf8":this.fillLast=utf8FillLast;t=4;break;case"base64":this.text=base64Text;this.end=base64End;t=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=n.allocUnsafe(t)}StringDecoder.prototype.write=function(e){if(e.length===0)return"";var t;var i;if(this.lastNeed){t=this.fillLast(e);if(t===undefined)return"";i=this.lastNeed;this.lastNeed=0}else{i=0}if(i>5===6)return 2;else if(e>>4===14)return 3;else if(e>>3===30)return 4;return e>>6===2?-1:-2}function utf8CheckIncomplete(e,t,i){var n=t.length-1;if(n=0){if(r>0)e.lastNeed=r-1;return r}if(--n=0){if(r>0)e.lastNeed=r-2;return r}if(--n=0){if(r>0){if(r===2)r=0;else e.lastNeed=r-3}return r}return 0}function utf8CheckExtraBytes(e,t,i){if((t[0]&192)!==128){e.lastNeed=0;return"�"}if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128){e.lastNeed=1;return"�"}if(e.lastNeed>2&&t.length>2){if((t[2]&192)!==128){e.lastNeed=2;return"�"}}}}function utf8FillLast(e){var t=this.lastTotal-this.lastNeed;var i=utf8CheckExtraBytes(this,e,t);if(i!==undefined)return i;if(this.lastNeed<=e.length){e.copy(this.lastChar,t,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}e.copy(this.lastChar,t,0,e.length);this.lastNeed-=e.length}function utf8Text(e,t){var i=utf8CheckIncomplete(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=i;var n=e.length-(i-this.lastNeed);e.copy(this.lastChar,0,n);return e.toString("utf8",t,n)}function utf8End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+"�";return t}function utf16Text(e,t){if((e.length-t)%2===0){var i=e.toString("utf16le",t);if(i){var n=i.charCodeAt(i.length-1);if(n>=55296&&n<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1];return i.slice(0,-1)}}return i}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=e[e.length-1];return e.toString("utf16le",t,e.length-1)}function utf16End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var i=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,i)}return t}function base64Text(e,t){var i=(e.length-t)%3;if(i===0)return e.toString("base64",t);this.lastNeed=3-i;this.lastTotal=3;if(i===1){this.lastChar[0]=e[e.length-1]}else{this.lastChar[0]=e[e.length-2];this.lastChar[1]=e[e.length-1]}return e.toString("base64",t,e.length-i)}function base64End(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed)return t+this.lastChar.toString("base64",0,3-this.lastNeed);return t}function simpleWrite(e){return e.toString(this.encoding)}function simpleEnd(e){return e&&e.length?this.write(e):""}},8193:(e,t,i)=>{var n=i(2413);if(process.env.READABLE_STREAM==="disable"&&n){e.exports=n;t=e.exports=n.Readable;t.Readable=n.Readable;t.Writable=n.Writable;t.Duplex=n.Duplex;t.Transform=n.Transform;t.PassThrough=n.PassThrough;t.Stream=n}else{t=e.exports=i(1195);t.Stream=n||t;t.Readable=t;t.Writable=i(8063);t.Duplex=i(2770);t.Transform=i(2826);t.PassThrough=i(143)}},9316:(e,t,i)=>{"use strict";const n=i(5622);const r=i(2282);const s=i(5747);const a=(e,t,i)=>{if(typeof e!=="string"){throw new TypeError(`Expected \`fromDir\` to be of type \`string\`, got \`${typeof e}\``)}if(typeof t!=="string"){throw new TypeError(`Expected \`moduleId\` to be of type \`string\`, got \`${typeof t}\``)}try{e=s.realpathSync(e)}catch(t){if(t.code==="ENOENT"){e=n.resolve(e)}else if(i){return}else{throw t}}const a=n.join(e,"noop.js");const o=()=>r._resolveFilename(t,{id:a,filename:a,paths:r._nodeModulePaths(e)});if(i){try{return o()}catch(e){return}}return o()};e.exports=((e,t)=>a(e,t));e.exports.silent=((e,t)=>a(e,t,true))},3413:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:true});function _interopDefault(e){return e&&typeof e==="object"&&"default"in e?e["default"]:e}var n=i(5622);var r=_interopDefault(n);var s=i(4855);var a=_interopDefault(i(1669));const o=function addExtension(e,t=".js"){if(!n.extname(e))e+=t;return e};const u={ArrayPattern(e,t){for(const i of t.elements){if(i)u[i.type](e,i)}},AssignmentPattern(e,t){u[t.left.type](e,t.left)},Identifier(e,t){e.push(t.name)},MemberExpression(){},ObjectPattern(e,t){for(const i of t.properties){if(i.type==="RestElement"){u.RestElement(e,i)}else{u[i.value.type](e,i.value)}}},RestElement(e,t){u[t.argument.type](e,t.argument)}};const l=function extractAssignedNames(e){const t=[];u[e.type](t,e);return t};const f={const:true,let:true};class Scope{constructor(e={}){this.parent=e.parent;this.isBlockScope=!!e.block;this.declarations=Object.create(null);if(e.params){e.params.forEach(e=>{l(e).forEach(e=>{this.declarations[e]=true})})}}addDeclaration(e,t,i){if(!t&&this.isBlockScope){this.parent.addDeclaration(e,t,i)}else if(e.id){l(e.id).forEach(e=>{this.declarations[e]=true})}}contains(e){return this.declarations[e]||(this.parent?this.parent.contains(e):false)}}const c=function attachScopes(e,t="scope"){let i=new Scope;s.walk(e,{enter(e,n){if(/(Function|Class)Declaration/.test(e.type)){i.addDeclaration(e,false,false)}if(e.type==="VariableDeclaration"){const t=e.kind;const n=f[t];e.declarations.forEach(e=>{i.addDeclaration(e,n,true)})}let r;if(/Function/.test(e.type)){r=new Scope({parent:i,block:false,params:e.params});if(e.type==="FunctionExpression"&&e.id){r.addDeclaration(e,false,false)}}if(e.type==="BlockStatement"&&!/Function/.test(n.type)){r=new Scope({parent:i,block:true})}if(e.type==="CatchClause"){r=new Scope({parent:i,params:e.param?[e.param]:[],block:true})}if(r){Object.defineProperty(e,t,{value:r,configurable:true});i=r}},leave(e){if(e[t])i=i.parent}});return i};function createCommonjsModule(e,t){return t={exports:{}},e(t,t.exports),t.exports}var h=createCommonjsModule(function(e,t){t.isInteger=(e=>{if(typeof e==="number"){return Number.isInteger(e)}if(typeof e==="string"&&e.trim()!==""){return Number.isInteger(Number(e))}return false});t.find=((e,t)=>e.nodes.find(e=>e.type===t));t.exceedsLimit=((e,i,n=1,r)=>{if(r===false)return false;if(!t.isInteger(e)||!t.isInteger(i))return false;return(Number(i)-Number(e))/Number(n)>=r});t.escapeNode=((e,t=0,i)=>{let n=e.nodes[t];if(!n)return;if(i&&n.type===i||n.type==="open"||n.type==="close"){if(n.escaped!==true){n.value="\\"+n.value;n.escaped=true}}});t.encloseBrace=(e=>{if(e.type!=="brace")return false;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}return false});t.isInvalidBrace=(e=>{if(e.type!=="brace")return false;if(e.invalid===true||e.dollar)return true;if(e.commas>>0+e.ranges>>0===0){e.invalid=true;return true}if(e.open!==true||e.close!==true){e.invalid=true;return true}return false});t.isOpenOrClose=(e=>{if(e.type==="open"||e.type==="close"){return true}return e.open===true||e.close===true});t.reduce=(e=>e.reduce((e,t)=>{if(t.type==="text")e.push(t.value);if(t.type==="range")t.type="text";return e},[]));t.flatten=((...e)=>{const t=[];const i=e=>{for(let n=0;n{let i=(e,n={})=>{let r=t.escapeInvalid&&h.isInvalidBrace(n);let s=e.invalid===true&&t.escapeInvalid===true;let a="";if(e.value){if((r||s)&&h.isOpenOrClose(e)){return"\\"+e.value}return e.value}if(e.value){return e.value}if(e.nodes){for(let t of e.nodes){a+=i(t)}}return a};return i(e)};var w=function(e){if(typeof e==="number"){return e-e===0}if(typeof e==="string"&&e.trim()!==""){return Number.isFinite?Number.isFinite(+e):isFinite(+e)}return false};const S=(e,t,i)=>{if(w(e)===false){throw new TypeError("toRegexRange: expected the first argument to be a number")}if(t===void 0||e===t){return String(e)}if(w(t)===false){throw new TypeError("toRegexRange: expected the second argument to be a number.")}let n=Object.assign({relaxZeros:true},i);if(typeof n.strictZeros==="boolean"){n.relaxZeros=n.strictZeros===false}let r=String(n.relaxZeros);let s=String(n.shorthand);let a=String(n.capture);let o=String(n.wrap);let u=e+":"+t+"="+r+s+a+o;if(S.cache.hasOwnProperty(u)){return S.cache[u].result}let l=Math.min(e,t);let f=Math.max(e,t);if(Math.abs(l-f)===1){let i=e+"|"+t;if(n.capture){return`(${i})`}if(n.wrap===false){return i}return`(?:${i})`}let c=hasPadding(e)||hasPadding(t);let h={min:e,max:t,a:l,b:f};let p=[];let d=[];if(c){h.isPadded=c;h.maxLen=String(h.max).length}if(l<0){let e=f<0?Math.abs(f):1;d=splitToPatterns(e,Math.abs(l),h,n);l=h.a=0}if(f>=0){p=splitToPatterns(l,f,h,n)}h.negatives=d;h.positives=p;h.result=collatePatterns(d,p,n);if(n.capture===true){h.result=`(${h.result})`}else if(n.wrap!==false&&p.length+d.length>1){h.result=`(?:${h.result})`}S.cache[u]=h;return h.result};function collatePatterns(e,t,i){let n=filterPatterns(e,t,"-",false,i)||[];let r=filterPatterns(t,e,"",false,i)||[];let s=filterPatterns(e,t,"-?",true,i)||[];let a=n.concat(s).concat(r);return a.join("|")}function splitToRanges(e,t){let i=1;let n=1;let r=countNines(e,i);let s=new Set([t]);while(e<=r&&r<=t){s.add(r);i+=1;r=countNines(e,i)}r=countZeros(t+1,n)-1;while(e1){o.count.pop()}o.count.push(u.count[0]);o.string=o.pattern+toQuantifier(o.count);a=t+1;continue}if(i.isPadded){l=padZeros(t,i,n)}u.string=l+u.pattern+toQuantifier(u.count);s.push(u);a=t+1;o=u}return s}function filterPatterns(e,t,i,n,r){let s=[];for(let r of e){let{string:e}=r;if(!n&&!contains(t,"string",e)){s.push(i+e)}if(n&&contains(t,"string",e)){s.push(i+e)}}return s}function zip(e,t){let i=[];for(let n=0;nt?1:t>e?-1:0}function contains(e,t,i){return e.some(e=>e[t]===i)}function countNines(e,t){return Number(String(e).slice(0,-t)+"9".repeat(t))}function countZeros(e,t){return e-e%Math.pow(10,t)}function toQuantifier(e){let[t=0,i=""]=e;if(i||t>1){return`{${t+(i?","+i:"")}}`}return""}function toCharacterClass(e,t,i){return`[${e}${t-e===1?"":"-"}${t}]`}function hasPadding(e){return/^-?(0+)\d/.test(e)}function padZeros(e,t,i){if(!t.isPadded){return e}let n=Math.abs(t.maxLen-String(e).length);let r=i.relaxZeros!==false;switch(n){case 0:return"";case 1:return r?"0?":"0";case 2:return r?"0{0,2}":"00";default:{return r?`0{0,${n}}`:`0{${n}}`}}}S.cache={};S.clearCache=(()=>S.cache={});var A=S;const R=e=>e!==null&&typeof e==="object"&&!Array.isArray(e);const k=e=>{return t=>e===true?Number(t):String(t)};const C=e=>{return typeof e==="number"||typeof e==="string"&&e!==""};const T=e=>Number.isInteger(+e);const O=e=>{let t=`${e}`;let i=-1;if(t[0]==="-")t=t.slice(1);if(t==="0")return false;while(t[++i]==="0");return i>0};const N=(e,t,i)=>{if(typeof e==="string"||typeof t==="string"){return true}return i.stringify===true};const I=(e,t,i)=>{if(t>0){let i=e[0]==="-"?"-":"";if(i)e=e.slice(1);e=i+e.padStart(i?t-1:t,"0")}if(i===false){return String(e)}return e};const L=(e,t)=>{let i=e[0]==="-"?"-":"";if(i){e=e.slice(1);t--}while(e.length{e.negatives.sort((e,t)=>et?1:0);e.positives.sort((e,t)=>et?1:0);let i=t.capture?"":"?:";let n="";let r="";let s;if(e.positives.length){n=e.positives.join("|")}if(e.negatives.length){r=`-(${i}${e.negatives.join("|")})`}if(n&&r){s=`${n}|${r}`}else{s=n||r}if(t.wrap){return`(${i}${s})`}return s};const M=(e,t,i,n)=>{if(i){return A(e,t,Object.assign({wrap:false},n))}let r=String.fromCharCode(e);if(e===t)return r;let s=String.fromCharCode(t);return`[${r}-${s}]`};const H=(e,t,i)=>{if(Array.isArray(e)){let t=i.wrap===true;let n=i.capture?"":"?:";return t?`(${n}${e.join("|")})`:e.join("|")}return A(e,t,i)};const F=(...e)=>{return new RangeError("Invalid range arguments: "+a.inspect(...e))};const B=(e,t,i)=>{if(i.strictRanges===true)throw F([e,t]);return[]};const D=(e,t)=>{if(t.strictRanges===true){throw new TypeError(`Expected step "${e}" to be a number`)}return[]};const $=(e,t,i=1,n={})=>{let r=Number(e);let s=Number(t);if(!Number.isInteger(r)||!Number.isInteger(s)){if(n.strictRanges===true)throw F([e,t]);return[]}if(r===0)r=0;if(s===0)s=0;let a=r>s;let o=String(e);let u=String(t);let l=String(i);i=Math.max(Math.abs(i),1);let f=O(o)||O(u)||O(l);let c=f?Math.max(o.length,u.length,l.length):0;let h=f===false&&N(e,t,n)===false;let p=n.transform||k(h);if(n.toRegex&&i===1){return M(L(e,c),L(t,c),true,n)}let d={negatives:[],positives:[]};let b=e=>d[e<0?"negatives":"positives"].push(Math.abs(e));let v=[];let g=0;while(a?r>=s:r<=s){if(n.toRegex===true&&i>1){b(r)}else{v.push(I(p(r,g),c,h))}r=a?r-i:r+i;g++}if(n.toRegex===true){return i>1?P(d,n):H(v,null,Object.assign({wrap:false},n))}return v};const W=(e,t,i=1,n={})=>{if(!T(e)&&e.length>1||!T(t)&&t.length>1){return B(e,t,n)}let r=n.transform||(e=>String.fromCharCode(e));let s=`${e}`.charCodeAt(0);let a=`${t}`.charCodeAt(0);let o=s>a;let u=Math.min(s,a);let l=Math.max(s,a);if(n.toRegex&&i===1){return M(u,l,false,n)}let f=[];let c=0;while(o?s>=a:s<=a){f.push(r(s,c));s=o?s-i:s+i;c++}if(n.toRegex===true){return H(f,null,{wrap:false,options:n})}return f};const U=(e,t,i,n={})=>{if(t==null&&C(e)){return[e]}if(!C(e)||!C(t)){return B(e,t,n)}if(typeof i==="function"){return U(e,t,1,{transform:i})}if(R(i)){return U(e,t,0,i)}let r=Object.assign({},n);if(r.capture===true)r.wrap=true;i=i||r.step||1;if(!T(i)){if(i!=null&&!R(i))return D(i,r);return U(e,t,1,i)}if(T(e)&&T(t)){return $(e,t,i,r)}return W(e,t,Math.max(Math.abs(i),1),r)};var j=U;const q=(e,t={})=>{let i=(e,n={})=>{let r=h.isInvalidBrace(n);let s=e.invalid===true&&t.escapeInvalid===true;let a=r===true||s===true;let o=t.escapeInvalid===true?"\\":"";let u="";if(e.isOpen===true){return o+e.value}if(e.isClose===true){return o+e.value}if(e.type==="open"){return a?o+e.value:"("}if(e.type==="close"){return a?o+e.value:")"}if(e.type==="comma"){return e.prev.type==="comma"?"":a?e.value:"|"}if(e.value){return e.value}if(e.nodes&&e.ranges>0){let i=h.reduce(e.nodes);let n=j(...i,Object.assign({},t,{wrap:false,toRegex:true}));if(n.length!==0){return i.length>1&&n.length>1?`(${n})`:n}}if(e.nodes){for(let t of e.nodes){u+=i(t,e)}}return u};return i(e)};var G=q;const V=(e="",t="",i=false)=>{let n=[];e=[].concat(e);t=[].concat(t);if(!t.length)return e;if(!e.length){return i?h.flatten(t).map(e=>`{${e}}`):t}for(let r of e){if(Array.isArray(r)){for(let e of r){n.push(V(e,t,i))}}else{for(let e of t){if(i===true&&typeof e==="string")e=`{${e}}`;n.push(Array.isArray(e)?V(r,e,i):r+e)}}}return h.flatten(n)};const K=(e,t={})=>{let i=t.rangeLimit===void 0?1e3:t.rangeLimit;let n=(e,r={})=>{e.queue=[];let s=r;let a=r.queue;while(s.type!=="brace"&&s.type!=="root"&&s.parent){s=s.parent;a=s.queue}if(e.invalid||e.dollar){a.push(V(a.pop(),E(e,t)));return}if(e.type==="brace"&&e.invalid!==true&&e.nodes.length===2){a.push(V(a.pop(),["{}"]));return}if(e.nodes&&e.ranges>0){let n=h.reduce(e.nodes);if(h.exceedsLimit(...n,t.step,i)){throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.")}let r=j(...n,t);if(r.length===0){r=E(e,t)}a.push(V(a.pop(),r));e.nodes=[];return}let o=h.encloseBrace(e);let u=e.queue;let l=e;while(l.type!=="brace"&&l.type!=="root"&&l.parent){l=l.parent;u=l.queue}for(let t=0;t",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:"\t",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\ufeff"};const{MAX_LENGTH:Z,CHAR_BACKSLASH:X,CHAR_BACKTICK:Y,CHAR_COMMA:J,CHAR_DOT:ee,CHAR_LEFT_PARENTHESES:te,CHAR_RIGHT_PARENTHESES:ie,CHAR_LEFT_CURLY_BRACE:ne,CHAR_RIGHT_CURLY_BRACE:re,CHAR_LEFT_SQUARE_BRACKET:se,CHAR_RIGHT_SQUARE_BRACKET:ae,CHAR_DOUBLE_QUOTE:oe,CHAR_SINGLE_QUOTE:ue,CHAR_NO_BREAK_SPACE:le,CHAR_ZERO_WIDTH_NOBREAK_SPACE:fe}=Q;const ce=(e,t={})=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}let i=t||{};let n=typeof i.maxLength==="number"?Math.min(Z,i.maxLength):Z;if(e.length>n){throw new SyntaxError(`Input length (${e.length}), exceeds max characters (${n})`)}let r={type:"root",input:e,nodes:[]};let s=[r];let a=r;let o=r;let u=0;let l=e.length;let f=0;let c=0;let h;const p=()=>e[f++];const d=e=>{if(e.type==="text"&&o.type==="dot"){o.type="text"}if(o&&o.type==="text"&&e.type==="text"){o.value+=e.value;return}a.nodes.push(e);e.parent=a;e.prev=o;o=e;return e};d({type:"bos"});while(f0){if(a.ranges>0){a.ranges=0;let e=a.nodes.shift();a.nodes=[e,{type:"text",value:E(a)}]}d({type:"comma",value:h});a.commas++;continue}if(h===ee&&c>0&&a.commas===0){let e=a.nodes;if(c===0||e.length===0){d({type:"text",value:h});continue}if(o.type==="dot"){a.range=[];o.value+=h;o.type="range";if(a.nodes.length!==3&&a.nodes.length!==5){a.invalid=true;a.ranges=0;o.type="text";continue}a.ranges++;a.args=[];continue}if(o.type==="range"){e.pop();let t=e[e.length-1];t.value+=o.value+h;o=t;a.ranges--;continue}d({type:"dot",value:h});continue}d({type:"text",value:h})}do{a=s.pop();if(a.type!=="root"){a.nodes.forEach(e=>{if(!e.nodes){if(e.type==="open")e.isOpen=true;if(e.type==="close")e.isClose=true;if(!e.nodes)e.type="text";e.invalid=true}});let e=s[s.length-1];let t=e.nodes.indexOf(a);e.nodes.splice(t,1,...a.nodes)}}while(s.length>0);d({type:"eos"});return r};var he=ce;const pe=(e,t={})=>{let i=[];if(Array.isArray(e)){for(let n of e){let e=pe.create(n,t);if(Array.isArray(e)){i.push(...e)}else{i.push(e)}}}else{i=[].concat(pe.create(e,t))}if(t&&t.expand===true&&t.nodupes===true){i=[...new Set(i)]}return i};pe.parse=((e,t={})=>he(e,t));pe.stringify=((e,t={})=>{if(typeof e==="string"){return E(pe.parse(e,t),t)}return E(e,t)});pe.compile=((e,t={})=>{if(typeof e==="string"){e=pe.parse(e,t)}return G(e,t)});pe.expand=((e,t={})=>{if(typeof e==="string"){e=pe.parse(e,t)}let i=z(e,t);if(t.noempty===true){i=i.filter(Boolean)}if(t.nodupes===true){i=[...new Set(i)]}return i});pe.create=((e,t={})=>{if(e===""||e.length<3){return[e]}return t.expand!==true?pe.compile(e,t):pe.expand(e,t)});var de=pe;const be="\\\\/";const ve=`[^${be}]`;const ge="\\.";const _e="\\+";const ye="\\?";const me="\\/";const xe="(?=.)";const Ee="[^/]";const we=`(?:${me}|$)`;const Se=`(?:^|${me})`;const Ae=`${ge}{1,2}${we}`;const Re=`(?!${ge})`;const ke=`(?!${Se}${Ae})`;const Ce=`(?!${ge}{0,1}${we})`;const Te=`(?!${Ae})`;const Oe=`[^.${me}]`;const Ne=`${Ee}*?`;const Ie={DOT_LITERAL:ge,PLUS_LITERAL:_e,QMARK_LITERAL:ye,SLASH_LITERAL:me,ONE_CHAR:xe,QMARK:Ee,END_ANCHOR:we,DOTS_SLASH:Ae,NO_DOT:Re,NO_DOTS:ke,NO_DOT_SLASH:Ce,NO_DOTS_SLASH:Te,QMARK_NO_DOT:Oe,STAR:Ne,START_ANCHOR:Se};const Le=Object.assign({},Ie,{SLASH_LITERAL:`[${be}]`,QMARK:ve,STAR:`${ve}*?`,DOTS_SLASH:`${ge}{1,2}(?:[${be}]|$)`,NO_DOT:`(?!${ge})`,NO_DOTS:`(?!(?:^|[${be}])${ge}{1,2}(?:[${be}]|$))`,NO_DOT_SLASH:`(?!${ge}{0,1}(?:[${be}]|$))`,NO_DOTS_SLASH:`(?!${ge}{1,2}(?:[${be}]|$))`,QMARK_NO_DOT:`[^.${be}]`,START_ANCHOR:`(?:^|[${be}])`,END_ANCHOR:`(?:[${be}]|$)`});const Pe={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};var Me={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Pe,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHAR:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:r.sep,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?Le:Ie}};var He=createCommonjsModule(function(e,t){const i=process.platform==="win32";const{REGEX_SPECIAL_CHARS:n,REGEX_SPECIAL_CHARS_GLOBAL:s,REGEX_REMOVE_BACKSLASH:a}=Me;t.isObject=(e=>e!==null&&typeof e==="object"&&!Array.isArray(e));t.hasRegexChars=(e=>n.test(e));t.isRegexChar=(e=>e.length===1&&t.hasRegexChars(e));t.escapeRegex=(e=>e.replace(s,"\\$1"));t.toPosixSlashes=(e=>e.replace(/\\/g,"/"));t.removeBackslashes=(e=>{return e.replace(a,e=>{return e==="\\"?"":e})});t.supportsLookbehinds=(()=>{let e=process.version.slice(1).split(".");if(e.length===3&&+e[0]>=9||+e[0]===8&&+e[1]>=10){return true}return false});t.isWindows=(e=>{if(e&&typeof e.windows==="boolean"){return e.windows}return i===true||r.sep==="\\"});t.escapeLast=((e,i,n)=>{let r=e.lastIndexOf(i,n);if(r===-1)return e;if(e[r-1]==="\\")return t.escapeLast(e,i,r-1);return e.slice(0,r)+"\\"+e.slice(r)})});var Fe=He.isObject;var Be=He.hasRegexChars;var De=He.isRegexChar;var $e=He.escapeRegex;var We=He.toPosixSlashes;var Ue=He.removeBackslashes;var je=He.supportsLookbehinds;var qe=He.isWindows;var Ge=He.escapeLast;const{CHAR_ASTERISK:Ve,CHAR_AT:Ke,CHAR_BACKWARD_SLASH:ze,CHAR_COMMA:Qe,CHAR_DOT:Ze,CHAR_EXCLAMATION_MARK:Xe,CHAR_FORWARD_SLASH:Ye,CHAR_LEFT_CURLY_BRACE:Je,CHAR_LEFT_PARENTHESES:et,CHAR_LEFT_SQUARE_BRACKET:tt,CHAR_PLUS:it,CHAR_QUESTION_MARK:nt,CHAR_RIGHT_CURLY_BRACE:rt,CHAR_RIGHT_PARENTHESES:st,CHAR_RIGHT_SQUARE_BRACKET:at}=Me;const ot=e=>{return e===Ye||e===ze};var ut=(e,t)=>{let i=t||{};let n=e.length-1;let r=-1;let s=0;let a=0;let o=false;let u=false;let l=false;let f=0;let c;let h;let p=false;let d=()=>r>=n;let b=()=>{c=h;return e.charCodeAt(++r)};while(r0){v=e.slice(0,s);e=e.slice(s);a-=s}if(_&&o===true&&a>0){_=e.slice(0,a);y=e.slice(a)}else if(o===true){_="";y=e}else{_=e}if(_&&_!==""&&_!=="/"&&_!==e){if(ot(_.charCodeAt(_.length-1))){_=_.slice(0,-1)}}if(i.unescape===true){if(y)y=He.removeBackslashes(y);if(_&&u===true){_=He.removeBackslashes(_)}}return{prefix:v,input:g,base:_,glob:y,negated:l,isGlob:o}};const{MAX_LENGTH:lt,POSIX_REGEX_SOURCE:ft,REGEX_NON_SPECIAL_CHAR:ct,REGEX_SPECIAL_CHARS_BACKREF:ht,REPLACEMENTS:pt}=Me;const dt=(e,t)=>{if(typeof t.expandRange==="function"){return t.expandRange(...e,t)}e.sort();let i=`[${e.join("-")}]`;try{}catch(t){return e.map(e=>He.escapeRegex(e)).join("..")}return i};const bt=e=>{let t=1;while(e.peek()==="!"&&(e.peek(2)!=="("||e.peek(3)==="?")){e.advance();e.start++;t++}if(t%2===0){return false}e.negated=true;e.start++;return true};const vt=(e,t)=>{return`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`};const gt=(e,t)=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}e=pt[e]||e;let i=Object.assign({},t);let n=typeof i.maxLength==="number"?Math.min(lt,i.maxLength):lt;let r=e.length;if(r>n){throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${n}`)}let s={type:"bos",value:"",output:i.prepend||""};let a=[s];let o=i.capture?"":"?:";let u=He.isWindows(t);const l=Me.globChars(u);const f=Me.extglobChars(l);const{DOT_LITERAL:c,PLUS_LITERAL:h,SLASH_LITERAL:p,ONE_CHAR:d,DOTS_SLASH:b,NO_DOT:v,NO_DOT_SLASH:g,NO_DOTS_SLASH:_,QMARK:y,QMARK_NO_DOT:m,STAR:x,START_ANCHOR:E}=l;const w=e=>{return`(${o}(?:(?!${E}${e.dot?b:c}).)*?)`};let S=i.dot?"":v;let A=i.bash===true?w(i):x;let R=i.dot?y:m;if(i.capture){A=`(${A})`}if(typeof i.noext==="boolean"){i.noextglob=i.noext}let k={index:-1,start:0,consumed:"",output:"",backtrack:false,brackets:0,braces:0,parens:0,quotes:0,tokens:a};let C=[];let T=[];let O=s;let N;const I=()=>k.index===r-1;const L=k.peek=((t=1)=>e[k.index+t]);const P=k.advance=(()=>e[++k.index]);const M=e=>{k.output+=e.output!=null?e.output:e.value;k.consumed+=e.value||""};const H=e=>{k[e]++;T.push(e)};const F=e=>{k[e]--;T.pop()};const B=e=>{if(O.type==="globstar"){let t=k.braces>0&&(e.type==="comma"||e.type==="brace");let i=C.length&&(e.type==="pipe"||e.type==="paren");if(e.type!=="slash"&&e.type!=="paren"&&!t&&!i){k.output=k.output.slice(0,-O.output.length);O.type="star";O.value="*";O.output=A;k.output+=O.output}}if(C.length&&e.type!=="paren"&&!f[e.value]){C[C.length-1].inner+=e.value}if(e.value||e.output)M(e);if(O&&O.type==="text"&&e.type==="text"){O.value+=e.value;return}e.prev=O;a.push(e);O=e};const D=(e,t)=>{let n=Object.assign({},f[t],{conditions:1,inner:""});n.prev=O;n.parens=k.parens;n.output=k.output;let r=(i.capture?"(":"")+n.open;B({type:e,value:t,output:k.output?"":d});B({type:"paren",extglob:true,value:P(),output:r});H("parens");C.push(n)};const $=t=>{let n=t.close+(i.capture?")":"");if(t.type==="negate"){let r=A;if(t.inner&&t.inner.length>1&&t.inner.includes("/")){r=w(i)}if(r!==A||I()||/^\)+$/.test(e.slice(k.index+1))){n=t.close=")$))"+r}if(t.prev.type==="bos"&&I()){k.negatedExtglob=true}}B({type:"paren",extglob:true,value:N,output:n});F("parens")};if(i.fastpaths!==false&&!/(^[*!]|[/{[()\]}"])/.test(e)){let t=false;let n=e.replace(ht,(e,i,n,r,s,a)=>{if(r==="\\"){t=true;return e}if(r==="?"){if(i){return i+r+(s?y.repeat(s.length):"")}if(a===0){return R+(s?y.repeat(s.length):"")}return y.repeat(n.length)}if(r==="."){return c.repeat(n.length)}if(r==="*"){if(i){return i+r+(s?A:"")}return A}return i?e:"\\"+e});if(t===true){if(i.unescape===true){n=n.replace(/\\/g,"")}else{n=n.replace(/\\+/g,e=>{return e.length%2===0?"\\\\":e?"\\":""})}}k.output=n;return k}while(!I()){N=P();if(N==="\0"){continue}if(N==="\\"){let t=L();if(t==="/"&&i.bash!==true){continue}if(t==="."||t===";"){continue}if(!t){N+="\\";B({type:"text",value:N});continue}let n=/^\\+/.exec(e.slice(k.index+1));let r=0;if(n&&n[0].length>2){r=n[0].length;k.index+=r;if(r%2!==0){N+="\\"}}if(i.unescape===true){N=P()||""}else{N+=P()||""}if(k.brackets===0){B({type:"text",value:N});continue}}if(k.brackets>0&&(N!=="]"||O.value==="["||O.value==="[^")){if(i.posix!==false&&N===":"){let e=O.value.slice(1);if(e.includes("[")){O.posix=true;if(e.includes(":")){let e=O.value.lastIndexOf("[");let t=O.value.slice(0,e);let i=O.value.slice(e+2);let n=ft[i];if(n){O.value=t+n;k.backtrack=true;P();if(!s.output&&a.indexOf(O)===1){s.output=d}continue}}}}if(N==="["&&L()!==":"||N==="-"&&L()==="]"){N="\\"+N}if(N==="]"&&(O.value==="["||O.value==="[^")){N="\\"+N}if(i.posix===true&&N==="!"&&O.value==="["){N="^"}O.value+=N;M({value:N});continue}if(k.quotes===1&&N!=='"'){N=He.escapeRegex(N);O.value+=N;M({value:N});continue}if(N==='"'){k.quotes=k.quotes===1?0:1;if(i.keepQuotes===true){B({type:"text",value:N})}continue}if(N==="("){B({type:"paren",value:N});H("parens");continue}if(N===")"){if(k.parens===0&&i.strictBrackets===true){throw new SyntaxError(vt("opening","("))}let e=C[C.length-1];if(e&&k.parens===e.parens+1){$(C.pop());continue}B({type:"paren",value:N,output:k.parens?")":"\\)"});F("parens");continue}if(N==="["){if(i.nobracket===true||!e.slice(k.index+1).includes("]")){if(i.nobracket!==true&&i.strictBrackets===true){throw new SyntaxError(vt("closing","]"))}N="\\"+N}else{H("brackets")}B({type:"bracket",value:N});continue}if(N==="]"){if(i.nobracket===true||O&&O.type==="bracket"&&O.value.length===1){B({type:"text",value:N,output:"\\"+N});continue}if(k.brackets===0){if(i.strictBrackets===true){throw new SyntaxError(vt("opening","["))}B({type:"text",value:N,output:"\\"+N});continue}F("brackets");let e=O.value.slice(1);if(O.posix!==true&&e[0]==="^"&&!e.includes("/")){N="/"+N}O.value+=N;M({value:N});if(i.literalBrackets===false||He.hasRegexChars(e)){continue}let t=He.escapeRegex(O.value);k.output=k.output.slice(0,-O.value.length);if(i.literalBrackets===true){k.output+=t;O.value=t;continue}O.value=`(${o}${t}|${O.value})`;k.output+=O.value;continue}if(N==="{"&&i.nobrace!==true){B({type:"brace",value:N,output:"("});H("braces");continue}if(N==="}"){if(i.nobrace===true||k.braces===0){B({type:"text",value:N,output:"\\"+N});continue}let e=")";if(k.dots===true){let t=a.slice();let n=[];for(let e=t.length-1;e>=0;e--){a.pop();if(t[e].type==="brace"){break}if(t[e].type!=="dots"){n.unshift(t[e].value)}}e=dt(n,i);k.backtrack=true}B({type:"brace",value:N,output:e});F("braces");continue}if(N==="|"){if(C.length>0){C[C.length-1].conditions++}B({type:"text",value:N});continue}if(N===","){let e=N;if(k.braces>0&&T[T.length-1]==="braces"){e="|"}B({type:"comma",value:N,output:e});continue}if(N==="/"){if(O.type==="dot"&&k.index===1){k.start=k.index+1;k.consumed="";k.output="";a.pop();O=s;continue}B({type:"slash",value:N,output:p});continue}if(N==="."){if(k.braces>0&&O.type==="dot"){if(O.value===".")O.output=c;O.type="dots";O.output+=N;O.value+=N;k.dots=true;continue}B({type:"dot",value:N,output:c});continue}if(N==="?"){if(O&&O.type==="paren"){let e=L();let t=N;if(e==="<"&&!He.supportsLookbehinds()){throw new Error("Node.js v10 or higher is required for regex lookbehinds")}if(O.value==="("&&!/[!=<:]/.test(e)||e==="<"&&!/[!=]/.test(L(2))){t="\\"+N}B({type:"text",value:N,output:t});continue}if(i.noextglob!==true&&L()==="("&&L(2)!=="?"){D("qmark",N);continue}if(i.dot!==true&&(O.type==="slash"||O.type==="bos")){B({type:"qmark",value:N,output:m});continue}B({type:"qmark",value:N,output:y});continue}if(N==="!"){if(i.noextglob!==true&&L()==="("){if(L(2)!=="?"||!/[!=<:]/.test(L(3))){D("negate",N);continue}}if(i.nonegate!==true&&k.index===0){bt(k);continue}}if(N==="+"){if(i.noextglob!==true&&L()==="("&&L(2)!=="?"){D("plus",N);continue}if(O&&(O.type==="bracket"||O.type==="paren"||O.type==="brace")){let e=O.extglob===true?"\\"+N:N;B({type:"plus",value:N,output:e});continue}if(k.parens>0&&i.regex!==false){B({type:"plus",value:N});continue}B({type:"plus",value:h});continue}if(N==="@"){if(i.noextglob!==true&&L()==="("&&L(2)!=="?"){B({type:"at",value:N,output:""});continue}B({type:"text",value:N});continue}if(N!=="*"){if(N==="$"||N==="^"){N="\\"+N}let t=ct.exec(e.slice(k.index+1));if(t){N+=t[0];k.index+=t[0].length}B({type:"text",value:N});continue}if(O&&(O.type==="globstar"||O.star===true)){O.type="star";O.star=true;O.value+=N;O.output=A;k.backtrack=true;k.consumed+=N;continue}if(i.noextglob!==true&&L()==="("&&L(2)!=="?"){D("star",N);continue}if(O.type==="star"){if(i.noglobstar===true){k.consumed+=N;continue}let t=O.prev;let n=t.prev;let r=t.type==="slash"||t.type==="bos";let s=n&&(n.type==="star"||n.type==="globstar");if(i.bash===true&&(!r||!I()&&L()!=="/")){B({type:"star",value:N,output:""});continue}let a=k.braces>0&&(t.type==="comma"||t.type==="brace");let o=C.length&&(t.type==="pipe"||t.type==="paren");if(!r&&t.type!=="paren"&&!a&&!o){B({type:"star",value:N,output:""});continue}while(e.slice(k.index+1,k.index+4)==="/**"){let t=e[k.index+4];if(t&&t!=="/"){break}k.consumed+="/**";k.index+=3}if(t.type==="bos"&&I()){O.type="globstar";O.value+=N;O.output=w(i);k.output=O.output;k.consumed+=N;continue}if(t.type==="slash"&&t.prev.type!=="bos"&&!s&&I()){k.output=k.output.slice(0,-(t.output+O.output).length);t.output="(?:"+t.output;O.type="globstar";O.output=w(i)+"|$)";O.value+=N;k.output+=t.output+O.output;k.consumed+=N;continue}let u=L();if(t.type==="slash"&&t.prev.type!=="bos"&&u==="/"){let e=L(2)!==void 0?"|$":"";k.output=k.output.slice(0,-(t.output+O.output).length);t.output="(?:"+t.output;O.type="globstar";O.output=`${w(i)}${p}|${p}${e})`;O.value+=N;k.output+=t.output+O.output;k.consumed+=N+P();B({type:"slash",value:N,output:""});continue}if(t.type==="bos"&&u==="/"){O.type="globstar";O.value+=N;O.output=`(?:^|${p}|${w(i)}${p})`;k.output=O.output;k.consumed+=N+P();B({type:"slash",value:N,output:""});continue}k.output=k.output.slice(0,-O.output.length);O.type="globstar";O.output=w(i);O.value+=N;k.output+=O.output;k.consumed+=N;continue}let t={type:"star",value:N,output:A};if(i.bash===true){t.output=".*?";if(O.type==="bos"||O.type==="slash"){t.output=S+t.output}B(t);continue}if(O&&(O.type==="bracket"||O.type==="paren")&&i.regex===true){t.output=N;B(t);continue}if(k.index===k.start||O.type==="slash"||O.type==="dot"){if(O.type==="dot"){k.output+=g;O.output+=g}else if(i.dot===true){k.output+=_;O.output+=_}else{k.output+=S;O.output+=S}if(L()!=="*"){k.output+=d;O.output+=d}}B(t)}while(k.brackets>0){if(i.strictBrackets===true)throw new SyntaxError(vt("closing","]"));k.output=He.escapeLast(k.output,"[");F("brackets")}while(k.parens>0){if(i.strictBrackets===true)throw new SyntaxError(vt("closing",")"));k.output=He.escapeLast(k.output,"(");F("parens")}while(k.braces>0){if(i.strictBrackets===true)throw new SyntaxError(vt("closing","}"));k.output=He.escapeLast(k.output,"{");F("braces")}if(i.strictSlashes!==true&&(O.type==="star"||O.type==="bracket")){B({type:"maybe_slash",value:"",output:`${p}?`})}if(k.backtrack===true){k.output="";for(let e of k.tokens){k.output+=e.output!=null?e.output:e.value;if(e.suffix){k.output+=e.suffix}}}return k};gt.fastpaths=((e,t)=>{let i=Object.assign({},t);let n=typeof i.maxLength==="number"?Math.min(lt,i.maxLength):lt;let r=e.length;if(r>n){throw new SyntaxError(`Input length: ${r}, exceeds maximum allowed length: ${n}`)}e=pt[e]||e;let s=He.isWindows(t);const{DOT_LITERAL:a,SLASH_LITERAL:o,ONE_CHAR:u,DOTS_SLASH:l,NO_DOT:f,NO_DOTS:c,NO_DOTS_SLASH:h,STAR:p,START_ANCHOR:d}=Me.globChars(s);let b=i.capture?"":"?:";let v=i.bash===true?".*?":p;let g=i.dot?c:f;let _=i.dot?h:f;if(i.capture){v=`(${v})`}const y=e=>{return`(${b}(?:(?!${d}${e.dot?l:a}).)*?)`};const m=e=>{switch(e){case"*":return`${g}${u}${v}`;case".*":return`${a}${u}${v}`;case"*.*":return`${g}${v}${a}${u}${v}`;case"*/*":return`${g}${v}${o}${u}${_}${v}`;case"**":return g+y(i);case"**/*":return`(?:${g}${y(i)}${o})?${_}${u}${v}`;case"**/*.*":return`(?:${g}${y(i)}${o})?${_}${v}${a}${u}${v}`;case"**/.*":return`(?:${g}${y(i)}${o})?${a}${u}${v}`;default:{let i=/^(.*?)\.(\w+)$/.exec(e);if(!i)return;let n=m(i[1],t);if(!n)return;return n+a+i[2]}}};let x=m(e);if(x&&i.strictSlashes!==true){x+=`${o}?`}return x});var _t=gt;const yt=(e,t,i=false)=>{if(Array.isArray(e)){let n=e.map(e=>yt(e,t,i));return e=>{for(let t of n){let i=t(e);if(i)return i}return false}}if(typeof e!=="string"||e===""){throw new TypeError("Expected pattern to be a non-empty string")}let n=t||{};let r=He.isWindows(t);let s=yt.makeRe(e,t,false,true);let a=s.state;delete s.state;let o=()=>false;if(n.ignore){let e=Object.assign({},t,{ignore:null,onMatch:null,onResult:null});o=yt(n.ignore,e,i)}const u=(i,u=false)=>{let{isMatch:l,match:f,output:c}=yt.test(i,s,t,{glob:e,posix:r});let h={glob:e,state:a,regex:s,posix:r,input:i,output:c,match:f,isMatch:l};if(typeof n.onResult==="function"){n.onResult(h)}if(l===false){h.isMatch=false;return u?h:false}if(o(i)){if(typeof n.onIgnore==="function"){n.onIgnore(h)}h.isMatch=false;return u?h:false}if(typeof n.onMatch==="function"){n.onMatch(h)}return u?h:true};if(i){u.state=a}return u};yt.test=((e,t,i,{glob:n,posix:r}={})=>{if(typeof e!=="string"){throw new TypeError("Expected input to be a string")}if(e===""){return{isMatch:false,output:""}}let s=i||{};let a=s.format||(r?He.toPosixSlashes:null);let o=e===n;let u=o&&a?a(e):e;if(o===false){u=a?a(e):e;o=u===n}if(o===false||s.capture===true){if(s.matchBase===true||s.basename===true){o=yt.matchBase(e,t,i,r)}else{o=t.exec(u)}}return{isMatch:!!o,match:o,output:u}});yt.matchBase=((e,t,i,n=He.isWindows(i))=>{let s=t instanceof RegExp?t:yt.makeRe(t,i);return s.test(r.basename(e))});yt.isMatch=((e,t,i)=>yt(t,i)(e));yt.parse=((e,t)=>_t(e,t));yt.scan=((e,t)=>ut(e,t));yt.makeRe=((e,t,i=false,n=false)=>{if(!e||typeof e!=="string"){throw new TypeError("Expected a non-empty string")}let r=t||{};let s=r.contains?"":"^";let a=r.contains?"":"$";let o={negated:false,fastpaths:true};let u="";let l;if(e.startsWith("./")){e=e.slice(2);u=o.prefix="./"}if(r.fastpaths!==false&&(e[0]==="."||e[0]==="*")){l=_t.fastpaths(e,t)}if(l===void 0){o=yt.parse(e,t);o.prefix=u+(o.prefix||"");l=o.output}if(i===true){return l}let f=`${s}(?:${l})${a}`;if(o&&o.negated===true){f=`^(?!${f}).*$`}let c=yt.toRegex(f,t);if(n===true){c.state=o}return c});yt.toRegex=((e,t)=>{try{let i=t||{};return new RegExp(e,i.flags||(i.nocase?"i":""))}catch(e){if(t&&t.debug===true)throw e;return/$^/}});yt.constants=Me;var mt=yt;var xt=mt;const Et=e=>typeof e==="string"&&(e===""||e==="./");const wt=(e,t,i)=>{t=[].concat(t);e=[].concat(e);let n=new Set;let r=new Set;let s=new Set;let a=0;let o=e=>{s.add(e.output);if(i&&i.onResult){i.onResult(e)}};for(let s=0;s!n.has(e));if(i&&l.length===0){if(i.failglob===true){throw new Error(`No matches found for "${t.join(", ")}"`)}if(i.nonull===true||i.nullglob===true){return i.unescape?t.map(e=>e.replace(/\\/g,"")):t}}return l};wt.match=wt;wt.matcher=((e,t)=>xt(e,t));wt.isMatch=((e,t,i)=>xt(t,i)(e));wt.any=wt.isMatch;wt.not=((e,t,i={})=>{t=[].concat(t).map(String);let n=new Set;let r=[];let s=e=>{if(i.onResult)i.onResult(e);r.push(e.output)};let a=wt(e,t,Object.assign({},i,{onResult:s}));for(let e of r){if(!a.includes(e)){n.add(e)}}return[...n]});wt.contains=((e,t,i)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${a.inspect(e)}"`)}if(Array.isArray(t)){return t.some(t=>wt.contains(e,t,i))}if(typeof t==="string"){if(Et(e)||Et(t)){return false}if(e.includes(t)||e.startsWith("./")&&e.slice(2).includes(t)){return true}}return wt.isMatch(e,t,Object.assign({},i,{contains:true}))});wt.matchKeys=((e,t,i)=>{if(!He.isObject(e)){throw new TypeError("Expected the first argument to be an object")}let n=wt(Object.keys(e),t,i);let r={};for(let t of n)r[t]=e[t];return r});wt.some=((e,t,i)=>{let n=[].concat(e);for(let e of[].concat(t)){let t=xt(String(e),i);if(n.some(e=>t(e))){return true}}return false});wt.every=((e,t,i)=>{let n=[].concat(e);for(let e of[].concat(t)){let t=xt(String(e),i);if(!n.every(e=>t(e))){return false}}return true});wt.all=((e,t,i)=>{if(typeof e!=="string"){throw new TypeError(`Expected a string: "${a.inspect(e)}"`)}return[].concat(t).every(t=>xt(t,i)(e))});wt.capture=((e,t,i)=>{let n=He.isWindows(i);let r=xt.makeRe(String(e),Object.assign({},i,{capture:true}));let s=r.exec(n?He.toPosixSlashes(t):t);if(s){return s.slice(1).map(e=>e===void 0?"":e)}});wt.makeRe=((...e)=>xt.makeRe(...e));wt.scan=((...e)=>xt.scan(...e));wt.parse=((e,t)=>{let i=[];for(let n of[].concat(e||[])){for(let e of de(String(n),t)){i.push(xt.parse(e,t))}}return i});wt.braces=((e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");if(t&&t.nobrace===true||!/\{.*\}/.test(e)){return[e]}return de(e,t)});wt.braceExpand=((e,t)=>{if(typeof e!=="string")throw new TypeError("Expected a string");return wt.braces(e,Object.assign({},t,{expand:true}))});var St=wt;function ensureArray(e){if(Array.isArray(e))return e;if(e==undefined)return[];return[e]}function getMatcherString(e,t){if(t===false){return e}return n.resolve(...typeof t==="string"?[t,e]:[e])}const At=function createFilter(e,t,i){const r=i&&i.resolve;const s=e=>{return e instanceof RegExp?e:{test:St.matcher(getMatcherString(e,r).split(n.sep).join("/"),{dot:true})}};const a=ensureArray(e).map(s);const o=ensureArray(t).map(s);return function(e){if(typeof e!=="string")return false;if(/\0/.test(e))return false;e=e.split(n.sep).join("/");for(let t=0;tt.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g,"_");if(/\d/.test(e[0])||Ct.has(e)){e=`_${e}`}return e||"_"};function stringify$2(e){return(JSON.stringify(e)||"undefined").replace(/[\u2028\u2029]/g,e=>`\\u${("000"+e.charCodeAt(0).toString(16)).slice(-4)}`)}function serializeArray(e,t,i){let n="[";const r=t?"\n"+i+t:"";for(let s=0;s0?",":""}${r}${serialize(a,t,i+t)}`}return n+`${t?"\n"+i:""}]`}function serializeObject(e,t,i){let n="{";const r=t?"\n"+i+t:"";const s=Object.keys(e);for(let a=0;a0?",":""}${r}${u}:${t?" ":""}${serialize(e[o],t,i+t)}`}return n+`${t?"\n"+i:""}}`}function serialize(e,t,i){if(e===Infinity)return"Infinity";if(e===-Infinity)return"-Infinity";if(e===0&&1/e===-Infinity)return"-0";if(e instanceof Date)return"new Date("+e.getTime()+")";if(e instanceof RegExp)return e.toString();if(e!==e)return"NaN";if(Array.isArray(e))return serializeArray(e,t,i);if(e===null)return"null";if(typeof e==="object")return serializeObject(e,t,i);return stringify$2(e)}const Ot=function dataToEsm(e,t={}){const i=t.compact?"":"indent"in t?t.indent:"\t";const n=t.compact?"":" ";const r=t.compact?"":"\n";const s=t.preferConst?"const":"var";if(t.namedExports===false||typeof e!=="object"||Array.isArray(e)||e instanceof Date||e instanceof RegExp||e===null){const r=serialize(e,t.compact?null:i,"");const s=n||(/^[{[\-\/]/.test(r)?"":" ");return`export default${s}${r};`}let a="";const o=[];const u=Object.keys(e);for(let l=0;l{e.exports=function(e){[process.stdout,process.stderr].forEach(function(t){if(t._handle&&t.isTTY&&typeof t._handle.setBlocking==="function"){t._handle.setBlocking(e)}})}},2317:(e,t,i)=>{var n=i(2357);var r=i(2935);var s=i(8614);if(typeof s!=="function"){s=s.EventEmitter}var a;if(process.__signal_exit_emitter__){a=process.__signal_exit_emitter__}else{a=process.__signal_exit_emitter__=new s;a.count=0;a.emitted={}}if(!a.infinite){a.setMaxListeners(Infinity);a.infinite=true}e.exports=function(e,t){n.equal(typeof e,"function","a callback must be provided for exit handler");if(u===false){load()}var i="exit";if(t&&t.alwaysLast){i="afterexit"}var r=function(){a.removeListener(i,e);if(a.listeners("exit").length===0&&a.listeners("afterexit").length===0){unload()}};a.on(i,e);return r};e.exports.unload=unload;function unload(){if(!u){return}u=false;r.forEach(function(e){try{process.removeListener(e,o[e])}catch(e){}});process.emit=f;process.reallyExit=l;a.count-=1}function emit(e,t,i){if(a.emitted[e]){return}a.emitted[e]=true;a.emit(e,t,i)}var o={};r.forEach(function(e){o[e]=function listener(){var t=process.listeners(e);if(t.length===a.count){unload();emit("exit",null,e);emit("afterexit",null,e);process.kill(process.pid,e)}}});e.exports.signals=function(){return r};e.exports.load=load;var u=false;function load(){if(u){return}u=true;a.count+=1;r=r.filter(function(e){try{process.on(e,o[e]);return true}catch(e){return false}});process.emit=processEmit;process.reallyExit=processReallyExit}var l=process.reallyExit;function processReallyExit(e){process.exitCode=e||0;emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);l.call(process,process.exitCode)}var f=process.emit;function processEmit(e,t){if(e==="exit"){if(t!==undefined){process.exitCode=t}var i=f.apply(this,arguments);emit("exit",process.exitCode,null);emit("afterexit",process.exitCode,null);return i}else{return f.apply(this,arguments)}}},2935:e=>{e.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32"){e.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT")}if(process.platform==="linux"){e.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}},1353:(e,t,i)=>{"use strict";const n=i(1255);const r=(e,t,i)=>{if(n(e)===false){throw new TypeError("toRegexRange: expected the first argument to be a number")}if(t===void 0||e===t){return String(e)}if(n(t)===false){throw new TypeError("toRegexRange: expected the second argument to be a number.")}let s={relaxZeros:true,...i};if(typeof s.strictZeros==="boolean"){s.relaxZeros=s.strictZeros===false}let a=String(s.relaxZeros);let o=String(s.shorthand);let u=String(s.capture);let l=String(s.wrap);let f=e+":"+t+"="+a+o+u+l;if(r.cache.hasOwnProperty(f)){return r.cache[f].result}let c=Math.min(e,t);let h=Math.max(e,t);if(Math.abs(c-h)===1){let i=e+"|"+t;if(s.capture){return`(${i})`}if(s.wrap===false){return i}return`(?:${i})`}let p=hasPadding(e)||hasPadding(t);let d={min:e,max:t,a:c,b:h};let b=[];let v=[];if(p){d.isPadded=p;d.maxLen=String(d.max).length}if(c<0){let e=h<0?Math.abs(h):1;v=splitToPatterns(e,Math.abs(c),d,s);c=d.a=0}if(h>=0){b=splitToPatterns(c,h,d,s)}d.negatives=v;d.positives=b;d.result=collatePatterns(v,b,s);if(s.capture===true){d.result=`(${d.result})`}else if(s.wrap!==false&&b.length+v.length>1){d.result=`(?:${d.result})`}r.cache[f]=d;return d.result};function collatePatterns(e,t,i){let n=filterPatterns(e,t,"-",false,i)||[];let r=filterPatterns(t,e,"",false,i)||[];let s=filterPatterns(e,t,"-?",true,i)||[];let a=n.concat(s).concat(r);return a.join("|")}function splitToRanges(e,t){let i=1;let n=1;let r=countNines(e,i);let s=new Set([t]);while(e<=r&&r<=t){s.add(r);i+=1;r=countNines(e,i)}r=countZeros(t+1,n)-1;while(e1){o.count.pop()}o.count.push(u.count[0]);o.string=o.pattern+toQuantifier(o.count);a=t+1;continue}if(i.isPadded){l=padZeros(t,i,n)}u.string=l+u.pattern+toQuantifier(u.count);s.push(u);a=t+1;o=u}return s}function filterPatterns(e,t,i,n,r){let s=[];for(let r of e){let{string:e}=r;if(!n&&!contains(t,"string",e)){s.push(i+e)}if(n&&contains(t,"string",e)){s.push(i+e)}}return s}function zip(e,t){let i=[];for(let n=0;nt?1:t>e?-1:0}function contains(e,t,i){return e.some(e=>e[t]===i)}function countNines(e,t){return Number(String(e).slice(0,-t)+"9".repeat(t))}function countZeros(e,t){return e-e%Math.pow(10,t)}function toQuantifier(e){let[t=0,i=""]=e;if(i||t>1){return`{${t+(i?","+i:"")}}`}return""}function toCharacterClass(e,t,i){return`[${e}${t-e===1?"":"-"}${t}]`}function hasPadding(e){return/^-?(0+)\d/.test(e)}function padZeros(e,t,i){if(!t.isPadded){return e}let n=Math.abs(t.maxLen-String(e).length);let r=i.relaxZeros!==false;switch(n){case 0:return"";case 1:return r?"0?":"0";case 2:return r?"0{0,2}":"00";default:{return r?`0{0,${n}}`:`0{${n}}`}}}r.cache={};r.clearCache=(()=>r.cache={});e.exports=r},1255:e=>{"use strict";e.exports=function(e){if(typeof e==="number"){return e-e===0}if(typeof e==="string"&&e.trim()!==""){return Number.isFinite?Number.isFinite(+e):isFinite(+e)}return false}},2262:(e,t,i)=>{e.exports=i(1669).deprecate},7378:(e,t,i)=>{"use strict";var n=i(5994);t.center=alignCenter;t.left=alignLeft;t.right=alignRight;function createPadding(e){var t="";var i=" ";var n=e;do{if(n%2){t+=i}n=Math.floor(n/2);i+=i}while(n);return t}function alignLeft(e,t){var i=e.trimRight();if(i.length===0&&e.length>=t)return e;var r="";var s=n(i);if(s=t)return e;var r="";var s=n(i);if(s=t)return e;var r="";var s="";var a=n(i);if(a{"use strict";e.exports=(e=>{if(Number.isNaN(e)){return false}if(e>=4352&&(e<=4447||e===9001||e===9002||11904<=e&&e<=12871&&e!==12351||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141)){return true}return false})},5994:(e,t,i)=>{"use strict";const n=i(148);const r=i(3869);e.exports=(e=>{if(typeof e!=="string"||e.length===0){return 0}e=n(e);let t=0;for(let i=0;i=127&&n<=159){continue}if(n>=768&&n<=879){continue}if(n>65535){i++}t+=r(n)?2:1}return t})},159:module=>{module.exports=eval("require")("aws-sdk")},8263:module=>{module.exports=eval("require")("mock-aws-s3")},1301:module=>{module.exports=eval("require")("nock")},2357:e=>{"use strict";e.exports=require("assert")},4293:e=>{"use strict";e.exports=require("buffer")},3129:e=>{"use strict";e.exports=require("child_process")},7619:e=>{"use strict";e.exports=require("constants")},8614:e=>{"use strict";e.exports=require("events")},5747:e=>{"use strict";e.exports=require("fs")},2282:e=>{"use strict";e.exports=require("module")},4993:e=>{"use strict";e.exports=require("next/dist/compiled/glob")},2519:e=>{"use strict";e.exports=require("next/dist/compiled/semver")},148:e=>{"use strict";e.exports=require("next/dist/compiled/strip-ansi")},2087:e=>{"use strict";e.exports=require("os")},5622:e=>{"use strict";e.exports=require("path")},8027:e=>{"use strict";e.exports=require("repl")},2413:e=>{"use strict";e.exports=require("stream")},8835:e=>{"use strict";e.exports=require("url")},1669:e=>{"use strict";e.exports=require("util")}};var __webpack_module_cache__={};function __nccwpck_require__(e){if(__webpack_module_cache__[e]){return __webpack_module_cache__[e].exports}var t=__webpack_module_cache__[e]={exports:{}};var i=true;try{__webpack_modules__[e].call(t.exports,t,t.exports,__nccwpck_require__);i=false}finally{if(i)delete __webpack_module_cache__[e]}return t.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(1652)})(); \ No newline at end of file diff --git a/packages/next/compiled/@vercel/nft/package.json b/packages/next/compiled/@vercel/nft/package.json new file mode 100644 index 000000000000000..501e74ab8d234d3 --- /dev/null +++ b/packages/next/compiled/@vercel/nft/package.json @@ -0,0 +1 @@ +{"name":"@vercel/nft","main":"index.js","license":"MIT"} diff --git a/packages/next/compiled/glob/LICENSE b/packages/next/compiled/glob/LICENSE new file mode 100644 index 000000000000000..42ca266df1d523b --- /dev/null +++ b/packages/next/compiled/glob/LICENSE @@ -0,0 +1,21 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and 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. + +## Glob Logo + +Glob's logo created by Tanya Brassie , licensed +under a Creative Commons Attribution-ShareAlike 4.0 International License +https://creativecommons.org/licenses/by-sa/4.0/ diff --git a/packages/next/compiled/glob/glob.js b/packages/next/compiled/glob/glob.js new file mode 100644 index 000000000000000..96cde4125dcd92b --- /dev/null +++ b/packages/next/compiled/glob/glob.js @@ -0,0 +1 @@ +module.exports=(()=>{var t={587:t=>{"use strict";t.exports=balanced;function balanced(t,r,e){if(t instanceof RegExp)t=maybeMatch(t,e);if(r instanceof RegExp)r=maybeMatch(r,e);var i=range(t,r,e);return i&&{start:i[0],end:i[1],pre:e.slice(0,i[0]),body:e.slice(i[0]+t.length,i[1]),post:e.slice(i[1]+r.length)}}function maybeMatch(t,r){var e=r.match(t);return e?e[0]:null}balanced.range=range;function range(t,r,e){var i,n,a,s,o;var c=e.indexOf(t);var h=e.indexOf(r,c+1);var u=c;if(c>=0&&h>0){i=[];a=e.length;while(u>=0&&!o){if(u==c){i.push(u);c=e.indexOf(t,u+1)}else if(i.length==1){o=[i.pop(),h]}else{n=i.pop();if(n=0?c:h}if(i.length){o=[a,s]}}return o}},533:(t,r,e)=>{var i=e(179);var n=e(587);t.exports=expandTop;var a="\0SLASH"+Math.random()+"\0";var s="\0OPEN"+Math.random()+"\0";var o="\0CLOSE"+Math.random()+"\0";var c="\0COMMA"+Math.random()+"\0";var h="\0PERIOD"+Math.random()+"\0";function numeric(t){return parseInt(t,10)==t?parseInt(t,10):t.charCodeAt(0)}function escapeBraces(t){return t.split("\\\\").join(a).split("\\{").join(s).split("\\}").join(o).split("\\,").join(c).split("\\.").join(h)}function unescapeBraces(t){return t.split(a).join("\\").split(s).join("{").split(o).join("}").split(c).join(",").split(h).join(".")}function parseCommaParts(t){if(!t)return[""];var r=[];var e=n("{","}",t);if(!e)return t.split(",");var i=e.pre;var a=e.body;var s=e.post;var o=i.split(",");o[o.length-1]+="{"+a+"}";var c=parseCommaParts(s);if(s.length){o[o.length-1]+=c.shift();o.push.apply(o,c)}r.push.apply(r,o);return r}function expandTop(t){if(!t)return[];if(t.substr(0,2)==="{}"){t="\\{\\}"+t.substr(2)}return expand(escapeBraces(t),true).map(unescapeBraces)}function identity(t){return t}function embrace(t){return"{"+t+"}"}function isPadded(t){return/^-?0\d/.test(t)}function lte(t,r){return t<=r}function gte(t,r){return t>=r}function expand(t,r){var e=[];var a=n("{","}",t);if(!a||/\$$/.test(a.pre))return[t];var s=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(a.body);var c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(a.body);var h=s||c;var u=a.body.indexOf(",")>=0;if(!h&&!u){if(a.post.match(/,.*\}/)){t=a.pre+"{"+a.body+o+a.post;return expand(t)}return[t]}var l;if(h){l=a.body.split(/\.\./)}else{l=parseCommaParts(a.body);if(l.length===1){l=expand(l[0],false).map(embrace);if(l.length===1){var f=a.post.length?expand(a.post,false):[""];return f.map(function(t){return a.pre+l[0]+t})}}}var p=a.pre;var f=a.post.length?expand(a.post,false):[""];var v;if(h){var m=numeric(l[0]);var d=numeric(l[1]);var g=Math.max(l[0].length,l[1].length);var y=l.length==3?Math.abs(numeric(l[2])):1;var b=lte;var _=d0){var O=new Array(E+1).join("0");if(k<0)S="-"+O+S.slice(1);else S=O+S}}}v.push(S)}}else{v=i(l,function(t){return expand(t,false)})}for(var A=0;A{t.exports=function(t,e){var i=[];for(var n=0;n{t.exports=realpath;realpath.realpath=realpath;realpath.sync=realpathSync;realpath.realpathSync=realpathSync;realpath.monkeypatch=monkeypatch;realpath.unmonkeypatch=unmonkeypatch;var i=e(747);var n=i.realpath;var a=i.realpathSync;var s=process.version;var o=/^v[0-5]\./.test(s);var c=e(145);function newError(t){return t&&t.syscall==="realpath"&&(t.code==="ELOOP"||t.code==="ENOMEM"||t.code==="ENAMETOOLONG")}function realpath(t,r,e){if(o){return n(t,r,e)}if(typeof r==="function"){e=r;r=null}n(t,r,function(i,n){if(newError(i)){c.realpath(t,r,e)}else{e(i,n)}})}function realpathSync(t,r){if(o){return a(t,r)}try{return a(t,r)}catch(e){if(newError(e)){return c.realpathSync(t,r)}else{throw e}}}function monkeypatch(){i.realpath=realpath;i.realpathSync=realpathSync}function unmonkeypatch(){i.realpath=n;i.realpathSync=a}},145:(t,r,e)=>{var i=e(622);var n=process.platform==="win32";var a=e(747);var s=process.env.NODE_DEBUG&&/fs/.test(process.env.NODE_DEBUG);function rethrow(){var t;if(s){var r=new Error;t=debugCallback}else t=missingCallback;return t;function debugCallback(t){if(t){r.message=t.message;t=r;missingCallback(t)}}function missingCallback(t){if(t){if(process.throwDeprecation)throw t;else if(!process.noDeprecation){var r="fs: missing callback "+(t.stack||t.message);if(process.traceDeprecation)console.trace(r);else console.error(r)}}}}function maybeCallback(t){return typeof t==="function"?t:rethrow()}var o=i.normalize;if(n){var c=/(.*?)(?:[\/\\]+|$)/g}else{var c=/(.*?)(?:[\/]+|$)/g}if(n){var h=/^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/}else{var h=/^[\/]*/}r.realpathSync=function realpathSync(t,r){t=i.resolve(t);if(r&&Object.prototype.hasOwnProperty.call(r,t)){return r[t]}var e=t,s={},o={};var u;var l;var f;var p;start();function start(){var r=h.exec(t);u=r[0].length;l=r[0];f=r[0];p="";if(n&&!o[f]){a.lstatSync(f);o[f]=true}}while(u=t.length){if(r)r[s]=t;return e(null,t)}c.lastIndex=l;var i=c.exec(t);v=f;f+=i[0];p=v+i[1];l=c.lastIndex;if(u[p]||r&&r[p]===p){return process.nextTick(LOOP)}if(r&&Object.prototype.hasOwnProperty.call(r,p)){return gotResolvedLink(r[p])}return a.lstat(p,gotStat)}function gotStat(t,i){if(t)return e(t);if(!i.isSymbolicLink()){u[p]=true;if(r)r[p]=p;return process.nextTick(LOOP)}if(!n){var s=i.dev.toString(32)+":"+i.ino.toString(32);if(o.hasOwnProperty(s)){return gotTarget(null,o[s],p)}}a.stat(p,function(t){if(t)return e(t);a.readlink(p,function(t,r){if(!n)o[s]=r;gotTarget(t,r)})})}function gotTarget(t,n,a){if(t)return e(t);var s=i.resolve(v,n);if(r)r[a]=s;gotResolvedLink(s)}function gotResolvedLink(r){t=i.resolve(r,t.slice(l));start()}}},889:(t,r,e)=>{var i=e(640);var n=Object.create(null);var a=e(754);t.exports=i(inflight);function inflight(t,r){if(n[t]){n[t].push(r);return null}else{n[t]=[r];return makeres(t)}}function makeres(t){return a(function RES(){var r=n[t];var e=r.length;var i=slice(arguments);try{for(var a=0;ae){r.splice(0,e);process.nextTick(function(){RES.apply(null,i)})}else{delete n[t]}}})}function slice(t){var r=t.length;var e=[];for(var i=0;i{try{var i=e(669);if(typeof i.inherits!=="function")throw"";t.exports=i.inherits}catch(r){t.exports=e(350)}},350:t=>{if(typeof Object.create==="function"){t.exports=function inherits(t,r){if(r){t.super_=r;t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:false,writable:true,configurable:true}})}}}else{t.exports=function inherits(t,r){if(r){t.super_=r;var e=function(){};e.prototype=r.prototype;t.prototype=new e;t.prototype.constructor=t}}}},944:(t,r,e)=>{t.exports=minimatch;minimatch.Minimatch=Minimatch;var i={sep:"/"};try{i=e(622)}catch(t){}var n=minimatch.GLOBSTAR=Minimatch.GLOBSTAR={};var a=e(533);var s={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}};var o="[^/]";var c=o+"*?";var h="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";var u="(?:(?!(?:\\/|^)\\.).)*?";var l=charSet("().*{}+?[]^$\\!");function charSet(t){return t.split("").reduce(function(t,r){t[r]=true;return t},{})}var f=/\/+/;minimatch.filter=filter;function filter(t,r){r=r||{};return function(e,i,n){return minimatch(e,t,r)}}function ext(t,r){t=t||{};r=r||{};var e={};Object.keys(r).forEach(function(t){e[t]=r[t]});Object.keys(t).forEach(function(r){e[r]=t[r]});return e}minimatch.defaults=function(t){if(!t||!Object.keys(t).length)return minimatch;var r=minimatch;var e=function minimatch(e,i,n){return r.minimatch(e,i,ext(t,n))};e.Minimatch=function Minimatch(e,i){return new r.Minimatch(e,ext(t,i))};return e};Minimatch.defaults=function(t){if(!t||!Object.keys(t).length)return Minimatch;return minimatch.defaults(t).Minimatch};function minimatch(t,r,e){if(typeof r!=="string"){throw new TypeError("glob pattern string required")}if(!e)e={};if(!e.nocomment&&r.charAt(0)==="#"){return false}if(r.trim()==="")return t==="";return new Minimatch(r,e).match(t)}function Minimatch(t,r){if(!(this instanceof Minimatch)){return new Minimatch(t,r)}if(typeof t!=="string"){throw new TypeError("glob pattern string required")}if(!r)r={};t=t.trim();if(i.sep!=="/"){t=t.split(i.sep).join("/")}this.options=r;this.set=[];this.pattern=t;this.regexp=null;this.negate=false;this.comment=false;this.empty=false;this.make()}Minimatch.prototype.debug=function(){};Minimatch.prototype.make=make;function make(){if(this._made)return;var t=this.pattern;var r=this.options;if(!r.nocomment&&t.charAt(0)==="#"){this.comment=true;return}if(!t){this.empty=true;return}this.parseNegate();var e=this.globSet=this.braceExpand();if(r.debug)this.debug=console.error;this.debug(this.pattern,e);e=this.globParts=e.map(function(t){return t.split(f)});this.debug(this.pattern,e);e=e.map(function(t,r,e){return t.map(this.parse,this)},this);this.debug(this.pattern,e);e=e.filter(function(t){return t.indexOf(false)===-1});this.debug(this.pattern,e);this.set=e}Minimatch.prototype.parseNegate=parseNegate;function parseNegate(){var t=this.pattern;var r=false;var e=this.options;var i=0;if(e.nonegate)return;for(var n=0,a=t.length;n1024*64){throw new TypeError("pattern is too long")}var e=this.options;if(!e.noglobstar&&t==="**")return n;if(t==="")return"";var i="";var a=!!e.nocase;var h=false;var u=[];var f=[];var v;var m=false;var d=-1;var g=-1;var y=t.charAt(0)==="."?"":e.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)";var b=this;function clearStateChar(){if(v){switch(v){case"*":i+=c;a=true;break;case"?":i+=o;a=true;break;default:i+="\\"+v;break}b.debug("clearStateChar %j %j",v,i);v=false}}for(var _=0,w=t.length,k;_-1;I--){var M=f[I];var x=i.slice(0,M.reStart);var L=i.slice(M.reStart,M.reEnd-8);var C=i.slice(M.reEnd-8,M.reEnd);var R=i.slice(M.reEnd);C+=R;var T=x.split("(").length-1;var N=R;for(_=0;_=0;s--){a=t[s];if(a)break}for(s=0;s>> no match, partial?",t,l,r,f);if(l===o)return true}return false}var v;if(typeof h==="string"){if(i.nocase){v=u.toLowerCase()===h.toLowerCase()}else{v=u===h}this.debug("string match",h,u,v)}else{v=u.match(h);this.debug("pattern match",h,u,v)}if(!v)return false}if(a===o&&s===c){return true}else if(a===o){return e}else if(s===c){var m=a===o-1&&t[a]==="";return m}throw new Error("wtf?")};function globUnescape(t){return t.replace(/\\(.)/g,"$1")}function regExpEscape(t){return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}},754:(t,r,e)=>{var i=e(640);t.exports=i(once);t.exports.strict=i(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(t){var r=function(){if(r.called)return r.value;r.called=true;return r.value=t.apply(this,arguments)};r.called=false;return r}function onceStrict(t){var r=function(){if(r.called)throw new Error(r.onceError);r.called=true;return r.value=t.apply(this,arguments)};var e=t.name||"Function wrapped with `once`";r.onceError=e+" shouldn't be called more than once";r.called=false;return r}},540:t=>{"use strict";function posix(t){return t.charAt(0)==="/"}function win32(t){var r=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;var e=r.exec(t);var i=e[1]||"";var n=Boolean(i&&i.charAt(1)!==":");return Boolean(e[2]||n)}t.exports=process.platform==="win32"?win32:posix;t.exports.posix=posix;t.exports.win32=win32},640:t=>{t.exports=wrappy;function wrappy(t,r){if(t&&r)return wrappy(t)(r);if(typeof t!=="function")throw new TypeError("need wrapper function");Object.keys(t).forEach(function(r){wrapper[r]=t[r]});return wrapper;function wrapper(){var r=new Array(arguments.length);for(var e=0;e{r.setopts=setopts;r.ownProp=ownProp;r.makeAbs=makeAbs;r.finish=finish;r.mark=mark;r.isIgnored=isIgnored;r.childrenIgnored=childrenIgnored;function ownProp(t,r){return Object.prototype.hasOwnProperty.call(t,r)}var i=e(622);var n=e(944);var a=e(540);var s=n.Minimatch;function alphasort(t,r){return t.localeCompare(r,"en")}function setupIgnores(t,r){t.ignore=r.ignore||[];if(!Array.isArray(t.ignore))t.ignore=[t.ignore];if(t.ignore.length){t.ignore=t.ignore.map(ignoreMap)}}function ignoreMap(t){var r=null;if(t.slice(-3)==="/**"){var e=t.replace(/(\/\*\*)+$/,"");r=new s(e,{dot:true})}return{matcher:new s(t,{dot:true}),gmatcher:r}}function setopts(t,r,e){if(!e)e={};if(e.matchBase&&-1===r.indexOf("/")){if(e.noglobstar){throw new Error("base matching requires globstar")}r="**/"+r}t.silent=!!e.silent;t.pattern=r;t.strict=e.strict!==false;t.realpath=!!e.realpath;t.realpathCache=e.realpathCache||Object.create(null);t.follow=!!e.follow;t.dot=!!e.dot;t.mark=!!e.mark;t.nodir=!!e.nodir;if(t.nodir)t.mark=true;t.sync=!!e.sync;t.nounique=!!e.nounique;t.nonull=!!e.nonull;t.nosort=!!e.nosort;t.nocase=!!e.nocase;t.stat=!!e.stat;t.noprocess=!!e.noprocess;t.absolute=!!e.absolute;t.maxLength=e.maxLength||Infinity;t.cache=e.cache||Object.create(null);t.statCache=e.statCache||Object.create(null);t.symlinks=e.symlinks||Object.create(null);setupIgnores(t,e);t.changedCwd=false;var n=process.cwd();if(!ownProp(e,"cwd"))t.cwd=n;else{t.cwd=i.resolve(e.cwd);t.changedCwd=t.cwd!==n}t.root=e.root||i.resolve(t.cwd,"/");t.root=i.resolve(t.root);if(process.platform==="win32")t.root=t.root.replace(/\\/g,"/");t.cwdAbs=a(t.cwd)?t.cwd:makeAbs(t,t.cwd);if(process.platform==="win32")t.cwdAbs=t.cwdAbs.replace(/\\/g,"/");t.nomount=!!e.nomount;e.nonegate=true;e.nocomment=true;t.minimatch=new s(r,e);t.options=t.minimatch.options}function finish(t){var r=t.nounique;var e=r?[]:Object.create(null);for(var i=0,n=t.matches.length;i{t.exports=glob;var i=e(747);var n=e(82);var a=e(944);var s=a.Minimatch;var o=e(989);var c=e(614).EventEmitter;var h=e(622);var u=e(357);var l=e(540);var f=e(10);var p=e(625);var v=p.setopts;var m=p.ownProp;var d=e(889);var g=e(669);var y=p.childrenIgnored;var b=p.isIgnored;var _=e(754);function glob(t,r,e){if(typeof r==="function")e=r,r={};if(!r)r={};if(r.sync){if(e)throw new TypeError("callback provided to sync glob");return f(t,r)}return new Glob(t,r,e)}glob.sync=f;var w=glob.GlobSync=f.GlobSync;glob.glob=glob;function extend(t,r){if(r===null||typeof r!=="object"){return t}var e=Object.keys(r);var i=e.length;while(i--){t[e[i]]=r[e[i]]}return t}glob.hasMagic=function(t,r){var e=extend({},r);e.noprocess=true;var i=new Glob(t,e);var n=i.minimatch.set;if(!t)return false;if(n.length>1)return true;for(var a=0;athis.maxLength)return r();if(!this.stat&&m(this.cache,e)){var a=this.cache[e];if(Array.isArray(a))a="DIR";if(!n||a==="DIR")return r(null,a);if(n&&a==="FILE")return r()}var s;var o=this.statCache[e];if(o!==undefined){if(o===false)return r(null,o);else{var c=o.isDirectory()?"DIR":"FILE";if(n&&c==="FILE")return r();else return r(null,c,o)}}var h=this;var u=d("stat\0"+e,lstatcb_);if(u)i.lstat(e,u);function lstatcb_(n,a){if(a&&a.isSymbolicLink()){return i.stat(e,function(i,n){if(i)h._stat2(t,e,null,a,r);else h._stat2(t,e,i,n,r)})}else{h._stat2(t,e,n,a,r)}}};Glob.prototype._stat2=function(t,r,e,i,n){if(e&&(e.code==="ENOENT"||e.code==="ENOTDIR")){this.statCache[r]=false;return n()}var a=t.slice(-1)==="/";this.statCache[r]=i;if(r.slice(-1)==="/"&&i&&!i.isDirectory())return n(null,false,i);var s=true;if(i)s=i.isDirectory()?"DIR":"FILE";this.cache[r]=this.cache[r]||s;if(a&&s==="FILE")return n();return n(null,s,i)}},10:(t,r,e)=>{t.exports=globSync;globSync.GlobSync=GlobSync;var i=e(747);var n=e(82);var a=e(944);var s=a.Minimatch;var o=e(957).Glob;var c=e(669);var h=e(622);var u=e(357);var l=e(540);var f=e(625);var p=f.setopts;var v=f.ownProp;var m=f.childrenIgnored;var d=f.isIgnored;function globSync(t,r){if(typeof r==="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(t,r).found}function GlobSync(t,r){if(!t)throw new Error("must provide pattern");if(typeof r==="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))return new GlobSync(t,r);p(this,t,r);if(this.noprocess)return this;var e=this.minimatch.set.length;this.matches=new Array(e);for(var i=0;ithis.maxLength)return false;if(!this.stat&&v(this.cache,r)){var n=this.cache[r];if(Array.isArray(n))n="DIR";if(!e||n==="DIR")return n;if(e&&n==="FILE")return false}var a;var s=this.statCache[r];if(!s){var o;try{o=i.lstatSync(r)}catch(t){if(t&&(t.code==="ENOENT"||t.code==="ENOTDIR")){this.statCache[r]=false;return false}}if(o&&o.isSymbolicLink()){try{s=i.statSync(r)}catch(t){s=o}}else{s=o}}this.statCache[r]=s;var n=true;if(s)n=s.isDirectory()?"DIR":"FILE";this.cache[r]=this.cache[r]||n;if(e&&n==="FILE")return false;return n};GlobSync.prototype._mark=function(t){return f.mark(this,t)};GlobSync.prototype._makeAbs=function(t){return f.makeAbs(this,t)}},357:t=>{"use strict";t.exports=require("assert")},614:t=>{"use strict";t.exports=require("events")},747:t=>{"use strict";t.exports=require("fs")},622:t=>{"use strict";t.exports=require("path")},669:t=>{"use strict";t.exports=require("util")}};var r={};function __nccwpck_require__(e){if(r[e]){return r[e].exports}var i=r[e]={exports:{}};var n=true;try{t[e](i,i.exports,__nccwpck_require__);n=false}finally{if(n)delete r[e]}return i.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(957)})(); \ No newline at end of file diff --git a/packages/next/compiled/glob/package.json b/packages/next/compiled/glob/package.json new file mode 100644 index 000000000000000..c5898c0b3a2b160 --- /dev/null +++ b/packages/next/compiled/glob/package.json @@ -0,0 +1 @@ +{"name":"glob","main":"glob.js","author":"Isaac Z. Schlueter (http://blog.izs.me/)","license":"ISC"} diff --git a/packages/next/compiled/terser/bundle.min.js b/packages/next/compiled/terser/bundle.min.js index 3ec8d6aee27a2c6..69063a3fa5a6361 100644 --- a/packages/next/compiled/terser/bundle.min.js +++ b/packages/next/compiled/terser/bundle.min.js @@ -1 +1 @@ -module.exports=(()=>{var e={89:function(e,t){(function(e,n){true?n(t):0})(this,function(e){"use strict";var t={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"};var n="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 i={5:n,"5module":n+" export import",6:n+" const class extends export import super"};var r=/^in(stanceof)?$/;var a="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var o="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var s=new RegExp("["+a+"]");var u=new RegExp("["+a+o+"]");a=o=null;var c=[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];var l=[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];function isInAstralSet(e,t){var n=65536;for(var i=0;ie){return false}n+=t[i+1];if(n>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&s.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,c)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&u.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,c)||isInAstralSet(e,l)}var f=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new f(e,{beforeExpr:true,binop:t})}var p={beforeExpr:true},_={startsExpr:true};var h={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return h[e]=new f(e,t)}var d={num:new f("num",_),regexp:new f("regexp",_),string:new f("string",_),name:new f("name",_),eof:new f("eof"),bracketL:new f("[",{beforeExpr:true,startsExpr:true}),bracketR:new f("]"),braceL:new f("{",{beforeExpr:true,startsExpr:true}),braceR:new f("}"),parenL:new f("(",{beforeExpr:true,startsExpr:true}),parenR:new f(")"),comma:new f(",",p),semi:new f(";",p),colon:new f(":",p),dot:new f("."),question:new f("?",p),questionDot:new f("?."),arrow:new f("=>",p),template:new f("template"),invalidTemplate:new f("invalidTemplate"),ellipsis:new f("...",p),backQuote:new f("`",_),dollarBraceL:new f("${",{beforeExpr:true,startsExpr:true}),eq:new f("=",{beforeExpr:true,isAssign:true}),assign:new f("_=",{beforeExpr:true,isAssign:true}),incDec:new f("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new f("!/~",{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 f("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new f("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",p),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",p),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",p),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",_),_if:kw("if"),_return:kw("return",p),_switch:kw("switch"),_throw:kw("throw",p),_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",_),_super:kw("super",_),_class:kw("class",_),_extends:kw("extends",p),_export:kw("export"),_import:kw("import",_),_null:kw("null",_),_true:kw("true",_),_false:kw("false",_),_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})};var m=/\r\n?|\n|\u2028|\u2029/;var E=new RegExp(m.source,"g");function isNewLine(e,t){return e===10||e===13||!t&&(e===8232||e===8233)}var g=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var v=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var D=Object.prototype;var b=D.hasOwnProperty;var y=D.toString;function has(e,t){return b.call(e,t)}var k=Array.isArray||function(e){return y.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var S=function Position(e,t){this.line=e;this.column=t};S.prototype.offset=function offset(e){return new S(this.line,this.column+e)};var T=function SourceLocation(e,t,n){this.start=t;this.end=n;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var n=1,i=0;;){E.lastIndex=i;var r=E.exec(e);if(r&&r.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(k(t.onToken)){var i=t.onToken;t.onToken=function(e){return i.push(e)}}if(k(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(n,i,r,a,o,s){var u={type:n?"Block":"Line",value:i,start:r,end:a};if(e.locations){u.loc=new T(this,o,s)}if(e.ranges){u.range=[r,a]}t.push(u)}}var C=1,R=2,x=C|R,F=4,O=8,w=16,M=32,N=64,I=128;function functionFlags(e,t){return R|(e?F:0)|(t?O:0)}var P=0,L=1,B=2,V=3,U=4,z=5;var K=function Parser(e,n,r){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(i[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var a="";if(e.allowReserved!==true){for(var o=e.ecmaVersion;;o--){if(a=t[o]){break}}if(e.sourceType==="module"){a+=" await"}}this.reservedWords=wordsRegexp(a);var s=(a?a+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(s);this.reservedWordsStrictBind=wordsRegexp(s+" "+t.strictBind);this.input=String(n);this.containsEsc=false;if(r){this.pos=r;this.lineStart=this.input.lastIndexOf("\n",r-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(m).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=d.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(C);this.regexpState=null};var G={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};K.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};G.inFunction.get=function(){return(this.currentVarScope().flags&R)>0};G.inGenerator.get=function(){return(this.currentVarScope().flags&O)>0};G.inAsync.get=function(){return(this.currentVarScope().flags&F)>0};G.allowSuper.get=function(){return(this.currentThisScope().flags&N)>0};G.allowDirectSuper.get=function(){return(this.currentThisScope().flags&I)>0};G.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};K.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&R)>0};K.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var n=this;for(var i=0;i=,?^&]/.test(r)||r==="!"&&this.input.charAt(i+1)==="=")}e+=t[0].length;v.lastIndex=e;e+=v.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};X.eat=function(e){if(this.type===e){this.next();return true}else{return false}};X.isContextual=function(e){return this.type===d.name&&this.value===e&&!this.containsEsc};X.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};X.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};X.canInsertSemicolon=function(){return this.type===d.eof||this.type===d.braceR||m.test(this.input.slice(this.lastTokEnd,this.start))};X.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};X.semicolon=function(){if(!this.eat(d.semi)&&!this.insertSemicolon()){this.unexpected()}};X.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};X.expect=function(e){this.eat(e)||this.unexpected()};X.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}X.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var n=t?e.parenthesizedAssign:e.parenthesizedBind;if(n>-1){this.raiseRecoverable(n,"Parenthesized pattern")}};X.checkExpressionErrors=function(e,t){if(!e){return false}var n=e.shorthandAssign;var i=e.doubleProto;if(!t){return n>=0||i>=0}if(n>=0){this.raise(n,"Shorthand property assignments are valid only in destructuring patterns")}if(i>=0){this.raiseRecoverable(i,"Redefinition of __proto__ property")}};X.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(r,false,!e);case d._class:if(e){this.unexpected()}return this.parseClass(r,true);case d._if:return this.parseIfStatement(r);case d._return:return this.parseReturnStatement(r);case d._switch:return this.parseSwitchStatement(r);case d._throw:return this.parseThrowStatement(r);case d._try:return this.parseTryStatement(r);case d._const:case d._var:a=a||this.value;if(e&&a!=="var"){this.unexpected()}return this.parseVarStatement(r,a);case d._while:return this.parseWhileStatement(r);case d._with:return this.parseWithStatement(r);case d.braceL:return this.parseBlock(true,r);case d.semi:return this.parseEmptyStatement(r);case d._export:case d._import:if(this.options.ecmaVersion>10&&i===d._import){v.lastIndex=this.pos;var o=v.exec(this.input);var s=this.pos+o[0].length,u=this.input.charCodeAt(s);if(u===40||u===46){return this.parseExpressionStatement(r,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){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 i===d._import?this.parseImport(r):this.parseExport(r,n);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(r,true,!e)}var c=this.value,l=this.parseExpression();if(i===d.name&&l.type==="Identifier"&&this.eat(d.colon)){return this.parseLabeledStatement(r,c,l,e)}else{return this.parseExpressionStatement(r,l)}}};W.parseBreakContinueStatement=function(e,t){var n=t==="break";this.next();if(this.eat(d.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==d.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(d.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};W.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(q);this.enterScope(0);this.expect(d.parenL);if(this.type===d.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var n=this.isLet();if(this.type===d._var||this.type===d._const||n){var i=this.startNode(),r=n?"let":this.value;this.next();this.parseVar(i,true,r);this.finishNode(i,"VariableDeclaration");if((this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&i.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===d._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,i)}if(t>-1){this.unexpected(t)}return this.parseFor(e,i)}var a=new DestructuringErrors;var o=this.parseExpression(true,a);if(this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===d._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}this.toAssignable(o,false,a);this.checkLVal(o);return this.parseForIn(e,o)}else{this.checkExpressionErrors(a,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,o)};W.parseFunctionStatement=function(e,t,n){this.next();return this.parseFunction(e,$|(n?0:Z),false,t)};W.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(d._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};W.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(d.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};W.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(d.braceL);this.labels.push(Y);this.enterScope(0);var t;for(var n=false;this.type!==d.braceR;){if(this.type===d._case||this.type===d._default){var i=this.type===d._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(i){t.test=this.parseExpression()}else{if(n){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}n=true;t.test=null}this.expect(d.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};W.parseThrowStatement=function(e){this.next();if(m.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var j=[];W.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===d._catch){var t=this.startNode();this.next();if(this.eat(d.parenL)){t.param=this.parseBindingAtom();var n=t.param.type==="Identifier";this.enterScope(n?M:0);this.checkLVal(t.param,n?U:B);this.expect(d.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(d._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};W.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};W.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(q);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};W.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};W.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};W.parseLabeledStatement=function(e,t,n,i){for(var r=0,a=this.labels;r=0;u--){var c=this.labels[u];if(c.statementStart===e.start){c.statementStart=this.start;c.kind=s}else{break}}this.labels.push({name:t,kind:s,statementStart:this.start});e.body=this.parseStatement(i?i.indexOf("label")===-1?i+"label":i:"label");this.labels.pop();e.label=n;return this.finishNode(e,"LabeledStatement")};W.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};W.parseBlock=function(e,t,n){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(d.braceL);if(e){this.enterScope(0)}while(this.type!==d.braceR){var i=this.parseStatement(null);t.body.push(i)}if(n){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};W.parseFor=function(e,t){e.init=t;this.expect(d.semi);e.test=this.type===d.semi?null:this.parseExpression();this.expect(d.semi);e.update=this.type===d.parenR?null:this.parseExpression();this.expect(d.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};W.parseForIn=function(e,t){var n=this.type===d._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!n||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(n?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(t.type==="AssignmentPattern"){this.raise(t.start,"Invalid left-hand side in for-loop")}e.left=t;e.right=n?this.parseExpression():this.parseMaybeAssign();this.expect(d.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,n?"ForInStatement":"ForOfStatement")};W.parseVar=function(e,t,n){e.declarations=[];e.kind=n;for(;;){var i=this.startNode();this.parseVarId(i,n);if(this.eat(d.eq)){i.init=this.parseMaybeAssign(t)}else if(n==="const"&&!(this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(i.id.type!=="Identifier"&&!(t&&(this.type===d._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{i.init=null}e.declarations.push(this.finishNode(i,"VariableDeclarator"));if(!this.eat(d.comma)){break}}return e};W.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLVal(e.id,t==="var"?L:B,false)};var $=1,Z=2,Q=4;W.parseFunction=function(e,t,n,i){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!i){if(this.type===d.star&&t&Z){this.unexpected()}e.generator=this.eat(d.star)}if(this.options.ecmaVersion>=8){e.async=!!i}if(t&$){e.id=t&Q&&this.type!==d.name?null:this.parseIdent();if(e.id&&!(t&Z)){this.checkLVal(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?L:B:V)}}var r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&$)){e.id=this.type===d.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,n,false);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(e,t&$?"FunctionDeclaration":"FunctionExpression")};W.parseFunctionParams=function(e){this.expect(d.parenL);e.params=this.parseBindingList(d.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};W.parseClass=function(e,t){this.next();var n=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var i=this.startNode();var r=false;i.body=[];this.expect(d.braceL);while(this.type!==d.braceR){var a=this.parseClassElement(e.superClass!==null);if(a){i.body.push(a);if(a.type==="MethodDefinition"&&a.kind==="constructor"){if(r){this.raise(a.start,"Duplicate constructor in the same class")}r=true}}}this.strict=n;this.next();e.body=this.finishNode(i,"ClassBody");return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};W.parseClassElement=function(e){var t=this;if(this.eat(d.semi)){return null}var n=this.startNode();var i=function(e,i){if(i===void 0)i=false;var r=t.start,a=t.startLoc;if(!t.eatContextual(e)){return false}if(t.type!==d.parenL&&(!i||!t.canInsertSemicolon())){return true}if(n.key){t.unexpected()}n.computed=false;n.key=t.startNodeAt(r,a);n.key.name=e;t.finishNode(n.key,"Identifier");return false};n.kind="method";n.static=i("static");var r=this.eat(d.star);var a=false;if(!r){if(this.options.ecmaVersion>=8&&i("async",true)){a=true;r=this.options.ecmaVersion>=9&&this.eat(d.star)}else if(i("get")){n.kind="get"}else if(i("set")){n.kind="set"}}if(!n.key){this.parsePropertyName(n)}var o=n.key;var s=false;if(!n.computed&&!n.static&&(o.type==="Identifier"&&o.name==="constructor"||o.type==="Literal"&&o.value==="constructor")){if(n.kind!=="method"){this.raise(o.start,"Constructor can't have get/set modifier")}if(r){this.raise(o.start,"Constructor can't be a generator")}if(a){this.raise(o.start,"Constructor can't be an async method")}n.kind="constructor";s=e}else if(n.static&&o.type==="Identifier"&&o.name==="prototype"){this.raise(o.start,"Classes may not have a static property named prototype")}this.parseClassMethod(n,r,a,s);if(n.kind==="get"&&n.value.params.length!==0){this.raiseRecoverable(n.value.start,"getter should have no params")}if(n.kind==="set"&&n.value.params.length!==1){this.raiseRecoverable(n.value.start,"setter should have exactly one param")}if(n.kind==="set"&&n.value.params[0].type==="RestElement"){this.raiseRecoverable(n.value.params[0].start,"Setter cannot use rest params")}return n};W.parseClassMethod=function(e,t,n,i){e.value=this.parseMethod(t,n,i);return this.finishNode(e,"MethodDefinition")};W.parseClassId=function(e,t){if(this.type===d.name){e.id=this.parseIdent();if(t){this.checkLVal(e.id,B,false)}}else{if(t===true){this.unexpected()}e.id=null}};W.parseClassSuper=function(e){e.superClass=this.eat(d._extends)?this.parseExprSubscripts():null};W.parseExport=function(e,t){this.next();if(this.eat(d.star)){if(this.options.ecmaVersion>=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==d.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(d._default)){this.checkExport(t,"default",this.lastTokStart);var n;if(this.type===d._function||(n=this.isAsyncFunction())){var i=this.startNode();this.next();if(n){this.next()}e.declaration=this.parseFunction(i,$|Q,false,n)}else if(this.type===d._class){var r=this.startNode();e.declaration=this.parseClass(r,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==d.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var a=0,o=e.specifiers;a=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(n){this.checkPatternErrors(n,true)}for(var i=0,r=e.properties;i=8&&!a&&o.name==="async"&&!this.canInsertSemicolon()&&this.eat(d._function)){return this.parseFunction(this.startNodeAt(i,r),0,false,true)}if(n&&!this.canInsertSemicolon()){if(this.eat(d.arrow)){return this.parseArrowExpression(this.startNodeAt(i,r),[o],false)}if(this.options.ecmaVersion>=8&&o.name==="async"&&this.type===d.name&&!a){o=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(d.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(i,r),[o],true)}}return o;case d.regexp:var s=this.value;t=this.parseLiteral(s.value);t.regex={pattern:s.pattern,flags:s.flags};return t;case d.num:case d.string:return this.parseLiteral(this.value);case d._null:case d._true:case d._false:t=this.startNode();t.value=this.type===d._null?null:this.type===d._true;t.raw=this.type.keyword;this.next();return this.finishNode(t,"Literal");case d.parenL:var u=this.start,c=this.parseParenAndDistinguishExpression(n);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)){e.parenthesizedAssign=u}if(e.parenthesizedBind<0){e.parenthesizedBind=u}}return c;case d.bracketL:t=this.startNode();this.next();t.elements=this.parseExprList(d.bracketR,true,true,e);return this.finishNode(t,"ArrayExpression");case d.braceL:return this.parseObj(false,e);case d._function:t=this.startNode();this.next();return this.parseFunction(t,0);case d._class:return this.parseClass(this.startNode(),false);case d._new:return this.parseNew();case d.backQuote:return this.parseTemplate();case d._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};ee.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case d.parenL:return this.parseDynamicImport(e);case d.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};ee.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(d.parenR)){var t=this.start;if(this.eat(d.comma)&&this.eat(d.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};ee.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};ee.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};ee.parseParenExpression=function(){this.expect(d.parenL);var e=this.parseExpression();this.expect(d.parenR);return e};ee.parseParenAndDistinguishExpression=function(e){var t=this.start,n=this.startLoc,i,r=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a=this.start,o=this.startLoc;var s=[],u=true,c=false;var l=new DestructuringErrors,f=this.yieldPos,p=this.awaitPos,_;this.yieldPos=0;this.awaitPos=0;while(this.type!==d.parenR){u?u=false:this.expect(d.comma);if(r&&this.afterTrailingComma(d.parenR,true)){c=true;break}else if(this.type===d.ellipsis){_=this.start;s.push(this.parseParenItem(this.parseRestBinding()));if(this.type===d.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{s.push(this.parseMaybeAssign(false,l,this.parseParenItem))}}var h=this.start,m=this.startLoc;this.expect(d.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(d.arrow)){this.checkPatternErrors(l,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=f;this.awaitPos=p;return this.parseParenArrowList(t,n,s)}if(!s.length||c){this.unexpected(this.lastTokStart)}if(_){this.unexpected(_)}this.checkExpressionErrors(l,true);this.yieldPos=f||this.yieldPos;this.awaitPos=p||this.awaitPos;if(s.length>1){i=this.startNodeAt(a,o);i.expressions=s;this.finishNodeAt(i,"SequenceExpression",h,m)}else{i=s[0]}}else{i=this.parseParenExpression()}if(this.options.preserveParens){var E=this.startNodeAt(t,n);E.expression=i;return this.finishNode(E,"ParenthesizedExpression")}else{return i}};ee.parseParenItem=function(e){return e};ee.parseParenArrowList=function(e,t,n){return this.parseArrowExpression(this.startNodeAt(e,t),n)};var te=[];ee.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(d.dot)){e.meta=t;var n=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(n){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.inNonArrowFunction()){this.raiseRecoverable(e.start,"'new.target' can only be used in functions")}return this.finishNode(e,"MetaProperty")}var i=this.start,r=this.startLoc,a=this.type===d._import;e.callee=this.parseSubscripts(this.parseExprAtom(),i,r,true);if(a&&e.callee.type==="ImportExpression"){this.raise(i,"Cannot use new with import()")}if(this.eat(d.parenL)){e.arguments=this.parseExprList(d.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=te}return this.finishNode(e,"NewExpression")};ee.parseTemplateElement=function(e){var t=e.isTagged;var n=this.startNode();if(this.type===d.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}n.value={raw:this.value,cooked:null}}else{n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();n.tail=this.type===d.backQuote;return this.finishNode(n,"TemplateElement")};ee.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var n=this.startNode();this.next();n.expressions=[];var i=this.parseTemplateElement({isTagged:t});n.quasis=[i];while(!i.tail){if(this.type===d.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(d.dollarBraceL);n.expressions.push(this.parseExpression());this.expect(d.braceR);n.quasis.push(i=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(n,"TemplateLiteral")};ee.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===d.name||this.type===d.num||this.type===d.string||this.type===d.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===d.star)&&!m.test(this.input.slice(this.lastTokEnd,this.start))};ee.parseObj=function(e,t){var n=this.startNode(),i=true,r={};n.properties=[];this.next();while(!this.eat(d.braceR)){if(!i){this.expect(d.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(d.braceR)){break}}else{i=false}var a=this.parseProperty(e,t);if(!e){this.checkPropClash(a,r,t)}n.properties.push(a)}return this.finishNode(n,e?"ObjectPattern":"ObjectExpression")};ee.parseProperty=function(e,t){var n=this.startNode(),i,r,a,o;if(this.options.ecmaVersion>=9&&this.eat(d.ellipsis)){if(e){n.argument=this.parseIdent(false);if(this.type===d.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(n,"RestElement")}if(this.type===d.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}n.argument=this.parseMaybeAssign(false,t);if(this.type===d.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(n,"SpreadElement")}if(this.options.ecmaVersion>=6){n.method=false;n.shorthand=false;if(e||t){a=this.start;o=this.startLoc}if(!e){i=this.eat(d.star)}}var s=this.containsEsc;this.parsePropertyName(n);if(!e&&!s&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(n)){r=true;i=this.options.ecmaVersion>=9&&this.eat(d.star);this.parsePropertyName(n,t)}else{r=false}this.parsePropertyValue(n,e,i,r,a,o,t,s);return this.finishNode(n,"Property")};ee.parsePropertyValue=function(e,t,n,i,r,a,o,s){if((n||i)&&this.type===d.colon){this.unexpected()}if(this.eat(d.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,o);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===d.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(n,i)}else if(!t&&!s&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==d.comma&&this.type!==d.braceR&&this.type!==d.eq)){if(n||i){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var u=e.kind==="get"?0:1;if(e.value.params.length!==u){var c=e.value.start;if(e.kind==="get"){this.raiseRecoverable(c,"getter should have no params")}else{this.raiseRecoverable(c,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(n||i){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=r}e.kind="init";if(t){e.value=this.parseMaybeDefault(r,a,e.key)}else if(this.type===d.eq&&o){if(o.shorthandAssign<0){o.shorthandAssign=this.start}e.value=this.parseMaybeDefault(r,a,e.key)}else{e.value=e.key}e.shorthand=true}else{this.unexpected()}};ee.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(d.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(d.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===d.num||this.type===d.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};ee.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};ee.parseMethod=function(e,t,n){var i=this.startNode(),r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.initFunction(i);if(this.options.ecmaVersion>=6){i.generator=e}if(this.options.ecmaVersion>=8){i.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,i.generator)|N|(n?I:0));this.expect(d.parenL);i.params=this.parseBindingList(d.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(i,false,true);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(i,"FunctionExpression")};ee.parseArrowExpression=function(e,t,n){var i=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;this.enterScope(functionFlags(n,false)|w);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!n}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false);this.yieldPos=i;this.awaitPos=r;this.awaitIdentPos=a;return this.finishNode(e,"ArrowFunctionExpression")};ee.parseFunctionBody=function(e,t,n){var i=t&&this.type!==d.braceL;var r=this.strict,a=false;if(i){e.body=this.parseMaybeAssign();e.expression=true;this.checkParams(e,false)}else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!r||o){a=this.strictDirective(this.end);if(a&&o){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var s=this.labels;this.labels=[];if(a){this.strict=true}this.checkParams(e,!r&&!a&&!t&&!n&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLVal(e.id,z)}e.body=this.parseBlock(false,undefined,a&&!r);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=s}this.exitScope()};ee.isSimpleParamList=function(e){for(var t=0,n=e;t-1||r.functions.indexOf(e)>-1||r.var.indexOf(e)>-1;r.lexical.push(e);if(this.inModule&&r.flags&C){delete this.undefinedExports[e]}}else if(t===U){var a=this.currentScope();a.lexical.push(e)}else if(t===V){var o=this.currentScope();if(this.treatFunctionsAsVar){i=o.lexical.indexOf(e)>-1}else{i=o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1}o.functions.push(e)}else{for(var s=this.scopeStack.length-1;s>=0;--s){var u=this.scopeStack[s];if(u.lexical.indexOf(e)>-1&&!(u.flags&M&&u.lexical[0]===e)||!this.treatFunctionsAsVarInScope(u)&&u.functions.indexOf(e)>-1){i=true;break}u.var.push(e);if(this.inModule&&u.flags&C){delete this.undefinedExports[e]}if(u.flags&x){break}}}if(i){this.raiseRecoverable(n,"Identifier '"+e+"' has already been declared")}};ie.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};ie.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};ie.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&x){return t}}};ie.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&x&&!(t.flags&w)){return t}}};var ae=function Node(e,t,n){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new T(e,n)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var oe=K.prototype;oe.startNode=function(){return new ae(this,this.start,this.startLoc)};oe.startNodeAt=function(e,t){return new ae(this,e,t)};function finishNodeAt(e,t,n,i){e.type=t;e.end=n;if(this.options.locations){e.loc.end=i}if(this.options.ranges){e.range[1]=n}return e}oe.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};oe.finishNodeAt=function(e,t,n,i){return finishNodeAt.call(this,e,t,n,i)};var se=function TokContext(e,t,n,i,r){this.token=e;this.isExpr=!!t;this.preserveSpace=!!n;this.override=i;this.generator=!!r};var ue={b_stat:new se("{",false),b_expr:new se("{",true),b_tmpl:new se("${",false),p_stat:new se("(",false),p_expr:new se("(",true),q_tmpl:new se("`",true,true,function(e){return e.tryReadTemplateToken()}),f_stat:new se("function",false),f_expr:new se("function",true),f_expr_gen:new se("function",true,false,null,true),f_gen:new se("function",false,false,null,true)};var ce=K.prototype;ce.initialContext=function(){return[ue.b_stat]};ce.braceIsBlock=function(e){var t=this.curContext();if(t===ue.f_expr||t===ue.f_stat){return true}if(e===d.colon&&(t===ue.b_stat||t===ue.b_expr)){return!t.isExpr}if(e===d._return||e===d.name&&this.exprAllowed){return m.test(this.input.slice(this.lastTokEnd,this.start))}if(e===d._else||e===d.semi||e===d.eof||e===d.parenR||e===d.arrow){return true}if(e===d.braceL){return t===ue.b_stat}if(e===d._var||e===d._const||e===d.name){return false}return!this.exprAllowed};ce.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if(t.token==="function"){return t.generator}}return false};ce.updateContext=function(e){var t,n=this.type;if(n.keyword&&e===d.dot){this.exprAllowed=false}else if(t=n.updateContext){t.call(this,e)}else{this.exprAllowed=n.beforeExpr}};d.parenR.updateContext=d.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var e=this.context.pop();if(e===ue.b_stat&&this.curContext().token==="function"){e=this.context.pop()}this.exprAllowed=!e.isExpr};d.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?ue.b_stat:ue.b_expr);this.exprAllowed=true};d.dollarBraceL.updateContext=function(){this.context.push(ue.b_tmpl);this.exprAllowed=true};d.parenL.updateContext=function(e){var t=e===d._if||e===d._for||e===d._with||e===d._while;this.context.push(t?ue.p_stat:ue.p_expr);this.exprAllowed=true};d.incDec.updateContext=function(){};d._function.updateContext=d._class.updateContext=function(e){if(e.beforeExpr&&e!==d.semi&&e!==d._else&&!(e===d._return&&m.test(this.input.slice(this.lastTokEnd,this.start)))&&!((e===d.colon||e===d.braceL)&&this.curContext()===ue.b_stat)){this.context.push(ue.f_expr)}else{this.context.push(ue.f_stat)}this.exprAllowed=false};d.backQuote.updateContext=function(){if(this.curContext()===ue.q_tmpl){this.context.pop()}else{this.context.push(ue.q_tmpl)}this.exprAllowed=false};d.star.updateContext=function(e){if(e===d._function){var t=this.context.length-1;if(this.context[t]===ue.f_expr){this.context[t]=ue.f_expr_gen}else{this.context[t]=ue.f_gen}}this.exprAllowed=true};d.name.updateContext=function(e){var t=false;if(this.options.ecmaVersion>=6&&e!==d.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){t=true}}this.exprAllowed=t};var le="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 fe=le+" Extended_Pictographic";var pe=fe;var _e={9:le,10:fe,11:pe};var he="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";var de="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 me=de+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var Ee=me+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var ge={9:de,10:me,11:Ee};var ve={};function buildUnicodeData(e){var t=ve[e]={binary:wordsRegexp(_e[e]+" "+he),nonBinary:{General_Category:wordsRegexp(he),Script:wordsRegexp(ge[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var De=K.prototype;var be=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"");this.unicodeProperties=ve[e.options.ecmaVersion>=11?11:e.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=[]};be.prototype.reset=function reset(e,t,n){var i=n.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=n;this.switchU=i&&this.parser.options.ecmaVersion>=6;this.switchN=i&&this.parser.options.ecmaVersion>=9};be.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};be.prototype.at=function at(e,t){if(t===void 0)t=false;var n=this.source;var i=n.length;if(e>=i){return-1}var r=n.charCodeAt(e);if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=i){return r}var a=n.charCodeAt(e+1);return a>=56320&&a<=57343?(r<<10)+a-56613888:r};be.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var n=this.source;var i=n.length;if(e>=i){return i}var r=n.charCodeAt(e),a;if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=i||(a=n.charCodeAt(e+1))<56320||a>57343){return e+1}return e+2};be.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};be.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};be.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};be.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}De.validateRegExpFlags=function(e){var t=e.validFlags;var n=e.flags;for(var i=0;i-1){this.raise(e.start,"Duplicate regular expression flag")}}};De.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};De.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,n=e.backReferenceNames;t=9){n=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!n;return true}}e.pos=t;return false};De.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};De.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};De.regexp_eatBracedQuantifier=function(e,t){var n=e.pos;if(e.eat(123)){var i=0,r=-1;if(this.regexp_eatDecimalDigits(e)){i=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){r=e.lastIntValue}if(e.eat(125)){if(r!==-1&&r=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};De.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};De.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};De.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}De.regexp_eatPatternCharacters=function(e){var t=e.pos;var n=0;while((n=e.current())!==-1&&!isSyntaxCharacter(n)){e.advance()}return e.pos!==t};De.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};De.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};De.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};De.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString(e.lastIntValue)}return true}return false};De.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var n=this.options.ecmaVersion>=11;var i=e.current(n);e.advance(n);if(i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)){i=e.lastIntValue}if(isRegExpIdentifierStart(i)){e.lastIntValue=i;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}De.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var n=this.options.ecmaVersion>=11;var i=e.current(n);e.advance(n);if(i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)){i=e.lastIntValue}if(isRegExpIdentifierPart(i)){e.lastIntValue=i;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}De.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};De.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var n=e.lastIntValue;if(e.switchU){if(n>e.maxBackReference){e.maxBackReference=n}return true}if(n<=e.numCapturingParens){return true}e.pos=t}return false};De.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};De.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};De.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};De.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};De.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};De.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}De.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var n=e.pos;var i=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var r=e.lastIntValue;if(i&&r>=55296&&r<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343){e.lastIntValue=(r-55296)*1024+(o-56320)+65536;return true}}e.pos=a;e.lastIntValue=r}return true}if(i&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(i){e.raise("Invalid unicode escape")}e.pos=n}return false};function isValidUnicode(e){return e>=0&&e<=1114111}De.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};De.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};De.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}De.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var n=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var i=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,n,i);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var r=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,r);return true}return false};De.regexp_validateUnicodePropertyNameAndValue=function(e,t,n){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(n)){e.raise("Invalid property value")}};De.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};De.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}De.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}De.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};De.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};De.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var n=e.lastIntValue;if(e.switchU&&(t===-1||n===-1)){e.raise("Invalid character class")}if(t!==-1&&n!==-1&&t>n){e.raise("Range out of order in character class")}}}};De.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var n=e.current();if(n===99||isOctalDigit(n)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var i=e.current();if(i!==93){e.lastIntValue=i;e.advance();return true}return false};De.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};De.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};De.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};De.regexp_eatDecimalDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isDecimalDigit(n=e.current())){e.lastIntValue=10*e.lastIntValue+(n-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}De.regexp_eatHexDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isHexDigit(n=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(n);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}De.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var n=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+n*8+e.lastIntValue}else{e.lastIntValue=t*8+n}}else{e.lastIntValue=t}return true}return false};De.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}De.regexp_eatFixedHexDigits=function(e,t){var n=e.pos;e.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(d.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};ke.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};ke.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=57344){return e}var t=this.input.charCodeAt(this.pos+1);return(e<<10)+t-56613888};ke.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,n=this.input.indexOf("*/",this.pos+=2);if(n===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=n+2;if(this.options.locations){E.lastIndex=t;var i;while((i=E.exec(this.input))&&i.index8&&e<14||e>=5760&&g.test(String.fromCharCode(e))){++this.pos}else{break e}}}};ke.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var n=this.type;this.type=e;this.value=t;this.updateContext(n)};ke.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(d.ellipsis)}else{++this.pos;return this.finishToken(d.dot)}};ke.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(d.assign,2)}return this.finishOp(d.slash,1)};ke.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;var i=e===42?d.star:d.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++n;i=d.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(d.assign,n+1)}return this.finishOp(i,n)};ke.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var n=this.input.charCodeAt(this.pos+2);if(n===61){return this.finishOp(d.assign,3)}}return this.finishOp(e===124?d.logicalOR:d.logicalAND,2)}if(t===61){return this.finishOp(d.assign,2)}return this.finishOp(e===124?d.bitwiseOR:d.bitwiseAND,1)};ke.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(d.assign,2)}return this.finishOp(d.bitwiseXOR,1)};ke.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||m.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(d.incDec,2)}if(t===61){return this.finishOp(d.assign,2)}return this.finishOp(d.plusMin,1)};ke.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;if(t===e){n=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+n)===61){return this.finishOp(d.assign,n+1)}return this.finishOp(d.bitShift,n)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){n=2}return this.finishOp(d.relational,n)};ke.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(d.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(d.arrow)}return this.finishOp(e===61?d.eq:d.prefix,1)};ke.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var n=this.input.charCodeAt(this.pos+2);if(n<48||n>57){return this.finishOp(d.questionDot,2)}}if(t===63){if(e>=12){var i=this.input.charCodeAt(this.pos+2);if(i===61){return this.finishOp(d.assign,3)}}return this.finishOp(d.coalesce,2)}}return this.finishOp(d.question,1)};ke.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(d.parenL);case 41:++this.pos;return this.finishToken(d.parenR);case 59:++this.pos;return this.finishToken(d.semi);case 44:++this.pos;return this.finishToken(d.comma);case 91:++this.pos;return this.finishToken(d.bracketL);case 93:++this.pos;return this.finishToken(d.bracketR);case 123:++this.pos;return this.finishToken(d.braceL);case 125:++this.pos;return this.finishToken(d.braceR);case 58:++this.pos;return this.finishToken(d.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(d.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(d.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(e)+"'")};ke.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,n)};ke.readRegexp=function(){var e,t,n=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(n,"Unterminated regular expression")}var i=this.input.charAt(this.pos);if(m.test(i)){this.raise(n,"Unterminated regular expression")}if(!e){if(i==="["){t=true}else if(i==="]"&&t){t=false}else if(i==="/"&&!t){break}e=i==="\\"}else{e=false}++this.pos}var r=this.input.slice(n,this.pos);++this.pos;var a=this.pos;var o=this.readWord1();if(this.containsEsc){this.unexpected(a)}var s=this.regexpState||(this.regexpState=new be(this));s.reset(n,r,o);this.validateRegExpFlags(s);this.validateRegExpPattern(s);var u=null;try{u=new RegExp(r,o)}catch(e){}return this.finishToken(d.regexp,{pattern:r,flags:o,value:u})};ke.readInt=function(e,t,n){var i=this.options.ecmaVersion>=12&&t===undefined;var r=n&&this.input.charCodeAt(this.pos)===48;var a=this.pos,o=0,s=0;for(var u=0,c=t==null?Infinity:t;u=97){f=l-97+10}else if(l>=65){f=l-65+10}else if(l>=48&&l<=57){f=l-48}else{f=Infinity}if(f>=e){break}s=l;o=o*e+f}if(i&&s===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===a||t!=null&&this.pos-a!==t){return null}return o};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}ke.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var n=this.readInt(e);if(n==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){n=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(d.num,n)};ke.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var n=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(n&&this.strict){this.raise(t,"Invalid number")}var i=this.input.charCodeAt(this.pos);if(!n&&!e&&this.options.ecmaVersion>=11&&i===110){var r=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(d.num,r)}if(n&&/[89]/.test(this.input.slice(t,this.pos))){n=false}if(i===46&&!n){++this.pos;this.readInt(10);i=this.input.charCodeAt(this.pos)}if((i===69||i===101)&&!n){i=this.input.charCodeAt(++this.pos);if(i===43||i===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var a=stringToNumber(this.input.slice(t,this.pos),n);return this.finishToken(d.num,a)};ke.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var n=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(n,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}ke.readString=function(e){var t="",n=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var i=this.input.charCodeAt(this.pos);if(i===e){break}if(i===92){t+=this.input.slice(n,this.pos);t+=this.readEscapedChar(false);n=this.pos}else{if(isNewLine(i,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(n,this.pos++);return this.finishToken(d.string,t)};var Se={};ke.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Se){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};ke.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Se}else{this.raise(e,t)}};ke.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var n=this.input.charCodeAt(this.pos);if(n===96||n===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===d.template||this.type===d.invalidTemplate)){if(n===36){this.pos+=2;return this.finishToken(d.dollarBraceL)}else{++this.pos;return this.finishToken(d.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(d.template,e)}if(n===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(n)){e+=this.input.slice(t,this.pos);++this.pos;switch(n){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(n);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};ke.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var i=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var r=parseInt(i,8);if(r>255){i=i.slice(0,-1);r=parseInt(i,8)}this.pos+=i.length-1;t=this.input.charCodeAt(this.pos);if((i!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-i.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(r)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};ke.readHexChar=function(e){var t=this.pos;var n=this.readInt(16,e);if(n===null){this.invalidStringToken(t,"Bad character escape sequence")}return n};ke.readWord1=function(){this.containsEsc=false;var e="",t=true,n=this.pos;var i=this.options.ecmaVersion>=6;while(this.pos5&&t<2015)t+=2009;i[n]=t}else{i[n]=e&&HOP(e,n)?e[n]:t[n]}}return i}function noop(){}function return_false(){return false}function return_true(){return true}function return_this(){return this}function return_null(){return null}var r=function(){function MAP(t,n,i){var r=[],a=[],o;function doit(){var s=n(t[o],o);var u=s instanceof Last;if(u)s=s.v;if(s instanceof AtTop){s=s.v;if(s instanceof Splice){a.push.apply(a,i?s.v.slice().reverse():s.v)}else{a.push(s)}}else if(s!==e){if(s instanceof Splice){r.push.apply(r,i?s.v.slice().reverse():s.v)}else{r.push(s)}}return u}if(Array.isArray(t)){if(i){for(o=t.length;--o>=0;)if(doit())break;r.reverse();a.reverse()}else{for(o=0;o=0;){if(e[n]===t)e.splice(n,1)}}function mergeSort(e,t){if(e.length<2)return e.slice();function merge(e,n){var i=[],r=0,a=0,o=0;while(r{n+=e})}return n}function has_annotation(e,t){return e._annotations&t}function set_annotation(e,t){e._annotations|=t}var s="";var u=true;var c="break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with";var l="false null true";var f="enum implements import interface package private protected public static super this "+l+" "+c;var p="return new delete throw else case yield await";c=makePredicate(c);f=makePredicate(f);p=makePredicate(p);l=makePredicate(l);var _=makePredicate(characters("+-*&%=<>!?|~^"));var h=/[0-9a-f]/i;var d=/^0x[0-9a-f]+$/i;var m=/^0[0-7]+$/;var E=/^0o[0-7]+$/i;var g=/^0b[01]+$/i;var v=/^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;var D=/^(0[xob])?[0-9a-f]+n$/i;var b=makePredicate(["in","instanceof","typeof","new","void","delete","++","--","+","-","!","~","&","|","^","*","**","/","%",">>","<<",">>>","<",">","<=",">=","==","===","!=","!==","?","=","+=","-=","||=","&&=","??=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&=","&&","??","||"]);var y=makePredicate(characters("  \n\r\t\f\v​           \u2028\u2029   \ufeff"));var k=makePredicate(characters("\n\r\u2028\u2029"));var S=makePredicate(characters(";]),:"));var T=makePredicate(characters("[{(,;:"));var A=makePredicate(characters("[]{}(),;:"));var C={ID_Start:/[$A-Z_a-z\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\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\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\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-\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\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\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-\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-\uA7AD\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\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[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\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]|\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]|\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]/,ID_Continue:/(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\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\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\u0C81-\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\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\u1369-\u1371\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-\u19DA\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\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\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-\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\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\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-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\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\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\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[\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]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\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]|\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]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\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])+/};function get_full_char(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){if(is_surrogate_pair_tail(e.charCodeAt(t+1))){return e.charAt(t)+e.charAt(t+1)}}else if(is_surrogate_pair_tail(e.charCodeAt(t))){if(is_surrogate_pair_head(e.charCodeAt(t-1))){return e.charAt(t-1)+e.charAt(t)}}return e.charAt(t)}function get_full_char_code(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){return 65536+(e.charCodeAt(t)-55296<<10)+e.charCodeAt(t+1)-56320}return e.charCodeAt(t)}function get_full_char_length(e){var t=0;for(var n=0;n65535){e-=65536;return String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)}return String.fromCharCode(e)}function is_surrogate_pair_head(e){return e>=55296&&e<=56319}function is_surrogate_pair_tail(e){return e>=56320&&e<=57343}function is_digit(e){return e>=48&&e<=57}function is_identifier_start(e){return C.ID_Start.test(e)}function is_identifier_char(e){return C.ID_Continue.test(e)}const R=/^[a-z_$][a-z0-9_$]*$/i;function is_basic_identifier_string(e){return R.test(e)}function is_identifier_string(e,t){if(R.test(e)){return true}if(!t&&/[\ud800-\udfff]/.test(e)){return false}var n=C.ID_Start.exec(e);if(!n||n.index!==0){return false}e=e.slice(n[0].length);if(!e){return true}n=C.ID_Continue.exec(e);return!!n&&n[0].length===e.length}function parse_js_number(e,t=true){if(!t&&e.includes("e")){return NaN}if(d.test(e)){return parseInt(e.substr(2),16)}else if(m.test(e)){return parseInt(e.substr(1),8)}else if(E.test(e)){return parseInt(e.substr(2),8)}else if(g.test(e)){return parseInt(e.substr(2),2)}else if(v.test(e)){return parseFloat(e)}else{var n=parseFloat(e);if(n==e)return n}}class JS_Parse_Error extends Error{constructor(e,t,n,i,r){super();this.name="SyntaxError";this.message=e;this.filename=t;this.line=n;this.col=i;this.pos=r}}function js_error(e,t,n,i,r){throw new JS_Parse_Error(e,t,n,i,r)}function is_token(e,t,n){return e.type==t&&(n==null||e.value==n)}var x={};function tokenizer(e,t,n,i){var r={text:e,filename:t,pos:0,tokpos:0,line:1,tokline:0,col:0,tokcol:0,newline_before:false,regex_allowed:false,brace_counter:0,template_braces:[],comments_before:[],directives:{},directive_stack:[]};function peek(){return get_full_char(r.text,r.pos)}function is_option_chain_op(){const e=r.text.charCodeAt(r.pos+1)===46;if(!e)return false;const t=r.text.charCodeAt(r.pos+2);return t<48||t>57}function next(e,t){var n=get_full_char(r.text,r.pos++);if(e&&!n)throw x;if(k.has(n)){r.newline_before=r.newline_before||!t;++r.line;r.col=0;if(n=="\r"&&peek()=="\n"){++r.pos;n="\n"}}else{if(n.length>1){++r.pos;++r.col}++r.col}return n}function forward(e){while(e--)next()}function looking_at(e){return r.text.substr(r.pos,e.length)==e}function find_eol(){var e=r.text;for(var t=r.pos,n=r.text.length;t="0"&&e<="7"}function read_escaped_char(e,t,n){var i=next(true,e);switch(i.charCodeAt(0)){case 110:return"\n";case 114:return"\r";case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 120:return String.fromCharCode(hex_bytes(2,t));case 117:if(peek()=="{"){next(true);if(peek()==="}")parse_error("Expecting hex-character between {}");while(peek()=="0")next(true);var a,o=find("}",true)-r.pos;if(o>6||(a=hex_bytes(o,t))>1114111){parse_error("Unicode reference out of bounds")}next(true);return from_char_code(a)}return String.fromCharCode(hex_bytes(4,t));case 10:return"";case 13:if(peek()=="\n"){next(true,e);return""}}if(is_octal(i)){if(n&&t){const e=i==="0"&&!is_octal(peek());if(!e){parse_error("Octal escape sequences are not allowed in template strings")}}return read_octal_escape_sequence(i,t)}return i}function read_octal_escape_sequence(e,t){var n=peek();if(n>="0"&&n<="7"){e+=next(true);if(e[0]<="3"&&(n=peek())>="0"&&n<="7")e+=next(true)}if(e==="0")return"\0";if(e.length>0&&next_token.has_directive("use strict")&&t)parse_error("Legacy octal escape sequences are not allowed in strict mode");return String.fromCharCode(parseInt(e,8))}function hex_bytes(e,t){var n=0;for(;e>0;--e){if(!t&&isNaN(parseInt(peek(),16))){return parseInt(n,16)||""}var i=next(true);if(isNaN(parseInt(i,16)))parse_error("Invalid hex-character pattern in string");n+=i}return parseInt(n,16)}var E=with_eof_error("Unterminated string constant",function(){const e=r.pos;var t=next(),n=[];for(;;){var i=next(true,true);if(i=="\\")i=read_escaped_char(true,true);else if(i=="\r"||i=="\n")parse_error("Unterminated string constant");else if(i==t)break;n.push(i)}var a=token("string",n.join(""));s=r.text.slice(e,r.pos);a.quote=t;return a});var g=with_eof_error("Unterminated template",function(e){if(e){r.template_braces.push(r.brace_counter)}var t="",n="",i,a;next(true,true);while((i=next(true,true))!="`"){if(i=="\r"){if(peek()=="\n")++r.pos;i="\n"}else if(i=="$"&&peek()=="{"){next(true,true);r.brace_counter++;a=token(e?"template_head":"template_substitution",t);s=n;u=false;return a}n+=i;if(i=="\\"){var c=r.pos;var l=o&&(o.type==="name"||o.type==="punc"&&(o.value===")"||o.value==="]"));i=read_escaped_char(true,!l,true);n+=r.text.substr(c,r.pos-c)}t+=i}r.template_braces.pop();a=token(e?"template_head":"template_substitution",t);s=n;u=true;return a});function skip_line_comment(e){var t=r.regex_allowed;var n=find_eol(),i;if(n==-1){i=r.text.substr(r.pos);r.pos=r.text.length}else{i=r.text.substring(r.pos,n);r.pos=n}r.col=r.tokcol+(r.pos-r.tokpos);r.comments_before.push(token(e,i,true));r.regex_allowed=t;return next_token}var v=with_eof_error("Unterminated multiline comment",function(){var e=r.regex_allowed;var t=find("*/",true);var n=r.text.substring(r.pos,t).replace(/\r\n|\r|\u2028|\u2029/g,"\n");forward(get_full_char_length(n)+2);r.comments_before.push(token("comment2",n,true));r.newline_before=r.newline_before||n.includes("\n");r.regex_allowed=e;return next_token});var S=with_eof_error("Unterminated identifier name",function(){var e=[],t,n=false;var i=function(){n=true;next();if(peek()!=="u"){parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}")}return read_escaped_char(false,true)};if((t=peek())==="\\"){t=i();if(!is_identifier_start(t)){parse_error("First identifier char is an invalid identifier char")}}else if(is_identifier_start(t)){next()}else{return""}e.push(t);while((t=peek())!=null){if((t=peek())==="\\"){t=i();if(!is_identifier_char(t)){parse_error("Invalid escaped identifier char")}}else{if(!is_identifier_char(t)){break}next()}e.push(t)}const r=e.join("");if(f.has(r)&&n){parse_error("Escaped characters are not allowed in keywords")}return r});var C=with_eof_error("Unterminated regular expression",function(e){var t=false,n,i=false;while(n=next(true))if(k.has(n)){parse_error("Unexpected line terminator")}else if(t){e+="\\"+n;t=false}else if(n=="["){i=true;e+=n}else if(n=="]"&&i){i=false;e+=n}else if(n=="/"&&!i){break}else if(n=="\\"){t=true}else{e+=n}const r=S();return token("regexp","/"+e+"/"+r)});function read_operator(e){function grow(e){if(!peek())return e;var t=e+peek();if(b.has(t)){next();return grow(t)}else{return e}}return token("operator",grow(e||next()))}function handle_slash(){next();switch(peek()){case"/":next();return skip_line_comment("comment1");case"*":next();return v()}return r.regex_allowed?C(""):read_operator("/")}function handle_eq_sign(){next();if(peek()===">"){next();return token("arrow","=>")}else{return read_operator("=")}}function handle_dot(){next();if(is_digit(peek().charCodeAt(0))){return read_num(".")}if(peek()==="."){next();next();return token("expand","...")}return token("punc",".")}function read_word(){var e=S();if(a)return token("name",e);return l.has(e)?token("atom",e):!c.has(e)?token("name",e):b.has(e)?token("operator",e):token("keyword",e)}function read_private_word(){next();return token("privatename",S())}function with_eof_error(e,t){return function(n){try{return t(n)}catch(t){if(t===x)parse_error(e);else throw t}}}function next_token(e){if(e!=null)return C(e);if(i&&r.pos==0&&looking_at("#!")){start_token();forward(2);skip_line_comment("comment5")}for(;;){skip_whitespace();start_token();if(n){if(looking_at("\x3c!--")){forward(4);skip_line_comment("comment3");continue}if(looking_at("--\x3e")&&r.newline_before){forward(3);skip_line_comment("comment4");continue}}var t=peek();if(!t)return token("eof");var a=t.charCodeAt(0);switch(a){case 34:case 39:return E();case 46:return handle_dot();case 47:{var o=handle_slash();if(o===next_token)continue;return o}case 61:return handle_eq_sign();case 63:{if(!is_option_chain_op())break;next();next();return token("punc","?.")}case 96:return g(true);case 123:r.brace_counter++;break;case 125:r.brace_counter--;if(r.template_braces.length>0&&r.template_braces[r.template_braces.length-1]===r.brace_counter)return g(false);break}if(is_digit(a))return read_num();if(A.has(t))return token("punc",next());if(_.has(t))return read_operator();if(a==92||is_identifier_start(t))return read_word();if(a==35)return read_private_word();break}parse_error("Unexpected character '"+t+"'")}next_token.next=next;next_token.peek=peek;next_token.context=function(e){if(e)r=e;return r};next_token.add_directive=function(e){r.directive_stack[r.directive_stack.length-1].push(e);if(r.directives[e]===undefined){r.directives[e]=1}else{r.directives[e]++}};next_token.push_directives_stack=function(){r.directive_stack.push([])};next_token.pop_directives_stack=function(){var e=r.directive_stack[r.directive_stack.length-1];for(var t=0;t0};return next_token}var F=makePredicate(["typeof","void","delete","--","++","!","~","-","+"]);var O=makePredicate(["--","++"]);var w=makePredicate(["=","+=","-=","??=","&&=","||=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&="]);var M=makePredicate(["??=","&&=","||="]);var N=function(e,t){for(var n=0;n","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],{});var I=makePredicate(["atom","num","big_int","string","regexp","name"]);function parse(e,t){const n=new WeakMap;t=defaults(t,{bare_returns:false,ecma:null,expression:false,filename:null,html5_comments:true,module:false,shebang:true,strict:false,toplevel:null},true);var i={input:typeof e=="string"?tokenizer(e,t.filename,t.html5_comments,t.shebang):e,token:null,prev:null,peeked:null,in_function:0,in_async:-1,in_generator:-1,in_directives:true,in_loop:0,labels:[]};i.token=next();function is(e,t){return is_token(i.token,e,t)}function peek(){return i.peeked||(i.peeked=i.input())}function next(){i.prev=i.token;if(!i.peeked)peek();i.token=i.peeked;i.peeked=null;i.in_directives=i.in_directives&&(i.token.type=="string"||is("punc",";"));return i.token}function prev(){return i.prev}function croak(e,t,n,r){var a=i.input.context();js_error(e,a.filename,t!=null?t:a.tokline,n!=null?n:a.tokcol,r!=null?r:a.tokpos)}function token_error(e,t){croak(t,e.line,e.col)}function unexpected(e){if(e==null)e=i.token;token_error(e,"Unexpected token: "+e.type+" ("+e.value+")")}function expect_token(e,t){if(is(e,t)){return next()}token_error(i.token,"Unexpected token "+i.token.type+" «"+i.token.value+"»"+", expected "+e+" «"+t+"»")}function expect(e){return expect_token("punc",e)}function has_newline_before(e){return e.nlb||!e.comments_before.every(e=>!e.nlb)}function can_insert_semicolon(){return!t.strict&&(is("eof")||is("punc","}")||has_newline_before(i.token))}function is_in_generator(){return i.in_generator===i.in_function}function is_in_async(){return i.in_async===i.in_function}function can_await(){return i.in_async===i.in_function||i.in_function===0&&i.input.has_directive("use strict")}function semicolon(e){if(is("punc",";"))next();else if(!e&&!can_insert_semicolon())unexpected()}function parenthesised(){expect("(");var e=k(true);expect(")");return e}function embed_tokens(e){return function _embed_tokens_wrapper(...t){const n=i.token;const r=e(...t);r.start=n;r.end=prev();return r}}function handle_regexp(){if(is("operator","/")||is("operator","/=")){i.peeked=null;i.token=i.input(i.token.value.substr(1))}}var r=embed_tokens(function statement(e,n,r){handle_regexp();switch(i.token.type){case"string":if(i.in_directives){var a=peek();if(!s.includes("\\")&&(is_token(a,"punc",";")||is_token(a,"punc","}")||has_newline_before(a)||is_token(a,"eof"))){i.input.add_directive(i.token.value)}else{i.in_directives=false}}var u=i.in_directives,f=simple_statement();return u&&f.body instanceof Xt?new X(f.body):f;case"template_head":case"num":case"big_int":case"regexp":case"operator":case"atom":return simple_statement();case"name":if(i.token.value=="async"&&is_token(peek(),"keyword","function")){next();next();if(n){croak("functions are not allowed as the body of a loop")}return o(pe,false,true,e)}if(i.token.value=="import"&&!is_token(peek(),"punc","(")&&!is_token(peek(),"punc",".")){next();var _=import_();semicolon();return _}return is_token(peek(),"punc",":")?labeled_statement():simple_statement();case"punc":switch(i.token.value){case"{":return new q({start:i.token,body:block_(),end:prev()});case"[":case"(":return simple_statement();case";":i.in_directives=false;next();return new Y;default:unexpected()}case"keyword":switch(i.token.value){case"break":next();return break_cont(ye);case"continue":next();return break_cont(ke);case"debugger":next();semicolon();return new G;case"do":next();var h=in_loop(statement);expect_token("keyword","while");var d=parenthesised();semicolon(true);return new J({body:h,condition:d});case"while":next();return new ee({condition:parenthesised(),body:in_loop(function(){return statement(false,true)})});case"for":next();return for_();case"class":next();if(n){croak("classes are not allowed as the body of a loop")}if(r){croak("classes are not allowed as the body of an if")}return class_(Et,e);case"function":next();if(n){croak("functions are not allowed as the body of a loop")}return o(pe,false,false,e);case"if":next();return if_();case"return":if(i.in_function==0&&!t.bare_returns)croak("'return' outside of function");next();var m=null;if(is("punc",";")){next()}else if(!can_insert_semicolon()){m=k(true);semicolon()}return new ve({value:m});case"switch":next();return new Ce({expression:parenthesised(),body:in_loop(switch_body_)});case"throw":next();if(has_newline_before(i.token))croak("Illegal newline after 'throw'");var m=k(true);semicolon();return new De({value:m});case"try":next();return try_();case"var":next();var _=c();semicolon();return _;case"let":next();var _=l();semicolon();return _;case"const":next();var _=p();semicolon();return _;case"with":if(i.input.has_directive("use strict")){croak("Strict mode may not include a with statement")}next();return new re({expression:parenthesised(),body:statement()});case"export":if(!is_token(peek(),"punc","(")){next();var _=export_();if(is("punc",";"))semicolon();return _}}}unexpected()});function labeled_statement(){var e=as_symbol(Pt);if(e.name==="await"&&is_in_async()){token_error(i.prev,"await cannot be used as label inside async function")}if(i.labels.some(t=>t.name===e.name)){croak("Label "+e.name+" defined twice")}expect(":");i.labels.push(e);var t=r();i.labels.pop();if(!(t instanceof Z)){e.references.forEach(function(t){if(t instanceof ke){t=t.label.start;croak("Continue label `"+e.name+"` refers to non-IterationStatement.",t.line,t.col,t.pos)}})}return new $({body:t,label:e})}function simple_statement(e){return new H({body:(e=k(true),semicolon(),e)})}function break_cont(e){var t=null,n;if(!can_insert_semicolon()){t=as_symbol(Ut,true)}if(t!=null){n=i.labels.find(e=>e.name===t.name);if(!n)croak("Undefined label "+t.name);t.thedef=n}else if(i.in_loop==0)croak(e.TYPE+" not inside a loop or switch");semicolon();var r=new e({label:t});if(n)n.references.push(r);return r}function for_(){var e="`for await` invalid in this context";var t=i.token;if(t.type=="name"&&t.value=="await"){if(!can_await()){token_error(t,e)}next()}else{t=false}expect("(");var n=null;if(!is("punc",";")){n=is("keyword","var")?(next(),c(true)):is("keyword","let")?(next(),l(true)):is("keyword","const")?(next(),p(true)):k(true,true);var r=is("operator","in");var a=is("name","of");if(t&&!a){token_error(t,e)}if(r||a){if(n instanceof Ne){if(n.definitions.length>1)token_error(n.start,"Only one variable declaration allowed in for..in loop")}else if(!(is_assignable(n)||(n=to_destructuring(n))instanceof _e)){token_error(n.start,"Invalid left-hand side in for..in loop")}next();if(r){return for_in(n)}else{return for_of(n,!!t)}}}else if(t){token_error(t,e)}return regular_for(n)}function regular_for(e){expect(";");var t=is("punc",";")?null:k(true);expect(";");var n=is("punc",")")?null:k(true);expect(")");return new te({init:e,condition:t,step:n,body:in_loop(function(){return r(false,true)})})}function for_of(e,t){var n=e instanceof Ne?e.definitions[0].name:null;var i=k(true);expect(")");return new ie({await:t,init:e,name:n,object:i,body:in_loop(function(){return r(false,true)})})}function for_in(e){var t=k(true);expect(")");return new ne({init:e,object:t,body:in_loop(function(){return r(false,true)})})}var a=function(e,t,n){if(has_newline_before(i.token)){croak("Unexpected newline before arrow (=>)")}expect_token("arrow","=>");var r=_function_body(is("punc","{"),false,n);var a=r instanceof Array&&r.length?r[r.length-1].end:r instanceof Array?e:r.end;return new fe({start:e,end:a,async:n,argnames:t,body:r})};var o=function(e,t,n,i){var r=e===pe;var a=is("operator","*");if(a){next()}var o=is("name")?as_symbol(r?Ct:Ft):null;if(r&&!o){if(i){e=le}else{unexpected()}}if(o&&e!==ce&&!(o instanceof bt))unexpected(prev());var s=[];var u=_function_body(true,a||t,n,o,s);return new e({start:s.start,end:u.end,is_generator:a,async:n,name:o,argnames:s,body:u})};function track_used_binding_identifiers(e,t){var n=new Set;var i=false;var r=false;var a=false;var o=!!t;var s={add_parameter:function(t){if(n.has(t.value)){if(i===false){i=t}s.check_strict()}else{n.add(t.value);if(e){switch(t.value){case"arguments":case"eval":case"yield":if(o){token_error(t,"Unexpected "+t.value+" identifier as parameter inside strict mode")}break;default:if(f.has(t.value)){unexpected()}}}}},mark_default_assignment:function(e){if(r===false){r=e}},mark_spread:function(e){if(a===false){a=e}},mark_strict_mode:function(){o=true},is_strict:function(){return r!==false||a!==false||o},check_strict:function(){if(s.is_strict()&&i!==false){token_error(i,"Parameter "+i.value+" was used already")}}};return s}function parameters(e){var t=track_used_binding_identifiers(true,i.input.has_directive("use strict"));expect("(");while(!is("punc",")")){var n=parameter(t);e.push(n);if(!is("punc",")")){expect(",")}if(n instanceof se){break}}next()}function parameter(e,t){var n;var r=false;if(e===undefined){e=track_used_binding_identifiers(true,i.input.has_directive("use strict"))}if(is("expand","...")){r=i.token;e.mark_spread(i.token);next()}n=binding_element(e,t);if(is("operator","=")&&r===false){e.mark_default_assignment(i.token);next();n=new it({start:n.start,left:n,operator:"=",right:k(false),end:i.token})}if(r!==false){if(!is("punc",")")){unexpected()}n=new se({start:r,expression:n,end:r})}e.check_strict();return n}function binding_element(e,t){var n=[];var r=true;var a=false;var o;var s=i.token;if(e===undefined){e=track_used_binding_identifiers(false,i.input.has_directive("use strict"))}t=t===undefined?At:t;if(is("punc","[")){next();while(!is("punc","]")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("punc")){switch(i.token.value){case",":n.push(new Qt({start:i.token,end:i.token}));continue;case"]":break;case"[":case"{":n.push(binding_element(e,t));break;default:unexpected()}}else if(is("name")){e.add_parameter(i.token);n.push(as_symbol(t))}else{croak("Invalid function parameter")}if(is("operator","=")&&a===false){e.mark_default_assignment(i.token);next();n[n.length-1]=new it({start:n[n.length-1].start,left:n[n.length-1],operator:"=",right:k(false),end:i.token})}if(a){if(!is("punc","]")){croak("Rest element must be last element")}n[n.length-1]=new se({start:o,expression:n[n.length-1],end:o})}}expect("]");e.check_strict();return new _e({start:s,names:n,is_array:true,end:prev()})}else if(is("punc","{")){next();while(!is("punc","}")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("name")&&(is_token(peek(),"punc")||is_token(peek(),"operator"))&&[",","}","="].includes(peek().value)){e.add_parameter(i.token);var u=prev();var c=as_symbol(t);if(a){n.push(new se({start:o,expression:c,end:c.end}))}else{n.push(new st({start:u,key:c.name,value:c,end:c.end}))}}else if(is("punc","}")){continue}else{var l=i.token;var f=as_property_name();if(f===null){unexpected(prev())}else if(prev().type==="name"&&!is("punc",":")){n.push(new st({start:prev(),key:f,value:new t({start:prev(),name:f,end:prev()}),end:prev()}))}else{expect(":");n.push(new st({start:l,quote:l.quote,key:f,value:binding_element(e,t),end:prev()}))}}if(a){if(!is("punc","}")){croak("Rest element must be last element")}}else if(is("operator","=")){e.mark_default_assignment(i.token);next();n[n.length-1].value=new it({start:n[n.length-1].value.start,left:n[n.length-1].value,operator:"=",right:k(false),end:i.token})}}expect("}");e.check_strict();return new _e({start:s,names:n,is_array:false,end:prev()})}else if(is("name")){e.add_parameter(i.token);return as_symbol(t)}else{croak("Invalid function parameter")}}function params_or_seq_(e,t){var n;var r;var a;var o=[];expect("(");while(!is("punc",")")){if(n)unexpected(n);if(is("expand","...")){n=i.token;if(t)r=i.token;next();o.push(new se({start:prev(),expression:k(),end:i.token}))}else{o.push(k())}if(!is("punc",")")){expect(",");if(is("punc",")")){a=prev();if(t)r=a}}}expect(")");if(e&&is("arrow","=>")){if(n&&a)unexpected(a)}else if(r){unexpected(r)}return o}function _function_body(e,t,n,r,a){var o=i.in_loop;var s=i.labels;var u=i.in_generator;var c=i.in_async;++i.in_function;if(t)i.in_generator=i.in_function;if(n)i.in_async=i.in_function;if(a)parameters(a);if(e)i.in_directives=true;i.in_loop=0;i.labels=[];if(e){i.input.push_directives_stack();var l=block_();if(r)_verify_symbol(r);if(a)a.forEach(_verify_symbol);i.input.pop_directives_stack()}else{var l=[new ve({start:i.token,value:k(false),end:i.token})]}--i.in_function;i.in_loop=o;i.labels=s;i.in_generator=u;i.in_async=c;return l}function _await_expression(){if(!can_await()){croak("Unexpected await expression outside async function",i.prev.line,i.prev.col,i.prev.pos)}return new Se({start:prev(),end:i.token,expression:v(true)})}function _yield_expression(){if(!is_in_generator()){croak("Unexpected yield expression outside generator function",i.prev.line,i.prev.col,i.prev.pos)}var e=i.token;var t=false;var n=true;if(can_insert_semicolon()||is("punc")&&S.has(i.token.value)){n=false}else if(is("operator","*")){t=true;next()}return new Te({start:e,is_star:t,expression:n?k():null,end:prev()})}function if_(){var e=parenthesised(),t=r(false,false,true),n=null;if(is("keyword","else")){next();n=r(false,false,true)}return new Ae({condition:e,body:t,alternative:n})}function block_(){expect("{");var e=[];while(!is("punc","}")){if(is("eof"))unexpected();e.push(r())}next();return e}function switch_body_(){expect("{");var e=[],t=null,n=null,a;while(!is("punc","}")){if(is("eof"))unexpected();if(is("keyword","case")){if(n)n.end=prev();t=[];n=new Fe({start:(a=i.token,next(),a),expression:k(true),body:t});e.push(n);expect(":")}else if(is("keyword","default")){if(n)n.end=prev();t=[];n=new xe({start:(a=i.token,next(),expect(":"),a),body:t});e.push(n)}else{if(!t)unexpected();t.push(r())}}if(n)n.end=prev();next();return e}function try_(){var e=block_(),t=null,n=null;if(is("keyword","catch")){var r=i.token;next();if(is("punc","{")){var a=null}else{expect("(");var a=parameter(undefined,Mt);expect(")")}t=new we({start:r,argname:a,body:block_(),end:prev()})}if(is("keyword","finally")){var r=i.token;next();n=new Me({start:r,body:block_(),end:prev()})}if(!t&&!n)croak("Missing catch/finally blocks");return new Oe({body:e,bcatch:t,bfinally:n})}function vardefs(e,t){var n=[];var r;for(;;){var a=t==="var"?yt:t==="const"?St:t==="let"?Tt:null;if(is("punc","{")||is("punc","[")){r=new Be({start:i.token,name:binding_element(undefined,a),value:is("operator","=")?(expect_token("operator","="),k(false,e)):null,end:prev()})}else{r=new Be({start:i.token,name:as_symbol(a),value:is("operator","=")?(next(),k(false,e)):!e&&t==="const"?croak("Missing initializer in const declaration"):null,end:prev()});if(r.name.name=="import")croak("Unexpected token: import")}n.push(r);if(!is("punc",","))break;next()}return n}var c=function(e){return new Ie({start:prev(),definitions:vardefs(e,"var"),end:prev()})};var l=function(e){return new Pe({start:prev(),definitions:vardefs(e,"let"),end:prev()})};var p=function(e){return new Le({start:prev(),definitions:vardefs(e,"const"),end:prev()})};var _=function(e){var t=i.token;expect_token("operator","new");if(is("punc",".")){next();expect_token("name","target");return g(new Dt({start:t,end:prev()}),e)}var n=h(false),r;if(is("punc","(")){next();r=expr_list(")",true)}else{r=[]}var a=new Xe({start:t,expression:n,args:r,end:prev()});annotate(a);return g(a,e)};function as_atom_node(){var e=i.token,t;switch(e.type){case"name":t=_make_symbol(Lt);break;case"num":t=new Ht({start:e,end:e,value:e.value,raw:s});break;case"big_int":t=new Wt({start:e,end:e,value:e.value});break;case"string":t=new Xt({start:e,end:e,value:e.value,quote:e.quote});break;case"regexp":const[n,i,r]=e.value.match(/^\/(.*)\/(\w*)$/);t=new qt({start:e,end:e,value:{source:i,flags:r}});break;case"atom":switch(e.value){case"false":t=new tn({start:e,end:e});break;case"true":t=new nn({start:e,end:e});break;case"null":t=new jt({start:e,end:e});break}break}next();return t}function to_fun_args(e,t){var n=function(e,t){if(t){return new it({start:e.start,left:e,operator:"=",right:t,end:t.end})}return e};if(e instanceof at){return n(new _e({start:e.start,end:e.end,is_array:false,names:e.properties.map(e=>to_fun_args(e))}),t)}else if(e instanceof st){e.value=to_fun_args(e.value);return n(e,t)}else if(e instanceof Qt){return e}else if(e instanceof _e){e.names=e.names.map(e=>to_fun_args(e));return n(e,t)}else if(e instanceof Lt){return n(new At({name:e.name,start:e.start,end:e.end}),t)}else if(e instanceof se){e.expression=to_fun_args(e.expression);return n(e,t)}else if(e instanceof rt){return n(new _e({start:e.start,end:e.end,is_array:true,names:e.elements.map(e=>to_fun_args(e))}),t)}else if(e instanceof nt){return n(to_fun_args(e.left,e.right),t)}else if(e instanceof it){e.left=to_fun_args(e.left);return e}else{croak("Invalid function parameter",e.start.line,e.start.col)}}var h=function(e,t){if(is("operator","new")){return _(e)}if(is("operator","import")){return import_meta()}var r=i.token;var s;var u=is("name","async")&&(s=peek()).value!="["&&s.type!="arrow"&&as_atom_node();if(is("punc")){switch(i.token.value){case"(":if(u&&!e)break;var c=params_or_seq_(t,!u);if(t&&is("arrow","=>")){return a(r,c.map(e=>to_fun_args(e)),!!u)}var l=u?new Ge({expression:u,args:c}):c.length==1?c[0]:new He({expressions:c});if(l.start){const e=r.comments_before.length;n.set(r,e);l.start.comments_before.unshift(...r.comments_before);r.comments_before=l.start.comments_before;if(e==0&&r.comments_before.length>0){var f=r.comments_before[0];if(!f.nlb){f.nlb=r.nlb;r.nlb=false}}r.comments_after=l.start.comments_after}l.start=r;var p=prev();if(l.end){p.comments_before=l.end.comments_before;l.end.comments_after.push(...p.comments_after);p.comments_after=l.end.comments_after}l.end=p;if(l instanceof Ge)annotate(l);return g(l,e);case"[":return g(d(),e);case"{":return g(E(),e)}if(!u)unexpected()}if(t&&is("name")&&is_token(peek(),"arrow")){var h=new At({name:i.token.value,start:r,end:r});next();return a(r,[h],!!u)}if(is("keyword","function")){next();var m=o(le,false,!!u);m.start=r;m.end=prev();return g(m,e)}if(u)return g(u,e);if(is("keyword","class")){next();var v=class_(gt);v.start=r;v.end=prev();return g(v,e)}if(is("template_head")){return g(template_string(),e)}if(I.has(i.token.type)){return g(as_atom_node(),e)}unexpected()};function template_string(){var e=[],t=i.token;e.push(new me({start:i.token,raw:s,value:i.token.value,end:i.token}));while(!u){next();handle_regexp();e.push(k(true));e.push(new me({start:i.token,raw:s,value:i.token.value,end:i.token}))}next();return new de({start:t,segments:e,end:i.token})}function expr_list(e,t,n){var r=true,a=[];while(!is("punc",e)){if(r)r=false;else expect(",");if(t&&is("punc",e))break;if(is("punc",",")&&n){a.push(new Qt({start:i.token,end:i.token}))}else if(is("expand","...")){next();a.push(new se({start:prev(),expression:k(),end:i.token}))}else{a.push(k(false))}}next();return a}var d=embed_tokens(function(){expect("[");return new rt({elements:expr_list("]",!t.strict,true)})});var m=embed_tokens((e,t)=>{return o(ce,e,t)});var E=embed_tokens(function object_or_destructuring_(){var e=i.token,n=true,r=[];expect("{");while(!is("punc","}")){if(n)n=false;else expect(",");if(!t.strict&&is("punc","}"))break;e=i.token;if(e.type=="expand"){next();r.push(new se({start:e,expression:k(false),end:prev()}));continue}var a=as_property_name();var o;if(!is("punc",":")){var s=concise_method_or_getset(a,e);if(s){r.push(s);continue}o=new Lt({start:prev(),name:a,end:prev()})}else if(a===null){unexpected(prev())}else{next();o=k(false)}if(is("operator","=")){next();o=new nt({start:e,left:o,operator:"=",right:k(false),logical:false,end:prev()})}r.push(new st({start:e,quote:e.quote,key:a instanceof z?a:""+a,value:o,end:prev()}))}next();return new at({properties:r})});function class_(e,t){var n,r,a,o,s=[];i.input.push_directives_stack();i.input.add_directive("use strict");if(i.token.type=="name"&&i.token.value!="extends"){a=as_symbol(e===Et?Ot:wt)}if(e===Et&&!a){if(t){e=gt}else{unexpected()}}if(i.token.value=="extends"){next();o=k(true)}expect("{");while(is("punc",";")){next()}while(!is("punc","}")){n=i.token;r=concise_method_or_getset(as_property_name(),n,true);if(!r){unexpected()}s.push(r);while(is("punc",";")){next()}}i.input.pop_directives_stack();next();return new e({start:n,name:a,extends:o,properties:s,end:prev()})}function concise_method_or_getset(e,t,n){const i=(e,n=Rt)=>{if(typeof e==="string"||typeof e==="number"){return new n({start:t,name:""+e,end:prev()})}else if(e===null){unexpected()}return e};const r=()=>!is("punc","(")&&!is("punc",",")&&!is("punc","}")&&!is("operator","=");var a=false;var o=false;var s=false;var u=false;var c=null;if(n&&e==="static"&&r()){o=true;e=as_property_name()}if(e==="async"&&r()){a=true;e=as_property_name()}if(prev().type==="operator"&&prev().value==="*"){s=true;e=as_property_name()}if((e==="get"||e==="set")&&r()){c=e;e=as_property_name()}if(prev().type==="privatename"){u=true}const l=prev();if(c!=null){if(!u){const n=c==="get"?ft:lt;e=i(e);return new n({start:t,static:o,key:e,quote:e instanceof Rt?l.quote:undefined,value:m(),end:prev()})}else{const n=c==="get"?ct:ut;return new n({start:t,static:o,key:i(e),value:m(),end:prev()})}}if(is("punc","(")){e=i(e);const n=u?_t:pt;var f=new n({start:t,static:o,is_generator:s,async:a,key:e,quote:e instanceof Rt?l.quote:undefined,value:m(s,a),end:prev()});return f}if(n){const n=i(e,xt);const r=n instanceof xt?l.quote:undefined;const a=u?mt:dt;if(is("operator","=")){next();return new a({start:t,static:o,quote:r,key:n,value:k(false),end:prev()})}else if(is("name")||is("privatename")||is("operator","*")||is("punc",";")||is("punc","}")){return new a({start:t,static:o,quote:r,key:n,end:prev()})}}}function import_(){var e=prev();var t;var n;if(is("name")){t=as_symbol(Nt)}if(is("punc",",")){next()}n=map_names(true);if(n||t){expect_token("name","from")}var r=i.token;if(r.type!=="string"){unexpected()}next();return new Ue({start:e,imported_name:t,imported_names:n,module_name:new Xt({start:r,value:r.value,quote:r.quote,end:r}),end:i.token})}function import_meta(){var e=i.token;expect_token("operator","import");expect_token("punc",".");expect_token("name","meta");return g(new ze({start:e,end:prev()}),false)}function map_name(e){function make_symbol(e){return new e({name:as_property_name(),start:prev(),end:prev()})}var t=e?It:Vt;var n=e?Nt:Bt;var r=i.token;var a;var o;if(e){a=make_symbol(t)}else{o=make_symbol(n)}if(is("name","as")){next();if(e){o=make_symbol(n)}else{a=make_symbol(t)}}else if(e){o=new n(a)}else{a=new t(o)}return new Ve({start:r,foreign_name:a,name:o,end:prev()})}function map_nameAsterisk(e,t){var n=e?It:Vt;var r=e?Nt:Bt;var a=i.token;var o;var s=prev();t=t||new r({name:"*",start:a,end:s});o=new n({name:"*",start:a,end:s});return new Ve({start:a,foreign_name:o,name:t,end:s})}function map_names(e){var t;if(is("punc","{")){next();t=[];while(!is("punc","}")){t.push(map_name(e));if(is("punc",",")){next()}}next()}else if(is("operator","*")){var n;next();if(e&&is("name","as")){next();n=as_symbol(e?Nt:Vt)}t=[map_nameAsterisk(e,n)]}return t}function export_(){var e=i.token;var t;var n;if(is("keyword","default")){t=true;next()}else if(n=map_names(false)){if(is("name","from")){next();var a=i.token;if(a.type!=="string"){unexpected()}next();return new Ke({start:e,is_default:t,exported_names:n,module_name:new Xt({start:a,value:a.value,quote:a.quote,end:a}),end:prev()})}else{return new Ke({start:e,is_default:t,exported_names:n,end:prev()})}}var o;var s;var u;if(is("punc","{")||t&&(is("keyword","class")||is("keyword","function"))&&is_token(peek(),"punc")){s=k(false);semicolon()}else if((o=r(t))instanceof Ne&&t){unexpected(o.start)}else if(o instanceof Ne||o instanceof pe||o instanceof Et){u=o}else if(o instanceof gt||o instanceof le){s=o}else if(o instanceof H){s=o.body}else{unexpected(o.start)}return new Ke({start:e,is_default:t,exported_value:s,exported_definition:u,end:prev()})}function as_property_name(){var e=i.token;switch(e.type){case"punc":if(e.value==="["){next();var t=k(false);expect("]");return t}else unexpected(e);case"operator":if(e.value==="*"){next();return null}if(!["delete","in","instanceof","new","typeof","void"].includes(e.value)){unexpected(e)}case"name":case"privatename":case"string":case"num":case"big_int":case"keyword":case"atom":next();return e.value;default:unexpected(e)}}function as_name(){var e=i.token;if(e.type!="name"&&e.type!="privatename")unexpected();next();return e.value}function _make_symbol(e){var t=i.token.value;return new(t=="this"?zt:t=="super"?Kt:e)({name:String(t),start:i.token,end:i.token})}function _verify_symbol(e){var t=e.name;if(is_in_generator()&&t=="yield"){token_error(e.start,"Yield cannot be used as identifier inside generators")}if(i.input.has_directive("use strict")){if(t=="yield"){token_error(e.start,"Unexpected yield identifier inside strict mode")}if(e instanceof bt&&(t=="arguments"||t=="eval")){token_error(e.start,"Unexpected "+t+" in strict mode")}}}function as_symbol(e,t){if(!is("name")){if(!t)croak("Name expected");return null}var n=_make_symbol(e);_verify_symbol(n);next();return n}function annotate(e){var t=e.start;var i=t.comments_before;const r=n.get(t);var a=r!=null?r:i.length;while(--a>=0){var o=i[a];if(/[@#]__/.test(o.value)){if(/[@#]__PURE__/.test(o.value)){set_annotation(e,an);break}if(/[@#]__INLINE__/.test(o.value)){set_annotation(e,on);break}if(/[@#]__NOINLINE__/.test(o.value)){set_annotation(e,sn);break}}}}var g=function(e,t,n){var i=e.start;if(is("punc",".")){next();const r=is("privatename")?Ye:qe;return g(new r({start:i,expression:e,optional:false,property:as_name(),end:prev()}),t,n)}if(is("punc","[")){next();var r=k(true);expect("]");return g(new je({start:i,expression:e,optional:false,property:r,end:prev()}),t,n)}if(t&&is("punc","(")){next();var a=new Ge({start:i,expression:e,optional:false,args:call_args(),end:prev()});annotate(a);return g(a,true,n)}if(is("punc","?.")){next();let n;if(t&&is("punc","(")){next();const t=new Ge({start:i,optional:true,expression:e,args:call_args(),end:prev()});annotate(t);n=g(t,true,true)}else if(is("name")||is("privatename")){const r=is("privatename")?Ye:qe;n=g(new r({start:i,expression:e,optional:true,property:as_name(),end:prev()}),t,true)}else if(is("punc","[")){next();const r=k(true);expect("]");n=g(new je({start:i,expression:e,optional:true,property:r,end:prev()}),t,true)}if(!n)unexpected();if(n instanceof $e)return n;return new $e({start:i,expression:n,end:prev()})}if(is("template_head")){if(n){unexpected()}return g(new he({start:i,prefix:e,template_string:template_string(),end:prev()}),t)}return e};function call_args(){var e=[];while(!is("punc",")")){if(is("expand","...")){next();e.push(new se({start:prev(),expression:k(false),end:prev()}))}else{e.push(k(false))}if(!is("punc",")")){expect(",")}}next();return e}var v=function(e,t){var n=i.token;if(n.type=="name"&&n.value=="await"&&can_await()){next();return _await_expression()}if(is("operator")&&F.has(n.value)){next();handle_regexp();var r=make_unary(Qe,n,v(e));r.start=n;r.end=prev();return r}var a=h(e,t);while(is("operator")&&O.has(i.token.value)&&!has_newline_before(i.token)){if(a instanceof fe)unexpected();a=make_unary(Je,i.token,a);a.start=n;a.end=i.token;next()}return a};function make_unary(e,t,n){var r=t.value;switch(r){case"++":case"--":if(!is_assignable(n))croak("Invalid use of "+r+" operator",t.line,t.col,t.pos);break;case"delete":if(n instanceof Lt&&i.input.has_directive("use strict"))croak("Calling delete on expression not allowed in strict mode",n.start.line,n.start.col,n.start.pos);break}return new e({operator:r,expression:n})}var D=function(e,t,n){var r=is("operator")?i.token.value:null;if(r=="in"&&n)r=null;if(r=="**"&&e instanceof Qe&&!is_token(e.start,"punc","(")&&e.operator!=="--"&&e.operator!=="++")unexpected(e.start);var a=r!=null?N[r]:null;if(a!=null&&(a>t||r==="**"&&t===a)){next();var o=D(v(true),a,n);return D(new et({start:e.start,left:e,operator:r,right:o,end:o.end}),t,n)}return e};function expr_ops(e){return D(v(true,true),0,e)}var b=function(e){var t=i.token;var n=expr_ops(e);if(is("operator","?")){next();var r=k(false);expect(":");return new tt({start:t,condition:n,consequent:r,alternative:k(false,e),end:prev()})}return n};function is_assignable(e){return e instanceof We||e instanceof Lt}function to_destructuring(e){if(e instanceof at){e=new _e({start:e.start,names:e.properties.map(to_destructuring),is_array:false,end:e.end})}else if(e instanceof rt){var t=[];for(var n=0;n=0;){a+="this."+t[o]+" = props."+t[o]+";"}const s=i&&Object.create(i.prototype);if(s&&s.initialize||n&&n.initialize)a+="this.initialize();";a+="}";a+="this.flags = 0;";a+="}";var u=new Function(a)();if(s){u.prototype=s;u.BASE=i}if(i)i.SUBCLASSES.push(u);u.prototype.CTOR=u;u.prototype.constructor=u;u.PROPS=t||null;u.SELF_PROPS=r;u.SUBCLASSES=[];if(e){u.prototype.TYPE=u.TYPE=e}if(n)for(o in n)if(HOP(n,o)){if(o[0]==="$"){u[o.substr(1)]=n[o]}else{u.prototype[o]=n[o]}}u.DEFMETHOD=function(e,t){this.prototype[e]=t};return u}const P=(e,t)=>Boolean(e.flags&t);const L=(e,t,n)=>{if(n){e.flags|=t}else{e.flags&=~t}};const B=1;const V=2;const U=4;class AST_Token{constructor(e,t,n,i,r,a,o,s,u){this.flags=a?1:0;this.type=e;this.value=t;this.line=n;this.col=i;this.pos=r;this.comments_before=o;this.comments_after=s;this.file=u;Object.seal(this)}get nlb(){return P(this,B)}set nlb(e){L(this,B,e)}get quote(){return!P(this,U)?"":P(this,V)?"'":'"'}set quote(e){L(this,V,e==="'");L(this,U,!!e)}}var z=DEFNODE("Node","start end",{_clone:function(e){if(e){var t=this.clone();return t.transform(new TreeTransformer(function(e){if(e!==t){return e.clone(true)}}))}return new this.CTOR(this)},clone:function(e){return this._clone(e)},$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(e){return e._visit(this)},walk:function(e){return this._walk(e)},_children_backwards:()=>{}},null);var K=DEFNODE("Statement",null,{$documentation:"Base class of all statements"});var G=DEFNODE("Debugger",null,{$documentation:"Represents a debugger statement"},K);var X=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"}},K);var H=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(e){return e._visit(this,function(){this.body._walk(e)})},_children_backwards(e){e(this.body)}},K);function walk_body(e,t){const n=e.body;for(var i=0,r=n.length;i SymbolDef for all variables/functions defined in this scope",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 e=this;while(e.is_block_scope()){e=e.parent_scope}return e},clone:function(e,t){var n=this._clone(e);if(e&&this.variables&&t&&!this._block_scope){n.figure_out_scope({},{toplevel:t,parent_scope:this.parent_scope})}else{if(this.variables)n.variables=new Map(this.variables);if(this.enclosed)n.enclosed=this.enclosed.slice();if(this._block_scope)n._block_scope=this._block_scope}return n},pinned:function(){return this.uses_eval||this.uses_with}},W);var oe=DEFNODE("Toplevel","globals",{$documentation:"The toplevel scope",$propdoc:{globals:"[Map/S] a map of name -> SymbolDef for all undeclared names"},wrap_commonjs:function(e){var t=this.body;var n="(function(exports){'$ORIG';})(typeof "+e+"=='undefined'?("+e+"={}):"+e+");";n=parse(n);n=n.transform(new TreeTransformer(function(e){if(e instanceof X&&e.value=="$ORIG"){return r.splice(t)}}));return n},wrap_enclose:function(e){if(typeof e!="string")e="";var t=e.indexOf(":");if(t<0)t=e.length;var n=this.body;return parse(["(function(",e.slice(0,t),'){"$ORIG"})(',e.slice(t+1),")"].join("")).transform(new TreeTransformer(function(e){if(e instanceof X&&e.value=="$ORIG"){return r.splice(n)}}))}},ae);var se=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(e){return e._visit(this,function(){this.expression.walk(e)})},_children_backwards(e){e(this.expression)}});var ue=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 e=[];for(var t=0;t b)"},ue);var pe=DEFNODE("Defun",null,{$documentation:"A function definition"},ue);var _e=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(e){return e._visit(this,function(){this.names.forEach(function(t){t._walk(e)})})},_children_backwards(e){let t=this.names.length;while(t--)e(this.names[t])},all_symbols:function(){var e=[];this.walk(new TreeWalker(function(t){if(t instanceof vt){e.push(t)}}));return e}});var he=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(e){return e._visit(this,function(){this.prefix._walk(e);this.template_string._walk(e)})},_children_backwards(e){e(this.template_string);e(this.prefix)}});var de=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(e){return e._visit(this,function(){this.segments.forEach(function(t){t._walk(e)})})},_children_backwards(e){let t=this.segments.length;while(t--)e(this.segments[t])}});var me=DEFNODE("TemplateSegment","value raw",{$documentation:"A segment of a template string literal",$propdoc:{value:"Content of the segment",raw:"Raw source of the segment"}});var Ee=DEFNODE("Jump",null,{$documentation:"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"},K);var ge=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(e){return e._visit(this,this.value&&function(){this.value._walk(e)})},_children_backwards(e){if(this.value)e(this.value)}},Ee);var ve=DEFNODE("Return",null,{$documentation:"A `return` statement"},ge);var De=DEFNODE("Throw",null,{$documentation:"A `throw` statement"},ge);var be=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(e){return e._visit(this,this.label&&function(){this.label._walk(e)})},_children_backwards(e){if(this.label)e(this.label)}},Ee);var ye=DEFNODE("Break",null,{$documentation:"A `break` statement"},be);var ke=DEFNODE("Continue",null,{$documentation:"A `continue` statement"},be);var Se=DEFNODE("Await","expression",{$documentation:"An `await` statement",$propdoc:{expression:"[AST_Node] the mandatory expression being awaited"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e)})},_children_backwards(e){e(this.expression)}});var Te=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(e){return e._visit(this,this.expression&&function(){this.expression._walk(e)})},_children_backwards(e){if(this.expression)e(this.expression)}});var Ae=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(e){return e._visit(this,function(){this.condition._walk(e);this.body._walk(e);if(this.alternative)this.alternative._walk(e)})},_children_backwards(e){if(this.alternative){e(this.alternative)}e(this.body);e(this.condition)}},j);var Ce=DEFNODE("Switch","expression",{$documentation:"A `switch` statement",$propdoc:{expression:"[AST_Node] the `switch` “discriminant”"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},W);var Re=DEFNODE("SwitchBranch",null,{$documentation:"Base class for `switch` branches"},W);var xe=DEFNODE("Default",null,{$documentation:"A `default` switch branch"},Re);var Fe=DEFNODE("Case","expression",{$documentation:"A `case` switch branch",$propdoc:{expression:"[AST_Node] the `case` expression"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},Re);var Oe=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(e){return e._visit(this,function(){walk_body(this,e);if(this.bcatch)this.bcatch._walk(e);if(this.bfinally)this.bfinally._walk(e)})},_children_backwards(e){if(this.bfinally)e(this.bfinally);if(this.bcatch)e(this.bcatch);let t=this.body.length;while(t--)e(this.body[t])}},W);var we=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(e){return e._visit(this,function(){if(this.argname)this.argname._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);if(this.argname)e(this.argname)}},W);var Me=DEFNODE("Finally",null,{$documentation:"A `finally` node; only makes sense as part of a `try` statement"},W);var Ne=DEFNODE("Definitions","definitions",{$documentation:"Base class for `var` or `const` nodes (variable declarations/initializations)",$propdoc:{definitions:"[AST_VarDef*] array of variable definitions"},_walk:function(e){return e._visit(this,function(){var t=this.definitions;for(var n=0,i=t.length;n a`"},et);var rt=DEFNODE("Array","elements",{$documentation:"An array literal",$propdoc:{elements:"[AST_Node*] array of elements"},_walk:function(e){return e._visit(this,function(){var t=this.elements;for(var n=0,i=t.length;nt._walk(e))})},_children_backwards(e){let t=this.properties.length;while(t--)e(this.properties[t]);if(this.extends)e(this.extends);if(this.name)e(this.name)}},ae);var dt=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(e){return e._visit(this,function(){if(this.key instanceof z)this.key._walk(e);if(this.value instanceof z)this.value._walk(e)})},_children_backwards(e){if(this.value instanceof z)e(this.value);if(this.key instanceof z)e(this.key)},computed_key(){return!(this.key instanceof xt)}},ot);var mt=DEFNODE("ClassProperty","",{$documentation:"A class property for a private property"},dt);var Et=DEFNODE("DefClass",null,{$documentation:"A class definition"},ht);var gt=DEFNODE("ClassExpression",null,{$documentation:"A class expression."},ht);var vt=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 Dt=DEFNODE("NewTarget",null,{$documentation:"A reference to new.target"});var bt=DEFNODE("SymbolDeclaration","init",{$documentation:"A declaration symbol (symbol in var/const, function name or argument, symbol in catch)"},vt);var yt=DEFNODE("SymbolVar",null,{$documentation:"Symbol defining a variable"},bt);var kt=DEFNODE("SymbolBlockDeclaration",null,{$documentation:"Base class for block-scoped declaration symbols"},bt);var St=DEFNODE("SymbolConst",null,{$documentation:"A constant declaration"},kt);var Tt=DEFNODE("SymbolLet",null,{$documentation:"A block-scoped `let` declaration"},kt);var At=DEFNODE("SymbolFunarg",null,{$documentation:"Symbol naming a function argument"},yt);var Ct=DEFNODE("SymbolDefun",null,{$documentation:"Symbol defining a function"},bt);var Rt=DEFNODE("SymbolMethod",null,{$documentation:"Symbol in an object defining a method"},vt);var xt=DEFNODE("SymbolClassProperty",null,{$documentation:"Symbol for a class property"},vt);var Ft=DEFNODE("SymbolLambda",null,{$documentation:"Symbol naming a function expression"},bt);var Ot=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."},kt);var wt=DEFNODE("SymbolClass",null,{$documentation:"Symbol naming a class's name. Lexically scoped to the class."},bt);var Mt=DEFNODE("SymbolCatch",null,{$documentation:"Symbol naming the exception in catch"},kt);var Nt=DEFNODE("SymbolImport",null,{$documentation:"Symbol referring to an imported name"},kt);var It=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"},vt);var Pt=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}},vt);var Lt=DEFNODE("SymbolRef",null,{$documentation:"Reference to some symbol (not definition/declaration)"},vt);var Bt=DEFNODE("SymbolExport",null,{$documentation:"Symbol referring to a name to export"},Lt);var Vt=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"},vt);var Ut=DEFNODE("LabelRef",null,{$documentation:"Reference to a label symbol"},vt);var zt=DEFNODE("This",null,{$documentation:"The `this` symbol"},vt);var Kt=DEFNODE("Super",null,{$documentation:"The `super` symbol"},zt);var Gt=DEFNODE("Constant",null,{$documentation:"Base class for all constants",getValue:function(){return this.value}});var Xt=DEFNODE("String","value quote",{$documentation:"A string literal",$propdoc:{value:"[string] the contents of this string",quote:"[string] the original quote character"}},Gt);var Ht=DEFNODE("Number","value raw",{$documentation:"A number literal",$propdoc:{value:"[number] the numeric value",raw:"[string] numeric value as string"}},Gt);var Wt=DEFNODE("BigInt","value",{$documentation:"A big int literal",$propdoc:{value:"[string] big int value"}},Gt);var qt=DEFNODE("RegExp","value",{$documentation:"A regexp literal",$propdoc:{value:"[RegExp] the actual regexp"}},Gt);var Yt=DEFNODE("Atom",null,{$documentation:"Base class for atoms"},Gt);var jt=DEFNODE("Null",null,{$documentation:"The `null` atom",value:null},Yt);var $t=DEFNODE("NaN",null,{$documentation:"The impossible value",value:0/0},Yt);var Zt=DEFNODE("Undefined",null,{$documentation:"The `undefined` value",value:function(){}()},Yt);var Qt=DEFNODE("Hole",null,{$documentation:"A hole in an array",value:function(){}()},Yt);var Jt=DEFNODE("Infinity",null,{$documentation:"The `Infinity` value",value:1/0},Yt);var en=DEFNODE("Boolean",null,{$documentation:"Base class for booleans"},Yt);var tn=DEFNODE("False",null,{$documentation:"The `false` atom",value:false},en);var nn=DEFNODE("True",null,{$documentation:"The `true` atom",value:true},en);function walk(e,t,n=[e]){const i=n.push.bind(n);while(n.length){const e=n.pop();const r=t(e,n);if(r){if(r===rn)return true;continue}e._children_backwards(i)}return false}function walk_parent(e,t,n){const i=[e];const r=i.push.bind(i);const a=n?n.slice():[];const o=[];let s;const u={parent:(e=0)=>{if(e===-1){return s}if(n&&e>=a.length){e-=a.length;return n[n.length-(e+1)]}return a[a.length-(1+e)]}};while(i.length){s=i.pop();while(o.length&&i.length==o[o.length-1]){a.pop();o.pop()}const e=t(s,u);if(e){if(e===rn)return true;continue}const n=i.length;s._children_backwards(r);if(i.length>n){a.push(s);o.push(n-1)}}return false}const rn=Symbol("abort walk");class TreeWalker{constructor(e){this.visit=e;this.stack=[];this.directives=Object.create(null)}_visit(e,t){this.push(e);var n=this.visit(e,t?function(){t.call(e)}:noop);if(!n&&t){t.call(e)}this.pop();return n}parent(e){return this.stack[this.stack.length-2-(e||0)]}push(e){if(e instanceof ue){this.directives=Object.create(this.directives)}else if(e instanceof X&&!this.directives[e.value]){this.directives[e.value]=e}else if(e instanceof ht){this.directives=Object.create(this.directives);if(!this.directives["use strict"]){this.directives["use strict"]=e}}this.stack.push(e)}pop(){var e=this.stack.pop();if(e instanceof ue||e instanceof ht){this.directives=Object.getPrototypeOf(this.directives)}}self(){return this.stack[this.stack.length-1]}find_parent(e){var t=this.stack;for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof e)return i}}has_directive(e){var t=this.directives[e];if(t)return t;var n=this.stack[this.stack.length-1];if(n instanceof ae&&n.body){for(var i=0;i=0;){var i=t[n];if(i instanceof $&&i.label.name==e.label.name)return i.body}else for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof Z||e instanceof ye&&i instanceof Ce)return i}}}class TreeTransformer extends TreeWalker{constructor(e,t){super();this.before=e;this.after=t}}const an=1;const on=2;const sn=4;var un=Object.freeze({__proto__:null,AST_Accessor:ce,AST_Array:rt,AST_Arrow:fe,AST_Assign:nt,AST_Atom:Yt,AST_Await:Se,AST_BigInt:Wt,AST_Binary:et,AST_Block:W,AST_BlockStatement:q,AST_Boolean:en,AST_Break:ye,AST_Call:Ge,AST_Case:Fe,AST_Catch:we,AST_Chain:$e,AST_Class:ht,AST_ClassExpression:gt,AST_ClassPrivateProperty:mt,AST_ClassProperty:dt,AST_ConciseMethod:pt,AST_Conditional:tt,AST_Const:Le,AST_Constant:Gt,AST_Continue:ke,AST_Debugger:G,AST_Default:xe,AST_DefaultAssign:it,AST_DefClass:Et,AST_Definitions:Ne,AST_Defun:pe,AST_Destructuring:_e,AST_Directive:X,AST_Do:J,AST_Dot:qe,AST_DotHash:Ye,AST_DWLoop:Q,AST_EmptyStatement:Y,AST_Exit:ge,AST_Expansion:se,AST_Export:Ke,AST_False:tn,AST_Finally:Me,AST_For:te,AST_ForIn:ne,AST_ForOf:ie,AST_Function:le,AST_Hole:Qt,AST_If:Ae,AST_Import:Ue,AST_ImportMeta:ze,AST_Infinity:Jt,AST_IterationStatement:Z,AST_Jump:Ee,AST_Label:Pt,AST_LabeledStatement:$,AST_LabelRef:Ut,AST_Lambda:ue,AST_Let:Pe,AST_LoopControl:be,AST_NameMapping:Ve,AST_NaN:$t,AST_New:Xe,AST_NewTarget:Dt,AST_Node:z,AST_Null:jt,AST_Number:Ht,AST_Object:at,AST_ObjectGetter:ft,AST_ObjectKeyVal:st,AST_ObjectProperty:ot,AST_ObjectSetter:lt,AST_PrefixedTemplateString:he,AST_PrivateGetter:ct,AST_PrivateMethod:_t,AST_PrivateSetter:ut,AST_PropAccess:We,AST_RegExp:qt,AST_Return:ve,AST_Scope:ae,AST_Sequence:He,AST_SimpleStatement:H,AST_Statement:K,AST_StatementWithBody:j,AST_String:Xt,AST_Sub:je,AST_Super:Kt,AST_Switch:Ce,AST_SwitchBranch:Re,AST_Symbol:vt,AST_SymbolBlockDeclaration:kt,AST_SymbolCatch:Mt,AST_SymbolClass:wt,AST_SymbolClassProperty:xt,AST_SymbolConst:St,AST_SymbolDeclaration:bt,AST_SymbolDefClass:Ot,AST_SymbolDefun:Ct,AST_SymbolExport:Bt,AST_SymbolExportForeign:Vt,AST_SymbolFunarg:At,AST_SymbolImport:Nt,AST_SymbolImportForeign:It,AST_SymbolLambda:Ft,AST_SymbolLet:Tt,AST_SymbolMethod:Rt,AST_SymbolRef:Lt,AST_SymbolVar:yt,AST_TemplateSegment:me,AST_TemplateString:de,AST_This:zt,AST_Throw:De,AST_Token:AST_Token,AST_Toplevel:oe,AST_True:nn,AST_Try:Oe,AST_Unary:Ze,AST_UnaryPostfix:Je,AST_UnaryPrefix:Qe,AST_Undefined:Zt,AST_Var:Ie,AST_VarDef:Be,AST_While:ee,AST_With:re,AST_Yield:Te,TreeTransformer:TreeTransformer,TreeWalker:TreeWalker,walk:walk,walk_abort:rn,walk_body:walk_body,walk_parent:walk_parent,_INLINE:on,_NOINLINE:sn,_PURE:an});function def_transform(e,t){e.DEFMETHOD("transform",function(e,n){let i=undefined;e.push(this);if(e.before)i=e.before(this,t,n);if(i===undefined){i=this;t(i,e);if(e.after){const t=e.after(i,n);if(t!==undefined)i=t}}e.pop();return i})}function do_list(e,t){return r(e,function(e){return e.transform(t,true)})}def_transform(z,noop);def_transform($,function(e,t){e.label=e.label.transform(t);e.body=e.body.transform(t)});def_transform(H,function(e,t){e.body=e.body.transform(t)});def_transform(W,function(e,t){e.body=do_list(e.body,t)});def_transform(J,function(e,t){e.body=e.body.transform(t);e.condition=e.condition.transform(t)});def_transform(ee,function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t)});def_transform(te,function(e,t){if(e.init)e.init=e.init.transform(t);if(e.condition)e.condition=e.condition.transform(t);if(e.step)e.step=e.step.transform(t);e.body=e.body.transform(t)});def_transform(ne,function(e,t){e.init=e.init.transform(t);e.object=e.object.transform(t);e.body=e.body.transform(t)});def_transform(re,function(e,t){e.expression=e.expression.transform(t);e.body=e.body.transform(t)});def_transform(ge,function(e,t){if(e.value)e.value=e.value.transform(t)});def_transform(be,function(e,t){if(e.label)e.label=e.label.transform(t)});def_transform(Ae,function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t);if(e.alternative)e.alternative=e.alternative.transform(t)});def_transform(Ce,function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)});def_transform(Fe,function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)});def_transform(Oe,function(e,t){e.body=do_list(e.body,t);if(e.bcatch)e.bcatch=e.bcatch.transform(t);if(e.bfinally)e.bfinally=e.bfinally.transform(t)});def_transform(we,function(e,t){if(e.argname)e.argname=e.argname.transform(t);e.body=do_list(e.body,t)});def_transform(Ne,function(e,t){e.definitions=do_list(e.definitions,t)});def_transform(Be,function(e,t){e.name=e.name.transform(t);if(e.value)e.value=e.value.transform(t)});def_transform(_e,function(e,t){e.names=do_list(e.names,t)});def_transform(ue,function(e,t){if(e.name)e.name=e.name.transform(t);e.argnames=do_list(e.argnames,t);if(e.body instanceof z){e.body=e.body.transform(t)}else{e.body=do_list(e.body,t)}});def_transform(Ge,function(e,t){e.expression=e.expression.transform(t);e.args=do_list(e.args,t)});def_transform(He,function(e,t){const n=do_list(e.expressions,t);e.expressions=n.length?n:[new Ht({value:0})]});def_transform(qe,function(e,t){e.expression=e.expression.transform(t)});def_transform(je,function(e,t){e.expression=e.expression.transform(t);e.property=e.property.transform(t)});def_transform($e,function(e,t){e.expression=e.expression.transform(t)});def_transform(Te,function(e,t){if(e.expression)e.expression=e.expression.transform(t)});def_transform(Se,function(e,t){e.expression=e.expression.transform(t)});def_transform(Ze,function(e,t){e.expression=e.expression.transform(t)});def_transform(et,function(e,t){e.left=e.left.transform(t);e.right=e.right.transform(t)});def_transform(tt,function(e,t){e.condition=e.condition.transform(t);e.consequent=e.consequent.transform(t);e.alternative=e.alternative.transform(t)});def_transform(rt,function(e,t){e.elements=do_list(e.elements,t)});def_transform(at,function(e,t){e.properties=do_list(e.properties,t)});def_transform(ot,function(e,t){if(e.key instanceof z){e.key=e.key.transform(t)}if(e.value)e.value=e.value.transform(t)});def_transform(ht,function(e,t){if(e.name)e.name=e.name.transform(t);if(e.extends)e.extends=e.extends.transform(t);e.properties=do_list(e.properties,t)});def_transform(se,function(e,t){e.expression=e.expression.transform(t)});def_transform(Ve,function(e,t){e.foreign_name=e.foreign_name.transform(t);e.name=e.name.transform(t)});def_transform(Ue,function(e,t){if(e.imported_name)e.imported_name=e.imported_name.transform(t);if(e.imported_names)do_list(e.imported_names,t);e.module_name=e.module_name.transform(t)});def_transform(Ke,function(e,t){if(e.exported_definition)e.exported_definition=e.exported_definition.transform(t);if(e.exported_value)e.exported_value=e.exported_value.transform(t);if(e.exported_names)do_list(e.exported_names,t);if(e.module_name)e.module_name=e.module_name.transform(t)});def_transform(de,function(e,t){e.segments=do_list(e.segments,t)});def_transform(he,function(e,t){e.prefix=e.prefix.transform(t);e.template_string=e.template_string.transform(t)});(function(){var e=function(e){var t=true;for(var n=0;n1||e.guardedHandlers&&e.guardedHandlers.length){throw new Error("Multiple catch clauses are not supported.")}return new Oe({start:my_start_token(e),end:my_end_token(e),body:from_moz(e.block).body,bcatch:from_moz(t[0]),bfinally:e.finalizer?new Me(from_moz(e.finalizer)):null})},Property:function(e){var t=e.key;var n={start:my_start_token(t||e.value),end:my_end_token(e.value),key:t.type=="Identifier"?t.name:t.value,value:from_moz(e.value)};if(e.computed){n.key=from_moz(e.key)}if(e.method){n.is_generator=e.value.generator;n.async=e.value.async;if(!e.computed){n.key=new Rt({name:n.key})}else{n.key=from_moz(e.key)}return new pt(n)}if(e.kind=="init"){if(t.type!="Identifier"&&t.type!="Literal"){n.key=from_moz(t)}return new st(n)}if(typeof n.key==="string"||typeof n.key==="number"){n.key=new Rt({name:n.key})}n.value=new ce(n.value);if(e.kind=="get")return new ft(n);if(e.kind=="set")return new lt(n);if(e.kind=="method"){n.async=e.value.async;n.is_generator=e.value.generator;n.quote=e.computed?'"':null;return new pt(n)}},MethodDefinition:function(e){var t={start:my_start_token(e),end:my_end_token(e),key:e.computed?from_moz(e.key):new Rt({name:e.key.name||e.key.value}),value:from_moz(e.value),static:e.static};if(e.kind=="get"){return new ft(t)}if(e.kind=="set"){return new lt(t)}t.is_generator=e.value.generator;t.async=e.value.async;return new pt(t)},FieldDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in FieldDefinition");t=from_moz(e.key)}return new dt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},PropertyDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in PropertyDefinition");t=from_moz(e.key)}return new dt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},ArrayExpression:function(e){return new rt({start:my_start_token(e),end:my_end_token(e),elements:e.elements.map(function(e){return e===null?new Qt:from_moz(e)})})},ObjectExpression:function(e){return new at({start:my_start_token(e),end:my_end_token(e),properties:e.properties.map(function(e){if(e.type==="SpreadElement"){return from_moz(e)}e.type="Property";return from_moz(e)})})},SequenceExpression:function(e){return new He({start:my_start_token(e),end:my_end_token(e),expressions:e.expressions.map(from_moz)})},MemberExpression:function(e){return new(e.computed?je:qe)({start:my_start_token(e),end:my_end_token(e),property:e.computed?from_moz(e.property):e.property.name,expression:from_moz(e.object),optional:e.optional||false})},ChainExpression:function(e){return new $e({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.expression)})},SwitchCase:function(e){return new(e.test?Fe:xe)({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.test),body:e.consequent.map(from_moz)})},VariableDeclaration:function(e){return new(e.kind==="const"?Le:e.kind==="let"?Pe:Ie)({start:my_start_token(e),end:my_end_token(e),definitions:e.declarations.map(from_moz)})},ImportDeclaration:function(e){var t=null;var n=null;e.specifiers.forEach(function(e){if(e.type==="ImportSpecifier"){if(!n){n=[]}n.push(new Ve({start:my_start_token(e),end:my_end_token(e),foreign_name:from_moz(e.imported),name:from_moz(e.local)}))}else if(e.type==="ImportDefaultSpecifier"){t=from_moz(e.local)}else if(e.type==="ImportNamespaceSpecifier"){if(!n){n=[]}n.push(new Ve({start:my_start_token(e),end:my_end_token(e),foreign_name:new It({name:"*"}),name:from_moz(e.local)}))}});return new Ue({start:my_start_token(e),end:my_end_token(e),imported_name:t,imported_names:n,module_name:from_moz(e.source)})},ExportAllDeclaration:function(e){return new Ke({start:my_start_token(e),end:my_end_token(e),exported_names:[new Ve({name:new Vt({name:"*"}),foreign_name:new Vt({name:"*"})})],module_name:from_moz(e.source)})},ExportNamedDeclaration:function(e){return new Ke({start:my_start_token(e),end:my_end_token(e),exported_definition:from_moz(e.declaration),exported_names:e.specifiers&&e.specifiers.length?e.specifiers.map(function(e){return new Ve({foreign_name:from_moz(e.exported),name:from_moz(e.local)})}):null,module_name:from_moz(e.source)})},ExportDefaultDeclaration:function(e){return new Ke({start:my_start_token(e),end:my_end_token(e),exported_value:from_moz(e.declaration),is_default:true})},Literal:function(e){var t=e.value,n={start:my_start_token(e),end:my_end_token(e)};var i=e.regex;if(i&&i.pattern){n.value={source:i.pattern,flags:i.flags};return new qt(n)}else if(i){const i=e.raw||t;const r=i.match(/^\/(.*)\/(\w*)$/);if(!r)throw new Error("Invalid regex source "+i);const[a,o,s]=r;n.value={source:o,flags:s};return new qt(n)}if(t===null)return new jt(n);switch(typeof t){case"string":n.value=t;return new Xt(n);case"number":n.value=t;n.raw=e.raw||t.toString();return new Ht(n);case"boolean":return new(t?nn:tn)(n)}},MetaProperty:function(e){if(e.meta.name==="new"&&e.property.name==="target"){return new Dt({start:my_start_token(e),end:my_end_token(e)})}else if(e.meta.name==="import"&&e.property.name==="meta"){return new ze({start:my_start_token(e),end:my_end_token(e)})}},Identifier:function(e){var t=n[n.length-2];return new(t.type=="LabeledStatement"?Pt:t.type=="VariableDeclarator"&&t.id===e?t.kind=="const"?St:t.kind=="let"?Tt:yt:/Import.*Specifier/.test(t.type)?t.local===e?Nt:It:t.type=="ExportSpecifier"?t.local===e?Bt:Vt:t.type=="FunctionExpression"?t.id===e?Ft:At:t.type=="FunctionDeclaration"?t.id===e?Ct:At:t.type=="ArrowFunctionExpression"?t.params.includes(e)?At:Lt:t.type=="ClassExpression"?t.id===e?wt:Lt:t.type=="Property"?t.key===e&&t.computed||t.value===e?Lt:Rt:t.type=="PropertyDefinition"||t.type==="FieldDefinition"?t.key===e&&t.computed||t.value===e?Lt:xt:t.type=="ClassDeclaration"?t.id===e?Ot:Lt:t.type=="MethodDefinition"?t.computed?Lt:Rt:t.type=="CatchClause"?Mt:t.type=="BreakStatement"||t.type=="ContinueStatement"?Ut:Lt)({start:my_start_token(e),end:my_end_token(e),name:e.name})},BigIntLiteral(e){return new Wt({start:my_start_token(e),end:my_end_token(e),value:e.value})}};t.UpdateExpression=t.UnaryExpression=function To_Moz_Unary(e){var t="prefix"in e?e.prefix:e.type=="UnaryExpression"?true:false;return new(t?Qe:Je)({start:my_start_token(e),end:my_end_token(e),operator:e.operator,expression:from_moz(e.argument)})};t.ClassDeclaration=t.ClassExpression=function From_Moz_Class(e){return new(e.type==="ClassDeclaration"?Et:gt)({start:my_start_token(e),end:my_end_token(e),name:from_moz(e.id),extends:from_moz(e.superClass),properties:e.body.body.map(from_moz)})};map("EmptyStatement",Y);map("BlockStatement",q,"body@body");map("IfStatement",Ae,"test>condition, consequent>body, alternate>alternative");map("LabeledStatement",$,"label>label, body>body");map("BreakStatement",ye,"label>label");map("ContinueStatement",ke,"label>label");map("WithStatement",re,"object>expression, body>body");map("SwitchStatement",Ce,"discriminant>expression, cases@body");map("ReturnStatement",ve,"argument>value");map("ThrowStatement",De,"argument>value");map("WhileStatement",ee,"test>condition, body>body");map("DoWhileStatement",J,"test>condition, body>body");map("ForStatement",te,"init>init, test>condition, update>step, body>body");map("ForInStatement",ne,"left>init, right>object, body>body");map("ForOfStatement",ie,"left>init, right>object, body>body, await=await");map("AwaitExpression",Se,"argument>expression");map("YieldExpression",Te,"argument>expression, delegate=is_star");map("DebuggerStatement",G);map("VariableDeclarator",Be,"id>name, init>value");map("CatchClause",we,"param>argname, body%body");map("ThisExpression",zt);map("Super",Kt);map("BinaryExpression",et,"operator=operator, left>left, right>right");map("LogicalExpression",et,"operator=operator, left>left, right>right");map("AssignmentExpression",nt,"operator=operator, left>left, right>right");map("ConditionalExpression",tt,"test>condition, consequent>consequent, alternate>alternative");map("NewExpression",Xe,"callee>expression, arguments@args");map("CallExpression",Ge,"callee>expression, optional=optional, arguments@args");def_to_moz(oe,function To_Moz_Program(e){return to_moz_scope("Program",e)});def_to_moz(se,function To_Moz_Spread(e){return{type:to_moz_in_destructuring()?"RestElement":"SpreadElement",argument:to_moz(e.expression)}});def_to_moz(he,function To_Moz_TaggedTemplateExpression(e){return{type:"TaggedTemplateExpression",tag:to_moz(e.prefix),quasi:to_moz(e.template_string)}});def_to_moz(de,function To_Moz_TemplateLiteral(e){var t=[];var n=[];for(var i=0;i({type:"BigIntLiteral",value:e.value}));en.DEFMETHOD("to_mozilla_ast",Gt.prototype.to_mozilla_ast);jt.DEFMETHOD("to_mozilla_ast",Gt.prototype.to_mozilla_ast);Qt.DEFMETHOD("to_mozilla_ast",function To_Moz_ArrayHole(){return null});W.DEFMETHOD("to_mozilla_ast",q.prototype.to_mozilla_ast);ue.DEFMETHOD("to_mozilla_ast",le.prototype.to_mozilla_ast);function my_start_token(e){var t=e.loc,n=t&&t.start;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.start,false,[],[],t&&t.source)}function my_end_token(e){var t=e.loc,n=t&&t.end;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.end,false,[],[],t&&t.source)}function map(e,n,i){var r="function From_Moz_"+e+"(M){\n";r+="return new U2."+n.name+"({\n"+"start: my_start_token(M),\n"+"end: my_end_token(M)";var a="function To_Moz_"+e+"(M){\n";a+="return {\n"+"type: "+JSON.stringify(e);if(i)i.split(/\s*,\s*/).forEach(function(e){var t=/([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(e);if(!t)throw new Error("Can't understand property map: "+e);var n=t[1],i=t[2],o=t[3];r+=",\n"+o+": ";a+=",\n"+n+": ";switch(i){case"@":r+="M."+n+".map(from_moz)";a+="M."+o+".map(to_moz)";break;case">":r+="from_moz(M."+n+")";a+="to_moz(M."+o+")";break;case"=":r+="M."+n;a+="M."+o;break;case"%":r+="from_moz(M."+n+").body";a+="to_moz_block(M)";break;default:throw new Error("Can't understand operator in propmap: "+e)}});r+="\n})\n}";a+="\n}\n}";r=new Function("U2","my_start_token","my_end_token","from_moz","return("+r+")")(un,my_start_token,my_end_token,from_moz);a=new Function("to_moz","to_moz_block","to_moz_scope","return("+a+")")(to_moz,to_moz_block,to_moz_scope);t[e]=r;def_to_moz(n,a)}var n=null;function from_moz(e){n.push(e);var i=e!=null?t[e.type](e):null;n.pop();return i}z.from_mozilla_ast=function(e){var t=n;n=[];var i=from_moz(e);n=t;return i};function set_moz_loc(e,t){var n=e.start;var i=e.end;if(!(n&&i)){return t}if(n.pos!=null&&i.endpos!=null){t.range=[n.pos,i.endpos]}if(n.line){t.loc={start:{line:n.line,column:n.col},end:i.endline?{line:i.endline,column:i.endcol}:null};if(n.file){t.loc.source=n.file}}return t}function def_to_moz(e,t){e.DEFMETHOD("to_mozilla_ast",function(e){return set_moz_loc(this,t(this,e))})}var i=null;function to_moz(e){if(i===null){i=[]}i.push(e);var t=e!=null?e.to_mozilla_ast(i[i.length-2]):null;i.pop();if(i.length===0){i=null}return t}function to_moz_in_destructuring(){var e=i.length;while(e--){if(i[e]instanceof _e){return true}}return false}function to_moz_block(e){return{type:"BlockStatement",body:e.body.map(to_moz)}}function to_moz_scope(e,t){var n=t.body.map(to_moz);if(t.body[0]instanceof H&&t.body[0].body instanceof Xt){n.unshift(to_moz(new Y(t.body[0])))}return{type:e,body:n}}})();function first_in_statement(e){let t=e.parent(-1);for(let n=0,i;i=e.parent(n);n++){if(i instanceof K&&i.body===t)return true;if(i instanceof He&&i.expressions[0]===t||i.TYPE==="Call"&&i.expression===t||i instanceof he&&i.prefix===t||i instanceof qe&&i.expression===t||i instanceof je&&i.expression===t||i instanceof tt&&i.condition===t||i instanceof et&&i.left===t||i instanceof Je&&i.expression===t){t=i}else{return false}}}function left_is_object(e){if(e instanceof at)return true;if(e instanceof He)return left_is_object(e.expressions[0]);if(e.TYPE==="Call")return left_is_object(e.expression);if(e instanceof he)return left_is_object(e.prefix);if(e instanceof qe||e instanceof je)return left_is_object(e.expression);if(e instanceof tt)return left_is_object(e.condition);if(e instanceof et)return left_is_object(e.left);if(e instanceof Je)return left_is_object(e.expression);return false}const cn=/^$|[;{][\s\n]*$/;const ln=10;const fn=32;const pn=/[@#]__(PURE|INLINE|NOINLINE)__/g;function is_some_comments(e){return(e.type==="comment2"||e.type==="comment1")&&/@preserve|@lic|@cc_on|^\**!/i.test(e.value)}function OutputStream(e){var t=!e;e=defaults(e,{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(e.shorthand===undefined)e.shorthand=e.ecma>5;var n=return_false;if(e.comments){let t=e.comments;if(typeof e.comments==="string"&&/^\/.*\/[a-zA-Z]*$/.test(e.comments)){var i=e.comments.lastIndexOf("/");t=new RegExp(e.comments.substr(1,i-1),e.comments.substr(i+1))}if(t instanceof RegExp){n=function(e){return e.type!="comment5"&&t.test(e.value)}}else if(typeof t==="function"){n=function(e){return e.type!="comment5"&&t(this,e)}}else if(t==="some"){n=is_some_comments}else{n=return_true}}var r=0;var a=0;var o=1;var s=0;var u="";let c=new Set;var l=e.ascii_only?function(t,n){if(e.ecma>=2015&&!e.safari10){t=t.replace(/[\ud800-\udbff][\udc00-\udfff]/g,function(e){var t=get_full_char_code(e,0).toString(16);return"\\u{"+t+"}"})}return t.replace(/[\u0000-\u001f\u007f-\uffff]/g,function(e){var t=e.charCodeAt(0).toString(16);if(t.length<=2&&!n){while(t.length<2)t="0"+t;return"\\x"+t}else{while(t.length<4)t="0"+t;return"\\u"+t}})}:function(e){return e.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g,function(e,t){if(t){return"\\u"+t.charCodeAt(0).toString(16)}return e})};function make_string(t,n){var i=0,r=0;t=t.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,function(n,a){switch(n){case'"':++i;return'"';case"'":++r;return"'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\t":return"\\t";case"\b":return"\\b";case"\f":return"\\f";case"\v":return e.ie8?"\\x0B":"\\v";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";case"\ufeff":return"\\ufeff";case"\0":return/[0-9]/.test(get_full_char(t,a+1))?"\\x00":"\\0"}return n});function quote_single(){return"'"+t.replace(/\x27/g,"\\'")+"'"}function quote_double(){return'"'+t.replace(/\x22/g,'\\"')+'"'}function quote_template(){return"`"+t.replace(/`/g,"\\`")+"`"}t=l(t);if(n==="`")return quote_template();switch(e.quote_style){case 1:return quote_single();case 2:return quote_double();case 3:return n=="'"?quote_single():quote_double();default:return i>r?quote_single():quote_double()}}function encode_string(t,n){var i=make_string(t,n);if(e.inline_script){i=i.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi,"<\\/$1$2");i=i.replace(/\x3c!--/g,"\\x3c!--");i=i.replace(/--\x3e/g,"--\\x3e")}return i}function make_name(e){e=e.toString();e=l(e,true);return e}function make_indent(t){return" ".repeat(e.indent_start+r-t*e.indent_level)}var f=false;var p=false;var _=false;var h=0;var d=false;var m=false;var E=-1;var g="";var v,D,b=e.source_map&&[];var y=b?function(){b.forEach(function(t){try{let n=!t.name&&t.token.type=="name"?t.token.value:t.name;if(n instanceof vt){n=n.name}e.source_map.add(t.token.file,t.line,t.col,t.token.line,t.token.col,is_basic_identifier_string(n)?n:undefined)}catch(e){}});b=[]}:noop;var k=e.max_line_len?function(){if(a>e.max_line_len){if(h){var t=u.slice(0,h);var n=u.slice(h);if(b){var i=n.length-a;b.forEach(function(e){e.line++;e.col+=i})}u=t+"\n"+n;o++;s++;a=n.length}}if(h){h=0;y()}}:noop;var S=makePredicate("( [ + * / - , . `");function print(t){t=String(t);var n=get_full_char(t,0);if(d&&n){d=false;if(n!=="\n"){print("\n");C()}}if(m&&n){m=false;if(!/[\s;})]/.test(n)){A()}}E=-1;var i=g.charAt(g.length-1);if(_){_=false;if(i===":"&&n==="}"||(!n||!";}".includes(n))&&i!==";"){if(e.semicolons||S.has(n)){u+=";";a++;s++}else{k();if(a>0){u+="\n";s++;o++;a=0}if(/^\s+$/.test(t)){_=true}}if(!e.beautify)p=false}}if(p){if(is_identifier_char(i)&&(is_identifier_char(n)||n=="\\")||n=="/"&&n==i||(n=="+"||n=="-")&&n==g){u+=" ";a++;s++}p=false}if(v){b.push({token:v,name:D,line:o,col:a});v=false;if(!h)y()}u+=t;f=t[t.length-1]=="(";s+=t.length;var r=t.split(/\r?\n/),c=r.length-1;o+=c;a+=r[0].length;if(c>0){k();a=r[c].length}g=t}var T=function(){print("*")};var A=e.beautify?function(){print(" ")}:function(){p=true};var C=e.beautify?function(t){if(e.beautify){print(make_indent(t?.5:0))}}:noop;var R=e.beautify?function(e,t){if(e===true)e=next_indent();var n=r;r=e;var i=t();r=n;return i}:function(e,t){return t()};var x=e.beautify?function(){if(E<0)return print("\n");if(u[E]!="\n"){u=u.slice(0,E)+"\n"+u.slice(E);s++;o++}E++}:e.max_line_len?function(){k();h=u.length}:noop;var F=e.beautify?function(){print(";")}:function(){_=true};function force_semicolon(){_=false;print(";")}function next_indent(){return r+e.indent_level}function with_block(e){var t;print("{");x();R(next_indent(),function(){t=e()});C();print("}");return t}function with_parens(e){print("(");var t=e();print(")");return t}function with_square(e){print("[");var t=e();print("]");return t}function comma(){print(",");A()}function colon(){print(":");A()}var O=b?function(e,t){v=e;D=t}:noop;function get(){if(h){k()}return u}function has_nlb(){let e=u.length-1;while(e>=0){const t=u.charCodeAt(e);if(t===ln){return true}if(t!==fn){return false}e--}return true}function filter_comment(t){if(!e.preserve_annotations){t=t.replace(pn," ")}if(/^\s*$/.test(t)){return""}return t.replace(/(<\s*\/\s*)(script)/i,"<\\/$2")}function prepend_comments(t){var i=this;var r=t.start;if(!r)return;var a=i.printed_comments;const o=t instanceof ge&&t.value;if(r.comments_before&&a.has(r.comments_before)){if(o){r.comments_before=[]}else{return}}var u=r.comments_before;if(!u){u=r.comments_before=[]}a.add(u);if(o){var c=new TreeWalker(function(e){var t=c.parent();if(t instanceof ge||t instanceof et&&t.left===e||t.TYPE=="Call"&&t.expression===e||t instanceof tt&&t.condition===e||t instanceof qe&&t.expression===e||t instanceof He&&t.expressions[0]===e||t instanceof je&&t.expression===e||t instanceof Je){if(!e.start)return;var n=e.start.comments_before;if(n&&!a.has(n)){a.add(n);u=u.concat(n)}}else{return true}});c.push(t);t.value.walk(c)}if(s==0){if(u.length>0&&e.shebang&&u[0].type==="comment5"&&!a.has(u[0])){print("#!"+u.shift().value+"\n");C()}var l=e.preamble;if(l){print(l.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g,"\n"))}}u=u.filter(n,t).filter(e=>!a.has(e));if(u.length==0)return;var f=has_nlb();u.forEach(function(e,t){a.add(e);if(!f){if(e.nlb){print("\n");C();f=true}else if(t>0){A()}}if(/comment[134]/.test(e.type)){var n=filter_comment(e.value);if(n){print("//"+n+"\n");C()}f=true}else if(e.type=="comment2"){var n=filter_comment(e.value);if(n){print("/*"+n+"*/")}f=false}});if(!f){if(r.nlb){print("\n");C()}else{A()}}}function append_comments(e,t){var i=this;var r=e.end;if(!r)return;var a=i.printed_comments;var o=r[t?"comments_before":"comments_after"];if(!o||a.has(o))return;if(!(e instanceof K||o.every(e=>!/comment[134]/.test(e.type))))return;a.add(o);var s=u.length;o.filter(n,e).forEach(function(e,n){if(a.has(e))return;a.add(e);m=false;if(d){print("\n");C();d=false}else if(e.nlb&&(n>0||!has_nlb())){print("\n");C()}else if(n>0||!t){A()}if(/comment[134]/.test(e.type)){const t=filter_comment(e.value);if(t){print("//"+t)}d=true}else if(e.type=="comment2"){const t=filter_comment(e.value);if(t){print("/*"+t+"*/")}m=true}});if(u.length>s)E=s}var w=[];return{get:get,toString:get,indent:C,in_directive:false,use_asm:null,active_scope:null,indentation:function(){return r},current_width:function(){return a-r},should_break:function(){return e.width&&this.current_width()>=e.width},has_parens:function(){return f},newline:x,print:print,star:T,space:A,comma:comma,colon:colon,last:function(){return g},semicolon:F,force_semicolon:force_semicolon,to_utf8:l,print_name:function(e){print(make_name(e))},print_string:function(e,t,n){var i=encode_string(e,t);if(n===true&&!i.includes("\\")){if(!cn.test(u)){force_semicolon()}force_semicolon()}print(i)},print_template_string_chars:function(e){var t=encode_string(e,"`").replace(/\${/g,"\\${");return print(t.substr(1,t.length-2))},encode_string:encode_string,next_indent:next_indent,with_indent:R,with_block:with_block,with_parens:with_parens,with_square:with_square,add_mapping:O,option:function(t){return e[t]},printed_comments:c,prepend_comments:t?noop:prepend_comments,append_comments:t||n===return_false?noop:append_comments,line:function(){return o},col:function(){return a},pos:function(){return s},push_node:function(e){w.push(e)},pop_node:function(){return w.pop()},parent:function(e){return w[w.length-2-(e||0)]}}}(function(){function DEFPRINT(e,t){e.DEFMETHOD("_codegen",t)}z.DEFMETHOD("print",function(e,t){var n=this,i=n._codegen;if(n instanceof ae){e.active_scope=n}else if(!e.use_asm&&n instanceof X&&n.value=="use asm"){e.use_asm=e.active_scope}function doit(){e.prepend_comments(n);n.add_source_map(e);i(n,e);e.append_comments(n)}e.push_node(n);if(t||n.needs_parens(e)){e.with_parens(doit)}else{doit()}e.pop_node();if(n===e.use_asm){e.use_asm=null}});z.DEFMETHOD("_print",z.prototype.print);z.DEFMETHOD("print_to_string",function(e){var t=OutputStream(e);this.print(t);return t.get()});function PARENS(e,t){if(Array.isArray(e)){e.forEach(function(e){PARENS(e,t)})}else{e.DEFMETHOD("needs_parens",t)}}PARENS(z,return_false);PARENS(le,function(e){if(!e.has_parens()&&first_in_statement(e)){return true}if(e.option("webkit")){var t=e.parent();if(t instanceof We&&t.expression===this){return true}}if(e.option("wrap_iife")){var t=e.parent();if(t instanceof Ge&&t.expression===this){return true}}if(e.option("wrap_func_args")){var t=e.parent();if(t instanceof Ge&&t.args.includes(this)){return true}}return false});PARENS(fe,function(e){var t=e.parent();if(e.option("wrap_func_args")&&t instanceof Ge&&t.args.includes(this)){return true}return t instanceof We&&t.expression===this});PARENS(at,function(e){return!e.has_parens()&&first_in_statement(e)});PARENS(gt,first_in_statement);PARENS(Ze,function(e){var t=e.parent();return t instanceof We&&t.expression===this||t instanceof Ge&&t.expression===this||t instanceof et&&t.operator==="**"&&this instanceof Qe&&t.left===this&&this.operator!=="++"&&this.operator!=="--"});PARENS(Se,function(e){var t=e.parent();return t instanceof We&&t.expression===this||t instanceof Ge&&t.expression===this||t instanceof et&&t.operator==="**"&&t.left===this||e.option("safari10")&&t instanceof Qe});PARENS(He,function(e){var t=e.parent();return t instanceof Ge||t instanceof Ze||t instanceof et||t instanceof Be||t instanceof We||t instanceof rt||t instanceof ot||t instanceof tt||t instanceof fe||t instanceof it||t instanceof se||t instanceof ie&&this===t.object||t instanceof Te||t instanceof Ke});PARENS(et,function(e){var t=e.parent();if(t instanceof Ge&&t.expression===this)return true;if(t instanceof Ze)return true;if(t instanceof We&&t.expression===this)return true;if(t instanceof et){const e=t.operator;const n=this.operator;if(n==="??"&&(e==="||"||e==="&&")){return true}if(e==="??"&&(n==="||"||n==="&&")){return true}const i=N[e];const r=N[n];if(i>r||i==r&&(this===t.right||e=="**")){return true}}});PARENS(Te,function(e){var t=e.parent();if(t instanceof et&&t.operator!=="=")return true;if(t instanceof Ge&&t.expression===this)return true;if(t instanceof tt&&t.condition===this)return true;if(t instanceof Ze)return true;if(t instanceof We&&t.expression===this)return true});PARENS(We,function(e){var t=e.parent();if(t instanceof Xe&&t.expression===this){return walk(this,e=>{if(e instanceof ae)return true;if(e instanceof Ge){return rn}})}});PARENS(Ge,function(e){var t=e.parent(),n;if(t instanceof Xe&&t.expression===this||t instanceof Ke&&t.is_default&&this.expression instanceof le)return true;return this.expression instanceof le&&t instanceof We&&t.expression===this&&(n=e.parent(1))instanceof nt&&n.left===t});PARENS(Xe,function(e){var t=e.parent();if(this.args.length===0&&(t instanceof We||t instanceof Ge&&t.expression===this))return true});PARENS(Ht,function(e){var t=e.parent();if(t instanceof We&&t.expression===this){var n=this.getValue();if(n<0||/^0/.test(make_num(n))){return true}}});PARENS(Wt,function(e){var t=e.parent();if(t instanceof We&&t.expression===this){var n=this.getValue();if(n.startsWith("-")){return true}}});PARENS([nt,tt],function(e){var t=e.parent();if(t instanceof Ze)return true;if(t instanceof et&&!(t instanceof nt))return true;if(t instanceof Ge&&t.expression===this)return true;if(t instanceof tt&&t.condition===this)return true;if(t instanceof We&&t.expression===this)return true;if(this instanceof nt&&this.left instanceof _e&&this.left.is_array===false)return true});DEFPRINT(X,function(e,t){t.print_string(e.value,e.quote);t.semicolon()});DEFPRINT(se,function(e,t){t.print("...");e.expression.print(t)});DEFPRINT(_e,function(e,t){t.print(e.is_array?"[":"{");var n=e.names.length;e.names.forEach(function(e,i){if(i>0)t.comma();e.print(t);if(i==n-1&&e instanceof Qt)t.comma()});t.print(e.is_array?"]":"}")});DEFPRINT(G,function(e,t){t.print("debugger");t.semicolon()});function display_body(e,t,n,i){var r=e.length-1;n.in_directive=i;e.forEach(function(e,i){if(n.in_directive===true&&!(e instanceof X||e instanceof Y||e instanceof H&&e.body instanceof Xt)){n.in_directive=false}if(!(e instanceof Y)){n.indent();e.print(n);if(!(i==r&&t)){n.newline();if(t)n.newline()}}if(n.in_directive===true&&e instanceof H&&e.body instanceof Xt){n.in_directive=false}});n.in_directive=false}j.DEFMETHOD("_do_print_body",function(e){force_statement(this.body,e)});DEFPRINT(K,function(e,t){e.body.print(t);t.semicolon()});DEFPRINT(oe,function(e,t){display_body(e.body,true,t,true);t.print("")});DEFPRINT($,function(e,t){e.label.print(t);t.colon();e.body.print(t)});DEFPRINT(H,function(e,t){e.body.print(t);t.semicolon()});function print_braced_empty(e,t){t.print("{");t.with_indent(t.next_indent(),function(){t.append_comments(e,true)});t.print("}")}function print_braced(e,t,n){if(e.body.length>0){t.with_block(function(){display_body(e.body,false,t,n)})}else print_braced_empty(e,t)}DEFPRINT(q,function(e,t){print_braced(e,t)});DEFPRINT(Y,function(e,t){t.semicolon()});DEFPRINT(J,function(e,t){t.print("do");t.space();make_block(e.body,t);t.space();t.print("while");t.space();t.with_parens(function(){e.condition.print(t)});t.semicolon()});DEFPRINT(ee,function(e,t){t.print("while");t.space();t.with_parens(function(){e.condition.print(t)});t.space();e._do_print_body(t)});DEFPRINT(te,function(e,t){t.print("for");t.space();t.with_parens(function(){if(e.init){if(e.init instanceof Ne){e.init.print(t)}else{parenthesize_for_noin(e.init,t,true)}t.print(";");t.space()}else{t.print(";")}if(e.condition){e.condition.print(t);t.print(";");t.space()}else{t.print(";")}if(e.step){e.step.print(t)}});t.space();e._do_print_body(t)});DEFPRINT(ne,function(e,t){t.print("for");if(e.await){t.space();t.print("await")}t.space();t.with_parens(function(){e.init.print(t);t.space();t.print(e instanceof ie?"of":"in");t.space();e.object.print(t)});t.space();e._do_print_body(t)});DEFPRINT(re,function(e,t){t.print("with");t.space();t.with_parens(function(){e.expression.print(t)});t.space();e._do_print_body(t)});ue.DEFMETHOD("_do_print",function(e,t){var n=this;if(!t){if(n.async){e.print("async");e.space()}e.print("function");if(n.is_generator){e.star()}if(n.name){e.space()}}if(n.name instanceof vt){n.name.print(e)}else if(t&&n.name instanceof z){e.with_square(function(){n.name.print(e)})}e.with_parens(function(){n.argnames.forEach(function(t,n){if(n)e.comma();t.print(e)})});e.space();print_braced(n,e,true)});DEFPRINT(ue,function(e,t){e._do_print(t)});DEFPRINT(he,function(e,t){var n=e.prefix;var i=n instanceof ue||n instanceof et||n instanceof tt||n instanceof He||n instanceof Ze||n instanceof qe&&n.expression instanceof at;if(i)t.print("(");e.prefix.print(t);if(i)t.print(")");e.template_string.print(t)});DEFPRINT(de,function(e,t){var n=t.parent()instanceof he;t.print("`");for(var i=0;i");e.space();const r=t.body[0];if(t.body.length===1&&r instanceof ve){const t=r.value;if(!t){e.print("{}")}else if(left_is_object(t)){e.print("(");t.print(e);e.print(")")}else{t.print(e)}}else{print_braced(t,e)}if(i){e.print(")")}});ge.DEFMETHOD("_do_print",function(e,t){e.print(t);if(this.value){e.space();const t=this.value.start.comments_before;if(t&&t.length&&!e.printed_comments.has(t)){e.print("(");this.value.print(e);e.print(")")}else{this.value.print(e)}}e.semicolon()});DEFPRINT(ve,function(e,t){e._do_print(t,"return")});DEFPRINT(De,function(e,t){e._do_print(t,"throw")});DEFPRINT(Te,function(e,t){var n=e.is_star?"*":"";t.print("yield"+n);if(e.expression){t.space();e.expression.print(t)}});DEFPRINT(Se,function(e,t){t.print("await");t.space();var n=e.expression;var i=!(n instanceof Ge||n instanceof Lt||n instanceof We||n instanceof Ze||n instanceof Gt||n instanceof Se||n instanceof at);if(i)t.print("(");e.expression.print(t);if(i)t.print(")")});be.DEFMETHOD("_do_print",function(e,t){e.print(t);if(this.label){e.space();this.label.print(e)}e.semicolon()});DEFPRINT(ye,function(e,t){e._do_print(t,"break")});DEFPRINT(ke,function(e,t){e._do_print(t,"continue")});function make_then(e,t){var n=e.body;if(t.option("braces")||t.option("ie8")&&n instanceof J)return make_block(n,t);if(!n)return t.force_semicolon();while(true){if(n instanceof Ae){if(!n.alternative){make_block(e.body,t);return}n=n.alternative}else if(n instanceof j){n=n.body}else break}force_statement(e.body,t)}DEFPRINT(Ae,function(e,t){t.print("if");t.space();t.with_parens(function(){e.condition.print(t)});t.space();if(e.alternative){make_then(e,t);t.space();t.print("else");t.space();if(e.alternative instanceof Ae)e.alternative.print(t);else force_statement(e.alternative,t)}else{e._do_print_body(t)}});DEFPRINT(Ce,function(e,t){t.print("switch");t.space();t.with_parens(function(){e.expression.print(t)});t.space();var n=e.body.length-1;if(n<0)print_braced_empty(e,t);else t.with_block(function(){e.body.forEach(function(e,i){t.indent(true);e.print(t);if(i0)t.newline()})})});Re.DEFMETHOD("_do_print_body",function(e){e.newline();this.body.forEach(function(t){e.indent();t.print(e);e.newline()})});DEFPRINT(xe,function(e,t){t.print("default:");e._do_print_body(t)});DEFPRINT(Fe,function(e,t){t.print("case");t.space();e.expression.print(t);t.print(":");e._do_print_body(t)});DEFPRINT(Oe,function(e,t){t.print("try");t.space();print_braced(e,t);if(e.bcatch){t.space();e.bcatch.print(t)}if(e.bfinally){t.space();e.bfinally.print(t)}});DEFPRINT(we,function(e,t){t.print("catch");if(e.argname){t.space();t.with_parens(function(){e.argname.print(t)})}t.space();print_braced(e,t)});DEFPRINT(Me,function(e,t){t.print("finally");t.space();print_braced(e,t)});Ne.DEFMETHOD("_do_print",function(e,t){e.print(t);e.space();this.definitions.forEach(function(t,n){if(n)e.comma();t.print(e)});var n=e.parent();var i=n instanceof te||n instanceof ne;var r=!i||n&&n.init!==this;if(r)e.semicolon()});DEFPRINT(Pe,function(e,t){e._do_print(t,"let")});DEFPRINT(Ie,function(e,t){e._do_print(t,"var")});DEFPRINT(Le,function(e,t){e._do_print(t,"const")});DEFPRINT(Ue,function(e,t){t.print("import");t.space();if(e.imported_name){e.imported_name.print(t)}if(e.imported_name&&e.imported_names){t.print(",");t.space()}if(e.imported_names){if(e.imported_names.length===1&&e.imported_names[0].foreign_name.name==="*"){e.imported_names[0].print(t)}else{t.print("{");e.imported_names.forEach(function(n,i){t.space();n.print(t);if(i{if(e instanceof ae)return true;if(e instanceof et&&e.operator=="in"){return rn}})}e.print(t,i)}DEFPRINT(Be,function(e,t){e.name.print(t);if(e.value){t.space();t.print("=");t.space();var n=t.parent(1);var i=n instanceof te||n instanceof ne;parenthesize_for_noin(e.value,t,i)}});DEFPRINT(Ge,function(e,t){e.expression.print(t);if(e instanceof Xe&&e.args.length===0)return;if(e.expression instanceof Ge||e.expression instanceof ue){t.add_mapping(e.start)}if(e.optional)t.print("?.");t.with_parens(function(){e.args.forEach(function(e,n){if(n)t.comma();e.print(t)})})});DEFPRINT(Xe,function(e,t){t.print("new");t.space();Ge.prototype._codegen(e,t)});He.DEFMETHOD("_do_print",function(e){this.expressions.forEach(function(t,n){if(n>0){e.comma();if(e.should_break()){e.newline();e.indent()}}t.print(e)})});DEFPRINT(He,function(e,t){e._do_print(t)});DEFPRINT(qe,function(e,t){var n=e.expression;n.print(t);var i=e.property;var r=f.has(i)?t.option("ie8"):!is_identifier_string(i,t.option("ecma")>=2015||t.option("safari10"));if(e.optional)t.print("?.");if(r){t.print("[");t.add_mapping(e.end);t.print_string(i);t.print("]")}else{if(n instanceof Ht&&n.getValue()>=0){if(!/[xa-f.)]/i.test(t.last())){t.print(".")}}if(!e.optional)t.print(".");t.add_mapping(e.end);t.print_name(i)}});DEFPRINT(Ye,function(e,t){var n=e.expression;n.print(t);var i=e.property;if(e.optional)t.print("?");t.print(".#");t.print_name(i)});DEFPRINT(je,function(e,t){e.expression.print(t);if(e.optional)t.print("?.");t.print("[");e.property.print(t);t.print("]")});DEFPRINT($e,function(e,t){e.expression.print(t)});DEFPRINT(Qe,function(e,t){var n=e.operator;t.print(n);if(/^[a-z]/i.test(n)||/[+-]$/.test(n)&&e.expression instanceof Qe&&/^[+-]/.test(e.expression.operator)){t.space()}e.expression.print(t)});DEFPRINT(Je,function(e,t){e.expression.print(t);t.print(e.operator)});DEFPRINT(et,function(e,t){var n=e.operator;e.left.print(t);if(n[0]==">"&&e.left instanceof Je&&e.left.operator=="--"){t.print(" ")}else{t.space()}t.print(n);if((n=="<"||n=="<<")&&e.right instanceof Qe&&e.right.operator=="!"&&e.right.expression instanceof Qe&&e.right.expression.operator=="--"){t.print(" ")}else{t.space()}e.right.print(t)});DEFPRINT(tt,function(e,t){e.condition.print(t);t.space();t.print("?");t.space();e.consequent.print(t);t.space();t.colon();e.alternative.print(t)});DEFPRINT(rt,function(e,t){t.with_square(function(){var n=e.elements,i=n.length;if(i>0)t.space();n.forEach(function(e,n){if(n)t.comma();e.print(t);if(n===i-1&&e instanceof Qt)t.comma()});if(i>0)t.space()})});DEFPRINT(at,function(e,t){if(e.properties.length>0)t.with_block(function(){e.properties.forEach(function(e,n){if(n){t.print(",");t.newline()}t.indent();e.print(t)});t.newline()});else print_braced_empty(e,t)});DEFPRINT(ht,function(e,t){t.print("class");t.space();if(e.name){e.name.print(t);t.space()}if(e.extends){var n=!(e.extends instanceof Lt)&&!(e.extends instanceof We)&&!(e.extends instanceof gt)&&!(e.extends instanceof le);t.print("extends");if(n){t.print("(")}else{t.space()}e.extends.print(t);if(n){t.print(")")}else{t.space()}}if(e.properties.length>0)t.with_block(function(){e.properties.forEach(function(e,n){if(n){t.newline()}t.indent();e.print(t)});t.newline()});else t.print("{}")});DEFPRINT(Dt,function(e,t){t.print("new.target")});function print_property_name(e,t,n){if(n.option("quote_keys")){return n.print_string(e)}if(""+ +e==e&&e>=0){if(n.option("keep_numbers")){return n.print(e)}return n.print(make_num(e))}var i=f.has(e)?n.option("ie8"):n.option("ecma")<2015||n.option("safari10")?!is_basic_identifier_string(e):!is_identifier_string(e,true);if(i||t&&n.option("keep_quoted_props")){return n.print_string(e,t)}return n.print_name(e)}DEFPRINT(st,function(e,t){function get_name(e){var t=e.definition();return t?t.mangled_name||t.name:e.name}var n=t.option("shorthand");if(n&&e.value instanceof vt&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value)===e.key&&!f.has(e.key)){print_property_name(e.key,e.quote,t)}else if(n&&e.value instanceof it&&e.value.left instanceof vt&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value.left)===e.key){print_property_name(e.key,e.quote,t);t.space();t.print("=");t.space();e.value.right.print(t)}else{if(!(e.key instanceof z)){print_property_name(e.key,e.quote,t)}else{t.with_square(function(){e.key.print(t)})}t.colon();e.value.print(t)}});DEFPRINT(mt,(e,t)=>{if(e.static){t.print("static");t.space()}t.print("#");print_property_name(e.key.name,e.quote,t);if(e.value){t.print("=");e.value.print(t)}t.semicolon()});DEFPRINT(dt,(e,t)=>{if(e.static){t.print("static");t.space()}if(e.key instanceof xt){print_property_name(e.key.name,e.quote,t)}else{t.print("[");e.key.print(t);t.print("]")}if(e.value){t.print("=");e.value.print(t)}t.semicolon()});ot.DEFMETHOD("_print_getter_setter",function(e,t,n){var i=this;if(i.static){n.print("static");n.space()}if(e){n.print(e);n.space()}if(i.key instanceof Rt){if(t)n.print("#");print_property_name(i.key.name,i.quote,n)}else{n.with_square(function(){i.key.print(n)})}i.value._do_print(n,true)});DEFPRINT(lt,function(e,t){e._print_getter_setter("set",false,t)});DEFPRINT(ft,function(e,t){e._print_getter_setter("get",false,t)});DEFPRINT(ut,function(e,t){e._print_getter_setter("set",true,t)});DEFPRINT(ct,function(e,t){e._print_getter_setter("get",true,t)});DEFPRINT(_t,function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,true,t)});DEFPRINT(pt,function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,false,t)});vt.DEFMETHOD("_do_print",function(e){var t=this.definition();e.print_name(t?t.mangled_name||t.name:this.name)});DEFPRINT(vt,function(e,t){e._do_print(t)});DEFPRINT(Qt,noop);DEFPRINT(zt,function(e,t){t.print("this")});DEFPRINT(Kt,function(e,t){t.print("super")});DEFPRINT(Gt,function(e,t){t.print(e.getValue())});DEFPRINT(Xt,function(e,t){t.print_string(e.getValue(),e.quote,t.in_directive)});DEFPRINT(Ht,function(e,t){if((t.option("keep_numbers")||t.use_asm)&&e.raw){t.print(e.raw)}else{t.print(make_num(e.getValue()))}});DEFPRINT(Wt,function(e,t){t.print(e.getValue()+"n")});const e=/(<\s*\/\s*script)/i;const t=(e,t)=>t.replace("/","\\/");DEFPRINT(qt,function(n,i){let{source:r,flags:a}=n.getValue();r=regexp_source_fix(r);a=a?sort_regexp_flags(a):"";r=r.replace(e,t);i.print(i.to_utf8(`/${r}/${a}`));const o=i.parent();if(o instanceof et&&/^\w/.test(o.operator)&&o.left===n){i.print(" ")}});function force_statement(e,t){if(t.option("braces")){make_block(e,t)}else{if(!e||e instanceof Y)t.force_semicolon();else e.print(t)}}function best_of(e){var t=e[0],n=t.length;for(var i=1;i{return e===null&&t===null||e.TYPE===t.TYPE&&e.shallow_cmp(t)};const hn=(e,t)=>{if(!_n(e,t))return false;const n=[e];const i=[t];const r=n.push.bind(n);const a=i.push.bind(i);while(n.length&&i.length){const e=n.pop();const t=i.pop();if(!_n(e,t))return false;e._children_backwards(r);t._children_backwards(a);if(n.length!==i.length){return false}}return n.length==0&&i.length==0};const dn=e=>{const t=Object.keys(e).map(t=>{if(e[t]==="eq"){return`this.${t} === other.${t}`}else if(e[t]==="exist"){return`(this.${t} == null ? other.${t} == null : this.${t} === other.${t})`}else{throw new Error(`mkshallow: Unexpected instruction: ${e[t]}`)}}).join(" && ");return new Function("other","return "+t)};const mn=()=>true;z.prototype.shallow_cmp=function(){throw new Error("did not find a shallow_cmp function for "+this.constructor.name)};G.prototype.shallow_cmp=mn;X.prototype.shallow_cmp=dn({value:"eq"});H.prototype.shallow_cmp=mn;W.prototype.shallow_cmp=mn;Y.prototype.shallow_cmp=mn;$.prototype.shallow_cmp=dn({"label.name":"eq"});J.prototype.shallow_cmp=mn;ee.prototype.shallow_cmp=mn;te.prototype.shallow_cmp=dn({init:"exist",condition:"exist",step:"exist"});ne.prototype.shallow_cmp=mn;ie.prototype.shallow_cmp=mn;re.prototype.shallow_cmp=mn;oe.prototype.shallow_cmp=mn;se.prototype.shallow_cmp=mn;ue.prototype.shallow_cmp=dn({is_generator:"eq",async:"eq"});_e.prototype.shallow_cmp=dn({is_array:"eq"});he.prototype.shallow_cmp=mn;de.prototype.shallow_cmp=mn;me.prototype.shallow_cmp=dn({value:"eq"});Ee.prototype.shallow_cmp=mn;be.prototype.shallow_cmp=mn;Se.prototype.shallow_cmp=mn;Te.prototype.shallow_cmp=dn({is_star:"eq"});Ae.prototype.shallow_cmp=dn({alternative:"exist"});Ce.prototype.shallow_cmp=mn;Re.prototype.shallow_cmp=mn;Oe.prototype.shallow_cmp=dn({bcatch:"exist",bfinally:"exist"});we.prototype.shallow_cmp=dn({argname:"exist"});Me.prototype.shallow_cmp=mn;Ne.prototype.shallow_cmp=mn;Be.prototype.shallow_cmp=dn({value:"exist"});Ve.prototype.shallow_cmp=mn;Ue.prototype.shallow_cmp=dn({imported_name:"exist",imported_names:"exist"});ze.prototype.shallow_cmp=mn;Ke.prototype.shallow_cmp=dn({exported_definition:"exist",exported_value:"exist",exported_names:"exist",module_name:"eq",is_default:"eq"});Ge.prototype.shallow_cmp=mn;He.prototype.shallow_cmp=mn;We.prototype.shallow_cmp=mn;$e.prototype.shallow_cmp=mn;qe.prototype.shallow_cmp=dn({property:"eq"});Ye.prototype.shallow_cmp=dn({property:"eq"});Ze.prototype.shallow_cmp=dn({operator:"eq"});et.prototype.shallow_cmp=dn({operator:"eq"});tt.prototype.shallow_cmp=mn;rt.prototype.shallow_cmp=mn;at.prototype.shallow_cmp=mn;ot.prototype.shallow_cmp=mn;st.prototype.shallow_cmp=dn({key:"eq"});lt.prototype.shallow_cmp=dn({static:"eq"});ft.prototype.shallow_cmp=dn({static:"eq"});pt.prototype.shallow_cmp=dn({static:"eq",is_generator:"eq",async:"eq"});ht.prototype.shallow_cmp=dn({name:"exist",extends:"exist"});dt.prototype.shallow_cmp=dn({static:"eq"});vt.prototype.shallow_cmp=dn({name:"eq"});Dt.prototype.shallow_cmp=mn;zt.prototype.shallow_cmp=mn;Kt.prototype.shallow_cmp=mn;Xt.prototype.shallow_cmp=dn({value:"eq"});Ht.prototype.shallow_cmp=dn({value:"eq"});Wt.prototype.shallow_cmp=dn({value:"eq"});qt.prototype.shallow_cmp=function(e){return this.value.flags===e.value.flags&&this.value.source===e.value.source};Yt.prototype.shallow_cmp=mn;const En=1<<0;const gn=1<<1;let vn=null;let Dn=null;class SymbolDef{constructor(e,t,n){this.name=t.name;this.orig=[t];this.init=n;this.eliminated=0;this.assignments=0;this.scope=e;this.replaced=0;this.global=false;this.export=0;this.mangled_name=null;this.undeclared=false;this.id=SymbolDef.next_id++;this.chained=false;this.direct_access=false;this.escaped=0;this.recursive_refs=0;this.references=[];this.should_replace=undefined;this.single_use=false;this.fixed=false;Object.seal(this)}fixed_value(){if(!this.fixed||this.fixed instanceof z)return this.fixed;return this.fixed()}unmangleable(e){if(!e)e={};if(vn&&vn.has(this.id)&&keep_name(e.keep_fnames,this.orig[0].name))return true;return this.global&&!e.toplevel||this.export&En||this.undeclared||!e.eval&&this.scope.pinned()||(this.orig[0]instanceof Ft||this.orig[0]instanceof Ct)&&keep_name(e.keep_fnames,this.orig[0].name)||this.orig[0]instanceof Rt||(this.orig[0]instanceof wt||this.orig[0]instanceof Ot)&&keep_name(e.keep_classnames,this.orig[0].name)}mangle(e){const t=e.cache&&e.cache.props;if(this.global&&t&&t.has(this.name)){this.mangled_name=t.get(this.name)}else if(!this.mangled_name&&!this.unmangleable(e)){var n=this.scope;var i=this.orig[0];if(e.ie8&&i instanceof Ft)n=n.parent_scope;const r=redefined_catch_def(this);this.mangled_name=r?r.mangled_name||r.name:n.next_mangled(e,this);if(this.global&&t){t.set(this.name,this.mangled_name)}}}}SymbolDef.next_id=1;function redefined_catch_def(e){if(e.orig[0]instanceof Mt&&e.scope.is_block_scope()){return e.scope.get_defun_scope().variables.get(e.name)}}ae.DEFMETHOD("figure_out_scope",function(e,{parent_scope:t=null,toplevel:n=this}={}){e=defaults(e,{cache:null,ie8:false,safari10:false});if(!(n instanceof oe)){throw new Error("Invalid toplevel scope")}var i=this.parent_scope=t;var r=new Map;var a=null;var o=null;var s=[];var u=new TreeWalker((t,n)=>{if(t.is_block_scope()){const r=i;t.block_scope=i=new ae(t);i._block_scope=true;const a=t instanceof we?r.parent_scope:r;i.init_scope_vars(a);i.uses_with=r.uses_with;i.uses_eval=r.uses_eval;if(e.safari10){if(t instanceof te||t instanceof ne){s.push(i)}}if(t instanceof Ce){const e=i;i=r;t.expression.walk(u);i=e;for(let e=0;e{if(e===t)return true;if(t instanceof kt){return e instanceof Ft}return!(e instanceof Tt||e instanceof St)})){js_error(`"${t.name}" is redeclared`,t.start.file,t.start.line,t.start.col,t.start.pos)}if(!(t instanceof At))mark_export(h,2);if(a!==i){t.mark_enclosed();var h=i.find_variable(t);if(t.thedef!==h){t.thedef=h;t.reference()}}}else if(t instanceof Ut){var d=r.get(t.name);if(!d)throw new Error(string_template("Undefined label {name} [{line},{col}]",{name:t.name,line:t.start.line,col:t.start.col}));t.thedef=d}if(!(i instanceof oe)&&(t instanceof Ke||t instanceof Ue)){js_error(`"${t.TYPE}" statement may only appear at the top level`,t.start.file,t.start.line,t.start.col,t.start.pos)}});this.walk(u);function mark_export(e,t){if(o){var n=0;do{t++}while(u.parent(n++)!==o)}var i=u.parent(t);if(e.export=i instanceof Ke?En:0){var r=i.exported_definition;if((r instanceof pe||r instanceof Et)&&i.is_default){e.export=gn}}}const c=this instanceof oe;if(c){this.globals=new Map}var u=new TreeWalker(e=>{if(e instanceof be&&e.label){e.label.thedef.references.push(e);return true}if(e instanceof Lt){var t=e.name;if(t=="eval"&&u.parent()instanceof Ge){for(var i=e.scope;i&&!i.uses_eval;i=i.parent_scope){i.uses_eval=true}}var r;if(u.parent()instanceof Ve&&u.parent(1).module_name||!(r=e.scope.find_variable(t))){r=n.def_global(e);if(e instanceof Bt)r.export=En}else if(r.scope instanceof ue&&t=="arguments"){r.scope.uses_arguments=true}e.thedef=r;e.reference();if(e.scope.is_block_scope()&&!(r.orig[0]instanceof kt)){e.scope=e.scope.get_defun_scope()}return true}var a;if(e instanceof Mt&&(a=redefined_catch_def(e.definition()))){var i=e.scope;while(i){push_uniq(i.enclosed,a);if(i===a.scope)break;i=i.parent_scope}}});this.walk(u);if(e.ie8||e.safari10){walk(this,e=>{if(e instanceof Mt){var t=e.name;var i=e.thedef.references;var r=e.scope.get_defun_scope();var a=r.find_variable(t)||n.globals.get(t)||r.def_variable(e);i.forEach(function(e){e.thedef=a;e.reference()});e.thedef=a;e.reference();return true}})}if(e.safari10){for(const e of s){e.parent_scope.variables.forEach(function(t){push_uniq(e.enclosed,t)})}}});oe.DEFMETHOD("def_global",function(e){var t=this.globals,n=e.name;if(t.has(n)){return t.get(n)}else{var i=new SymbolDef(this,e);i.undeclared=true;i.global=true;t.set(n,i);return i}});ae.DEFMETHOD("init_scope_vars",function(e){this.variables=new Map;this.uses_with=false;this.uses_eval=false;this.parent_scope=e;this.enclosed=[];this.cname=-1});ae.DEFMETHOD("conflicting_def",function(e){return this.enclosed.find(t=>t.name===e)||this.variables.has(e)||this.parent_scope&&this.parent_scope.conflicting_def(e)});ae.DEFMETHOD("conflicting_def_shallow",function(e){return this.enclosed.find(t=>t.name===e)||this.variables.has(e)});ae.DEFMETHOD("add_child_scope",function(e){if(e.parent_scope===this)return;e.parent_scope=this;const t=(()=>{const e=[];let t=this;do{e.push(t)}while(t=t.parent_scope);e.reverse();return e})();const n=new Set(e.enclosed);const i=[];for(const e of t){i.forEach(t=>push_uniq(e.enclosed,t));for(const t of e.variables.values()){if(n.has(t)){push_uniq(i,t);push_uniq(e.enclosed,t)}}}});function find_scopes_visible_from(e){const t=new Set;for(const n of new Set(e)){(function bubble_up(e){if(e==null||t.has(e))return;t.add(e);bubble_up(e.parent_scope)})(n)}return[...t]}ae.DEFMETHOD("create_symbol",function(e,{source:t,tentative_name:n,scope:i,conflict_scopes:r=[i],init:a=null}={}){let o;r=find_scopes_visible_from(r);if(n){n=o=n.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/gi,"_");let e=0;while(r.find(e=>e.conflicting_def_shallow(o))){o=n+"$"+e++}}if(!o){throw new Error("No symbol name could be generated in create_symbol()")}const s=make_node(e,t,{name:o,scope:i});this.def_variable(s,a||null);s.mark_enclosed();return s});z.DEFMETHOD("is_block_scope",return_false);ht.DEFMETHOD("is_block_scope",return_false);ue.DEFMETHOD("is_block_scope",return_false);oe.DEFMETHOD("is_block_scope",return_false);Re.DEFMETHOD("is_block_scope",return_false);W.DEFMETHOD("is_block_scope",return_true);ae.DEFMETHOD("is_block_scope",function(){return this._block_scope||false});Z.DEFMETHOD("is_block_scope",return_true);ue.DEFMETHOD("init_scope_vars",function(){ae.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false;this.def_variable(new At({name:"arguments",start:this.start,end:this.end}))});fe.DEFMETHOD("init_scope_vars",function(){ae.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false});vt.DEFMETHOD("mark_enclosed",function(){var e=this.definition();var t=this.scope;while(t){push_uniq(t.enclosed,e);if(t===e.scope)break;t=t.parent_scope}});vt.DEFMETHOD("reference",function(){this.definition().references.push(this);this.mark_enclosed()});ae.DEFMETHOD("find_variable",function(e){if(e instanceof vt)e=e.name;return this.variables.get(e)||this.parent_scope&&this.parent_scope.find_variable(e)});ae.DEFMETHOD("def_function",function(e,t){var n=this.def_variable(e,t);if(!n.init||n.init instanceof pe)n.init=t;return n});ae.DEFMETHOD("def_variable",function(e,t){var n=this.variables.get(e.name);if(n){n.orig.push(e);if(n.init&&(n.scope!==e.scope||n.init instanceof le)){n.init=t}}else{n=new SymbolDef(this,e,t);this.variables.set(e.name,n);n.global=!this.parent_scope}return e.thedef=n});function next_mangled(e,t){var n=e.enclosed;e:while(true){var i=bn(++e.cname);if(f.has(i))continue;if(t.reserved.has(i))continue;if(Dn&&Dn.has(i))continue e;for(let e=n.length;--e>=0;){const r=n[e];const a=r.mangled_name||r.unmangleable(t)&&r.name;if(i==a)continue e}return i}}ae.DEFMETHOD("next_mangled",function(e){return next_mangled(this,e)});oe.DEFMETHOD("next_mangled",function(e){let t;const n=this.mangled_names;do{t=next_mangled(this,e)}while(n.has(t));return t});le.DEFMETHOD("next_mangled",function(e,t){var n=t.orig[0]instanceof At&&this.name&&this.name.definition();var i=n?n.mangled_name||n.name:null;while(true){var r=next_mangled(this,e);if(!i||i!=r)return r}});vt.DEFMETHOD("unmangleable",function(e){var t=this.definition();return!t||t.unmangleable(e)});Pt.DEFMETHOD("unmangleable",return_false);vt.DEFMETHOD("unreferenced",function(){return!this.definition().references.length&&!this.scope.pinned()});vt.DEFMETHOD("definition",function(){return this.thedef});vt.DEFMETHOD("global",function(){return this.thedef.global});oe.DEFMETHOD("_default_mangler_options",function(e){e=defaults(e,{eval:false,ie8:false,keep_classnames:false,keep_fnames:false,module:false,reserved:[],toplevel:false});if(e.module)e.toplevel=true;if(!Array.isArray(e.reserved)&&!(e.reserved instanceof Set)){e.reserved=[]}e.reserved=new Set(e.reserved);e.reserved.add("arguments");return e});oe.DEFMETHOD("mangle_names",function(e){e=this._default_mangler_options(e);var t=-1;var n=[];if(e.keep_fnames){vn=new Set}const i=this.mangled_names=new Set;if(e.cache){this.globals.forEach(collect);if(e.cache.props){e.cache.props.forEach(function(e){i.add(e)})}}var r=new TreeWalker(function(i,r){if(i instanceof $){var a=t;r();t=a;return true}if(i instanceof ae){i.variables.forEach(collect);return}if(i.is_block_scope()){i.block_scope.variables.forEach(collect);return}if(vn&&i instanceof Be&&i.value instanceof ue&&!i.value.name&&keep_name(e.keep_fnames,i.name.name)){vn.add(i.name.definition().id);return}if(i instanceof Pt){let e;do{e=bn(++t)}while(f.has(e));i.mangled_name=e;return true}if(!(e.ie8||e.safari10)&&i instanceof Mt){n.push(i.definition());return}});this.walk(r);if(e.keep_fnames||e.keep_classnames){Dn=new Set;n.forEach(t=>{if(t.name.length<6&&t.unmangleable(e)){Dn.add(t.name)}})}n.forEach(t=>{t.mangle(e)});vn=null;Dn=null;function collect(t){const i=!e.reserved.has(t.name)&&!(t.export&En);if(i){n.push(t)}}});oe.DEFMETHOD("find_colliding_names",function(e){const t=e.cache&&e.cache.props;const n=new Set;e.reserved.forEach(to_avoid);this.globals.forEach(add_def);this.walk(new TreeWalker(function(e){if(e instanceof ae)e.variables.forEach(add_def);if(e instanceof Mt)add_def(e.definition())}));return n;function to_avoid(e){n.add(e)}function add_def(n){var i=n.name;if(n.global&&t&&t.has(i))i=t.get(i);else if(!n.unmangleable(e))return;to_avoid(i)}});oe.DEFMETHOD("expand_names",function(e){bn.reset();bn.sort();e=this._default_mangler_options(e);var t=this.find_colliding_names(e);var n=0;this.globals.forEach(rename);this.walk(new TreeWalker(function(e){if(e instanceof ae)e.variables.forEach(rename);if(e instanceof Mt)rename(e.definition())}));function next_name(){var e;do{e=bn(n++)}while(t.has(e)||f.has(e));return e}function rename(t){if(t.global&&e.cache)return;if(t.unmangleable(e))return;if(e.reserved.has(t.name))return;const n=redefined_catch_def(t);const i=t.name=n?n.name:next_name();t.orig.forEach(function(e){e.name=i});t.references.forEach(function(e){e.name=i})}});z.DEFMETHOD("tail_node",return_this);He.DEFMETHOD("tail_node",function(){return this.expressions[this.expressions.length-1]});oe.DEFMETHOD("compute_char_frequency",function(e){e=this._default_mangler_options(e);try{z.prototype.print=function(t,n){this._print(t,n);if(this instanceof vt&&!this.unmangleable(e)){bn.consider(this.name,-1)}else if(e.properties){if(this instanceof Ye){bn.consider("#"+this.property,-1)}else if(this instanceof qe){bn.consider(this.property,-1)}else if(this instanceof je){skip_string(this.property)}}};bn.consider(this.print_to_string(),1)}finally{z.prototype.print=z.prototype._print}bn.sort();function skip_string(e){if(e instanceof Xt){bn.consider(e.value,-1)}else if(e instanceof tt){skip_string(e.consequent);skip_string(e.alternative)}else if(e instanceof He){skip_string(e.tail_node())}}});const bn=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");const t="0123456789".split("");let n;let i;function reset(){i=new Map;e.forEach(function(e){i.set(e,0)});t.forEach(function(e){i.set(e,0)})}base54.consider=function(e,t){for(var n=e.length;--n>=0;){i.set(e[n],i.get(e[n])+t)}};function compare(e,t){return i.get(t)-i.get(e)}base54.sort=function(){n=mergeSort(e,compare).concat(mergeSort(t,compare))};base54.reset=reset;reset();function base54(e){var t="",i=54;e++;do{e--;t+=n[e%i];e=Math.floor(e/i);i=64}while(e>0);return t}return base54})();let yn=undefined;z.prototype.size=function(e,t){yn=e&&e.mangle_options;let n=0;walk_parent(this,(e,t)=>{n+=e._size(t);if(e instanceof fe&&e.is_braceless()){n+=e.body[0].value._size(t);return true}},t||e&&e.stack);yn=undefined;return n};z.prototype._size=(()=>0);G.prototype._size=(()=>8);X.prototype._size=function(){return 2+this.value.length};const kn=e=>e.length&&e.length-1;W.prototype._size=function(){return 2+kn(this.body)};oe.prototype._size=function(){return kn(this.body)};Y.prototype._size=(()=>1);$.prototype._size=(()=>2);J.prototype._size=(()=>9);ee.prototype._size=(()=>7);te.prototype._size=(()=>8);ne.prototype._size=(()=>8);re.prototype._size=(()=>6);se.prototype._size=(()=>3);const Sn=e=>(e.is_generator?1:0)+(e.async?6:0);ce.prototype._size=function(){return Sn(this)+4+kn(this.argnames)+kn(this.body)};le.prototype._size=function(e){const t=!!first_in_statement(e);return t*2+Sn(this)+12+kn(this.argnames)+kn(this.body)};pe.prototype._size=function(){return Sn(this)+13+kn(this.argnames)+kn(this.body)};fe.prototype._size=function(){let e=2+kn(this.argnames);if(!(this.argnames.length===1&&this.argnames[0]instanceof vt)){e+=2}const t=this.is_braceless()?0:kn(this.body)+2;return Sn(this)+e+t};_e.prototype._size=(()=>2);de.prototype._size=function(){return 2+Math.floor(this.segments.length/2)*3};me.prototype._size=function(){return this.value.length};ve.prototype._size=function(){return this.value?7:6};De.prototype._size=(()=>6);ye.prototype._size=function(){return this.label?6:5};ke.prototype._size=function(){return this.label?9:8};Ae.prototype._size=(()=>4);Ce.prototype._size=function(){return 8+kn(this.body)};Fe.prototype._size=function(){return 5+kn(this.body)};xe.prototype._size=function(){return 8+kn(this.body)};Oe.prototype._size=function(){return 3+kn(this.body)};we.prototype._size=function(){let e=7+kn(this.body);if(this.argname){e+=2}return e};Me.prototype._size=function(){return 7+kn(this.body)};const Tn=(e,t)=>e+kn(t.definitions);Ie.prototype._size=function(){return Tn(4,this)};Pe.prototype._size=function(){return Tn(4,this)};Le.prototype._size=function(){return Tn(6,this)};Be.prototype._size=function(){return this.value?1:0};Ve.prototype._size=function(){return this.name?4:0};Ue.prototype._size=function(){let e=6;if(this.imported_name)e+=1;if(this.imported_name||this.imported_names)e+=5;if(this.imported_names){e+=2+kn(this.imported_names)}return e};ze.prototype._size=(()=>11);Ke.prototype._size=function(){let e=7+(this.is_default?8:0);if(this.exported_value){e+=this.exported_value._size()}if(this.exported_names){e+=2+kn(this.exported_names)}if(this.module_name){e+=5}return e};Ge.prototype._size=function(){if(this.optional){return 4+kn(this.args)}return 2+kn(this.args)};Xe.prototype._size=function(){return 6+kn(this.args)};He.prototype._size=function(){return kn(this.expressions)};qe.prototype._size=function(){if(this.optional){return this.property.length+2}return this.property.length+1};Ye.prototype._size=function(){if(this.optional){return this.property.length+3}return this.property.length+2};je.prototype._size=function(){return this.optional?4:2};Ze.prototype._size=function(){if(this.operator==="typeof")return 7;if(this.operator==="void")return 5;return this.operator.length};et.prototype._size=function(e){if(this.operator==="in")return 4;let t=this.operator.length;if((this.operator==="+"||this.operator==="-")&&this.right instanceof Ze&&this.right.operator===this.operator){t+=1}if(this.needs_parens(e)){t+=2}return t};tt.prototype._size=(()=>3);rt.prototype._size=function(){return 2+kn(this.elements)};at.prototype._size=function(e){let t=2;if(first_in_statement(e)){t+=2}return t+kn(this.properties)};const An=e=>typeof e==="string"?e.length:0;st.prototype._size=function(){return An(this.key)+1};const Cn=e=>e?7:0;ft.prototype._size=function(){return 5+Cn(this.static)+An(this.key)};lt.prototype._size=function(){return 5+Cn(this.static)+An(this.key)};pt.prototype._size=function(){return Cn(this.static)+An(this.key)+Sn(this)};_t.prototype._size=function(){return pt.prototype._size.call(this)+1};ct.prototype._size=ut.prototype._size=function(){return pt.prototype._size.call(this)+4};ht.prototype._size=function(){return(this.name?8:7)+(this.extends?8:0)};dt.prototype._size=function(){return Cn(this.static)+(typeof this.key==="string"?this.key.length+2:0)+(this.value?1:0)};mt.prototype._size=function(){return dt.prototype._size.call(this)+1};vt.prototype._size=function(){return!yn||this.definition().unmangleable(yn)?this.name.length:1};xt.prototype._size=function(){return this.name.length};Lt.prototype._size=bt.prototype._size=function(){const{name:e,thedef:t}=this;if(t&&t.global)return e.length;if(e==="arguments")return 9;return vt.prototype._size.call(this)};Dt.prototype._size=(()=>10);It.prototype._size=function(){return this.name.length};Vt.prototype._size=function(){return this.name.length};zt.prototype._size=(()=>4);Kt.prototype._size=(()=>5);Xt.prototype._size=function(){return this.value.length+2};Ht.prototype._size=function(){const{value:e}=this;if(e===0)return 1;if(e>0&&Math.floor(e)===e){return Math.floor(Math.log10(e)+1)}return e.toString().length};Wt.prototype._size=function(){return this.value.length};qt.prototype._size=function(){return this.value.toString().length};jt.prototype._size=(()=>4);$t.prototype._size=(()=>3);Zt.prototype._size=(()=>6);Qt.prototype._size=(()=>0);Jt.prototype._size=(()=>8);nn.prototype._size=(()=>4);tn.prototype._size=(()=>5);Se.prototype._size=(()=>6);Te.prototype._size=(()=>6);const Rn=1;const xn=2;const Fn=4;const On=8;const wn=16;const Mn=32;const Nn=256;const In=512;const Pn=1024;const Ln=Nn|In|Pn;const Bn=(e,t)=>e.flags&t;const Vn=(e,t)=>{e.flags|=t};const Un=(e,t)=>{e.flags&=~t};class Compressor extends TreeWalker{constructor(e,{false_by_default:t=false,mangle_options:n=false}){super();if(e.defaults!==undefined&&!e.defaults)t=true;this.options=defaults(e,{arguments:false,arrows:!t,booleans:!t,booleans_as_integers:false,collapse_vars:!t,comparisons:!t,computed_props:!t,conditionals:!t,dead_code:!t,defaults:true,directives:!t,drop_console:false,drop_debugger:!t,ecma:5,evaluate:!t,expression:false,global_defs:false,hoist_funs:false,hoist_props:!t,hoist_vars:false,ie8:false,if_return:!t,inline:!t,join_vars:!t,keep_classnames:false,keep_fargs:true,keep_fnames:false,keep_infinity:false,loops:!t,module:false,negate_iife:!t,passes:1,properties:!t,pure_getters:!t&&"strict",pure_funcs:null,reduce_funcs:!t,reduce_vars:!t,sequences:!t,side_effects:!t,switches:!t,top_retain:null,toplevel:!!(e&&e["top_retain"]),typeofs:!t,unsafe:false,unsafe_arrows:false,unsafe_comps:false,unsafe_Function:false,unsafe_math:false,unsafe_symbols:false,unsafe_methods:false,unsafe_proto:false,unsafe_regexp:false,unsafe_undefined:false,unused:!t,warnings:false},true);var i=this.options["global_defs"];if(typeof i=="object")for(var r in i){if(r[0]==="@"&&HOP(i,r)){i[r.slice(1)]=parse(i[r],{expression:true})}}if(this.options["inline"]===true)this.options["inline"]=3;var a=this.options["pure_funcs"];if(typeof a=="function"){this.pure_funcs=a}else{this.pure_funcs=a?function(e){return!a.includes(e.expression.print_to_string())}:return_true}var o=this.options["top_retain"];if(o instanceof RegExp){this.top_retain=function(e){return o.test(e.name)}}else if(typeof o=="function"){this.top_retain=o}else if(o){if(typeof o=="string"){o=o.split(/,/)}this.top_retain=function(e){return o.includes(e.name)}}if(this.options["module"]){this.directives["use strict"]=true;this.options["toplevel"]=true}var s=this.options["toplevel"];this.toplevel=typeof s=="string"?{funcs:/funcs/.test(s),vars:/vars/.test(s)}:{funcs:s,vars:s};var u=this.options["sequences"];this.sequences_limit=u==1?800:u|0;this.evaluated_regexps=new Map;this._toplevel=undefined;this.mangle_options=n}option(e){return this.options[e]}exposed(e){if(e.export)return true;if(e.global)for(var t=0,n=e.orig.length;t0||this.option("reduce_vars")){this._toplevel.reset_opt_flags(this)}this._toplevel=this._toplevel.transform(this);if(t>1){let e=0;walk(this._toplevel,()=>{e++});if(e=0){r.body[o]=r.body[o].transform(i)}}else if(r instanceof Ae){r.body=r.body.transform(i);if(r.alternative){r.alternative=r.alternative.transform(i)}}else if(r instanceof re){r.body=r.body.transform(i)}return r});n.transform(i)});function read_property(e,t){t=get_value(t);if(t instanceof z)return;var n;if(e instanceof rt){var i=e.elements;if(t=="length")return make_node_from_constant(i.length,e);if(typeof t=="number"&&t in i)n=i[t]}else if(e instanceof at){t=""+t;var r=e.properties;for(var a=r.length;--a>=0;){var o=r[a];if(!(o instanceof st))return;if(!n&&r[a].key===t)n=r[a].value}}return n instanceof Lt&&n.fixed_value()||n}function is_modified(e,t,n,i,r,a){var o=t.parent(r);var s=is_lhs(n,o);if(s)return s;if(!a&&o instanceof Ge&&o.expression===n&&!(i instanceof fe)&&!(i instanceof ht)&&!o.is_callee_pure(e)&&(!(i instanceof le)||!(o instanceof Xe)&&i.contains_this())){return true}if(o instanceof rt){return is_modified(e,t,o,o,r+1)}if(o instanceof st&&n===o.value){var u=t.parent(r+1);return is_modified(e,t,u,u,r+2)}if(o instanceof We&&o.expression===n){var c=read_property(i,o.property);return!a&&is_modified(e,t,o,c,r+1)}}(function(e){e(z,noop);function reset_def(e,t){t.assignments=0;t.chained=false;t.direct_access=false;t.escaped=0;t.recursive_refs=0;t.references=[];t.single_use=undefined;if(t.scope.pinned()){t.fixed=false}else if(t.orig[0]instanceof St||!e.exposed(t)){t.fixed=t.init}else{t.fixed=false}}function reset_variables(e,t,n){n.variables.forEach(function(n){reset_def(t,n);if(n.fixed===null){e.defs_to_safe_ids.set(n.id,e.safe_ids);mark(e,n,true)}else if(n.fixed){e.loop_ids.set(n.id,e.in_loop);mark(e,n,true)}})}function reset_block_variables(e,t){if(t.block_scope)t.block_scope.variables.forEach(t=>{reset_def(e,t)})}function push(e){e.safe_ids=Object.create(e.safe_ids)}function pop(e){e.safe_ids=Object.getPrototypeOf(e.safe_ids)}function mark(e,t,n){e.safe_ids[t.id]=n}function safe_to_read(e,t){if(t.single_use=="m")return false;if(e.safe_ids[t.id]){if(t.fixed==null){var n=t.orig[0];if(n instanceof At||n.name=="arguments")return false;t.fixed=make_node(Zt,n)}return true}return t.fixed instanceof pe}function safe_to_assign(e,t,n,i){if(t.fixed===undefined)return true;let r;if(t.fixed===null&&(r=e.defs_to_safe_ids.get(t.id))){r[t.id]=false;e.defs_to_safe_ids.delete(t.id);return true}if(!HOP(e.safe_ids,t.id))return false;if(!safe_to_read(e,t))return false;if(t.fixed===false)return false;if(t.fixed!=null&&(!i||t.references.length>t.assignments))return false;if(t.fixed instanceof pe){return i instanceof z&&t.fixed.parent_scope===n}return t.orig.every(e=>{return!(e instanceof St||e instanceof Ct||e instanceof Ft)})}function ref_once(e,t,n){return t.option("unused")&&!n.scope.pinned()&&n.references.length-n.recursive_refs==1&&e.loop_ids.get(n.id)===e.in_loop}function is_immutable(e){if(!e)return false;return e.is_constant()||e instanceof ue||e instanceof zt}function mark_escaped(e,t,n,i,r,a=0,o=1){var s=e.parent(a);if(r){if(r.is_constant())return;if(r instanceof gt)return}if(s instanceof nt&&(s.operator==="="||s.logical)&&i===s.right||s instanceof Ge&&(i!==s.expression||s instanceof Xe)||s instanceof ge&&i===s.value&&i.scope!==t.scope||s instanceof Be&&i===s.value||s instanceof Te&&i===s.value&&i.scope!==t.scope){if(o>1&&!(r&&r.is_constant_expression(n)))o=1;if(!t.escaped||t.escaped>o)t.escaped=o;return}else if(s instanceof rt||s instanceof Se||s instanceof et&&Gn.has(s.operator)||s instanceof tt&&i!==s.condition||s instanceof se||s instanceof He&&i===s.tail_node()){mark_escaped(e,t,n,s,s,a+1,o)}else if(s instanceof st&&i===s.value){var u=e.parent(a+1);mark_escaped(e,t,n,u,u,a+2,o)}else if(s instanceof We&&i===s.expression){r=read_property(r,s.property);mark_escaped(e,t,n,s,r,a+1,o+1);if(r)return}if(a>0)return;if(s instanceof He&&i!==s.tail_node())return;if(s instanceof H)return;t.direct_access=true}const t=e=>walk(e,e=>{if(!(e instanceof vt))return;var t=e.definition();if(!t)return;if(e instanceof Lt)t.references.push(e);t.fixed=false});e(ce,function(e,t,n){push(e);reset_variables(e,n,this);t();pop(e);return true});e(nt,function(e,n,i){var r=this;if(r.left instanceof _e){t(r.left);return}const a=()=>{if(r.logical){r.left.walk(e);push(e);r.right.walk(e);pop(e);return true}};var o=r.left;if(!(o instanceof Lt))return a();var s=o.definition();var u=safe_to_assign(e,s,o.scope,r.right);s.assignments++;if(!u)return a();var c=s.fixed;if(!c&&r.operator!="="&&!r.logical)return a();var l=r.operator=="=";var f=l?r.right:r;if(is_modified(i,e,r,f,0))return a();s.references.push(o);if(!r.logical){if(!l)s.chained=true;s.fixed=l?function(){return r.right}:function(){return make_node(et,r,{operator:r.operator.slice(0,-1),left:c instanceof z?c:c(),right:r.right})}}if(r.logical){mark(e,s,false);push(e);r.right.walk(e);pop(e);return true}mark(e,s,false);r.right.walk(e);mark(e,s,true);mark_escaped(e,s,o.scope,r,f,0,1);return true});e(et,function(e){if(!Gn.has(this.operator))return;this.left.walk(e);push(e);this.right.walk(e);pop(e);return true});e(W,function(e,t,n){reset_block_variables(n,this)});e(Fe,function(e){push(e);this.expression.walk(e);pop(e);push(e);walk_body(this,e);pop(e);return true});e(ht,function(e,t){Un(this,wn);push(e);t();pop(e);return true});e(tt,function(e){this.condition.walk(e);push(e);this.consequent.walk(e);pop(e);push(e);this.alternative.walk(e);pop(e);return true});e($e,function(e,t){const n=e.safe_ids;t();e.safe_ids=n;return true});e(Ge,function(e){this.expression.walk(e);if(this.optional){push(e)}for(const t of this.args)t.walk(e);return true});e(We,function(e){if(!this.optional)return;this.expression.walk(e);push(e);if(this.property instanceof z)this.property.walk(e);return true});e(xe,function(e,t){push(e);t();pop(e);return true});function mark_lambda(e,t,n){Un(this,wn);push(e);reset_variables(e,n,this);if(this.uses_arguments){t();pop(e);return}var i;if(!this.name&&(i=e.parent())instanceof Ge&&i.expression===this&&!i.args.some(e=>e instanceof se)&&this.argnames.every(e=>e instanceof vt)){this.argnames.forEach((t,n)=>{if(!t.definition)return;var r=t.definition();if(r.orig.length>1)return;if(r.fixed===undefined&&(!this.uses_arguments||e.has_directive("use strict"))){r.fixed=function(){return i.args[n]||make_node(Zt,i)};e.loop_ids.set(r.id,e.in_loop);mark(e,r,true)}else{r.fixed=false}})}t();pop(e);return true}e(ue,mark_lambda);e(J,function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);if(has_break_or_continue(this)){pop(e);push(e)}this.condition.walk(e);pop(e);e.in_loop=i;return true});e(te,function(e,t,n){reset_block_variables(n,this);if(this.init)this.init.walk(e);const i=e.in_loop;e.in_loop=this;push(e);if(this.condition)this.condition.walk(e);this.body.walk(e);if(this.step){if(has_break_or_continue(this)){pop(e);push(e)}this.step.walk(e)}pop(e);e.in_loop=i;return true});e(ne,function(e,n,i){reset_block_variables(i,this);t(this.init);this.object.walk(e);const r=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);pop(e);e.in_loop=r;return true});e(Ae,function(e){this.condition.walk(e);push(e);this.body.walk(e);pop(e);if(this.alternative){push(e);this.alternative.walk(e);pop(e)}return true});e($,function(e){push(e);this.body.walk(e);pop(e);return true});e(Mt,function(){this.definition().fixed=false});e(Lt,function(e,t,n){var i=this.definition();i.references.push(this);if(i.references.length==1&&!i.fixed&&i.orig[0]instanceof Ct){e.loop_ids.set(i.id,e.in_loop)}var r;if(i.fixed===undefined||!safe_to_read(e,i)){i.fixed=false}else if(i.fixed){r=this.fixed_value();if(r instanceof ue&&recursive_ref(e,i)){i.recursive_refs++}else if(r&&!n.exposed(i)&&ref_once(e,n,i)){i.single_use=r instanceof ue&&!r.pinned()||r instanceof ht||i.scope===this.scope&&r.is_constant_expression()}else{i.single_use=false}if(is_modified(n,e,this,r,0,is_immutable(r))){if(i.single_use){i.single_use="m"}else{i.fixed=false}}}mark_escaped(e,i,this.scope,this,r,0,1)});e(oe,function(e,t,n){this.globals.forEach(function(e){reset_def(n,e)});reset_variables(e,n,this)});e(Oe,function(e,t,n){reset_block_variables(n,this);push(e);walk_body(this,e);pop(e);if(this.bcatch){push(e);this.bcatch.walk(e);pop(e)}if(this.bfinally)this.bfinally.walk(e);return true});e(Ze,function(e){var t=this;if(t.operator!=="++"&&t.operator!=="--")return;var n=t.expression;if(!(n instanceof Lt))return;var i=n.definition();var r=safe_to_assign(e,i,n.scope,true);i.assignments++;if(!r)return;var a=i.fixed;if(!a)return;i.references.push(n);i.chained=true;i.fixed=function(){return make_node(et,t,{operator:t.operator.slice(0,-1),left:make_node(Qe,t,{operator:"+",expression:a instanceof z?a:a()}),right:make_node(Ht,t,{value:1})})};mark(e,i,true);return true});e(Be,function(e,n){var i=this;if(i.name instanceof _e){t(i.name);return}var r=i.name.definition();if(i.value){if(safe_to_assign(e,r,i.name.scope,i.value)){r.fixed=function(){return i.value};e.loop_ids.set(r.id,e.in_loop);mark(e,r,false);n();mark(e,r,true);return true}else{r.fixed=false}}});e(ee,function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);t();pop(e);e.in_loop=i;return true})})(function(e,t){e.DEFMETHOD("reduce_vars",t)});oe.DEFMETHOD("reset_opt_flags",function(e){const t=this;const n=e.option("reduce_vars");const i=new TreeWalker(function(r,a){Un(r,Ln);if(n){if(e.top_retain&&r instanceof pe&&i.parent()===t){Vn(r,Pn)}return r.reduce_vars(i,a,e)}});i.safe_ids=Object.create(null);i.in_loop=null;i.loop_ids=new Map;i.defs_to_safe_ids=new Map;t.walk(i)});vt.DEFMETHOD("fixed_value",function(){var e=this.thedef.fixed;if(!e||e instanceof z)return e;return e()});Lt.DEFMETHOD("is_immutable",function(){var e=this.definition().orig;return e.length==1&&e[0]instanceof Ft});function is_func_expr(e){return e instanceof fe||e instanceof le}function is_lhs_read_only(e){if(e instanceof zt)return true;if(e instanceof Lt)return e.definition().orig[0]instanceof Ft;if(e instanceof We){e=e.expression;if(e instanceof Lt){if(e.is_immutable())return false;e=e.fixed_value()}if(!e)return true;if(e instanceof qt)return false;if(e instanceof Gt)return true;return is_lhs_read_only(e)}return false}function is_ref_of(e,t){if(!(e instanceof Lt))return false;var n=e.definition().orig;for(var i=n.length;--i>=0;){if(n[i]instanceof t)return true}}function find_scope(e){for(let t=0;;t++){const n=e.parent(t);if(n instanceof oe)return n;if(n instanceof ue)return n;if(n.block_scope)return n.block_scope}}function find_variable(e,t){var n,i=0;while(n=e.parent(i++)){if(n instanceof ae)break;if(n instanceof we&&n.argname){n=n.argname.definition().scope;break}}return n.find_variable(t)}function make_sequence(e,t){if(t.length==1)return t[0];if(t.length==0)throw new Error("trying to create a sequence with length zero!");return make_node(He,e,{expressions:t.reduce(merge_sequence,[])})}function make_node_from_constant(e,t){switch(typeof e){case"string":return make_node(Xt,t,{value:e});case"number":if(isNaN(e))return make_node($t,t);if(isFinite(e)){return 1/e<0?make_node(Qe,t,{operator:"-",expression:make_node(Ht,t,{value:-e})}):make_node(Ht,t,{value:e})}return e<0?make_node(Qe,t,{operator:"-",expression:make_node(Jt,t)}):make_node(Jt,t);case"boolean":return make_node(e?nn:tn,t);case"undefined":return make_node(Zt,t);default:if(e===null){return make_node(jt,t,{value:null})}if(e instanceof RegExp){return make_node(qt,t,{value:{source:regexp_source_fix(e.source),flags:e.flags}})}throw new Error(string_template("Can't handle constant of type: {type}",{type:typeof e}))}}function maintain_this_binding(e,t,n){if(e instanceof Qe&&e.operator=="delete"||e instanceof Ge&&e.expression===t&&(n instanceof We||n instanceof Lt&&n.name=="eval")){return make_sequence(t,[make_node(Ht,t,{value:0}),n])}return n}function merge_sequence(e,t){if(t instanceof He){e.push(...t.expressions)}else{e.push(t)}return e}function as_statement_array(e){if(e===null)return[];if(e instanceof q)return e.body;if(e instanceof Y)return[];if(e instanceof K)return[e];throw new Error("Can't convert thing to statement array")}function is_empty(e){if(e===null)return true;if(e instanceof Y)return true;if(e instanceof q)return e.body.length==0;return false}function can_be_evicted_from_block(e){return!(e instanceof Et||e instanceof pe||e instanceof Pe||e instanceof Le||e instanceof Ke||e instanceof Ue)}function loop_body(e){if(e instanceof Z){return e.body instanceof q?e.body:e}return e}function is_iife_call(e){if(e.TYPE!="Call")return false;return e.expression instanceof le||is_iife_call(e.expression)}function is_undeclared_ref(e){return e instanceof Lt&&e.definition().undeclared}var zn=makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");Lt.DEFMETHOD("is_declared",function(e){return!this.definition().undeclared||e.option("unsafe")&&zn.has(this.name)});var Kn=makePredicate("Infinity NaN undefined");function is_identifier_atom(e){return e instanceof Jt||e instanceof $t||e instanceof Zt}function tighten_body(e,t){var n,i;var a=t.find_parent(ae).get_defun_scope();find_loop_scope_try();var o,s=10;do{o=false;eliminate_spurious_blocks(e);if(t.option("dead_code")){eliminate_dead_code(e,t)}if(t.option("if_return")){handle_if_return(e,t)}if(t.sequences_limit>0){sequencesize(e,t);sequencesize_2(e,t)}if(t.option("join_vars")){join_consecutive_vars(e)}if(t.option("collapse_vars")){collapse(e,t)}}while(o&&s-- >0);function find_loop_scope_try(){var e=t.self(),r=0;do{if(e instanceof we||e instanceof Me){r++}else if(e instanceof Z){n=true}else if(e instanceof ae){a=e;break}else if(e instanceof Oe){i=true}}while(e=t.parent(r++))}function collapse(e,t){if(a.pinned())return e;var s;var u=[];var c=e.length;var l=new TreeTransformer(function(e){if(A)return e;if(!T){if(e!==p[_])return e;_++;if(_1)||e instanceof Z&&!(e instanceof te)||e instanceof be||e instanceof Oe||e instanceof re||e instanceof Te||e instanceof Ke||e instanceof ht||n instanceof te&&e!==n.init||!y&&(e instanceof Lt&&!e.is_declared(t)&&!jn.has(e))||e instanceof Lt&&n instanceof Ge&&has_annotation(n,sn)){A=true;return e}if(!E&&(!D||!y)&&(n instanceof et&&Gn.has(n.operator)&&n.left!==e||n instanceof tt&&n.condition!==e||n instanceof Ae&&n.condition!==e)){E=n}if(R&&!(e instanceof bt)&&g.equivalent_to(e)){if(E){A=true;return e}if(is_lhs(e,n)){if(d)C++;return e}else{C++;if(d&&h instanceof Be)return e}o=A=true;if(h instanceof Je){return make_node(Qe,h,h)}if(h instanceof Be){var r=h.name.definition();var a=h.value;if(r.references.length-r.replaced==1&&!t.exposed(r)){r.replaced++;if(S&&is_identifier_atom(a)){return a.transform(t)}else{return maintain_this_binding(n,e,a)}}return make_node(nt,h,{operator:"=",logical:false,left:make_node(Lt,h.name,h.name),right:a})}Un(h,Mn);return h}var s;if(e instanceof Ge||e instanceof ge&&(b||g instanceof We||may_modify(g))||e instanceof We&&(b||e.expression.may_throw_on_access(t))||e instanceof Lt&&(v.get(e.name)||b&&may_modify(e))||e instanceof Be&&e.value&&(v.has(e.name.name)||b&&may_modify(e.name))||(s=is_lhs(e.left,e))&&(s instanceof We||v.has(s.name))||k&&(i?e.has_side_effects(t):side_effects_external(e))){m=e;if(e instanceof ae)A=true}return handle_custom_scan_order(e)},function(e){if(A)return;if(m===e)A=true;if(E===e)E=null});var f=new TreeTransformer(function(e){if(A)return e;if(!T){if(e!==p[_])return e;_++;if(_=0){if(c==0&&t.option("unused"))extract_args();var p=[];extract_candidates(e[c]);while(u.length>0){p=u.pop();var _=0;var h=p[p.length-1];var d=null;var m=null;var E=null;var g=get_lhs(h);if(!g||is_lhs_read_only(g)||g.has_side_effects(t))continue;var v=get_lvalues(h);var D=is_lhs_local(g);if(g instanceof Lt)v.set(g.name,false);var b=value_has_side_effects(h);var y=replace_all_symbols();var k=h.may_throw(t);var S=h.name instanceof At;var T=S;var A=false,C=0,R=!s||!T;if(!R){for(var x=t.self().argnames.lastIndexOf(h.name)+1;!A&&xC)C=false;else{A=false;_=0;T=S;for(var F=c;!A&&F!(e instanceof se))){var i=t.has_directive("use strict");if(i&&!member(i,n.body))i=false;var r=n.argnames.length;s=e.args.slice(r);var a=new Set;for(var o=r;--o>=0;){var c=n.argnames[o];var l=e.args[o];const r=c.definition&&c.definition();const p=r&&r.orig.length>1;if(p)continue;s.unshift(make_node(Be,c,{name:c,value:l}));if(a.has(c.name))continue;a.add(c.name);if(c instanceof se){var f=e.args.slice(o);if(f.every(e=>!has_overlapping_symbol(n,e,i))){u.unshift([make_node(Be,c,{name:c.expression,value:make_node(rt,e,{elements:f})})])}}else{if(!l){l=make_node(Zt,c).transform(t)}else if(l instanceof ue&&l.pinned()||has_overlapping_symbol(n,l,i)){l=null}if(l)u.unshift([make_node(Be,c,{name:c,value:l})])}}}}function extract_candidates(e){p.push(e);if(e instanceof nt){if(!e.left.has_side_effects(t)&&!(e.right instanceof $e)){u.push(p.slice())}extract_candidates(e.right)}else if(e instanceof et){extract_candidates(e.left);extract_candidates(e.right)}else if(e instanceof Ge&&!has_annotation(e,sn)){extract_candidates(e.expression);e.args.forEach(extract_candidates)}else if(e instanceof Fe){extract_candidates(e.expression)}else if(e instanceof tt){extract_candidates(e.condition);extract_candidates(e.consequent);extract_candidates(e.alternative)}else if(e instanceof Ne){var n=e.definitions.length;var i=n-200;if(i<0)i=0;for(;i1&&!(e.name instanceof At)||(i>1?mangleable_var(e):!t.exposed(n))){return make_node(Lt,e.name,e.name)}}else{const t=e instanceof nt?e.left:e.expression;return!is_ref_of(t,St)&&!is_ref_of(t,Tt)&&t}}function get_rvalue(e){if(e instanceof nt){return e.right}else{return e.value}}function get_lvalues(e){var n=new Map;if(e instanceof Ze)return n;var i=new TreeWalker(function(e){var r=e;while(r instanceof We)r=r.expression;if(r instanceof Lt||r instanceof zt){n.set(r.name,n.get(r.name)||is_modified(t,i,e,e,0))}});get_rvalue(e).walk(i);return n}function remove_candidate(n){if(n.name instanceof At){var i=t.parent(),a=t.self().argnames;var o=a.indexOf(n.name);if(o<0){i.args.length=Math.min(i.args.length,a.length-1)}else{var s=i.args;if(s[o])s[o]=make_node(Ht,s[o],{value:0})}return true}var u=false;return e[c].transform(new TreeTransformer(function(e,t,i){if(u)return e;if(e===n||e.body===n){u=true;if(e instanceof Be){e.value=e.name instanceof St?make_node(Zt,e.value):null;return e}return i?r.skip:null}},function(e){if(e instanceof He)switch(e.expressions.length){case 0:return null;case 1:return e.expressions[0]}}))}function is_lhs_local(e){while(e instanceof We)e=e.expression;return e instanceof Lt&&e.definition().scope===a&&!(n&&(v.has(e.name)||h instanceof Ze||h instanceof nt&&!h.logical&&h.operator!="="))}function value_has_side_effects(e){if(e instanceof Ze)return Xn.has(e.operator);return get_rvalue(e).has_side_effects(t)}function replace_all_symbols(){if(b)return false;if(d)return true;if(g instanceof Lt){var e=g.definition();if(e.references.length-e.replaced==(h instanceof Be?1:2)){return true}}return false}function may_modify(e){if(!e.definition)return true;var t=e.definition();if(t.orig.length==1&&t.orig[0]instanceof Ct)return false;if(t.scope.get_defun_scope()!==a)return true;return!t.references.every(e=>{var t=e.scope.get_defun_scope();if(t.TYPE=="Scope")t=t.parent_scope;return t===a})}function side_effects_external(e,t){if(e instanceof nt)return side_effects_external(e.left,true);if(e instanceof Ze)return side_effects_external(e.expression,true);if(e instanceof Be)return e.value&&side_effects_external(e.value);if(t){if(e instanceof qe)return side_effects_external(e.expression,true);if(e instanceof je)return side_effects_external(e.expression,true);if(e instanceof Lt)return e.definition().scope!==a}return false}}function eliminate_spurious_blocks(e){var t=[];for(var n=0;n=0;){var s=e[a];var u=next_index(a);var c=e[u];if(r&&!c&&s instanceof ve){if(!s.value){o=true;e.splice(a,1);continue}if(s.value instanceof Qe&&s.value.operator=="void"){o=true;e[a]=make_node(H,s,{body:s.value.expression});continue}}if(s instanceof Ae){var l=aborts(s.body);if(can_merge_flow(l)){if(l.label){remove(l.label.thedef.references,l)}o=true;s=s.clone();s.condition=s.condition.negate(t);var f=as_statement_array_with_return(s.body,l);s.body=make_node(q,s,{body:as_statement_array(s.alternative).concat(extract_functions())});s.alternative=make_node(q,s,{body:f});e[a]=s.transform(t);continue}var l=aborts(s.alternative);if(can_merge_flow(l)){if(l.label){remove(l.label.thedef.references,l)}o=true;s=s.clone();s.body=make_node(q,s.body,{body:as_statement_array(s.body).concat(extract_functions())});var f=as_statement_array_with_return(s.alternative,l);s.alternative=make_node(q,s.alternative,{body:f});e[a]=s.transform(t);continue}}if(s instanceof Ae&&s.body instanceof ve){var p=s.body.value;if(!p&&!s.alternative&&(r&&!c||c instanceof ve&&!c.value)){o=true;e[a]=make_node(H,s.condition,{body:s.condition});continue}if(p&&!s.alternative&&c instanceof ve&&c.value){o=true;s=s.clone();s.alternative=c;e[a]=s.transform(t);e.splice(u,1);continue}if(p&&!s.alternative&&(!c&&r&&i||c instanceof ve)){o=true;s=s.clone();s.alternative=c||make_node(ve,s,{value:null});e[a]=s.transform(t);if(c)e.splice(u,1);continue}var _=e[prev_index(a)];if(t.option("sequences")&&r&&!s.alternative&&_ instanceof Ae&&_.body instanceof ve&&next_index(u)==e.length&&c instanceof H){o=true;s=s.clone();s.alternative=make_node(q,c,{body:[c,make_node(ve,c,{value:null})]});e[a]=s.transform(t);e.splice(u,1);continue}}}function has_multiple_if_returns(e){var t=0;for(var n=e.length;--n>=0;){var i=e[n];if(i instanceof Ae&&i.body instanceof ve){if(++t>1)return true}}return false}function is_return_void(e){return!e||e instanceof Qe&&e.operator=="void"}function can_merge_flow(i){if(!i)return false;for(var o=a+1,s=e.length;o=0;){var i=e[n];if(!(i instanceof Ie&&declarations_only(i))){break}}return n}}function eliminate_dead_code(e,t){var n;var i=t.self();for(var r=0,a=0,s=e.length;r!e.value)}function sequencesize(e,t){if(e.length<2)return;var n=[],i=0;function push_seq(){if(!n.length)return;var t=make_sequence(n[0],n);e[i++]=make_node(H,t,{body:t});n=[]}for(var r=0,a=e.length;r=t.sequences_limit)push_seq();var u=s.body;if(n.length>0)u=u.drop_side_effect_free(t);if(u)merge_sequence(n,u)}else if(s instanceof Ne&&declarations_only(s)||s instanceof pe){e[i++]=s}else{push_seq();e[i++]=s}}push_seq();e.length=i;if(i!=a)o=true}function to_simple_statement(e,t){if(!(e instanceof q))return e;var n=null;for(var i=0,r=e.body.length;i{if(e instanceof ae)return true;if(e instanceof et&&e.operator==="in"){return rn}});if(!e){if(a.init)a.init=cons_seq(a.init);else{a.init=i.body;n--;o=true}}}}else if(a instanceof ne){if(!(a.init instanceof Le)&&!(a.init instanceof Pe)){a.object=cons_seq(a.object)}}else if(a instanceof Ae){a.condition=cons_seq(a.condition)}else if(a instanceof Ce){a.expression=cons_seq(a.expression)}else if(a instanceof re){a.expression=cons_seq(a.expression)}}if(t.option("conditionals")&&a instanceof Ae){var s=[];var u=to_simple_statement(a.body,s);var c=to_simple_statement(a.alternative,s);if(u!==false&&c!==false&&s.length>0){var l=s.length;s.push(make_node(Ae,a,{condition:a.condition,body:u||make_node(Y,a.body),alternative:c}));s.unshift(n,1);[].splice.apply(e,s);r+=l;n+=l+1;i=null;o=true;continue}}e[n++]=a;i=a instanceof H?a:null}e.length=n}function join_object_assignments(e,n){if(!(e instanceof Ne))return;var i=e.definitions[e.definitions.length-1];if(!(i.value instanceof at))return;var r;if(n instanceof nt&&!n.logical){r=[n]}else if(n instanceof He){r=n.expressions.slice()}if(!r)return;var o=false;do{var s=r[0];if(!(s instanceof nt))break;if(s.operator!="=")break;if(!(s.left instanceof We))break;var u=s.left.expression;if(!(u instanceof Lt))break;if(i.name.name!=u.name)break;if(!s.right.is_constant_expression(a))break;var c=s.left.property;if(c instanceof z){c=c.evaluate(t)}if(c instanceof z)break;c=""+c;var l=t.option("ecma")<2015&&t.has_directive("use strict")?function(e){return e.key!=c&&(e.key&&e.key.name!=c)}:function(e){return e.key&&e.key.name!=c};if(!i.value.properties.every(l))break;var f=i.value.properties.filter(function(e){return e.key===c})[0];if(!f){i.value.properties.push(make_node(st,s,{key:c,value:s.right}))}else{f.value=new He({start:f.start,expressions:[f.value.clone(),s.right.clone()],end:f.end})}r.shift();o=true}while(r.length);return o&&r}function join_consecutive_vars(e){var t;for(var n=0,i=-1,r=e.length;n{if(i instanceof Ie){i.remove_initializers();n.push(i);return true}if(i instanceof pe&&(i===t||!e.has_directive("use strict"))){n.push(i===t?i:make_node(Ie,i,{definitions:[make_node(Be,i,{name:make_node(yt,i.name,i.name),value:null})]}));return true}if(i instanceof Ke||i instanceof Ue){n.push(i);return true}if(i instanceof ae){return true}})}function get_value(e){if(e instanceof Gt){return e.getValue()}if(e instanceof Qe&&e.operator=="void"&&e.expression instanceof Gt){return}return e}function is_undefined(e,t){return Bn(e,On)||e instanceof Zt||e instanceof Qe&&e.operator=="void"&&!e.expression.has_side_effects(t)}(function(e){z.DEFMETHOD("may_throw_on_access",function(e){return!e.option("pure_getters")||this._dot_throw(e)});function is_strict(e){return/strict/.test(e.option("pure_getters"))}e(z,is_strict);e(jt,return_true);e(Zt,return_true);e(Gt,return_false);e(rt,return_false);e(at,function(e){if(!is_strict(e))return false;for(var t=this.properties.length;--t>=0;)if(this.properties[t]._dot_throw(e))return true;return false});e(ht,return_false);e(ot,return_false);e(ft,return_true);e(se,function(e){return this.expression._dot_throw(e)});e(le,return_false);e(fe,return_false);e(Je,return_false);e(Qe,function(){return this.operator=="void"});e(et,function(e){return(this.operator=="&&"||this.operator=="||"||this.operator=="??")&&(this.left._dot_throw(e)||this.right._dot_throw(e))});e(nt,function(e){if(this.logical)return true;return this.operator=="="&&this.right._dot_throw(e)});e(tt,function(e){return this.consequent._dot_throw(e)||this.alternative._dot_throw(e)});e(qe,function(e){if(!is_strict(e))return false;if(this.property=="prototype"){return!(this.expression instanceof le||this.expression instanceof ht)}return true});e($e,function(e){return this.expression._dot_throw(e)});e(He,function(e){return this.tail_node()._dot_throw(e)});e(Lt,function(e){if(this.name==="arguments")return false;if(Bn(this,On))return true;if(!is_strict(e))return false;if(is_undeclared_ref(this)&&this.is_declared(e))return false;if(this.is_immutable())return false;var t=this.fixed_value();return!t||t._dot_throw(e)})})(function(e,t){e.DEFMETHOD("_dot_throw",t)});(function(e){const t=makePredicate("! delete");const n=makePredicate("in instanceof == != === !== < <= >= >");e(z,return_false);e(Qe,function(){return t.has(this.operator)});e(et,function(){return n.has(this.operator)||Gn.has(this.operator)&&this.left.is_boolean()&&this.right.is_boolean()});e(tt,function(){return this.consequent.is_boolean()&&this.alternative.is_boolean()});e(nt,function(){return this.operator=="="&&this.right.is_boolean()});e(He,function(){return this.tail_node().is_boolean()});e(nn,return_true);e(tn,return_true)})(function(e,t){e.DEFMETHOD("is_boolean",t)});(function(e){e(z,return_false);e(Ht,return_true);var t=makePredicate("+ - ~ ++ --");e(Ze,function(){return t.has(this.operator)});var n=makePredicate("- * / % & | ^ << >> >>>");e(et,function(e){return n.has(this.operator)||this.operator=="+"&&this.left.is_number(e)&&this.right.is_number(e)});e(nt,function(e){return n.has(this.operator.slice(0,-1))||this.operator=="="&&this.right.is_number(e)});e(He,function(e){return this.tail_node().is_number(e)});e(tt,function(e){return this.consequent.is_number(e)&&this.alternative.is_number(e)})})(function(e,t){e.DEFMETHOD("is_number",t)});(function(e){e(z,return_false);e(Xt,return_true);e(de,return_true);e(Qe,function(){return this.operator=="typeof"});e(et,function(e){return this.operator=="+"&&(this.left.is_string(e)||this.right.is_string(e))});e(nt,function(e){return(this.operator=="="||this.operator=="+=")&&this.right.is_string(e)});e(He,function(e){return this.tail_node().is_string(e)});e(tt,function(e){return this.consequent.is_string(e)&&this.alternative.is_string(e)})})(function(e,t){e.DEFMETHOD("is_string",t)});var Gn=makePredicate("&& || ??");var Xn=makePredicate("delete ++ --");function is_lhs(e,t){if(t instanceof Ze&&Xn.has(t.operator))return t.expression;if(t instanceof nt&&t.left===e)return e}(function(e){function to_node(e,t){if(e instanceof z)return make_node(e.CTOR,t,e);if(Array.isArray(e))return make_node(rt,t,{elements:e.map(function(e){return to_node(e,t)})});if(e&&typeof e=="object"){var n=[];for(var i in e)if(HOP(e,i)){n.push(make_node(st,t,{key:i,value:to_node(e[i],t)}))}return make_node(at,t,{properties:n})}return make_node_from_constant(e,t)}oe.DEFMETHOD("resolve_defines",function(e){if(!e.option("global_defs"))return this;this.figure_out_scope({ie8:e.option("ie8")});return this.transform(new TreeTransformer(function(t){var n=t._find_defs(e,"");if(!n)return;var i=0,r=t,a;while(a=this.parent(i++)){if(!(a instanceof We))break;if(a.expression!==r)break;r=a}if(is_lhs(r,a)){return}return n}))});e(z,noop);e($e,function(e,t){return this.expression._find_defs(e,t)});e(qe,function(e,t){return this.expression._find_defs(e,"."+this.property+t)});e(bt,function(){if(!this.global())return});e(Lt,function(e,t){if(!this.global())return;var n=e.option("global_defs");var i=this.name+t;if(HOP(n,i))return to_node(n[i],this)})})(function(e,t){e.DEFMETHOD("_find_defs",t)});function best_of_expression(e,t){return e.size()>t.size()?t:e}function best_of_statement(e,t){return best_of_expression(make_node(H,e,{body:e}),make_node(H,t,{body:t})).body}function best_of(e,t,n){return(first_in_statement(e)?best_of_statement:best_of_expression)(t,n)}function convert_to_predicate(e){const t=new Map;for(var n of Object.keys(e)){t.set(n,makePredicate(e[n]))}return t}var Hn=["constructor","toString","valueOf"];var Wn=convert_to_predicate({Array:["indexOf","join","lastIndexOf","slice"].concat(Hn),Boolean:Hn,Function:Hn,Number:["toExponential","toFixed","toPrecision"].concat(Hn),Object:Hn,RegExp:["test"].concat(Hn),String:["charAt","charCodeAt","concat","indexOf","italics","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","trim"].concat(Hn)});var qn=convert_to_predicate({Array:["isArray"],Math:["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","atan2","pow","max","min"],Number:["isFinite","isNaN"],Object:["create","getOwnPropertyDescriptor","getOwnPropertyNames","getPrototypeOf","isExtensible","isFrozen","isSealed","keys"],String:["fromCharCode"]});(function(e){z.DEFMETHOD("evaluate",function(e){if(!e.option("evaluate"))return this;var t=this._eval(e,1);if(!t||t instanceof RegExp)return t;if(typeof t=="function"||typeof t=="object")return this;return t});var t=makePredicate("! ~ - + void");z.DEFMETHOD("is_constant",function(){if(this instanceof Gt){return!(this instanceof qt)}else{return this instanceof Qe&&this.expression instanceof Gt&&t.has(this.operator)}});e(K,function(){throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]",this.start))});e(ue,return_this);e(ht,return_this);e(z,return_this);e(Gt,function(){return this.getValue()});e(Wt,return_this);e(qt,function(e){let t=e.evaluated_regexps.get(this);if(t===undefined){try{t=(0,eval)(this.print_to_string())}catch(e){t=null}e.evaluated_regexps.set(this,t)}return t||this});e(de,function(){if(this.segments.length!==1)return this;return this.segments[0].value});e(le,function(e){if(e.option("unsafe")){var t=function(){};t.node=this;t.toString=(()=>this.print_to_string());return t}return this});e(rt,function(e,t){if(e.option("unsafe")){var n=[];for(var i=0,r=this.elements.length;itypeof e==="object"||typeof e==="function"||typeof e==="symbol";e(et,function(e,t){if(!i.has(this.operator))t++;var n=this.left._eval(e,t);if(n===this.left)return this;var o=this.right._eval(e,t);if(o===this.right)return this;var s;if(n!=null&&o!=null&&r.has(this.operator)&&a(n)&&a(o)&&typeof n===typeof o){return this}switch(this.operator){case"&&":s=n&&o;break;case"||":s=n||o;break;case"??":s=n!=null?n:o;break;case"|":s=n|o;break;case"&":s=n&o;break;case"^":s=n^o;break;case"+":s=n+o;break;case"*":s=n*o;break;case"**":s=Math.pow(n,o);break;case"/":s=n/o;break;case"%":s=n%o;break;case"-":s=n-o;break;case"<<":s=n<>":s=n>>o;break;case">>>":s=n>>>o;break;case"==":s=n==o;break;case"===":s=n===o;break;case"!=":s=n!=o;break;case"!==":s=n!==o;break;case"<":s=n":s=n>o;break;case">=":s=n>=o;break;default:return this}if(isNaN(s)&&e.find_parent(re)){return this}return s});e(tt,function(e,t){var n=this.condition._eval(e,t);if(n===this.condition)return this;var i=n?this.consequent:this.alternative;var r=i._eval(e,t);return r===i?this:r});const o=new Set;e(Lt,function(e,t){if(o.has(this))return this;var n=this.fixed_value();if(!n)return this;o.add(this);const i=n._eval(e,t);o.delete(this);if(i===n)return this;if(i&&typeof i=="object"){var r=this.definition().escaped;if(r&&t>r)return this}return i});var s={Array:Array,Math:Math,Number:Number,Object:Object,String:String};var u=convert_to_predicate({Math:["E","LN10","LN2","LOG2E","LOG10E","PI","SQRT1_2","SQRT2"],Number:["MAX_VALUE","MIN_VALUE","NaN","NEGATIVE_INFINITY","POSITIVE_INFINITY"]});const c=new Set(["dotAll","global","ignoreCase","multiline","sticky","unicode"]);e(We,function(e,t){if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")){var n=this.property;if(n instanceof z){n=n._eval(e,t);if(n===this.property)return this}var i=this.expression;var r;if(is_undeclared_ref(i)){var a;var o=i.name==="hasOwnProperty"&&n==="call"&&(a=e.parent()&&e.parent().args)&&(a&&a[0]&&a[0].evaluate(e));o=o instanceof qe?o.expression:o;if(o==null||o.thedef&&o.thedef.undeclared){return this.clone()}var l=u.get(i.name);if(!l||!l.has(n))return this;r=s[i.name]}else{r=i._eval(e,t+1);if(r instanceof RegExp){if(n=="source"){return regexp_source_fix(r.source)}else if(n=="flags"||c.has(n)){return r[n]}}if(!r||r===i||!HOP(r,n))return this;if(typeof r=="function")switch(n){case"name":return r.node.name?r.node.name.name:"";case"length":return r.node.length_property();default:return this}}return r[n]}return this});e($e,function(e,t){const n=this.expression._eval(e,t);return n===this.expression?this:n});e(Ge,function(e,t){var n=this.expression;if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")&&n instanceof We){var i=n.property;if(i instanceof z){i=i._eval(e,t);if(i===n.property)return this}var r;var a=n.expression;if(is_undeclared_ref(a)){var o=a.name==="hasOwnProperty"&&i==="call"&&(this.args[0]&&this.args[0].evaluate(e));o=o instanceof qe?o.expression:o;if(o==null||o.thedef&&o.thedef.undeclared){return this.clone()}var u=qn.get(a.name);if(!u||!u.has(i))return this;r=s[a.name]}else{r=a._eval(e,t+1);if(r===a||!r)return this;var c=Wn.get(r.constructor.name);if(!c||!c.has(i))return this}var l=[];for(var f=0,p=this.args.length;f";return n;case"<":n.operator=">=";return n;case">=":n.operator="<";return n;case">":n.operator="<=";return n}}switch(i){case"==":n.operator="!=";return n;case"!=":n.operator="==";return n;case"===":n.operator="!==";return n;case"!==":n.operator="===";return n;case"&&":n.operator="||";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"||":n.operator="&&";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"??":n.right=n.right.negate(e);return best(this,n,t)}return basic_negation(this)})})(function(e,t){e.DEFMETHOD("negate",function(e,n){return t.call(this,e,n)})});var Yn=makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");Ge.DEFMETHOD("is_callee_pure",function(e){if(e.option("unsafe")){var t=this.expression;var n=this.args&&this.args[0]&&this.args[0].evaluate(e);if(t.expression&&t.expression.name==="hasOwnProperty"&&(n==null||n.thedef&&n.thedef.undeclared)){return false}if(is_undeclared_ref(t)&&Yn.has(t.name))return true;let i;if(t instanceof qe&&is_undeclared_ref(t.expression)&&(i=qn.get(t.expression.name))&&i.has(t.property)){return true}}return!!has_annotation(this,an)||!e.pure_funcs(this)});z.DEFMETHOD("is_call_pure",return_false);qe.DEFMETHOD("is_call_pure",function(e){if(!e.option("unsafe"))return;const t=this.expression;let n;if(t instanceof rt){n=Wn.get("Array")}else if(t.is_boolean()){n=Wn.get("Boolean")}else if(t.is_number(e)){n=Wn.get("Number")}else if(t instanceof qt){n=Wn.get("RegExp")}else if(t.is_string(e)){n=Wn.get("String")}else if(!this.may_throw_on_access(e)){n=Wn.get("Object")}return n&&n.has(this.property)});const jn=new Set(["Number","String","Array","Object","Function","Promise"]);(function(e){e(z,return_true);e(Y,return_false);e(Gt,return_false);e(zt,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].has_side_effects(t))return true;return false}e(W,function(e){return any(this.body,e)});e(Ge,function(e){if(!this.is_callee_pure(e)&&(!this.expression.is_call_pure(e)||this.expression.has_side_effects(e))){return true}return any(this.args,e)});e(Ce,function(e){return this.expression.has_side_effects(e)||any(this.body,e)});e(Fe,function(e){return this.expression.has_side_effects(e)||any(this.body,e)});e(Oe,function(e){return any(this.body,e)||this.bcatch&&this.bcatch.has_side_effects(e)||this.bfinally&&this.bfinally.has_side_effects(e)});e(Ae,function(e){return this.condition.has_side_effects(e)||this.body&&this.body.has_side_effects(e)||this.alternative&&this.alternative.has_side_effects(e)});e($,function(e){return this.body.has_side_effects(e)});e(H,function(e){return this.body.has_side_effects(e)});e(ue,return_false);e(ht,function(e){if(this.extends&&this.extends.has_side_effects(e)){return true}return any(this.properties,e)});e(et,function(e){return this.left.has_side_effects(e)||this.right.has_side_effects(e)});e(nt,return_true);e(tt,function(e){return this.condition.has_side_effects(e)||this.consequent.has_side_effects(e)||this.alternative.has_side_effects(e)});e(Ze,function(e){return Xn.has(this.operator)||this.expression.has_side_effects(e)});e(Lt,function(e){return!this.is_declared(e)&&!jn.has(this.name)});e(xt,return_false);e(bt,return_false);e(at,function(e){return any(this.properties,e)});e(ot,function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.value&&this.value.has_side_effects(e)});e(dt,function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.static&&this.value&&this.value.has_side_effects(e)});e(pt,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(ft,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(lt,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(rt,function(e){return any(this.elements,e)});e(qe,function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)});e(je,function(e){if(this.optional&&is_nullish(this.expression,e)){return false}return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)||this.property.has_side_effects(e)});e($e,function(e){return this.expression.has_side_effects(e)});e(He,function(e){return any(this.expressions,e)});e(Ne,function(e){return any(this.definitions,e)});e(Be,function(){return this.value});e(me,return_false);e(de,function(e){return any(this.segments,e)})})(function(e,t){e.DEFMETHOD("has_side_effects",t)});(function(e){e(z,return_true);e(Gt,return_false);e(Y,return_false);e(ue,return_false);e(bt,return_false);e(zt,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].may_throw(t))return true;return false}e(ht,function(e){if(this.extends&&this.extends.may_throw(e))return true;return any(this.properties,e)});e(rt,function(e){return any(this.elements,e)});e(nt,function(e){if(this.right.may_throw(e))return true;if(!e.has_directive("use strict")&&this.operator=="="&&this.left instanceof Lt){return false}return this.left.may_throw(e)});e(et,function(e){return this.left.may_throw(e)||this.right.may_throw(e)});e(W,function(e){return any(this.body,e)});e(Ge,function(e){if(this.optional&&is_nullish(this.expression,e))return false;if(any(this.args,e))return true;if(this.is_callee_pure(e))return false;if(this.expression.may_throw(e))return true;return!(this.expression instanceof ue)||any(this.expression.body,e)});e(Fe,function(e){return this.expression.may_throw(e)||any(this.body,e)});e(tt,function(e){return this.condition.may_throw(e)||this.consequent.may_throw(e)||this.alternative.may_throw(e)});e(Ne,function(e){return any(this.definitions,e)});e(Ae,function(e){return this.condition.may_throw(e)||this.body&&this.body.may_throw(e)||this.alternative&&this.alternative.may_throw(e)});e($,function(e){return this.body.may_throw(e)});e(at,function(e){return any(this.properties,e)});e(ot,function(e){return this.value?this.value.may_throw(e):false});e(dt,function(e){return this.computed_key()&&this.key.may_throw(e)||this.static&&this.value&&this.value.may_throw(e)});e(pt,function(e){return this.computed_key()&&this.key.may_throw(e)});e(ft,function(e){return this.computed_key()&&this.key.may_throw(e)});e(lt,function(e){return this.computed_key()&&this.key.may_throw(e)});e(ve,function(e){return this.value&&this.value.may_throw(e)});e(He,function(e){return any(this.expressions,e)});e(H,function(e){return this.body.may_throw(e)});e(qe,function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)});e(je,function(e){if(this.optional&&is_nullish(this.expression,e))return false;return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)||this.property.may_throw(e)});e($e,function(e){return this.expression.may_throw(e)});e(Ce,function(e){return this.expression.may_throw(e)||any(this.body,e)});e(Lt,function(e){return!this.is_declared(e)&&!jn.has(this.name)});e(xt,return_false);e(Oe,function(e){return this.bcatch?this.bcatch.may_throw(e):any(this.body,e)||this.bfinally&&this.bfinally.may_throw(e)});e(Ze,function(e){if(this.operator=="typeof"&&this.expression instanceof Lt)return false;return this.expression.may_throw(e)});e(Be,function(e){if(!this.value)return false;return this.value.may_throw(e)})})(function(e,t){e.DEFMETHOD("may_throw",t)});(function(e){function all_refs_local(e){let t=true;walk(this,n=>{if(n instanceof Lt){if(Bn(this,wn)){t=false;return rn}var i=n.definition();if(member(i,this.enclosed)&&!this.variables.has(i.name)){if(e){var r=e.find_variable(n);if(i.undeclared?!r:r===i){t="f";return true}}t=false;return rn}return true}if(n instanceof zt&&this instanceof fe){t=false;return rn}});return t}e(z,return_false);e(Gt,return_true);e(ht,function(e){if(this.extends&&!this.extends.is_constant_expression(e)){return false}for(const t of this.properties){if(t.computed_key()&&!t.key.is_constant_expression(e)){return false}if(t.static&&t.value&&!t.value.is_constant_expression(e)){return false}}return all_refs_local.call(this,e)});e(ue,all_refs_local);e(Ze,function(){return this.expression.is_constant_expression()});e(et,function(){return this.left.is_constant_expression()&&this.right.is_constant_expression()});e(rt,function(){return this.elements.every(e=>e.is_constant_expression())});e(at,function(){return this.properties.every(e=>e.is_constant_expression())});e(ot,function(){return!!(!(this.key instanceof z)&&this.value&&this.value.is_constant_expression())})})(function(e,t){e.DEFMETHOD("is_constant_expression",t)});function aborts(e){return e&&e.aborts()}(function(e){e(K,return_null);e(Ee,return_this);function block_aborts(){for(var e=0;e{if(e instanceof bt){const n=e.definition();if((t||n.global)&&!o.has(n.id)){o.set(n.id,n)}}})}if(n.value){if(n.name instanceof _e){n.walk(f)}else{var r=n.name.definition();map_add(c,r.id,n.value);if(!r.chained&&n.name.fixed_value()===n.value){s.set(r.id,n)}}if(n.value.has_side_effects(e)){n.value.walk(f)}}});return true}return scan_ref_scoped(r,a)});t.walk(f);f=new TreeWalker(scan_ref_scoped);o.forEach(function(e){var t=c.get(e.id);if(t)t.forEach(function(e){e.walk(f)})});var p=new TreeTransformer(function before(c,f,_){var h=p.parent();if(i){const e=a(c);if(e instanceof Lt){var d=e.definition();var m=o.has(d.id);if(c instanceof nt){if(!m||s.has(d.id)&&s.get(d.id)!==c){return maintain_this_binding(h,c,c.right.transform(p))}}else if(!m)return _?r.skip:make_node(Ht,c,{value:0})}}if(l!==t)return;var d;if(c.name&&(c instanceof gt&&!keep_name(e.option("keep_classnames"),(d=c.name.definition()).name)||c instanceof le&&!keep_name(e.option("keep_fnames"),(d=c.name.definition()).name))){if(!o.has(d.id)||d.orig.length>1)c.name=null}if(c instanceof ue&&!(c instanceof ce)){var E=!e.option("keep_fargs");for(var g=c.argnames,v=g.length;--v>=0;){var D=g[v];if(D instanceof se){D=D.expression}if(D instanceof it){D=D.left}if(!(D instanceof _e)&&!o.has(D.definition().id)){Vn(D,Rn);if(E){g.pop()}}else{E=false}}}if((c instanceof pe||c instanceof Et)&&c!==t){const t=c.name.definition();let i=t.global&&!n||o.has(t.id);if(!i){t.eliminated++;if(c instanceof Et){const t=c.drop_side_effect_free(e);if(t){return make_node(H,c,{body:t})}}return _?r.skip:make_node(Y,c)}}if(c instanceof Ne&&!(h instanceof ne&&h.init===c)){var b=!(h instanceof oe)&&!(c instanceof Ie);var y=[],k=[],S=[];var T=[];c.definitions.forEach(function(t){if(t.value)t.value=t.value.transform(p);var n=t.name instanceof _e;var r=n?new SymbolDef(null,{name:""}):t.name.definition();if(b&&r.global)return S.push(t);if(!(i||b)||n&&(t.name.names.length||t.name.is_array||e.option("pure_getters")!=true)||o.has(r.id)){if(t.value&&s.has(r.id)&&s.get(r.id)!==t){t.value=t.value.drop_side_effect_free(e)}if(t.name instanceof yt){var a=u.get(r.id);if(a.length>1&&(!t.value||r.orig.indexOf(t.name)>r.eliminated)){if(t.value){var l=make_node(Lt,t.name,t.name);r.references.push(l);var f=make_node(nt,t,{operator:"=",logical:false,left:l,right:t.value});if(s.get(r.id)===t){s.set(r.id,f)}T.push(f.transform(p))}remove(a,t);r.eliminated++;return}}if(t.value){if(T.length>0){if(S.length>0){T.push(t.value);t.value=make_sequence(t.value,T)}else{y.push(make_node(H,c,{body:make_sequence(c,T)}))}T=[]}S.push(t)}else{k.push(t)}}else if(r.orig[0]instanceof Mt){var _=t.value&&t.value.drop_side_effect_free(e);if(_)T.push(_);t.value=null;k.push(t)}else{var _=t.value&&t.value.drop_side_effect_free(e);if(_){T.push(_)}r.eliminated++}});if(k.length>0||S.length>0){c.definitions=k.concat(S);y.push(c)}if(T.length>0){y.push(make_node(H,c,{body:make_sequence(c,T)}))}switch(y.length){case 0:return _?r.skip:make_node(Y,c);case 1:return y[0];default:return _?r.splice(y):make_node(q,c,{body:y})}}if(c instanceof te){f(c,this);var A;if(c.init instanceof q){A=c.init;c.init=A.body.pop();A.body.push(c)}if(c.init instanceof H){c.init=c.init.body}else if(is_empty(c.init)){c.init=null}return!A?c:_?r.splice(A.body):A}if(c instanceof $&&c.body instanceof te){f(c,this);if(c.body instanceof q){var A=c.body;c.body=A.body.pop();A.body.push(c);return _?r.splice(A.body):A}return c}if(c instanceof q){f(c,this);if(_&&c.body.every(can_be_evicted_from_block)){return r.splice(c.body)}return c}if(c instanceof ae){const e=l;l=c;f(c,this);l=e;return c}});t.transform(p);function scan_ref_scoped(e,n){var i;const r=a(e);if(r instanceof Lt&&!is_ref_of(e.left,kt)&&t.variables.get(r.name)===(i=r.definition())){if(e instanceof nt){e.right.walk(f);if(!i.chained&&e.left.fixed_value()===e.right){s.set(i.id,e)}}return true}if(e instanceof Lt){i=e.definition();if(!o.has(i.id)){o.set(i.id,i);if(i.orig[0]instanceof Mt){const e=i.scope.is_block_scope()&&i.scope.get_defun_scope().variables.get(i.name);if(e)o.set(e.id,e)}}return true}if(e instanceof ae){var u=l;l=e;n();l=u;return true}}});ae.DEFMETHOD("hoist_declarations",function(e){var t=this;if(e.has_directive("use asm"))return t;if(!Array.isArray(t.body))return t;var n=e.option("hoist_funs");var i=e.option("hoist_vars");if(n||i){var r=[];var a=[];var o=new Map,s=0,u=0;walk(t,e=>{if(e instanceof ae&&e!==t)return true;if(e instanceof Ie){++u;return true}});i=i&&u>1;var c=new TreeTransformer(function before(u){if(u!==t){if(u instanceof X){r.push(u);return make_node(Y,u)}if(n&&u instanceof pe&&!(c.parent()instanceof Ke)&&c.parent()===t){a.push(u);return make_node(Y,u)}if(i&&u instanceof Ie&&!u.definitions.some(e=>e.name instanceof _e)){u.definitions.forEach(function(e){o.set(e.name.name,e);++s});var l=u.to_assignments(e);var f=c.parent();if(f instanceof ne&&f.init===u){if(l==null){var p=u.definitions[0].name;return make_node(Lt,p,p)}return l}if(f instanceof te&&f.init===u){return l}if(!l)return make_node(Y,u);return make_node(H,u,{body:l})}if(u instanceof ae)return u}});t=t.transform(c);if(s>0){var l=[];const e=t instanceof ue;const n=e?t.args_as_names():null;o.forEach((t,i)=>{if(e&&n.some(e=>e.name===t.name.name)){o.delete(i)}else{t=t.clone();t.value=null;l.push(t);o.set(i,t)}});if(l.length>0){for(var f=0;fe instanceof se||e.computed_key())){s(o,this);const e=new Map;const n=[];l.properties.forEach(({key:i,value:r})=>{const s=find_scope(a);const c=t.create_symbol(u.CTOR,{source:u,scope:s,conflict_scopes:new Set([s,...u.definition().references.map(e=>e.scope)]),tentative_name:u.name+"_"+i});e.set(String(i),c.definition());n.push(make_node(Be,o,{name:c,value:r}))});i.set(c.id,e);return r.splice(n)}}else if(o instanceof We&&o.expression instanceof Lt){const e=i.get(o.expression.definition().id);if(e){const t=e.get(String(get_value(o.property)));const n=make_node(Lt,o,{name:t.name,scope:o.expression.scope,thedef:t});n.reference({});return n}}});return t.transform(a)});(function(e){function trim(e,t,n){var i=e.length;if(!i)return null;var r=[],a=false;for(var o=0;o0){o[0].body=a.concat(o[0].body)}e.body=o;while(n=o[o.length-1]){var h=n.body[n.body.length-1];if(h instanceof ye&&t.loopcontrol_target(h)===e)n.body.pop();if(n.body.length||n instanceof Fe&&(s||n.expression.has_side_effects(t)))break;if(o.pop()===s)s=null}if(o.length==0){return make_node(q,e,{body:a.concat(make_node(H,e.expression,{body:e.expression}))}).optimize(t)}if(o.length==1&&(o[0]===u||o[0]===s)){var d=false;var m=new TreeWalker(function(t){if(d||t instanceof ue||t instanceof H)return true;if(t instanceof ye&&m.loopcontrol_target(t)===e)d=true});e.walk(m);if(!d){var E=o[0].body.slice();var f=o[0].expression;if(f)E.unshift(make_node(H,f,{body:f}));E.unshift(make_node(H,e.expression,{body:e.expression}));return make_node(q,e,{body:E}).optimize(t)}}return e;function eliminate_branch(e,n){if(n&&!aborts(n)){n.body=n.body.concat(e.body)}else{trim_unreachable_code(t,e,a)}}});def_optimize(Oe,function(e,t){tighten_body(e.body,t);if(e.bcatch&&e.bfinally&&e.bfinally.body.every(is_empty))e.bfinally=null;if(t.option("dead_code")&&e.body.every(is_empty)){var n=[];if(e.bcatch){trim_unreachable_code(t,e.bcatch,n)}if(e.bfinally)n.push(...e.bfinally.body);return make_node(q,e,{body:n}).optimize(t)}return e});Ne.DEFMETHOD("remove_initializers",function(){var e=[];this.definitions.forEach(function(t){if(t.name instanceof bt){t.value=null;e.push(t)}else{walk(t.name,n=>{if(n instanceof bt){e.push(make_node(Be,t,{name:n,value:null}))}})}});this.definitions=e});Ne.DEFMETHOD("to_assignments",function(e){var t=e.option("reduce_vars");var n=[];for(const e of this.definitions){if(e.value){var i=make_node(Lt,e.name,e.name);n.push(make_node(nt,e,{operator:"=",logical:false,left:i,right:e.value}));if(t)i.definition().fixed=false}else if(e.value){var r=make_node(Be,e,{name:e.name,value:e.value});var a=make_node(Ie,e,{definitions:[r]});n.push(a)}const o=e.name.definition();o.eliminated++;o.replaced--}if(n.length==0)return null;return make_sequence(this,n)});def_optimize(Ne,function(e){if(e.definitions.length==0)return make_node(Y,e);return e});def_optimize(Be,function(e,t){if(e.name instanceof Tt&&e.value!=null&&is_undefined(e.value,t)){e.value=null}return e});def_optimize(Ue,function(e){return e});function retain_top_func(e,t){return t.top_retain&&e instanceof pe&&Bn(e,Pn)&&e.name&&t.top_retain(e.name)}def_optimize(Ge,function(e,t){var n=e.expression;var i=n;inline_array_like_spread(e.args);var r=e.args.every(e=>!(e instanceof se));if(t.option("reduce_vars")&&i instanceof Lt&&!has_annotation(e,sn)){const e=i.fixed_value();if(!retain_top_func(e,t)){i=e}}if(e.optional&&is_nullish(i,t)){return make_node(Zt,e)}var a=i instanceof ue;if(a&&i.pinned())return e;if(t.option("unused")&&r&&a&&!i.uses_arguments){var o=0,s=0;for(var u=0,c=e.args.length;u=i.argnames.length;if(f||Bn(i.argnames[u],Rn)){var l=e.args[u].drop_side_effect_free(t);if(l){e.args[o++]=l}else if(!f){e.args[o++]=make_node(Ht,e.args[u],{value:0});continue}}else{e.args[o++]=e.args[u]}s=o}e.args.length=s}if(t.option("unsafe")){if(is_undeclared_ref(n))switch(n.name){case"Array":if(e.args.length!=1){return make_node(rt,e,{elements:e.args}).optimize(t)}else if(e.args[0]instanceof Ht&&e.args[0].value<=11){const t=[];for(let n=0;n=1&&e.args.length<=2&&e.args.every(e=>{var n=e.evaluate(t);p.push(n);return e!==n})){let[n,i]=p;n=regexp_source_fix(new RegExp(n).source);const r=make_node(qt,e,{value:{source:n,flags:i}});if(r._eval(t)!==r){return r}}break}else if(n instanceof qe)switch(n.property){case"toString":if(e.args.length==0&&!n.expression.may_throw_on_access(t)){return make_node(et,e,{left:make_node(Xt,e,{value:""}),operator:"+",right:n.expression}).optimize(t)}break;case"join":if(n.expression instanceof rt)e:{var _;if(e.args.length>0){_=e.args[0].evaluate(t);if(_===e.args[0])break e}var h=[];var d=[];for(var u=0,c=n.expression.elements.length;u0){h.push(make_node(Xt,e,{value:d.join(_)}));d.length=0}h.push(m)}}if(d.length>0){h.push(make_node(Xt,e,{value:d.join(_)}))}if(h.length==0)return make_node(Xt,e,{value:""});if(h.length==1){if(h[0].is_string(t)){return h[0]}return make_node(et,h[0],{operator:"+",left:make_node(Xt,e,{value:""}),right:h[0]})}if(_==""){var g;if(h[0].is_string(t)||h[1].is_string(t)){g=h.shift()}else{g=make_node(Xt,e,{value:""})}return h.reduce(function(e,t){return make_node(et,t,{operator:"+",left:e,right:t})},g).optimize(t)}var l=e.clone();l.expression=l.expression.clone();l.expression.expression=l.expression.expression.clone();l.expression.expression.elements=h;return best_of(t,e,l)}break;case"charAt":if(n.expression.is_string(t)){var v=e.args[0];var D=v?v.evaluate(t):0;if(D!==v){return make_node(je,n,{expression:n.expression,property:make_node_from_constant(D|0,v||n)}).optimize(t)}}break;case"apply":if(e.args.length==2&&e.args[1]instanceof rt){var b=e.args[1].elements.slice();b.unshift(e.args[0]);return make_node(Ge,e,{expression:make_node(qe,n,{expression:n.expression,optional:false,property:"call"}),args:b}).optimize(t)}break;case"call":var y=n.expression;if(y instanceof Lt){y=y.fixed_value()}if(y instanceof ue&&!y.contains_this()){return(e.args.length?make_sequence(this,[e.args[0],make_node(Ge,e,{expression:n.expression,args:e.args.slice(1)})]):make_node(Ge,e,{expression:n.expression,args:[]})).optimize(t)}break}}if(t.option("unsafe_Function")&&is_undeclared_ref(n)&&n.name=="Function"){if(e.args.length==0)return make_node(le,e,{argnames:[],body:[]}).optimize(t);if(e.args.every(e=>e instanceof Xt)){try{var k="n(function("+e.args.slice(0,-1).map(function(e){return e.value}).join(",")+"){"+e.args[e.args.length-1].value+"})";var S=parse(k);var T={ie8:t.option("ie8")};S.figure_out_scope(T);var A=new Compressor(t.options,{mangle_options:t.mangle_options});S=S.transform(A);S.figure_out_scope(T);bn.reset();S.compute_char_frequency(T);S.mangle_names(T);var C;walk(S,e=>{if(is_func_expr(e)){C=e;return rn}});var k=OutputStream();q.prototype._codegen.call(C,C,k);e.args=[make_node(Xt,e,{value:C.argnames.map(function(e){return e.print_to_string()}).join(",")}),make_node(Xt,e.args[e.args.length-1],{value:k.get().replace(/^{|}$/g,"")})];return e}catch(e){if(!(e instanceof JS_Parse_Error)){throw e}}}}var R=a&&i.body[0];var x=a&&!i.is_generator&&!i.async;var F=x&&t.option("inline")&&!e.is_callee_pure(t);if(F&&R instanceof ve){let n=R.value;if(!n||n.is_constant_expression()){if(n){n=n.clone(true)}else{n=make_node(Zt,e)}const i=e.args.concat(n);return make_sequence(e,i).optimize(t)}if(i.argnames.length===1&&i.argnames[0]instanceof At&&e.args.length<2&&n instanceof Lt&&n.name===i.argnames[0].name){const n=(e.args[0]||make_node(Zt)).optimize(t);let i;if(n instanceof We&&(i=t.parent())instanceof Ge&&i.expression===e){return make_sequence(e,[make_node(Ht,e,{value:0}),n])}return n}}if(F){var O,w,M=-1;let a;let o;let s;if(r&&!i.uses_arguments&&!(t.parent()instanceof ht)&&!(i.name&&i instanceof le)&&(o=can_flatten_body(R))&&(n===i||has_annotation(e,on)||t.option("unused")&&(a=n.definition()).references.length==1&&!recursive_ref(t,a)&&i.is_constant_expression(n.scope))&&!has_annotation(e,an|sn)&&!i.contains_this()&&can_inject_symbols()&&(s=find_scope(t))&&!scope_encloses_variables_in_this_scope(s,i)&&!function in_default_assign(){let e=0;let n;while(n=t.parent(e++)){if(n instanceof it)return true;if(n instanceof W)break}return false}()&&!(O instanceof ht)){Vn(i,Nn);s.add_child_scope(i);return make_sequence(e,flatten_fn(o)).optimize(t)}}if(F&&has_annotation(e,on)){Vn(i,Nn);i=make_node(i.CTOR===pe?le:i.CTOR,i,i);i.figure_out_scope({},{parent_scope:find_scope(t),toplevel:t.get_toplevel()});return make_node(Ge,e,{expression:i,args:e.args}).optimize(t)}const N=x&&t.option("side_effects")&&i.body.every(is_empty);if(N){var b=e.args.concat(make_node(Zt,e));return make_sequence(e,b).optimize(t)}if(t.option("negate_iife")&&t.parent()instanceof H&&is_iife_call(e)){return e.negate(t,true)}var I=e.evaluate(t);if(I!==e){I=make_node_from_constant(I,e).optimize(t);return best_of(t,I,e)}return e;function return_value(t){if(!t)return make_node(Zt,e);if(t instanceof ve){if(!t.value)return make_node(Zt,e);return t.value.clone(true)}if(t instanceof H){return make_node(Qe,t,{operator:"void",expression:t.body.clone(true)})}}function can_flatten_body(e){var n=i.body;var r=n.length;if(t.option("inline")<3){return r==1&&return_value(e)}e=null;for(var a=0;a!e.value)){return false}}else if(e){return false}else if(!(o instanceof Y)){e=o}}return return_value(e)}function can_inject_args(e,t){for(var n=0,r=i.argnames.length;n=0;){var s=a.definitions[o].name;if(s instanceof _e||e.has(s.name)||Kn.has(s.name)||O.conflicting_def(s.name)){return false}if(w)w.push(s.definition())}}return true}function can_inject_symbols(){var e=new Set;do{O=t.parent(++M);if(O.is_block_scope()&&O.block_scope){O.block_scope.variables.forEach(function(t){e.add(t.name)})}if(O instanceof we){if(O.argname){e.add(O.argname.name)}}else if(O instanceof Z){w=[]}else if(O instanceof Lt){if(O.fixed_value()instanceof ae)return false}}while(!(O instanceof ae));var n=!(O instanceof oe)||t.toplevel.vars;var r=t.option("inline");if(!can_inject_vars(e,r>=3&&n))return false;if(!can_inject_args(e,r>=2&&n))return false;return!w||w.length==0||!is_reachable(i,w)}function append_var(t,n,i,r){var a=i.definition();const o=O.variables.has(i.name);if(!o){O.variables.set(i.name,a);O.enclosed.push(a);t.push(make_node(Be,i,{name:i,value:null}))}var s=make_node(Lt,i,i);a.references.push(s);if(r)n.push(make_node(nt,e,{operator:"=",logical:false,left:s,right:r.clone()}))}function flatten_args(t,n){var r=i.argnames.length;for(var a=e.args.length;--a>=r;){n.push(e.args[a])}for(a=r;--a>=0;){var o=i.argnames[a];var s=e.args[a];if(Bn(o,Rn)||!o.name||O.conflicting_def(o.name)){if(s)n.push(s)}else{var u=make_node(yt,o,o);o.definition().orig.push(u);if(!s&&w)s=make_node(Zt,e);append_var(t,n,u,s)}}t.reverse();n.reverse()}function flatten_vars(e,t){var n=t.length;for(var r=0,a=i.body.length;re.name!=l.name)){var f=i.variables.get(l.name);var p=make_node(Lt,l,l);f.references.push(p);t.splice(n++,0,make_node(nt,c,{operator:"=",logical:false,left:p,right:make_node(Zt,l)}))}}}}function flatten_fn(e){var n=[];var r=[];flatten_args(n,r);flatten_vars(n,r);r.push(e);if(n.length){const e=O.body.indexOf(t.parent(M-1))+1;O.body.splice(e,0,make_node(Ie,i,{definitions:n}))}return r.map(e=>e.clone(true))}});def_optimize(Xe,function(e,t){if(t.option("unsafe")&&is_undeclared_ref(e.expression)&&["Object","RegExp","Function","Error","Array"].includes(e.expression.name))return make_node(Ge,e,e).transform(t);return e});def_optimize(He,function(e,t){if(!t.option("side_effects"))return e;var n=[];filter_for_side_effects();var i=n.length-1;trim_right_for_undefined();if(i==0){e=maintain_this_binding(t.parent(),t.self(),n[0]);if(!(e instanceof He))e=e.optimize(t);return e}e.expressions=n;return e;function filter_for_side_effects(){var i=first_in_statement(t);var r=e.expressions.length-1;e.expressions.forEach(function(e,a){if(a0&&is_undefined(n[i],t))i--;if(i0){var n=this.clone();n.right=make_sequence(this.right,t.slice(a));t=t.slice(0,a);t.push(n);return make_sequence(this,t).optimize(e)}}}return this});var Qn=makePredicate("== === != !== * & | ^");function is_object(e){return e instanceof rt||e instanceof ue||e instanceof at||e instanceof ht}def_optimize(et,function(e,t){function reversible(){return e.left.is_constant()||e.right.is_constant()||!e.left.has_side_effects(t)&&!e.right.has_side_effects(t)}function reverse(t){if(reversible()){if(t)e.operator=t;var n=e.left;e.left=e.right;e.right=n}}if(Qn.has(e.operator)){if(e.right.is_constant()&&!e.left.is_constant()){if(!(e.left instanceof et&&N[e.left.operator]>=N[e.operator])){reverse()}}}e=e.lift_sequences(t);if(t.option("comparisons"))switch(e.operator){case"===":case"!==":var n=true;if(e.left.is_string(t)&&e.right.is_string(t)||e.left.is_number(t)&&e.right.is_number(t)||e.left.is_boolean()&&e.right.is_boolean()||e.left.equivalent_to(e.right)){e.operator=e.operator.substr(0,2)}case"==":case"!=":if(!n&&is_undefined(e.left,t)){e.left=make_node(jt,e.left)}else if(t.option("typeofs")&&e.left instanceof Xt&&e.left.value=="undefined"&&e.right instanceof Qe&&e.right.operator=="typeof"){var i=e.right.expression;if(i instanceof Lt?i.is_declared(t):!(i instanceof We&&t.option("ie8"))){e.right=i;e.left=make_node(Zt,e.left).optimize(t);if(e.operator.length==2)e.operator+="="}}else if(e.left instanceof Lt&&e.right instanceof Lt&&e.left.definition()===e.right.definition()&&is_object(e.left.fixed_value())){return make_node(e.operator[0]=="="?nn:tn,e)}break;case"&&":case"||":var r=e.left;if(r.operator==e.operator){r=r.right}if(r instanceof et&&r.operator==(e.operator=="&&"?"!==":"===")&&e.right instanceof et&&r.operator==e.right.operator&&(is_undefined(r.left,t)&&e.right.left instanceof jt||r.left instanceof jt&&is_undefined(e.right.left,t))&&!r.right.has_side_effects(t)&&r.right.equivalent_to(e.right.right)){var a=make_node(et,e,{operator:r.operator.slice(0,-1),left:make_node(jt,e),right:r.right});if(r!==e.left){a=make_node(et,e,{operator:e.operator,left:e.left.left,right:a})}return a}break}if(e.operator=="+"&&t.in_boolean_context()){var o=e.left.evaluate(t);var s=e.right.evaluate(t);if(o&&typeof o=="string"){return make_sequence(e,[e.right,make_node(nn,e)]).optimize(t)}if(s&&typeof s=="string"){return make_sequence(e,[e.left,make_node(nn,e)]).optimize(t)}}if(t.option("comparisons")&&e.is_boolean()){if(!(t.parent()instanceof et)||t.parent()instanceof nt){var u=make_node(Qe,e,{operator:"!",expression:e.negate(t,first_in_statement(t))});e=best_of(t,e,u)}if(t.option("unsafe_comps")){switch(e.operator){case"<":reverse(">");break;case"<=":reverse(">=");break}}}if(e.operator=="+"){if(e.right instanceof Xt&&e.right.getValue()==""&&e.left.is_string(t)){return e.left}if(e.left instanceof Xt&&e.left.getValue()==""&&e.right.is_string(t)){return e.right}if(e.left instanceof et&&e.left.operator=="+"&&e.left.left instanceof Xt&&e.left.left.getValue()==""&&e.right.is_string(t)){e.left=e.left.right;return e}}if(t.option("evaluate")){switch(e.operator){case"&&":var o=Bn(e.left,xn)?true:Bn(e.left,Fn)?false:e.left.evaluate(t);if(!o){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}else if(!(o instanceof z)){return make_sequence(e,[e.left,e.right]).optimize(t)}var s=e.right.evaluate(t);if(!s){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(tn,e)]).optimize(t)}else{Vn(e,Fn)}}else if(!(s instanceof z)){var c=t.parent();if(c.operator=="&&"&&c.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}if(e.left.operator=="||"){var l=e.left.right.evaluate(t);if(!l)return make_node(tt,e,{condition:e.left.left,consequent:e.right,alternative:e.left.right}).optimize(t)}break;case"||":var o=Bn(e.left,xn)?true:Bn(e.left,Fn)?false:e.left.evaluate(t);if(!o){return make_sequence(e,[e.left,e.right]).optimize(t)}else if(!(o instanceof z)){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}var s=e.right.evaluate(t);if(!s){var c=t.parent();if(c.operator=="||"&&c.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}else if(!(s instanceof z)){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(nn,e)]).optimize(t)}else{Vn(e,xn)}}if(e.left.operator=="&&"){var l=e.left.right.evaluate(t);if(l&&!(l instanceof z))return make_node(tt,e,{condition:e.left.left,consequent:e.left.right,alternative:e.right}).optimize(t)}break;case"??":if(is_nullish(e.left,t)){return e.right}var o=e.left.evaluate(t);if(!(o instanceof z)){return o==null?e.right:e.left}if(t.in_boolean_context()){const n=e.right.evaluate(t);if(!(n instanceof z)&&!n){return e.left}}}var f=true;switch(e.operator){case"+":if(e.right instanceof Gt&&e.left instanceof et&&e.left.operator=="+"&&e.left.is_string(t)){var p=make_node(et,e,{operator:"+",left:e.left.right,right:e.right});var _=p.optimize(t);if(p!==_){e=make_node(et,e,{operator:"+",left:e.left.left,right:_})}}if(e.left instanceof et&&e.left.operator=="+"&&e.left.is_string(t)&&e.right instanceof et&&e.right.operator=="+"&&e.right.is_string(t)){var p=make_node(et,e,{operator:"+",left:e.left.right,right:e.right.left});var h=p.optimize(t);if(p!==h){e=make_node(et,e,{operator:"+",left:make_node(et,e.left,{operator:"+",left:e.left.left,right:h}),right:e.right.right})}}if(e.right instanceof Qe&&e.right.operator=="-"&&e.left.is_number(t)){e=make_node(et,e,{operator:"-",left:e.left,right:e.right.expression});break}if(e.left instanceof Qe&&e.left.operator=="-"&&reversible()&&e.right.is_number(t)){e=make_node(et,e,{operator:"-",left:e.right,right:e.left.expression});break}if(e.left instanceof de){var d=e.left;var _=e.right.evaluate(t);if(_!=e.right){d.segments[d.segments.length-1].value+=String(_);return d}}if(e.right instanceof de){var _=e.right;var d=e.left.evaluate(t);if(d!=e.left){_.segments[0].value=String(d)+_.segments[0].value;return _}}if(e.left instanceof de&&e.right instanceof de){var d=e.left;var m=d.segments;var _=e.right;m[m.length-1].value+=_.segments[0].value;for(var E=1;E<_.segments.length;E++){m.push(_.segments[E])}return d}case"*":f=t.option("unsafe_math");case"&":case"|":case"^":if(e.left.is_number(t)&&e.right.is_number(t)&&reversible()&&!(e.left instanceof et&&e.left.operator!=e.operator&&N[e.left.operator]>=N[e.operator])){var g=make_node(et,e,{operator:e.operator,left:e.right,right:e.left});if(e.right instanceof Gt&&!(e.left instanceof Gt)){e=best_of(t,g,e)}else{e=best_of(t,e,g)}}if(f&&e.is_number(t)){if(e.right instanceof et&&e.right.operator==e.operator){e=make_node(et,e,{operator:e.operator,left:make_node(et,e.left,{operator:e.operator,left:e.left,right:e.right.left,start:e.left.start,end:e.right.left.end}),right:e.right.right})}if(e.right instanceof Gt&&e.left instanceof et&&e.left.operator==e.operator){if(e.left.left instanceof Gt){e=make_node(et,e,{operator:e.operator,left:make_node(et,e.left,{operator:e.operator,left:e.left.left,right:e.right,start:e.left.left.start,end:e.right.end}),right:e.left.right})}else if(e.left.right instanceof Gt){e=make_node(et,e,{operator:e.operator,left:make_node(et,e.left,{operator:e.operator,left:e.left.right,right:e.right,start:e.left.right.start,end:e.right.end}),right:e.left.left})}}if(e.left instanceof et&&e.left.operator==e.operator&&e.left.right instanceof Gt&&e.right instanceof et&&e.right.operator==e.operator&&e.right.left instanceof Gt){e=make_node(et,e,{operator:e.operator,left:make_node(et,e.left,{operator:e.operator,left:make_node(et,e.left.left,{operator:e.operator,left:e.left.right,right:e.right.left,start:e.left.right.start,end:e.right.left.end}),right:e.left.left}),right:e.right.right})}}}}if(e.right instanceof et&&e.right.operator==e.operator&&(Gn.has(e.operator)||e.operator=="+"&&(e.right.left.is_string(t)||e.left.is_string(t)&&e.right.right.is_string(t)))){e.left=make_node(et,e.left,{operator:e.operator,left:e.left.transform(t),right:e.right.left.transform(t)});e.right=e.right.right.transform(t);return e.transform(t)}var v=e.evaluate(t);if(v!==e){v=make_node_from_constant(v,e).optimize(t);return best_of(t,v,e)}return e});def_optimize(Bt,function(e){return e});function recursive_ref(e,t){var n;for(var i=0;n=e.parent(i);i++){if(n instanceof ue||n instanceof ht){var r=n.name;if(r&&r.definition()===t)break}}return n}function within_array_or_object_literal(e){var t,n=0;while(t=e.parent(n++)){if(t instanceof K)return false;if(t instanceof rt||t instanceof st||t instanceof at){return true}}return false}def_optimize(Lt,function(e,t){if(!t.option("ie8")&&is_undeclared_ref(e)&&!t.find_parent(re)){switch(e.name){case"undefined":return make_node(Zt,e).optimize(t);case"NaN":return make_node($t,e).optimize(t);case"Infinity":return make_node(Jt,e).optimize(t)}}const n=t.parent();if(t.option("reduce_vars")&&is_lhs(e,n)!==e){const a=e.definition();const o=find_scope(t);if(t.top_retain&&a.global&&t.top_retain(a)){a.fixed=false;a.single_use=false;return e}let s=e.fixed_value();let u=a.single_use&&!(n instanceof Ge&&n.is_callee_pure(t)||has_annotation(n,sn))&&!(n instanceof Ke&&s instanceof ue&&s.name);if(u&&s instanceof z){u=!s.has_side_effects(t)&&!s.may_throw(t)}if(u&&(s instanceof ue||s instanceof ht)){if(retain_top_func(s,t)){u=false}else if(a.scope!==e.scope&&(a.escaped==1||Bn(s,wn)||within_array_or_object_literal(t)||!t.option("reduce_funcs"))){u=false}else if(recursive_ref(t,a)){u=false}else if(a.scope!==e.scope||a.orig[0]instanceof At){u=s.is_constant_expression(e.scope);if(u=="f"){var i=e.scope;do{if(i instanceof pe||is_func_expr(i)){Vn(i,wn)}}while(i=i.parent_scope)}}}if(u&&s instanceof ue){u=a.scope===e.scope&&!scope_encloses_variables_in_this_scope(o,s)||n instanceof Ge&&n.expression===e&&!scope_encloses_variables_in_this_scope(o,s)&&!(s.name&&s.name.definition().recursive_refs>0)}if(u&&s){if(s instanceof Et){Vn(s,Nn);s=make_node(gt,s,s)}if(s instanceof pe){Vn(s,Nn);s=make_node(le,s,s)}if(a.recursive_refs>0&&s.name instanceof Ct){const e=s.name.definition();let t=s.variables.get(s.name.name);let n=t&&t.orig[0];if(!(n instanceof Ft)){n=make_node(Ft,s.name,s.name);n.scope=s;s.name=n;t=s.def_function(n)}walk(s,n=>{if(n instanceof Lt&&n.definition()===e){n.thedef=t;t.references.push(n)}})}if((s instanceof ue||s instanceof ht)&&s.parent_scope!==o){s=s.clone(true,t.get_toplevel());o.add_child_scope(s)}return s.optimize(t)}if(s){let n;if(s instanceof zt){if(!(a.orig[0]instanceof At)&&a.references.every(e=>a.scope===e.scope)){n=s}}else{var r=s.evaluate(t);if(r!==s&&(t.option("unsafe_regexp")||!(r instanceof RegExp))){n=make_node_from_constant(r,s)}}if(n){const i=e.size(t);const r=n.size(t);let o=0;if(t.option("unused")&&!t.exposed(a)){o=(i+2+r)/(a.references.length-a.assignments)}if(r<=i+o){return n}}}}return e});function scope_encloses_variables_in_this_scope(e,t){for(const n of t.enclosed){if(t.variables.has(n.name)){continue}const i=e.find_variable(n.name);if(i){if(i===n)continue;return true}}return false}function is_atomic(e,t){return e instanceof Lt||e.TYPE===t.TYPE}def_optimize(Zt,function(e,t){if(t.option("unsafe_undefined")){var n=find_variable(t,"undefined");if(n){var i=make_node(Lt,e,{name:"undefined",scope:n.scope,thedef:n});Vn(i,On);return i}}var r=is_lhs(t.self(),t.parent());if(r&&is_atomic(r,e))return e;return make_node(Qe,e,{operator:"void",expression:make_node(Ht,e,{value:0})})});def_optimize(Jt,function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&is_atomic(n,e))return e;if(t.option("keep_infinity")&&!(n&&!is_atomic(n,e))&&!find_variable(t,"Infinity")){return e}return make_node(et,e,{operator:"/",left:make_node(Ht,e,{value:1}),right:make_node(Ht,e,{value:0})})});def_optimize($t,function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&!is_atomic(n,e)||find_variable(t,"NaN")){return make_node(et,e,{operator:"/",left:make_node(Ht,e,{value:0}),right:make_node(Ht,e,{value:0})})}return e});function is_reachable(e,t){const n=e=>{if(e instanceof Lt&&member(e.definition(),t)){return rn}};return walk_parent(e,(t,i)=>{if(t instanceof ae&&t!==e){var r=i.parent();if(r instanceof Ge&&r.expression===t)return;if(walk(t,n))return rn;return true}})}const Jn=makePredicate("+ - / * % >> << >>> | ^ &");const ei=makePredicate("* | ^ &");def_optimize(nt,function(e,t){if(e.logical){return e.lift_sequences(t)}var n;if(t.option("dead_code")&&e.left instanceof Lt&&(n=e.left.definition()).scope===t.find_parent(ue)){var i=0,r,a=e;do{r=a;a=t.parent(i++);if(a instanceof ge){if(in_try(i,a))break;if(is_reachable(n.scope,[n]))break;if(e.operator=="=")return e.right;n.fixed=false;return make_node(et,e,{operator:e.operator.slice(0,-1),left:e.left,right:e.right}).optimize(t)}}while(a instanceof et&&a.right===r||a instanceof He&&a.tail_node()===r)}e=e.lift_sequences(t);if(e.operator=="="&&e.left instanceof Lt&&e.right instanceof et){if(e.right.left instanceof Lt&&e.right.left.name==e.left.name&&Jn.has(e.right.operator)){e.operator=e.right.operator+"=";e.right=e.right.right}else if(e.right.right instanceof Lt&&e.right.right.name==e.left.name&&ei.has(e.right.operator)&&!e.right.left.has_side_effects(t)){e.operator=e.right.operator+"=";e.right=e.right.left}}return e;function in_try(n,i){var r=e.right;e.right=make_node(jt,r);var a=i.may_throw(t);e.right=r;var o=e.left.definition().scope;var s;while((s=t.parent(n++))!==o){if(s instanceof Oe){if(s.bfinally)return true;if(a&&s.bcatch)return true}}}});def_optimize(it,function(e,t){if(!t.option("evaluate")){return e}var n=e.right.evaluate(t);if(n===undefined){e=e.left}else if(n!==e.right){n=make_node_from_constant(n,e.right);e.right=best_of_expression(n,e.right)}return e});function is_nullish(e,t){let n;return e instanceof jt||is_undefined(e,t)||e instanceof Lt&&(n=e.definition().fixed)instanceof z&&is_nullish(n,t)||e instanceof We&&e.optional&&is_nullish(e.expression,t)||e instanceof Ge&&e.optional&&is_nullish(e.expression,t)||e instanceof $e&&is_nullish(e.expression,t)}function is_nullish_check(e,t,n){if(t.may_throw(n))return false;let i;if(e instanceof et&&e.operator==="=="&&((i=is_nullish(e.left,n)&&e.left)||(i=is_nullish(e.right,n)&&e.right))&&(i===e.left?e.right:e.left).equivalent_to(t)){return true}if(e instanceof et&&e.operator==="||"){let i;let r;const a=e=>{if(!(e instanceof et&&(e.operator==="==="||e.operator==="=="))){return false}let a=0;let o;if(e.left instanceof jt){a++;i=e;o=e.right}if(e.right instanceof jt){a++;i=e;o=e.left}if(is_undefined(e.left,n)){a++;r=e;o=e.right}if(is_undefined(e.right,n)){a++;r=e;o=e.left}if(a!==1){return false}if(!o.equivalent_to(t)){return false}return true};if(!a(e.left))return false;if(!a(e.right))return false;if(i&&r&&i!==r){return true}}return false}def_optimize(tt,function(e,t){if(!t.option("conditionals"))return e;if(e.condition instanceof He){var n=e.condition.expressions.slice();e.condition=n.pop();n.push(e);return make_sequence(e,n)}var i=e.condition.evaluate(t);if(i!==e.condition){if(i){return maintain_this_binding(t.parent(),t.self(),e.consequent)}else{return maintain_this_binding(t.parent(),t.self(),e.alternative)}}var r=i.negate(t,first_in_statement(t));if(best_of(t,i,r)===r){e=make_node(tt,e,{condition:r,consequent:e.alternative,alternative:e.consequent})}var a=e.condition;var o=e.consequent;var s=e.alternative;if(a instanceof Lt&&o instanceof Lt&&a.definition()===o.definition()){return make_node(et,e,{operator:"||",left:a,right:s})}if(o instanceof nt&&s instanceof nt&&o.operator===s.operator&&o.logical===s.logical&&o.left.equivalent_to(s.left)&&(!e.condition.has_side_effects(t)||o.operator=="="&&!o.left.has_side_effects(t))){return make_node(nt,e,{operator:o.operator,left:o.left,logical:o.logical,right:make_node(tt,e,{condition:e.condition,consequent:o.right,alternative:s.right})})}var u;if(o instanceof Ge&&s.TYPE===o.TYPE&&o.args.length>0&&o.args.length==s.args.length&&o.expression.equivalent_to(s.expression)&&!e.condition.has_side_effects(t)&&!o.expression.has_side_effects(t)&&typeof(u=single_arg_diff())=="number"){var c=o.clone();c.args[u]=make_node(tt,e,{condition:e.condition,consequent:o.args[u],alternative:s.args[u]});return c}if(s instanceof tt&&o.equivalent_to(s.consequent)){return make_node(tt,e,{condition:make_node(et,e,{operator:"||",left:a,right:s.condition}),consequent:o,alternative:s.alternative}).optimize(t)}if(t.option("ecma")>=2020&&is_nullish_check(a,s,t)){return make_node(et,e,{operator:"??",left:s,right:o}).optimize(t)}if(s instanceof He&&o.equivalent_to(s.expressions[s.expressions.length-1])){return make_sequence(e,[make_node(et,e,{operator:"||",left:a,right:make_sequence(e,s.expressions.slice(0,-1))}),o]).optimize(t)}if(s instanceof et&&s.operator=="&&"&&o.equivalent_to(s.right)){return make_node(et,e,{operator:"&&",left:make_node(et,e,{operator:"||",left:a,right:s.left}),right:o}).optimize(t)}if(o instanceof tt&&o.alternative.equivalent_to(s)){return make_node(tt,e,{condition:make_node(et,e,{left:e.condition,operator:"&&",right:o.condition}),consequent:o.consequent,alternative:s})}if(o.equivalent_to(s)){return make_sequence(e,[e.condition,o]).optimize(t)}if(o instanceof et&&o.operator=="||"&&o.right.equivalent_to(s)){return make_node(et,e,{operator:"||",left:make_node(et,e,{operator:"&&",left:e.condition,right:o.left}),right:s}).optimize(t)}var l=t.in_boolean_context();if(is_true(e.consequent)){if(is_false(e.alternative)){return booleanize(e.condition)}return make_node(et,e,{operator:"||",left:booleanize(e.condition),right:e.alternative})}if(is_false(e.consequent)){if(is_true(e.alternative)){return booleanize(e.condition.negate(t))}return make_node(et,e,{operator:"&&",left:booleanize(e.condition.negate(t)),right:e.alternative})}if(is_true(e.alternative)){return make_node(et,e,{operator:"||",left:booleanize(e.condition.negate(t)),right:e.consequent})}if(is_false(e.alternative)){return make_node(et,e,{operator:"&&",left:booleanize(e.condition),right:e.consequent})}return e;function booleanize(e){if(e.is_boolean())return e;return make_node(Qe,e,{operator:"!",expression:e.negate(t)})}function is_true(e){return e instanceof nn||l&&e instanceof Gt&&e.getValue()||e instanceof Qe&&e.operator=="!"&&e.expression instanceof Gt&&!e.expression.getValue()}function is_false(e){return e instanceof tn||l&&e instanceof Gt&&!e.getValue()||e instanceof Qe&&e.operator=="!"&&e.expression instanceof Gt&&e.expression.getValue()}function single_arg_diff(){var e=o.args;var t=s.args;for(var n=0,i=e.length;n=2015;var i=this.expression;if(i instanceof at){var r=i.properties;for(var a=r.length;--a>=0;){var o=r[a];if(""+(o instanceof pt?o.key.name:o.key)==e){const e=r.every(e=>(e instanceof st||n&&e instanceof pt&&!e.is_generator)&&!e.computed_key());if(!e)return;if(!safe_to_flatten(o.value,t))return;return make_node(je,this,{expression:make_node(rt,i,{elements:r.map(function(e){var t=e.value;if(t instanceof ce){t=make_node(le,t,t)}var n=e.key;if(n instanceof z&&!(n instanceof Rt)){return make_sequence(e,[n,t])}return t})}),property:make_node(Ht,this,{value:a})})}}}});def_optimize(je,function(e,t){var n=e.expression;var i=e.property;if(t.option("properties")){var r=i.evaluate(t);if(r!==i){if(typeof r=="string"){if(r=="undefined"){r=undefined}else{var a=parseFloat(r);if(a.toString()==r){r=a}}}i=e.property=best_of_expression(i,make_node_from_constant(r,i).transform(t));var o=""+r;if(is_basic_identifier_string(o)&&o.length<=i.size()+1){return make_node(qe,e,{expression:n,optional:e.optional,property:o,quote:i.quote}).optimize(t)}}}var s;e:if(t.option("arguments")&&n instanceof Lt&&n.name=="arguments"&&n.definition().orig.length==1&&(s=n.scope)instanceof ue&&s.uses_arguments&&!(s instanceof fe)&&i instanceof Ht){var u=i.getValue();var c=new Set;var l=s.argnames;for(var f=0;f1){_=null}}else if(!_&&!t.option("keep_fargs")&&u=s.argnames.length){_=s.create_symbol(At,{source:s,scope:s,tentative_name:"argument_"+s.argnames.length});s.argnames.push(_)}}if(_){var d=make_node(Lt,e,_);d.reference({});Un(_,Rn);return d}}if(is_lhs(e,t.parent()))return e;if(r!==i){var m=e.flatten_object(o,t);if(m){n=e.expression=m.expression;i=e.property=m.property}}if(t.option("properties")&&t.option("side_effects")&&i instanceof Ht&&n instanceof rt){var u=i.getValue();var E=n.elements;var g=E[u];e:if(safe_to_flatten(g,t)){var v=true;var D=[];for(var b=E.length;--b>u;){var a=E[b].drop_side_effect_free(t);if(a){D.unshift(a);if(v&&a.has_side_effects(t))v=false}}if(g instanceof se)break e;g=g instanceof Qt?make_node(Zt,g):g;if(!v)D.unshift(g);while(--b>=0){var a=E[b];if(a instanceof se)break e;a=a.drop_side_effect_free(t);if(a)D.unshift(a);else u--}if(v){D.push(g);return make_sequence(e,D).optimize(t)}else return make_node(je,e,{expression:make_node(rt,n,{elements:D}),property:make_node(Ht,i,{value:u})})}}var y=e.evaluate(t);if(y!==e){y=make_node_from_constant(y,e).optimize(t);return best_of(t,y,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node(Zt,e)}return e});def_optimize($e,function(e,t){e.expression=e.expression.optimize(t);return e});ue.DEFMETHOD("contains_this",function(){return walk(this,e=>{if(e instanceof zt)return rn;if(e!==this&&e instanceof ae&&!(e instanceof fe)){return true}})});def_optimize(qe,function(e,t){const n=t.parent();if(is_lhs(e,n))return e;if(t.option("unsafe_proto")&&e.expression instanceof qe&&e.expression.property=="prototype"){var i=e.expression.expression;if(is_undeclared_ref(i))switch(i.name){case"Array":e.expression=make_node(rt,e.expression,{elements:[]});break;case"Function":e.expression=make_node(le,e.expression,{argnames:[],body:[]});break;case"Number":e.expression=make_node(Ht,e.expression,{value:0});break;case"Object":e.expression=make_node(at,e.expression,{properties:[]});break;case"RegExp":e.expression=make_node(qt,e.expression,{value:{source:"t",flags:""}});break;case"String":e.expression=make_node(Xt,e.expression,{value:""});break}}if(!(n instanceof Ge)||!has_annotation(n,sn)){const n=e.flatten_object(e.property,t);if(n)return n.optimize(t)}let r=e.evaluate(t);if(r!==e){r=make_node_from_constant(r,e).optimize(t);return best_of(t,r,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node(Zt,e)}return e});function literals_in_boolean_context(e,t){if(t.in_boolean_context()){return best_of(t,e,make_sequence(e,[e,make_node(nn,e)]).optimize(t))}return e}function inline_array_like_spread(e){for(var t=0;te instanceof Qt)){e.splice(t,1,...i.elements);t--}}}}def_optimize(rt,function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_array_like_spread(e.elements);return e});function inline_object_prop_spread(e,t){for(var n=0;ne instanceof st)){e.splice(n,1,...r.properties);n--}else if(r instanceof Gt&&!(r instanceof Xt)){e.splice(n,1)}else if(is_nullish(r,t)){e.splice(n,1)}}}}def_optimize(at,function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_object_prop_spread(e.properties,t);return e});def_optimize(qt,literals_in_boolean_context);def_optimize(ve,function(e,t){if(e.value&&is_undefined(e.value,t)){e.value=null}return e});def_optimize(fe,opt_AST_Lambda);def_optimize(le,function(e,t){e=opt_AST_Lambda(e,t);if(t.option("unsafe_arrows")&&t.option("ecma")>=2015&&!e.name&&!e.is_generator&&!e.uses_arguments&&!e.pinned()){const n=walk(e,e=>{if(e instanceof zt)return rn});if(!n)return make_node(fe,e,e).optimize(t)}return e});def_optimize(ht,function(e){return e});def_optimize(Te,function(e,t){if(e.expression&&!e.is_star&&is_undefined(e.expression,t)){e.expression=null}return e});def_optimize(de,function(e,t){if(!t.option("evaluate")||t.parent()instanceof he){return e}var n=[];for(var i=0;i=2015&&(!(n instanceof RegExp)||n.test(e.key+""))){var i=e.key;var r=e.value;var a=r instanceof fe&&Array.isArray(r.body)&&!r.contains_this();if((a||r instanceof le)&&!r.name){return make_node(pt,e,{async:r.async,is_generator:r.is_generator,key:i instanceof z?i:make_node(Rt,e,{name:i}),value:make_node(ce,r,r),quote:e.quote})}}return e});def_optimize(_e,function(e,t){if(t.option("pure_getters")==true&&t.option("unused")&&!e.is_array&&Array.isArray(e.names)&&!is_destructuring_export_decl(t)&&!(e.names[e.names.length-1]instanceof se)){var n=[];for(var i=0;i1)throw new Error("inline source map only works with singular input");t.sourceMap.content=read_source_map(e[a])}}}r=t.parse.toplevel}if(i&&t.mangle.properties.keep_quoted!=="strict"){reserve_quoted_keys(r,i)}if(t.wrap){r=r.wrap_commonjs(t.wrap)}if(t.enclose){r=r.wrap_enclose(t.enclose)}if(n)n.rename=Date.now();if(n)n.compress=Date.now();if(t.compress){r=new Compressor(t.compress,{mangle_options:t.mangle}).compress(r)}if(n)n.scope=Date.now();if(t.mangle)r.figure_out_scope(t.mangle);if(n)n.mangle=Date.now();if(t.mangle){bn.reset();r.compute_char_frequency(t.mangle);r.mangle_names(t.mangle)}if(n)n.properties=Date.now();if(t.mangle&&t.mangle.properties){r=mangle_properties(r,t.mangle.properties)}if(n)n.format=Date.now();var o={};if(t.format.ast){o.ast=r}if(t.format.spidermonkey){o.ast=r.to_mozilla_ast()}if(!HOP(t.format,"code")||t.format.code){if(t.sourceMap){t.format.source_map=await SourceMap({file:t.sourceMap.filename,orig:t.sourceMap.content,root:t.sourceMap.root});if(t.sourceMap.includeSources){if(e instanceof oe){throw new Error("original source content unavailable")}else for(var a in e)if(HOP(e,a)){t.format.source_map.get().setSourceContent(a,e[a])}}}delete t.format.ast;delete t.format.code;delete t.format.spidermonkey;var s=OutputStream(t.format);r.print(s);o.code=s.get();if(t.sourceMap){if(t.sourceMap.asObject){o.map=t.format.source_map.get().toJSON()}else{o.map=t.format.source_map.toString()}if(t.sourceMap.url=="inline"){var u=typeof o.map==="object"?JSON.stringify(o.map):o.map;o.code+="\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+ii(u)}else if(t.sourceMap.url){o.code+="\n//# sourceMappingURL="+t.sourceMap.url}}}if(t.nameCache&&t.mangle){if(t.mangle.cache)t.nameCache.vars=cache_to_json(t.mangle.cache);if(t.mangle.properties&&t.mangle.properties.cache){t.nameCache.props=cache_to_json(t.mangle.properties.cache)}}if(t.format&&t.format.source_map){t.format.source_map.destroy()}if(n){n.end=Date.now();o.timings={parse:.001*(n.rename-n.parse),rename:.001*(n.compress-n.rename),compress:.001*(n.scope-n.compress),scope:.001*(n.mangle-n.scope),mangle:.001*(n.properties-n.mangle),properties:.001*(n.format-n.properties),format:.001*(n.end-n.format),total:.001*(n.end-n.start)}}return o}async function run_cli({program:e,packageJson:t,fs:i,path:r}){const a=new Set(["cname","parent_scope","scope","uses_eval","uses_with"]);var o={};var s={compress:false,mangle:false};const u=await _default_options();e.version(t.name+" "+t.version);e.parseArgv=e.parse;e.parse=undefined;if(process.argv.includes("ast"))e.helpInformation=describe_ast;else if(process.argv.includes("options"))e.helpInformation=function(){var e=[];for(var t in u){e.push("--"+(t==="sourceMap"?"source-map":t)+" options:");e.push(format_object(u[t]));e.push("")}return e.join("\n")};e.option("-p, --parse ","Specify parser options.",parse_js());e.option("-c, --compress [options]","Enable compressor/specify compressor options.",parse_js());e.option("-m, --mangle [options]","Mangle names/specify mangler options.",parse_js());e.option("--mangle-props [options]","Mangle properties/specify mangler options.",parse_js());e.option("-f, --format [options]","Format options.",parse_js());e.option("-b, --beautify [options]","Alias for --format.",parse_js());e.option("-o, --output ","Output file (default STDOUT).");e.option("--comments [filter]","Preserve copyright comments in the output.");e.option("--config-file ","Read minify() options from JSON file.");e.option("-d, --define [=value]","Global definitions.",parse_js("define"));e.option("--ecma ","Specify ECMAScript release: 5, 2015, 2016 or 2017...");e.option("-e, --enclose [arg[,...][:value[,...]]]","Embed output in a big function with configurable arguments and values.");e.option("--ie8","Support non-standard Internet Explorer 8.");e.option("--keep-classnames","Do not mangle/drop class names.");e.option("--keep-fnames","Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");e.option("--module","Input is an ES6 module");e.option("--name-cache ","File to hold mangled name mappings.");e.option("--rename","Force symbol expansion.");e.option("--no-rename","Disable symbol expansion.");e.option("--safari10","Support non-standard Safari 10.");e.option("--source-map [options]","Enable source map/specify source map options.",parse_js());e.option("--timings","Display operations run time on STDERR.");e.option("--toplevel","Compress and/or mangle variables in toplevel scope.");e.option("--wrap ","Embed everything as a function with “exports” corresponding to “name” globally.");e.arguments("[files...]").parseArgv(process.argv);if(e.configFile){s=JSON.parse(read_file(e.configFile))}if(!e.output&&e.sourceMap&&e.sourceMap.url!="inline"){fatal("ERROR: cannot write source map to STDOUT")}["compress","enclose","ie8","mangle","module","safari10","sourceMap","toplevel","wrap"].forEach(function(t){if(t in e){s[t]=e[t]}});if("ecma"in e){if(e.ecma!=(e.ecma|0))fatal("ERROR: ecma must be an integer");const t=e.ecma|0;if(t>5&&t<2015)s.ecma=t+2009;else s.ecma=t}if(e.format||e.beautify){const t=e.format||e.beautify;s.format=typeof t==="object"?t:{}}if(e.comments){if(typeof s.format!="object")s.format={};s.format.comments=typeof e.comments=="string"?e.comments=="false"?false:e.comments:"some"}if(e.define){if(typeof s.compress!="object")s.compress={};if(typeof s.compress.global_defs!="object")s.compress.global_defs={};for(var c in e.define){s.compress.global_defs[c]=e.define[c]}}if(e.keepClassnames){s.keep_classnames=true}if(e.keepFnames){s.keep_fnames=true}if(e.mangleProps){if(e.mangleProps.domprops){delete e.mangleProps.domprops}else{if(typeof e.mangleProps!="object")e.mangleProps={};if(!Array.isArray(e.mangleProps.reserved))e.mangleProps.reserved=[]}if(typeof s.mangle!="object")s.mangle={};s.mangle.properties=e.mangleProps}if(e.nameCache){s.nameCache=JSON.parse(read_file(e.nameCache,"{}"))}if(e.output=="ast"){s.format={ast:true,code:false}}if(e.parse){if(!e.parse.acorn&&!e.parse.spidermonkey){s.parse=e.parse}else if(e.sourceMap&&e.sourceMap.content=="inline"){fatal("ERROR: inline source map only works with built-in parser")}}if(~e.rawArgs.indexOf("--rename")){s.rename=true}else if(!e.rename){s.rename=false}let l=e=>e;if(typeof e.sourceMap=="object"&&"base"in e.sourceMap){l=function(){var t=e.sourceMap.base;delete s.sourceMap.base;return function(e){return r.relative(t,e)}}()}let f;if(s.files&&s.files.length){f=s.files;delete s.files}else if(e.args.length){f=e.args}if(f){simple_glob(f).forEach(function(e){o[l(e)]=read_file(e)})}else{await new Promise(e=>{var t=[];process.stdin.setEncoding("utf8");process.stdin.on("data",function(e){t.push(e)}).on("end",function(){o=[t.join("")];e()});process.stdin.resume()})}await run_cli();function convert_ast(e){return z.from_mozilla_ast(Object.keys(o).reduce(e,null))}async function run_cli(){var t=e.sourceMap&&e.sourceMap.content;if(t&&t!=="inline"){s.sourceMap.content=read_file(t,t)}if(e.timings)s.timings=true;try{if(e.parse){if(e.parse.acorn){o=convert_ast(function(t,i){return n(89).parse(o[i],{ecmaVersion:2018,locations:true,program:t,sourceFile:i,sourceType:s.module||e.parse.module?"module":"script"})})}else if(e.parse.spidermonkey){o=convert_ast(function(e,t){var n=JSON.parse(o[t]);if(!e)return n;e.body=e.body.concat(n.body);return e})}}}catch(e){fatal(e)}let r;try{r=await minify(o,s)}catch(e){if(e.name=="SyntaxError"){print_error("Parse error at "+e.filename+":"+e.line+","+e.col);var u=e.col;var c=o[e.filename].split(/\r?\n/);var l=c[e.line-1];if(!l&&!u){l=c[e.line-2];u=l.length}if(l){var f=70;if(u>f){l=l.slice(u-f);u=f}print_error(l.slice(0,80));print_error(l.slice(0,u).replace(/\S/g," ")+"^")}}if(e.defs){print_error("Supported options:");print_error(format_object(e.defs))}fatal(e);return}if(e.output=="ast"){if(!s.compress&&!s.mangle){r.ast.figure_out_scope({})}console.log(JSON.stringify(r.ast,function(e,t){if(t)switch(e){case"thedef":return symdef(t);case"enclosed":return t.length?t.map(symdef):undefined;case"variables":case"globals":return t.size?collect_from_map(t,symdef):undefined}if(a.has(e))return;if(t instanceof AST_Token)return;if(t instanceof Map)return;if(t instanceof z){var n={_class:"AST_"+t.TYPE};if(t.block_scope){n.variables=t.block_scope.variables;n.enclosed=t.block_scope.enclosed}t.CTOR.PROPS.forEach(function(e){n[e]=t[e]});return n}return t},2))}else if(e.output=="spidermonkey"){try{const e=await minify(r.code,{compress:false,mangle:false,format:{ast:true,code:false}});console.log(JSON.stringify(e.ast.to_mozilla_ast(),null,2))}catch(e){fatal(e);return}}else if(e.output){i.writeFileSync(e.output,r.code);if(s.sourceMap&&s.sourceMap.url!=="inline"&&r.map){i.writeFileSync(e.output+".map",r.map)}}else{console.log(r.code)}if(e.nameCache){i.writeFileSync(e.nameCache,JSON.stringify(s.nameCache))}if(r.timings)for(var p in r.timings){print_error("- "+p+": "+r.timings[p].toFixed(3)+"s")}}function fatal(e){if(e instanceof Error)e=e.stack.replace(/^\S*?Error:/,"ERROR:");print_error(e);process.exit(1)}function simple_glob(e){if(Array.isArray(e)){return[].concat.apply([],e.map(simple_glob))}if(e&&e.match(/[*?]/)){var t=r.dirname(e);try{var n=i.readdirSync(t)}catch(e){}if(n){var a="^"+r.basename(e).replace(/[.+^$[\]\\(){}]/g,"\\$&").replace(/\*/g,"[^/\\\\]*").replace(/\?/g,"[^/\\\\]")+"$";var o=process.platform==="win32"?"i":"";var s=new RegExp(a,o);var u=n.filter(function(e){return s.test(e)}).map(function(e){return r.join(t,e)});if(u.length)return u}}return[e]}function read_file(e,t){try{return i.readFileSync(e,"utf8")}catch(e){if((e.code=="ENOENT"||e.code=="ENAMETOOLONG")&&t!=null)return t;fatal(e)}}function parse_js(e){return function(t,n){n=n||{};try{walk(parse(t,{expression:true}),t=>{if(t instanceof nt){var i=t.left.print_to_string();var r=t.right;if(e){n[i]=r}else if(r instanceof rt){n[i]=r.elements.map(to_string)}else if(r instanceof qt){r=r.value;n[i]=new RegExp(r.source,r.flags)}else{n[i]=to_string(r)}return true}if(t instanceof vt||t instanceof We){var i=t.print_to_string();n[i]=true;return true}if(!(t instanceof He))throw t;function to_string(e){return e instanceof Gt?e.getValue():e.print_to_string({quote_keys:true})}})}catch(i){if(e){fatal("Error parsing arguments for '"+e+"': "+t)}else{n[t]=null}}return n}}function symdef(e){var t=1e6+e.id+" "+e.name;if(e.mangled_name)t+=" "+e.mangled_name;return t}function collect_from_map(e,t){var n=[];e.forEach(function(e){n.push(t(e))});return n}function format_object(e){var t=[];var n="";Object.keys(e).map(function(t){if(n.length!/^\$/.test(e));if(n.length>0){e.space();e.with_parens(function(){n.forEach(function(t,n){if(n)e.space();e.print(t)})})}if(t.documentation){e.space();e.print_string(t.documentation)}if(t.SUBCLASSES.length>0){e.space();e.with_block(function(){t.SUBCLASSES.forEach(function(t){e.indent();doitem(t);e.newline()})})}}doitem(z);return e+"\n"}}async function _default_options(){const e={};Object.keys(infer_options({0:0})).forEach(t=>{const n=infer_options({[t]:{0:0}});if(n)e[t]=n});return e}async function infer_options(e){try{await minify("",e)}catch(e){return e.defs}}e._default_options=_default_options;e._run_cli=run_cli;e.minify=minify})},241:e=>{"use strict";e.exports=require("next/dist/compiled/source-map")}};var t={};function __nccwpck_require__(n){if(t[n]){return t[n].exports}var i=t[n]={exports:{}};var r=true;try{e[n].call(i.exports,i,i.exports,__nccwpck_require__);r=false}finally{if(r)delete t[n]}return i.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(633)})(); \ No newline at end of file +module.exports=(()=>{var e={89:function(e,t){(function(e,n){true?n(t):0})(this,function(e){"use strict";var t={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"};var n="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 i={5:n,"5module":n+" export import",6:n+" const class extends export import super"};var r=/^in(stanceof)?$/;var a="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var o="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var s=new RegExp("["+a+"]");var u=new RegExp("["+a+o+"]");a=o=null;var c=[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];var l=[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];function isInAstralSet(e,t){var n=65536;for(var i=0;ie){return false}n+=t[i+1];if(n>=e){return true}}}function isIdentifierStart(e,t){if(e<65){return e===36}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&s.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,c)}function isIdentifierChar(e,t){if(e<48){return e===36}if(e<58){return true}if(e<65){return false}if(e<91){return true}if(e<97){return e===95}if(e<123){return true}if(e<=65535){return e>=170&&u.test(String.fromCharCode(e))}if(t===false){return false}return isInAstralSet(e,c)||isInAstralSet(e,l)}var f=function TokenType(e,t){if(t===void 0)t={};this.label=e;this.keyword=t.keyword;this.beforeExpr=!!t.beforeExpr;this.startsExpr=!!t.startsExpr;this.isLoop=!!t.isLoop;this.isAssign=!!t.isAssign;this.prefix=!!t.prefix;this.postfix=!!t.postfix;this.binop=t.binop||null;this.updateContext=null};function binop(e,t){return new f(e,{beforeExpr:true,binop:t})}var p={beforeExpr:true},_={startsExpr:true};var h={};function kw(e,t){if(t===void 0)t={};t.keyword=e;return h[e]=new f(e,t)}var d={num:new f("num",_),regexp:new f("regexp",_),string:new f("string",_),name:new f("name",_),privateId:new f("privateId",_),eof:new f("eof"),bracketL:new f("[",{beforeExpr:true,startsExpr:true}),bracketR:new f("]"),braceL:new f("{",{beforeExpr:true,startsExpr:true}),braceR:new f("}"),parenL:new f("(",{beforeExpr:true,startsExpr:true}),parenR:new f(")"),comma:new f(",",p),semi:new f(";",p),colon:new f(":",p),dot:new f("."),question:new f("?",p),questionDot:new f("?."),arrow:new f("=>",p),template:new f("template"),invalidTemplate:new f("invalidTemplate"),ellipsis:new f("...",p),backQuote:new f("`",_),dollarBraceL:new f("${",{beforeExpr:true,startsExpr:true}),eq:new f("=",{beforeExpr:true,isAssign:true}),assign:new f("_=",{beforeExpr:true,isAssign:true}),incDec:new f("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new f("!/~",{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 f("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new f("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",p),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",p),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",p),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",_),_if:kw("if"),_return:kw("return",p),_switch:kw("switch"),_throw:kw("throw",p),_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",_),_super:kw("super",_),_class:kw("class",_),_extends:kw("extends",p),_export:kw("export"),_import:kw("import",_),_null:kw("null",_),_true:kw("true",_),_false:kw("false",_),_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})};var m=/\r\n?|\n|\u2028|\u2029/;var E=new RegExp(m.source,"g");function isNewLine(e,t){return e===10||e===13||!t&&(e===8232||e===8233)}var g=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var v=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var D=Object.prototype;var b=D.hasOwnProperty;var y=D.toString;function has(e,t){return b.call(e,t)}var k=Array.isArray||function(e){return y.call(e)==="[object Array]"};function wordsRegexp(e){return new RegExp("^(?:"+e.replace(/ /g,"|")+")$")}var S=function Position(e,t){this.line=e;this.column=t};S.prototype.offset=function offset(e){return new S(this.line,this.column+e)};var T=function SourceLocation(e,t,n){this.start=t;this.end=n;if(e.sourceFile!==null){this.source=e.sourceFile}};function getLineInfo(e,t){for(var n=1,i=0;;){E.lastIndex=i;var r=E.exec(e);if(r&&r.index=2015){t.ecmaVersion-=2009}if(t.allowReserved==null){t.allowReserved=t.ecmaVersion<5}if(k(t.onToken)){var i=t.onToken;t.onToken=function(e){return i.push(e)}}if(k(t.onComment)){t.onComment=pushComment(t,t.onComment)}return t}function pushComment(e,t){return function(n,i,r,a,o,s){var u={type:n?"Block":"Line",value:i,start:r,end:a};if(e.locations){u.loc=new T(this,o,s)}if(e.ranges){u.range=[r,a]}t.push(u)}}var R=1,x=2,F=R|x,O=4,w=8,M=16,N=32,I=64,P=128;function functionFlags(e,t){return x|(e?O:0)|(t?w:0)}var L=0,B=1,V=2,U=3,z=4,K=5;var G=function Parser(e,n,r){this.options=e=getOptions(e);this.sourceFile=e.sourceFile;this.keywords=wordsRegexp(i[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var a="";if(e.allowReserved!==true){a=t[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3];if(e.sourceType==="module"){a+=" await"}}this.reservedWords=wordsRegexp(a);var o=(a?a+" ":"")+t.strict;this.reservedWordsStrict=wordsRegexp(o);this.reservedWordsStrictBind=wordsRegexp(o+" "+t.strictBind);this.input=String(n);this.containsEsc=false;if(r){this.pos=r;this.lineStart=this.input.lastIndexOf("\n",r-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(m).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=d.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=e.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.potentialArrowInForAwait=false;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports=Object.create(null);if(this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(R);this.regexpState=null;this.privateNameStack=[]};var X={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true},inNonArrowFunction:{configurable:true}};G.prototype.parse=function parse(){var e=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(e)};X.inFunction.get=function(){return(this.currentVarScope().flags&x)>0};X.inGenerator.get=function(){return(this.currentVarScope().flags&w)>0&&!this.currentVarScope().inClassFieldInit};X.inAsync.get=function(){return(this.currentVarScope().flags&O)>0&&!this.currentVarScope().inClassFieldInit};X.allowSuper.get=function(){var e=this.currentThisScope();var t=e.flags;var n=e.inClassFieldInit;return(t&I)>0||n};X.allowDirectSuper.get=function(){return(this.currentThisScope().flags&P)>0};X.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};X.inNonArrowFunction.get=function(){var e=this.currentThisScope();var t=e.flags;var n=e.inClassFieldInit;return(t&x)>0||n};G.extend=function extend(){var e=[],t=arguments.length;while(t--)e[t]=arguments[t];var n=this;for(var i=0;i=,?^&]/.test(r)||r==="!"&&this.input.charAt(i+1)==="=")}e+=t[0].length;v.lastIndex=e;e+=v.exec(this.input)[0].length;if(this.input[e]===";"){e++}}};H.eat=function(e){if(this.type===e){this.next();return true}else{return false}};H.isContextual=function(e){return this.type===d.name&&this.value===e&&!this.containsEsc};H.eatContextual=function(e){if(!this.isContextual(e)){return false}this.next();return true};H.expectContextual=function(e){if(!this.eatContextual(e)){this.unexpected()}};H.canInsertSemicolon=function(){return this.type===d.eof||this.type===d.braceR||m.test(this.input.slice(this.lastTokEnd,this.start))};H.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};H.semicolon=function(){if(!this.eat(d.semi)&&!this.insertSemicolon()){this.unexpected()}};H.afterTrailingComma=function(e,t){if(this.type===e){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!t){this.next()}return true}};H.expect=function(e){this.eat(e)||this.unexpected()};H.unexpected=function(e){this.raise(e!=null?e:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}H.checkPatternErrors=function(e,t){if(!e){return}if(e.trailingComma>-1){this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element")}var n=t?e.parenthesizedAssign:e.parenthesizedBind;if(n>-1){this.raiseRecoverable(n,"Parenthesized pattern")}};H.checkExpressionErrors=function(e,t){if(!e){return false}var n=e.shorthandAssign;var i=e.doubleProto;if(!t){return n>=0||i>=0}if(n>=0){this.raise(n,"Shorthand property assignments are valid only in destructuring patterns")}if(i>=0){this.raiseRecoverable(i,"Redefinition of __proto__ property")}};H.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(r,false,!e);case d._class:if(e){this.unexpected()}return this.parseClass(r,true);case d._if:return this.parseIfStatement(r);case d._return:return this.parseReturnStatement(r);case d._switch:return this.parseSwitchStatement(r);case d._throw:return this.parseThrowStatement(r);case d._try:return this.parseTryStatement(r);case d._const:case d._var:a=a||this.value;if(e&&a!=="var"){this.unexpected()}return this.parseVarStatement(r,a);case d._while:return this.parseWhileStatement(r);case d._with:return this.parseWithStatement(r);case d.braceL:return this.parseBlock(true,r);case d.semi:return this.parseEmptyStatement(r);case d._export:case d._import:if(this.options.ecmaVersion>10&&i===d._import){v.lastIndex=this.pos;var o=v.exec(this.input);var s=this.pos+o[0].length,u=this.input.charCodeAt(s);if(u===40||u===46){return this.parseExpressionStatement(r,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!t){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 i===d._import?this.parseImport(r):this.parseExport(r,n);default:if(this.isAsyncFunction()){if(e){this.unexpected()}this.next();return this.parseFunctionStatement(r,true,!e)}var c=this.value,l=this.parseExpression();if(i===d.name&&l.type==="Identifier"&&this.eat(d.colon)){return this.parseLabeledStatement(r,c,l,e)}else{return this.parseExpressionStatement(r,l)}}};q.parseBreakContinueStatement=function(e,t){var n=t==="break";this.next();if(this.eat(d.semi)||this.insertSemicolon()){e.label=null}else if(this.type!==d.name){this.unexpected()}else{e.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(d.semi)}else{this.semicolon()}return this.finishNode(e,"DoWhileStatement")};q.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(Y);this.enterScope(0);this.expect(d.parenL);if(this.type===d.semi){if(t>-1){this.unexpected(t)}return this.parseFor(e,null)}var n=this.isLet();if(this.type===d._var||this.type===d._const||n){var i=this.startNode(),r=n?"let":this.value;this.next();this.parseVar(i,true,r);this.finishNode(i,"VariableDeclaration");if((this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&i.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===d._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}return this.parseForIn(e,i)}if(t>-1){this.unexpected(t)}return this.parseFor(e,i)}var a=new DestructuringErrors;var o=this.parseExpression(t>-1?"await":true,a);if(this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===d._in){if(t>-1){this.unexpected(t)}}else{e.await=t>-1}}this.toAssignable(o,false,a);this.checkLValPattern(o);return this.parseForIn(e,o)}else{this.checkExpressionErrors(a,true)}if(t>-1){this.unexpected(t)}return this.parseFor(e,o)};q.parseFunctionStatement=function(e,t,n){this.next();return this.parseFunction(e,Z|(n?0:Q),false,t)};q.parseIfStatement=function(e){this.next();e.test=this.parseParenExpression();e.consequent=this.parseStatement("if");e.alternate=this.eat(d._else)?this.parseStatement("if"):null;return this.finishNode(e,"IfStatement")};q.parseReturnStatement=function(e){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(d.semi)||this.insertSemicolon()){e.argument=null}else{e.argument=this.parseExpression();this.semicolon()}return this.finishNode(e,"ReturnStatement")};q.parseSwitchStatement=function(e){this.next();e.discriminant=this.parseParenExpression();e.cases=[];this.expect(d.braceL);this.labels.push(j);this.enterScope(0);var t;for(var n=false;this.type!==d.braceR;){if(this.type===d._case||this.type===d._default){var i=this.type===d._case;if(t){this.finishNode(t,"SwitchCase")}e.cases.push(t=this.startNode());t.consequent=[];this.next();if(i){t.test=this.parseExpression()}else{if(n){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}n=true;t.test=null}this.expect(d.colon)}else{if(!t){this.unexpected()}t.consequent.push(this.parseStatement(null))}}this.exitScope();if(t){this.finishNode(t,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(e,"SwitchStatement")};q.parseThrowStatement=function(e){this.next();if(m.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}e.argument=this.parseExpression();this.semicolon();return this.finishNode(e,"ThrowStatement")};var $=[];q.parseTryStatement=function(e){this.next();e.block=this.parseBlock();e.handler=null;if(this.type===d._catch){var t=this.startNode();this.next();if(this.eat(d.parenL)){t.param=this.parseBindingAtom();var n=t.param.type==="Identifier";this.enterScope(n?N:0);this.checkLValPattern(t.param,n?z:V);this.expect(d.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}t.param=null;this.enterScope(0)}t.body=this.parseBlock(false);this.exitScope();e.handler=this.finishNode(t,"CatchClause")}e.finalizer=this.eat(d._finally)?this.parseBlock():null;if(!e.handler&&!e.finalizer){this.raise(e.start,"Missing catch or finally clause")}return this.finishNode(e,"TryStatement")};q.parseVarStatement=function(e,t){this.next();this.parseVar(e,false,t);this.semicolon();return this.finishNode(e,"VariableDeclaration")};q.parseWhileStatement=function(e){this.next();e.test=this.parseParenExpression();this.labels.push(Y);e.body=this.parseStatement("while");this.labels.pop();return this.finishNode(e,"WhileStatement")};q.parseWithStatement=function(e){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();e.object=this.parseParenExpression();e.body=this.parseStatement("with");return this.finishNode(e,"WithStatement")};q.parseEmptyStatement=function(e){this.next();return this.finishNode(e,"EmptyStatement")};q.parseLabeledStatement=function(e,t,n,i){for(var r=0,a=this.labels;r=0;u--){var c=this.labels[u];if(c.statementStart===e.start){c.statementStart=this.start;c.kind=s}else{break}}this.labels.push({name:t,kind:s,statementStart:this.start});e.body=this.parseStatement(i?i.indexOf("label")===-1?i+"label":i:"label");this.labels.pop();e.label=n;return this.finishNode(e,"LabeledStatement")};q.parseExpressionStatement=function(e,t){e.expression=t;this.semicolon();return this.finishNode(e,"ExpressionStatement")};q.parseBlock=function(e,t,n){if(e===void 0)e=true;if(t===void 0)t=this.startNode();t.body=[];this.expect(d.braceL);if(e){this.enterScope(0)}while(this.type!==d.braceR){var i=this.parseStatement(null);t.body.push(i)}if(n){this.strict=false}this.next();if(e){this.exitScope()}return this.finishNode(t,"BlockStatement")};q.parseFor=function(e,t){e.init=t;this.expect(d.semi);e.test=this.type===d.semi?null:this.parseExpression();this.expect(d.semi);e.update=this.type===d.parenR?null:this.parseExpression();this.expect(d.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,"ForStatement")};q.parseForIn=function(e,t){var n=this.type===d._in;this.next();if(t.type==="VariableDeclaration"&&t.declarations[0].init!=null&&(!n||this.options.ecmaVersion<8||this.strict||t.kind!=="var"||t.declarations[0].id.type!=="Identifier")){this.raise(t.start,(n?"for-in":"for-of")+" loop variable declaration may not have an initializer")}e.left=t;e.right=n?this.parseExpression():this.parseMaybeAssign();this.expect(d.parenR);e.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(e,n?"ForInStatement":"ForOfStatement")};q.parseVar=function(e,t,n){e.declarations=[];e.kind=n;for(;;){var i=this.startNode();this.parseVarId(i,n);if(this.eat(d.eq)){i.init=this.parseMaybeAssign(t)}else if(n==="const"&&!(this.type===d._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(i.id.type!=="Identifier"&&!(t&&(this.type===d._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{i.init=null}e.declarations.push(this.finishNode(i,"VariableDeclarator"));if(!this.eat(d.comma)){break}}return e};q.parseVarId=function(e,t){e.id=this.parseBindingAtom();this.checkLValPattern(e.id,t==="var"?B:V,false)};var Z=1,Q=2,J=4;q.parseFunction=function(e,t,n,i){this.initFunction(e);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!i){if(this.type===d.star&&t&Q){this.unexpected()}e.generator=this.eat(d.star)}if(this.options.ecmaVersion>=8){e.async=!!i}if(t&Z){e.id=t&J&&this.type!==d.name?null:this.parseIdent();if(e.id&&!(t&Q)){this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?B:V:U)}}var r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(e.async,e.generator));if(!(t&Z)){e.id=this.type===d.name?this.parseIdent():null}this.parseFunctionParams(e);this.parseFunctionBody(e,n,false);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(e,t&Z?"FunctionDeclaration":"FunctionExpression")};q.parseFunctionParams=function(e){this.expect(d.parenL);e.params=this.parseBindingList(d.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};q.parseClass=function(e,t){this.next();var n=this.strict;this.strict=true;this.parseClassId(e,t);this.parseClassSuper(e);var i=this.enterClassBody();var r=this.startNode();var a=false;r.body=[];this.expect(d.braceL);while(this.type!==d.braceR){var o=this.parseClassElement(e.superClass!==null);if(o){r.body.push(o);if(o.type==="MethodDefinition"&&o.kind==="constructor"){if(a){this.raise(o.start,"Duplicate constructor in the same class")}a=true}else if(o.key.type==="PrivateIdentifier"&&isPrivateNameConflicted(i,o)){this.raiseRecoverable(o.key.start,"Identifier '#"+o.key.name+"' has already been declared")}}}this.strict=n;this.next();e.body=this.finishNode(r,"ClassBody");this.exitClassBody();return this.finishNode(e,t?"ClassDeclaration":"ClassExpression")};q.parseClassElement=function(e){if(this.eat(d.semi)){return null}var t=this.options.ecmaVersion;var n=this.startNode();var i="";var r=false;var a=false;var o="method";n.static=false;if(this.eatContextual("static")){if(this.isClassElementNameStart()||this.type===d.star){n.static=true}else{i="static"}}if(!i&&t>=8&&this.eatContextual("async")){if((this.isClassElementNameStart()||this.type===d.star)&&!this.canInsertSemicolon()){a=true}else{i="async"}}if(!i&&(t>=9||!a)&&this.eat(d.star)){r=true}if(!i&&!a&&!r){var s=this.value;if(this.eatContextual("get")||this.eatContextual("set")){if(this.isClassElementNameStart()){o=s}else{i=s}}}if(i){n.computed=false;n.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc);n.key.name=i;this.finishNode(n.key,"Identifier")}else{this.parseClassElementName(n)}if(t<13||this.type===d.parenL||o!=="method"||r||a){var u=!n.static&&checkKeyName(n,"constructor");var c=u&&e;if(u&&o!=="method"){this.raise(n.key.start,"Constructor can't have get/set modifier")}n.kind=u?"constructor":o;this.parseClassMethod(n,r,a,c)}else{this.parseClassField(n)}return n};q.isClassElementNameStart=function(){return this.type===d.name||this.type===d.privateId||this.type===d.num||this.type===d.string||this.type===d.bracketL||this.type.keyword};q.parseClassElementName=function(e){if(this.type===d.privateId){if(this.value==="constructor"){this.raise(this.start,"Classes can't have an element named '#constructor'")}e.computed=false;e.key=this.parsePrivateIdent()}else{this.parsePropertyName(e)}};q.parseClassMethod=function(e,t,n,i){var r=e.key;if(e.kind==="constructor"){if(t){this.raise(r.start,"Constructor can't be a generator")}if(n){this.raise(r.start,"Constructor can't be an async method")}}else if(e.static&&checkKeyName(e,"prototype")){this.raise(r.start,"Classes may not have a static property named prototype")}var a=e.value=this.parseMethod(t,n,i);if(e.kind==="get"&&a.params.length!==0){this.raiseRecoverable(a.start,"getter should have no params")}if(e.kind==="set"&&a.params.length!==1){this.raiseRecoverable(a.start,"setter should have exactly one param")}if(e.kind==="set"&&a.params[0].type==="RestElement"){this.raiseRecoverable(a.params[0].start,"Setter cannot use rest params")}return this.finishNode(e,"MethodDefinition")};q.parseClassField=function(e){if(checkKeyName(e,"constructor")){this.raise(e.key.start,"Classes can't have a field named 'constructor'")}else if(e.static&&checkKeyName(e,"prototype")){this.raise(e.key.start,"Classes can't have a static field named 'prototype'")}if(this.eat(d.eq)){var t=this.currentThisScope();var n=t.inClassFieldInit;t.inClassFieldInit=true;e.value=this.parseMaybeAssign();t.inClassFieldInit=n}else{e.value=null}this.semicolon();return this.finishNode(e,"PropertyDefinition")};q.parseClassId=function(e,t){if(this.type===d.name){e.id=this.parseIdent();if(t){this.checkLValSimple(e.id,V,false)}}else{if(t===true){this.unexpected()}e.id=null}};q.parseClassSuper=function(e){e.superClass=this.eat(d._extends)?this.parseExprSubscripts():null};q.enterClassBody=function(){var e={declared:Object.create(null),used:[]};this.privateNameStack.push(e);return e.declared};q.exitClassBody=function(){var e=this.privateNameStack.pop();var t=e.declared;var n=e.used;var i=this.privateNameStack.length;var r=i===0?null:this.privateNameStack[i-1];for(var a=0;a=11){if(this.eatContextual("as")){e.exported=this.parseIdent(true);this.checkExport(t,e.exported.name,this.lastTokStart)}else{e.exported=null}}this.expectContextual("from");if(this.type!==d.string){this.unexpected()}e.source=this.parseExprAtom();this.semicolon();return this.finishNode(e,"ExportAllDeclaration")}if(this.eat(d._default)){this.checkExport(t,"default",this.lastTokStart);var n;if(this.type===d._function||(n=this.isAsyncFunction())){var i=this.startNode();this.next();if(n){this.next()}e.declaration=this.parseFunction(i,Z|J,false,n)}else if(this.type===d._class){var r=this.startNode();e.declaration=this.parseClass(r,"nullableID")}else{e.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(e,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){e.declaration=this.parseStatement(null);if(e.declaration.type==="VariableDeclaration"){this.checkVariableExport(t,e.declaration.declarations)}else{this.checkExport(t,e.declaration.id.name,e.declaration.id.start)}e.specifiers=[];e.source=null}else{e.declaration=null;e.specifiers=this.parseExportSpecifiers(t);if(this.eatContextual("from")){if(this.type!==d.string){this.unexpected()}e.source=this.parseExprAtom()}else{for(var a=0,o=e.specifiers;a=6&&e){switch(e.type){case"Identifier":if(this.inAsync&&e.name==="await"){this.raise(e.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern";if(n){this.checkPatternErrors(n,true)}for(var i=0,r=e.properties;i=8&&!a&&o.name==="async"&&!this.canInsertSemicolon()&&this.eat(d._function)){return this.parseFunction(this.startNodeAt(i,r),0,false,true)}if(n&&!this.canInsertSemicolon()){if(this.eat(d.arrow)){return this.parseArrowExpression(this.startNodeAt(i,r),[o],false)}if(this.options.ecmaVersion>=8&&o.name==="async"&&this.type===d.name&&!a&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc)){o=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(d.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(i,r),[o],true)}}return o;case d.regexp:var s=this.value;t=this.parseLiteral(s.value);t.regex={pattern:s.pattern,flags:s.flags};return t;case d.num:case d.string:return this.parseLiteral(this.value);case d._null:case d._true:case d._false:t=this.startNode();t.value=this.type===d._null?null:this.type===d._true;t.raw=this.type.keyword;this.next();return this.finishNode(t,"Literal");case d.parenL:var u=this.start,c=this.parseParenAndDistinguishExpression(n);if(e){if(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(c)){e.parenthesizedAssign=u}if(e.parenthesizedBind<0){e.parenthesizedBind=u}}return c;case d.bracketL:t=this.startNode();this.next();t.elements=this.parseExprList(d.bracketR,true,true,e);return this.finishNode(t,"ArrayExpression");case d.braceL:return this.parseObj(false,e);case d._function:t=this.startNode();this.next();return this.parseFunction(t,0);case d._class:return this.parseClass(this.startNode(),false);case d._new:return this.parseNew();case d.backQuote:return this.parseTemplate();case d._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};te.parseExprImport=function(){var e=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var t=this.parseIdent(true);switch(this.type){case d.parenL:return this.parseDynamicImport(e);case d.dot:e.meta=t;return this.parseImportMeta(e);default:this.unexpected()}};te.parseDynamicImport=function(e){this.next();e.source=this.parseMaybeAssign();if(!this.eat(d.parenR)){var t=this.start;if(this.eat(d.comma)&&this.eat(d.parenR)){this.raiseRecoverable(t,"Trailing comma is not allowed in import()")}else{this.unexpected(t)}}return this.finishNode(e,"ImportExpression")};te.parseImportMeta=function(e){this.next();var t=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="meta"){this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'")}if(t){this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere){this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(e,"MetaProperty")};te.parseLiteral=function(e){var t=this.startNode();t.value=e;t.raw=this.input.slice(this.start,this.end);if(t.raw.charCodeAt(t.raw.length-1)===110){t.bigint=t.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(t,"Literal")};te.parseParenExpression=function(){this.expect(d.parenL);var e=this.parseExpression();this.expect(d.parenR);return e};te.parseParenAndDistinguishExpression=function(e){var t=this.start,n=this.startLoc,i,r=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a=this.start,o=this.startLoc;var s=[],u=true,c=false;var l=new DestructuringErrors,f=this.yieldPos,p=this.awaitPos,_;this.yieldPos=0;this.awaitPos=0;while(this.type!==d.parenR){u?u=false:this.expect(d.comma);if(r&&this.afterTrailingComma(d.parenR,true)){c=true;break}else if(this.type===d.ellipsis){_=this.start;s.push(this.parseParenItem(this.parseRestBinding()));if(this.type===d.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{s.push(this.parseMaybeAssign(false,l,this.parseParenItem))}}var h=this.start,m=this.startLoc;this.expect(d.parenR);if(e&&!this.canInsertSemicolon()&&this.eat(d.arrow)){this.checkPatternErrors(l,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=f;this.awaitPos=p;return this.parseParenArrowList(t,n,s)}if(!s.length||c){this.unexpected(this.lastTokStart)}if(_){this.unexpected(_)}this.checkExpressionErrors(l,true);this.yieldPos=f||this.yieldPos;this.awaitPos=p||this.awaitPos;if(s.length>1){i=this.startNodeAt(a,o);i.expressions=s;this.finishNodeAt(i,"SequenceExpression",h,m)}else{i=s[0]}}else{i=this.parseParenExpression()}if(this.options.preserveParens){var E=this.startNodeAt(t,n);E.expression=i;return this.finishNode(E,"ParenthesizedExpression")}else{return i}};te.parseParenItem=function(e){return e};te.parseParenArrowList=function(e,t,n){return this.parseArrowExpression(this.startNodeAt(e,t),n)};var ne=[];te.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var e=this.startNode();var t=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(d.dot)){e.meta=t;var n=this.containsEsc;e.property=this.parseIdent(true);if(e.property.name!=="target"){this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'")}if(n){this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters")}if(!this.inNonArrowFunction){this.raiseRecoverable(e.start,"'new.target' can only be used in functions")}return this.finishNode(e,"MetaProperty")}var i=this.start,r=this.startLoc,a=this.type===d._import;e.callee=this.parseSubscripts(this.parseExprAtom(),i,r,true);if(a&&e.callee.type==="ImportExpression"){this.raise(i,"Cannot use new with import()")}if(this.eat(d.parenL)){e.arguments=this.parseExprList(d.parenR,this.options.ecmaVersion>=8,false)}else{e.arguments=ne}return this.finishNode(e,"NewExpression")};te.parseTemplateElement=function(e){var t=e.isTagged;var n=this.startNode();if(this.type===d.invalidTemplate){if(!t){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}n.value={raw:this.value,cooked:null}}else{n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();n.tail=this.type===d.backQuote;return this.finishNode(n,"TemplateElement")};te.parseTemplate=function(e){if(e===void 0)e={};var t=e.isTagged;if(t===void 0)t=false;var n=this.startNode();this.next();n.expressions=[];var i=this.parseTemplateElement({isTagged:t});n.quasis=[i];while(!i.tail){if(this.type===d.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(d.dollarBraceL);n.expressions.push(this.parseExpression());this.expect(d.braceR);n.quasis.push(i=this.parseTemplateElement({isTagged:t}))}this.next();return this.finishNode(n,"TemplateLiteral")};te.isAsyncProp=function(e){return!e.computed&&e.key.type==="Identifier"&&e.key.name==="async"&&(this.type===d.name||this.type===d.num||this.type===d.string||this.type===d.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===d.star)&&!m.test(this.input.slice(this.lastTokEnd,this.start))};te.parseObj=function(e,t){var n=this.startNode(),i=true,r={};n.properties=[];this.next();while(!this.eat(d.braceR)){if(!i){this.expect(d.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(d.braceR)){break}}else{i=false}var a=this.parseProperty(e,t);if(!e){this.checkPropClash(a,r,t)}n.properties.push(a)}return this.finishNode(n,e?"ObjectPattern":"ObjectExpression")};te.parseProperty=function(e,t){var n=this.startNode(),i,r,a,o;if(this.options.ecmaVersion>=9&&this.eat(d.ellipsis)){if(e){n.argument=this.parseIdent(false);if(this.type===d.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(n,"RestElement")}if(this.type===d.parenL&&t){if(t.parenthesizedAssign<0){t.parenthesizedAssign=this.start}if(t.parenthesizedBind<0){t.parenthesizedBind=this.start}}n.argument=this.parseMaybeAssign(false,t);if(this.type===d.comma&&t&&t.trailingComma<0){t.trailingComma=this.start}return this.finishNode(n,"SpreadElement")}if(this.options.ecmaVersion>=6){n.method=false;n.shorthand=false;if(e||t){a=this.start;o=this.startLoc}if(!e){i=this.eat(d.star)}}var s=this.containsEsc;this.parsePropertyName(n);if(!e&&!s&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(n)){r=true;i=this.options.ecmaVersion>=9&&this.eat(d.star);this.parsePropertyName(n,t)}else{r=false}this.parsePropertyValue(n,e,i,r,a,o,t,s);return this.finishNode(n,"Property")};te.parsePropertyValue=function(e,t,n,i,r,a,o,s){if((n||i)&&this.type===d.colon){this.unexpected()}if(this.eat(d.colon)){e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,o);e.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===d.parenL){if(t){this.unexpected()}e.kind="init";e.method=true;e.value=this.parseMethod(n,i)}else if(!t&&!s&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type==="Identifier"&&(e.key.name==="get"||e.key.name==="set")&&(this.type!==d.comma&&this.type!==d.braceR&&this.type!==d.eq)){if(n||i){this.unexpected()}e.kind=e.key.name;this.parsePropertyName(e);e.value=this.parseMethod(false);var u=e.kind==="get"?0:1;if(e.value.params.length!==u){var c=e.value.start;if(e.kind==="get"){this.raiseRecoverable(c,"getter should have no params")}else{this.raiseRecoverable(c,"setter should have exactly one param")}}else{if(e.kind==="set"&&e.value.params[0].type==="RestElement"){this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!e.computed&&e.key.type==="Identifier"){if(n||i){this.unexpected()}this.checkUnreserved(e.key);if(e.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=r}e.kind="init";if(t){e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else if(this.type===d.eq&&o){if(o.shorthandAssign<0){o.shorthandAssign=this.start}e.value=this.parseMaybeDefault(r,a,this.copyNode(e.key))}else{e.value=this.copyNode(e.key)}e.shorthand=true}else{this.unexpected()}};te.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(d.bracketL)){e.computed=true;e.key=this.parseMaybeAssign();this.expect(d.bracketR);return e.key}else{e.computed=false}}return e.key=this.type===d.num||this.type===d.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};te.initFunction=function(e){e.id=null;if(this.options.ecmaVersion>=6){e.generator=e.expression=false}if(this.options.ecmaVersion>=8){e.async=false}};te.parseMethod=function(e,t,n){var i=this.startNode(),r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;this.initFunction(i);if(this.options.ecmaVersion>=6){i.generator=e}if(this.options.ecmaVersion>=8){i.async=!!t}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(t,i.generator)|I|(n?P:0));this.expect(d.parenL);i.params=this.parseBindingList(d.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(i,false,true);this.yieldPos=r;this.awaitPos=a;this.awaitIdentPos=o;return this.finishNode(i,"FunctionExpression")};te.parseArrowExpression=function(e,t,n){var i=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;this.enterScope(functionFlags(n,false)|M);this.initFunction(e);if(this.options.ecmaVersion>=8){e.async=!!n}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;e.params=this.toAssignableList(t,true);this.parseFunctionBody(e,true,false);this.yieldPos=i;this.awaitPos=r;this.awaitIdentPos=a;return this.finishNode(e,"ArrowFunctionExpression")};te.parseFunctionBody=function(e,t,n){var i=t&&this.type!==d.braceL;var r=this.strict,a=false;if(i){e.body=this.parseMaybeAssign();e.expression=true;this.checkParams(e,false)}else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);if(!r||o){a=this.strictDirective(this.end);if(a&&o){this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var s=this.labels;this.labels=[];if(a){this.strict=true}this.checkParams(e,!r&&!a&&!t&&!n&&this.isSimpleParamList(e.params));if(this.strict&&e.id){this.checkLValSimple(e.id,K)}e.body=this.parseBlock(false,undefined,a&&!r);e.expression=false;this.adaptDirectivePrologue(e.body.body);this.labels=s}this.exitScope()};te.isSimpleParamList=function(e){for(var t=0,n=e;t-1||r.functions.indexOf(e)>-1||r.var.indexOf(e)>-1;r.lexical.push(e);if(this.inModule&&r.flags&R){delete this.undefinedExports[e]}}else if(t===z){var a=this.currentScope();a.lexical.push(e)}else if(t===U){var o=this.currentScope();if(this.treatFunctionsAsVar){i=o.lexical.indexOf(e)>-1}else{i=o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1}o.functions.push(e)}else{for(var s=this.scopeStack.length-1;s>=0;--s){var u=this.scopeStack[s];if(u.lexical.indexOf(e)>-1&&!(u.flags&N&&u.lexical[0]===e)||!this.treatFunctionsAsVarInScope(u)&&u.functions.indexOf(e)>-1){i=true;break}u.var.push(e);if(this.inModule&&u.flags&R){delete this.undefinedExports[e]}if(u.flags&F){break}}}if(i){this.raiseRecoverable(n,"Identifier '"+e+"' has already been declared")}};re.checkLocalExport=function(e){if(this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1){this.undefinedExports[e.name]=e}};re.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};re.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&F){return t}}};re.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&F&&!(t.flags&M)){return t}}};var oe=function Node(e,t,n){this.type="";this.start=t;this.end=0;if(e.options.locations){this.loc=new T(e,n)}if(e.options.directSourceFile){this.sourceFile=e.options.directSourceFile}if(e.options.ranges){this.range=[t,0]}};var se=G.prototype;se.startNode=function(){return new oe(this,this.start,this.startLoc)};se.startNodeAt=function(e,t){return new oe(this,e,t)};function finishNodeAt(e,t,n,i){e.type=t;e.end=n;if(this.options.locations){e.loc.end=i}if(this.options.ranges){e.range[1]=n}return e}se.finishNode=function(e,t){return finishNodeAt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)};se.finishNodeAt=function(e,t,n,i){return finishNodeAt.call(this,e,t,n,i)};se.copyNode=function(e){var t=new oe(this,e.start,this.startLoc);for(var n in e){t[n]=e[n]}return t};var ue=function TokContext(e,t,n,i,r){this.token=e;this.isExpr=!!t;this.preserveSpace=!!n;this.override=i;this.generator=!!r};var ce={b_stat:new ue("{",false),b_expr:new ue("{",true),b_tmpl:new ue("${",false),p_stat:new ue("(",false),p_expr:new ue("(",true),q_tmpl:new ue("`",true,true,function(e){return e.tryReadTemplateToken()}),f_stat:new ue("function",false),f_expr:new ue("function",true),f_expr_gen:new ue("function",true,false,null,true),f_gen:new ue("function",false,false,null,true)};var le=G.prototype;le.initialContext=function(){return[ce.b_stat]};le.braceIsBlock=function(e){var t=this.curContext();if(t===ce.f_expr||t===ce.f_stat){return true}if(e===d.colon&&(t===ce.b_stat||t===ce.b_expr)){return!t.isExpr}if(e===d._return||e===d.name&&this.exprAllowed){return m.test(this.input.slice(this.lastTokEnd,this.start))}if(e===d._else||e===d.semi||e===d.eof||e===d.parenR||e===d.arrow){return true}if(e===d.braceL){return t===ce.b_stat}if(e===d._var||e===d._const||e===d.name){return false}return!this.exprAllowed};le.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if(t.token==="function"){return t.generator}}return false};le.updateContext=function(e){var t,n=this.type;if(n.keyword&&e===d.dot){this.exprAllowed=false}else if(t=n.updateContext){t.call(this,e)}else{this.exprAllowed=n.beforeExpr}};d.parenR.updateContext=d.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var e=this.context.pop();if(e===ce.b_stat&&this.curContext().token==="function"){e=this.context.pop()}this.exprAllowed=!e.isExpr};d.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?ce.b_stat:ce.b_expr);this.exprAllowed=true};d.dollarBraceL.updateContext=function(){this.context.push(ce.b_tmpl);this.exprAllowed=true};d.parenL.updateContext=function(e){var t=e===d._if||e===d._for||e===d._with||e===d._while;this.context.push(t?ce.p_stat:ce.p_expr);this.exprAllowed=true};d.incDec.updateContext=function(){};d._function.updateContext=d._class.updateContext=function(e){if(e.beforeExpr&&e!==d._else&&!(e===d.semi&&this.curContext()!==ce.p_stat)&&!(e===d._return&&m.test(this.input.slice(this.lastTokEnd,this.start)))&&!((e===d.colon||e===d.braceL)&&this.curContext()===ce.b_stat)){this.context.push(ce.f_expr)}else{this.context.push(ce.f_stat)}this.exprAllowed=false};d.backQuote.updateContext=function(){if(this.curContext()===ce.q_tmpl){this.context.pop()}else{this.context.push(ce.q_tmpl)}this.exprAllowed=false};d.star.updateContext=function(e){if(e===d._function){var t=this.context.length-1;if(this.context[t]===ce.f_expr){this.context[t]=ce.f_expr_gen}else{this.context[t]=ce.f_gen}}this.exprAllowed=true};d.name.updateContext=function(e){var t=false;if(this.options.ecmaVersion>=6&&e!==d.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){t=true}}this.exprAllowed=t};var fe="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 pe=fe+" Extended_Pictographic";var _e=pe;var he=_e+" EBase EComp EMod EPres ExtPict";var de={9:fe,10:pe,11:_e,12:he};var me="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";var Ee="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 ge=Ee+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ve=ge+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var De=ve+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";var be={9:Ee,10:ge,11:ve,12:De};var ye={};function buildUnicodeData(e){var t=ye[e]={binary:wordsRegexp(de[e]+" "+me),nonBinary:{General_Category:wordsRegexp(me),Script:wordsRegexp(be[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script;t.nonBinary.gc=t.nonBinary.General_Category;t.nonBinary.sc=t.nonBinary.Script;t.nonBinary.scx=t.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);buildUnicodeData(12);var ke=G.prototype;var Se=function RegExpValidationState(e){this.parser=e;this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"");this.unicodeProperties=ye[e.options.ecmaVersion>=12?12:e.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=[]};Se.prototype.reset=function reset(e,t,n){var i=n.indexOf("u")!==-1;this.start=e|0;this.source=t+"";this.flags=n;this.switchU=i&&this.parser.options.ecmaVersion>=6;this.switchN=i&&this.parser.options.ecmaVersion>=9};Se.prototype.raise=function raise(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};Se.prototype.at=function at(e,t){if(t===void 0)t=false;var n=this.source;var i=n.length;if(e>=i){return-1}var r=n.charCodeAt(e);if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=i){return r}var a=n.charCodeAt(e+1);return a>=56320&&a<=57343?(r<<10)+a-56613888:r};Se.prototype.nextIndex=function nextIndex(e,t){if(t===void 0)t=false;var n=this.source;var i=n.length;if(e>=i){return i}var r=n.charCodeAt(e),a;if(!(t||this.switchU)||r<=55295||r>=57344||e+1>=i||(a=n.charCodeAt(e+1))<56320||a>57343){return e+1}return e+2};Se.prototype.current=function current(e){if(e===void 0)e=false;return this.at(this.pos,e)};Se.prototype.lookahead=function lookahead(e){if(e===void 0)e=false;return this.at(this.nextIndex(this.pos,e),e)};Se.prototype.advance=function advance(e){if(e===void 0)e=false;this.pos=this.nextIndex(this.pos,e)};Se.prototype.eat=function eat(e,t){if(t===void 0)t=false;if(this.current(t)===e){this.advance(t);return true}return false};function codePointToString(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}ke.validateRegExpFlags=function(e){var t=e.validFlags;var n=e.flags;for(var i=0;i-1){this.raise(e.start,"Duplicate regular expression flag")}}};ke.validateRegExpPattern=function(e){this.regexp_pattern(e);if(!e.switchN&&this.options.ecmaVersion>=9&&e.groupNames.length>0){e.switchN=true;this.regexp_pattern(e)}};ke.regexp_pattern=function(e){e.pos=0;e.lastIntValue=0;e.lastStringValue="";e.lastAssertionIsQuantifiable=false;e.numCapturingParens=0;e.maxBackReference=0;e.groupNames.length=0;e.backReferenceNames.length=0;this.regexp_disjunction(e);if(e.pos!==e.source.length){if(e.eat(41)){e.raise("Unmatched ')'")}if(e.eat(93)||e.eat(125)){e.raise("Lone quantifier brackets")}}if(e.maxBackReference>e.numCapturingParens){e.raise("Invalid escape")}for(var t=0,n=e.backReferenceNames;t=9){n=e.eat(60)}if(e.eat(61)||e.eat(33)){this.regexp_disjunction(e);if(!e.eat(41)){e.raise("Unterminated group")}e.lastAssertionIsQuantifiable=!n;return true}}e.pos=t;return false};ke.regexp_eatQuantifier=function(e,t){if(t===void 0)t=false;if(this.regexp_eatQuantifierPrefix(e,t)){e.eat(63);return true}return false};ke.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)};ke.regexp_eatBracedQuantifier=function(e,t){var n=e.pos;if(e.eat(123)){var i=0,r=-1;if(this.regexp_eatDecimalDigits(e)){i=e.lastIntValue;if(e.eat(44)&&this.regexp_eatDecimalDigits(e)){r=e.lastIntValue}if(e.eat(125)){if(r!==-1&&r=9){this.regexp_groupSpecifier(e)}else if(e.current()===63){e.raise("Invalid group")}this.regexp_disjunction(e);if(e.eat(41)){e.numCapturingParens+=1;return true}e.raise("Unterminated group")}return false};ke.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)};ke.regexp_eatInvalidBracedQuantifier=function(e){if(this.regexp_eatBracedQuantifier(e,true)){e.raise("Nothing to repeat")}return false};ke.regexp_eatSyntaxCharacter=function(e){var t=e.current();if(isSyntaxCharacter(t)){e.lastIntValue=t;e.advance();return true}return false};function isSyntaxCharacter(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}ke.regexp_eatPatternCharacters=function(e){var t=e.pos;var n=0;while((n=e.current())!==-1&&!isSyntaxCharacter(n)){e.advance()}return e.pos!==t};ke.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();if(t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124){e.advance();return true}return false};ke.regexp_groupSpecifier=function(e){if(e.eat(63)){if(this.regexp_eatGroupName(e)){if(e.groupNames.indexOf(e.lastStringValue)!==-1){e.raise("Duplicate capture group name")}e.groupNames.push(e.lastStringValue);return}e.raise("Invalid group")}};ke.regexp_eatGroupName=function(e){e.lastStringValue="";if(e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62)){return true}e.raise("Invalid capture group name")}return false};ke.regexp_eatRegExpIdentifierName=function(e){e.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(e)){e.lastStringValue+=codePointToString(e.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(e)){e.lastStringValue+=codePointToString(e.lastIntValue)}return true}return false};ke.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos;var n=this.options.ecmaVersion>=11;var i=e.current(n);e.advance(n);if(i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)){i=e.lastIntValue}if(isRegExpIdentifierStart(i)){e.lastIntValue=i;return true}e.pos=t;return false};function isRegExpIdentifierStart(e){return isIdentifierStart(e,true)||e===36||e===95}ke.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos;var n=this.options.ecmaVersion>=11;var i=e.current(n);e.advance(n);if(i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)){i=e.lastIntValue}if(isRegExpIdentifierPart(i)){e.lastIntValue=i;return true}e.pos=t;return false};function isRegExpIdentifierPart(e){return isIdentifierChar(e,true)||e===36||e===95||e===8204||e===8205}ke.regexp_eatAtomEscape=function(e){if(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)){return true}if(e.switchU){if(e.current()===99){e.raise("Invalid unicode escape")}e.raise("Invalid escape")}return false};ke.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var n=e.lastIntValue;if(e.switchU){if(n>e.maxBackReference){e.maxBackReference=n}return true}if(n<=e.numCapturingParens){return true}e.pos=t}return false};ke.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e)){e.backReferenceNames.push(e.lastStringValue);return true}e.raise("Invalid named reference")}return false};ke.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,false)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)};ke.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e)){return true}e.pos=t}return false};ke.regexp_eatZero=function(e){if(e.current()===48&&!isDecimalDigit(e.lookahead())){e.lastIntValue=0;e.advance();return true}return false};ke.regexp_eatControlEscape=function(e){var t=e.current();if(t===116){e.lastIntValue=9;e.advance();return true}if(t===110){e.lastIntValue=10;e.advance();return true}if(t===118){e.lastIntValue=11;e.advance();return true}if(t===102){e.lastIntValue=12;e.advance();return true}if(t===114){e.lastIntValue=13;e.advance();return true}return false};ke.regexp_eatControlLetter=function(e){var t=e.current();if(isControlLetter(t)){e.lastIntValue=t%32;e.advance();return true}return false};function isControlLetter(e){return e>=65&&e<=90||e>=97&&e<=122}ke.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){if(t===void 0)t=false;var n=e.pos;var i=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var r=e.lastIntValue;if(i&&r>=55296&&r<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343){e.lastIntValue=(r-55296)*1024+(o-56320)+65536;return true}}e.pos=a;e.lastIntValue=r}return true}if(i&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&isValidUnicode(e.lastIntValue)){return true}if(i){e.raise("Invalid unicode escape")}e.pos=n}return false};function isValidUnicode(e){return e>=0&&e<=1114111}ke.regexp_eatIdentityEscape=function(e){if(e.switchU){if(this.regexp_eatSyntaxCharacter(e)){return true}if(e.eat(47)){e.lastIntValue=47;return true}return false}var t=e.current();if(t!==99&&(!e.switchN||t!==107)){e.lastIntValue=t;e.advance();return true}return false};ke.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48);e.advance()}while((t=e.current())>=48&&t<=57);return true}return false};ke.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(isCharacterClassEscape(t)){e.lastIntValue=-1;e.advance();return true}if(e.switchU&&this.options.ecmaVersion>=9&&(t===80||t===112)){e.lastIntValue=-1;e.advance();if(e.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(e)&&e.eat(125)){return true}e.raise("Invalid property name")}return false};function isCharacterClassEscape(e){return e===100||e===68||e===115||e===83||e===119||e===87}ke.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var n=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var i=e.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(e,n,i);return true}}e.pos=t;if(this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var r=e.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(e,r);return true}return false};ke.regexp_validateUnicodePropertyNameAndValue=function(e,t,n){if(!has(e.unicodeProperties.nonBinary,t)){e.raise("Invalid property name")}if(!e.unicodeProperties.nonBinary[t].test(n)){e.raise("Invalid property value")}};ke.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(!e.unicodeProperties.binary.test(t)){e.raise("Invalid property name")}};ke.regexp_eatUnicodePropertyName=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyNameCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyNameCharacter(e){return isControlLetter(e)||e===95}ke.regexp_eatUnicodePropertyValue=function(e){var t=0;e.lastStringValue="";while(isUnicodePropertyValueCharacter(t=e.current())){e.lastStringValue+=codePointToString(t);e.advance()}return e.lastStringValue!==""};function isUnicodePropertyValueCharacter(e){return isUnicodePropertyNameCharacter(e)||isDecimalDigit(e)}ke.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)};ke.regexp_eatCharacterClass=function(e){if(e.eat(91)){e.eat(94);this.regexp_classRanges(e);if(e.eat(93)){return true}e.raise("Unterminated character class")}return false};ke.regexp_classRanges=function(e){while(this.regexp_eatClassAtom(e)){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var n=e.lastIntValue;if(e.switchU&&(t===-1||n===-1)){e.raise("Invalid character class")}if(t!==-1&&n!==-1&&t>n){e.raise("Range out of order in character class")}}}};ke.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e)){return true}if(e.switchU){var n=e.current();if(n===99||isOctalDigit(n)){e.raise("Invalid class escape")}e.raise("Invalid escape")}e.pos=t}var i=e.current();if(i!==93){e.lastIntValue=i;e.advance();return true}return false};ke.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98)){e.lastIntValue=8;return true}if(e.switchU&&e.eat(45)){e.lastIntValue=45;return true}if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e)){return true}e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)};ke.regexp_eatClassControlLetter=function(e){var t=e.current();if(isDecimalDigit(t)||t===95){e.lastIntValue=t%32;e.advance();return true}return false};ke.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2)){return true}if(e.switchU){e.raise("Invalid escape")}e.pos=t}return false};ke.regexp_eatDecimalDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isDecimalDigit(n=e.current())){e.lastIntValue=10*e.lastIntValue+(n-48);e.advance()}return e.pos!==t};function isDecimalDigit(e){return e>=48&&e<=57}ke.regexp_eatHexDigits=function(e){var t=e.pos;var n=0;e.lastIntValue=0;while(isHexDigit(n=e.current())){e.lastIntValue=16*e.lastIntValue+hexToInt(n);e.advance()}return e.pos!==t};function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function hexToInt(e){if(e>=65&&e<=70){return 10+(e-65)}if(e>=97&&e<=102){return 10+(e-97)}return e-48}ke.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var n=e.lastIntValue;if(t<=3&&this.regexp_eatOctalDigit(e)){e.lastIntValue=t*64+n*8+e.lastIntValue}else{e.lastIntValue=t*8+n}}else{e.lastIntValue=t}return true}return false};ke.regexp_eatOctalDigit=function(e){var t=e.current();if(isOctalDigit(t)){e.lastIntValue=t-48;e.advance();return true}e.lastIntValue=0;return false};function isOctalDigit(e){return e>=48&&e<=55}ke.regexp_eatFixedHexDigits=function(e,t){var n=e.pos;e.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(d.eof)}if(e.override){return e.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};Ae.readToken=function(e){if(isIdentifierStart(e,this.options.ecmaVersion>=6)||e===92){return this.readWord()}return this.getTokenFromCode(e)};Ae.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320){return e}var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888};Ae.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition();var t=this.pos,n=this.input.indexOf("*/",this.pos+=2);if(n===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=n+2;if(this.options.locations){E.lastIndex=t;var i;while((i=E.exec(this.input))&&i.index8&&e<14||e>=5760&&g.test(String.fromCharCode(e))){++this.pos}else{break e}}}};Ae.finishToken=function(e,t){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var n=this.type;this.type=e;this.value=t;this.updateContext(n)};Ae.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57){return this.readNumber(true)}var t=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&e===46&&t===46){this.pos+=3;return this.finishToken(d.ellipsis)}else{++this.pos;return this.finishToken(d.dot)}};Ae.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(e===61){return this.finishOp(d.assign,2)}return this.finishOp(d.slash,1)};Ae.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;var i=e===42?d.star:d.modulo;if(this.options.ecmaVersion>=7&&e===42&&t===42){++n;i=d.starstar;t=this.input.charCodeAt(this.pos+2)}if(t===61){return this.finishOp(d.assign,n+1)}return this.finishOp(i,n)};Ae.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12){var n=this.input.charCodeAt(this.pos+2);if(n===61){return this.finishOp(d.assign,3)}}return this.finishOp(e===124?d.logicalOR:d.logicalAND,2)}if(t===61){return this.finishOp(d.assign,2)}return this.finishOp(e===124?d.bitwiseOR:d.bitwiseAND,1)};Ae.readToken_caret=function(){var e=this.input.charCodeAt(this.pos+1);if(e===61){return this.finishOp(d.assign,2)}return this.finishOp(d.bitwiseXOR,1)};Ae.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||m.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(d.incDec,2)}if(t===61){return this.finishOp(d.assign,2)}return this.finishOp(d.plusMin,1)};Ae.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1);var n=1;if(t===e){n=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+n)===61){return this.finishOp(d.assign,n+1)}return this.finishOp(d.bitShift,n)}if(t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(t===61){n=2}return this.finishOp(d.relational,n)};Ae.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===61){return this.finishOp(d.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(e===61&&t===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(d.arrow)}return this.finishOp(e===61?d.eq:d.prefix,1)};Ae.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var n=this.input.charCodeAt(this.pos+2);if(n<48||n>57){return this.finishOp(d.questionDot,2)}}if(t===63){if(e>=12){var i=this.input.charCodeAt(this.pos+2);if(i===61){return this.finishOp(d.assign,3)}}return this.finishOp(d.coalesce,2)}}return this.finishOp(d.question,1)};Ae.readToken_numberSign=function(){var e=this.options.ecmaVersion;var t=35;if(e>=13){++this.pos;t=this.fullCharCodeAtPos();if(isIdentifierStart(t,true)||t===92){return this.finishToken(d.privateId,this.readWord1())}}this.raise(this.pos,"Unexpected character '"+codePointToString$1(t)+"'")};Ae.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(d.parenL);case 41:++this.pos;return this.finishToken(d.parenR);case 59:++this.pos;return this.finishToken(d.semi);case 44:++this.pos;return this.finishToken(d.comma);case 91:++this.pos;return this.finishToken(d.bracketL);case 93:++this.pos;return this.finishToken(d.bracketR);case 123:++this.pos;return this.finishToken(d.braceL);case 125:++this.pos;return this.finishToken(d.braceR);case 58:++this.pos;return this.finishToken(d.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(d.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(t===111||t===79){return this.readRadixNumber(8)}if(t===98||t===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(d.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+codePointToString$1(e)+"'")};Ae.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);this.pos+=t;return this.finishToken(e,n)};Ae.readRegexp=function(){var e,t,n=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(n,"Unterminated regular expression")}var i=this.input.charAt(this.pos);if(m.test(i)){this.raise(n,"Unterminated regular expression")}if(!e){if(i==="["){t=true}else if(i==="]"&&t){t=false}else if(i==="/"&&!t){break}e=i==="\\"}else{e=false}++this.pos}var r=this.input.slice(n,this.pos);++this.pos;var a=this.pos;var o=this.readWord1();if(this.containsEsc){this.unexpected(a)}var s=this.regexpState||(this.regexpState=new Se(this));s.reset(n,r,o);this.validateRegExpFlags(s);this.validateRegExpPattern(s);var u=null;try{u=new RegExp(r,o)}catch(e){}return this.finishToken(d.regexp,{pattern:r,flags:o,value:u})};Ae.readInt=function(e,t,n){var i=this.options.ecmaVersion>=12&&t===undefined;var r=n&&this.input.charCodeAt(this.pos)===48;var a=this.pos,o=0,s=0;for(var u=0,c=t==null?Infinity:t;u=97){f=l-97+10}else if(l>=65){f=l-65+10}else if(l>=48&&l<=57){f=l-48}else{f=Infinity}if(f>=e){break}s=l;o=o*e+f}if(i&&s===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===a||t!=null&&this.pos-a!==t){return null}return o};function stringToNumber(e,t){if(t){return parseInt(e,8)}return parseFloat(e.replace(/_/g,""))}function stringToBigInt(e){if(typeof BigInt!=="function"){return null}return BigInt(e.replace(/_/g,""))}Ae.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var n=this.readInt(e);if(n==null){this.raise(this.start+2,"Expected number in radix "+e)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){n=stringToBigInt(this.input.slice(t,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(d.num,n)};Ae.readNumber=function(e){var t=this.pos;if(!e&&this.readInt(10,undefined,true)===null){this.raise(t,"Invalid number")}var n=this.pos-t>=2&&this.input.charCodeAt(t)===48;if(n&&this.strict){this.raise(t,"Invalid number")}var i=this.input.charCodeAt(this.pos);if(!n&&!e&&this.options.ecmaVersion>=11&&i===110){var r=stringToBigInt(this.input.slice(t,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(d.num,r)}if(n&&/[89]/.test(this.input.slice(t,this.pos))){n=false}if(i===46&&!n){++this.pos;this.readInt(10);i=this.input.charCodeAt(this.pos)}if((i===69||i===101)&&!n){i=this.input.charCodeAt(++this.pos);if(i===43||i===45){++this.pos}if(this.readInt(10)===null){this.raise(t,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var a=stringToNumber(this.input.slice(t,this.pos),n);return this.finishToken(d.num,a)};Ae.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){if(this.options.ecmaVersion<6){this.unexpected()}var n=++this.pos;t=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(t>1114111){this.invalidStringToken(n,"Code point out of bounds")}}else{t=this.readHexChar(4)}return t};function codePointToString$1(e){if(e<=65535){return String.fromCharCode(e)}e-=65536;return String.fromCharCode((e>>10)+55296,(e&1023)+56320)}Ae.readString=function(e){var t="",n=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var i=this.input.charCodeAt(this.pos);if(i===e){break}if(i===92){t+=this.input.slice(n,this.pos);t+=this.readEscapedChar(false);n=this.pos}else{if(isNewLine(i,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}t+=this.input.slice(n,this.pos++);return this.finishToken(d.string,t)};var Ce={};Ae.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(e){if(e===Ce){this.readInvalidTemplateToken()}else{throw e}}this.inTemplateElement=false};Ae.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw Ce}else{this.raise(e,t)}};Ae.readTmplToken=function(){var e="",t=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var n=this.input.charCodeAt(this.pos);if(n===96||n===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===d.template||this.type===d.invalidTemplate)){if(n===36){this.pos+=2;return this.finishToken(d.dollarBraceL)}else{++this.pos;return this.finishToken(d.backQuote)}}e+=this.input.slice(t,this.pos);return this.finishToken(d.template,e)}if(n===92){e+=this.input.slice(t,this.pos);e+=this.readEscapedChar(true);t=this.pos}else if(isNewLine(n)){e+=this.input.slice(t,this.pos);++this.pos;switch(n){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:e+="\n";break;default:e+=String.fromCharCode(n);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}t=this.pos}else{++this.pos}}};Ae.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var i=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var r=parseInt(i,8);if(r>255){i=i.slice(0,-1);r=parseInt(i,8)}this.pos+=i.length-1;t=this.input.charCodeAt(this.pos);if((i!=="0"||t===56||t===57)&&(this.strict||e)){this.invalidStringToken(this.pos-1-i.length,e?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(r)}if(isNewLine(t)){return""}return String.fromCharCode(t)}};Ae.readHexChar=function(e){var t=this.pos;var n=this.readInt(16,e);if(n===null){this.invalidStringToken(t,"Bad character escape sequence")}return n};Ae.readWord1=function(){this.containsEsc=false;var e="",t=true,n=this.pos;var i=this.options.ecmaVersion>=6;while(this.pos5&&t<2015)t+=2009;i[n]=t}else{i[n]=e&&HOP(e,n)?e[n]:t[n]}}return i}function noop(){}function return_false(){return false}function return_true(){return true}function return_this(){return this}function return_null(){return null}var r=function(){function MAP(t,n,i){var r=[],a=[],o;function doit(){var s=n(t[o],o);var u=s instanceof Last;if(u)s=s.v;if(s instanceof AtTop){s=s.v;if(s instanceof Splice){a.push.apply(a,i?s.v.slice().reverse():s.v)}else{a.push(s)}}else if(s!==e){if(s instanceof Splice){r.push.apply(r,i?s.v.slice().reverse():s.v)}else{r.push(s)}}return u}if(Array.isArray(t)){if(i){for(o=t.length;--o>=0;)if(doit())break;r.reverse();a.reverse()}else{for(o=0;o=0;){if(e[n]===t)e.splice(n,1)}}function mergeSort(e,t){if(e.length<2)return e.slice();function merge(e,n){var i=[],r=0,a=0,o=0;while(r{n+=e})}return n}function has_annotation(e,t){return e._annotations&t}function set_annotation(e,t){e._annotations|=t}var s="";var u=true;var c="break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with";var l="false null true";var f="enum implements import interface package private protected public static super this "+l+" "+c;var p="return new delete throw else case yield await";c=makePredicate(c);f=makePredicate(f);p=makePredicate(p);l=makePredicate(l);var _=makePredicate(characters("+-*&%=<>!?|~^"));var h=/[0-9a-f]/i;var d=/^0x[0-9a-f]+$/i;var m=/^0[0-7]+$/;var E=/^0o[0-7]+$/i;var g=/^0b[01]+$/i;var v=/^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;var D=/^(0[xob])?[0-9a-f]+n$/i;var b=makePredicate(["in","instanceof","typeof","new","void","delete","++","--","+","-","!","~","&","|","^","*","**","/","%",">>","<<",">>>","<",">","<=",">=","==","===","!=","!==","?","=","+=","-=","||=","&&=","??=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&=","&&","??","||"]);var y=makePredicate(characters("  \n\r\t\f\v​           \u2028\u2029   \ufeff"));var k=makePredicate(characters("\n\r\u2028\u2029"));var S=makePredicate(characters(";]),:"));var T=makePredicate(characters("[{(,;:"));var A=makePredicate(characters("[]{}(),;:"));var C={ID_Start:/[$A-Z_a-z\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\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\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\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-\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\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\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-\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-\uA7AD\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\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[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\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]|\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]|\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]/,ID_Continue:/(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\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\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\u0C81-\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\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\u1369-\u1371\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-\u19DA\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\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\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\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\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-\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\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\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-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\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\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\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[\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]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\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]|\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]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\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])+/};function get_full_char(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){if(is_surrogate_pair_tail(e.charCodeAt(t+1))){return e.charAt(t)+e.charAt(t+1)}}else if(is_surrogate_pair_tail(e.charCodeAt(t))){if(is_surrogate_pair_head(e.charCodeAt(t-1))){return e.charAt(t-1)+e.charAt(t)}}return e.charAt(t)}function get_full_char_code(e,t){if(is_surrogate_pair_head(e.charCodeAt(t))){return 65536+(e.charCodeAt(t)-55296<<10)+e.charCodeAt(t+1)-56320}return e.charCodeAt(t)}function get_full_char_length(e){var t=0;for(var n=0;n65535){e-=65536;return String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)}return String.fromCharCode(e)}function is_surrogate_pair_head(e){return e>=55296&&e<=56319}function is_surrogate_pair_tail(e){return e>=56320&&e<=57343}function is_digit(e){return e>=48&&e<=57}function is_identifier_start(e){return C.ID_Start.test(e)}function is_identifier_char(e){return C.ID_Continue.test(e)}const R=/^[a-z_$][a-z0-9_$]*$/i;function is_basic_identifier_string(e){return R.test(e)}function is_identifier_string(e,t){if(R.test(e)){return true}if(!t&&/[\ud800-\udfff]/.test(e)){return false}var n=C.ID_Start.exec(e);if(!n||n.index!==0){return false}e=e.slice(n[0].length);if(!e){return true}n=C.ID_Continue.exec(e);return!!n&&n[0].length===e.length}function parse_js_number(e,t=true){if(!t&&e.includes("e")){return NaN}if(d.test(e)){return parseInt(e.substr(2),16)}else if(m.test(e)){return parseInt(e.substr(1),8)}else if(E.test(e)){return parseInt(e.substr(2),8)}else if(g.test(e)){return parseInt(e.substr(2),2)}else if(v.test(e)){return parseFloat(e)}else{var n=parseFloat(e);if(n==e)return n}}class JS_Parse_Error extends Error{constructor(e,t,n,i,r){super();this.name="SyntaxError";this.message=e;this.filename=t;this.line=n;this.col=i;this.pos=r}}function js_error(e,t,n,i,r){throw new JS_Parse_Error(e,t,n,i,r)}function is_token(e,t,n){return e.type==t&&(n==null||e.value==n)}var x={};function tokenizer(e,t,n,i){var r={text:e,filename:t,pos:0,tokpos:0,line:1,tokline:0,col:0,tokcol:0,newline_before:false,regex_allowed:false,brace_counter:0,template_braces:[],comments_before:[],directives:{},directive_stack:[]};function peek(){return get_full_char(r.text,r.pos)}function is_option_chain_op(){const e=r.text.charCodeAt(r.pos+1)===46;if(!e)return false;const t=r.text.charCodeAt(r.pos+2);return t<48||t>57}function next(e,t){var n=get_full_char(r.text,r.pos++);if(e&&!n)throw x;if(k.has(n)){r.newline_before=r.newline_before||!t;++r.line;r.col=0;if(n=="\r"&&peek()=="\n"){++r.pos;n="\n"}}else{if(n.length>1){++r.pos;++r.col}++r.col}return n}function forward(e){while(e--)next()}function looking_at(e){return r.text.substr(r.pos,e.length)==e}function find_eol(){var e=r.text;for(var t=r.pos,n=r.text.length;t="0"&&e<="7"}function read_escaped_char(e,t,n){var i=next(true,e);switch(i.charCodeAt(0)){case 110:return"\n";case 114:return"\r";case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 120:return String.fromCharCode(hex_bytes(2,t));case 117:if(peek()=="{"){next(true);if(peek()==="}")parse_error("Expecting hex-character between {}");while(peek()=="0")next(true);var a,o=find("}",true)-r.pos;if(o>6||(a=hex_bytes(o,t))>1114111){parse_error("Unicode reference out of bounds")}next(true);return from_char_code(a)}return String.fromCharCode(hex_bytes(4,t));case 10:return"";case 13:if(peek()=="\n"){next(true,e);return""}}if(is_octal(i)){if(n&&t){const e=i==="0"&&!is_octal(peek());if(!e){parse_error("Octal escape sequences are not allowed in template strings")}}return read_octal_escape_sequence(i,t)}return i}function read_octal_escape_sequence(e,t){var n=peek();if(n>="0"&&n<="7"){e+=next(true);if(e[0]<="3"&&(n=peek())>="0"&&n<="7")e+=next(true)}if(e==="0")return"\0";if(e.length>0&&next_token.has_directive("use strict")&&t)parse_error("Legacy octal escape sequences are not allowed in strict mode");return String.fromCharCode(parseInt(e,8))}function hex_bytes(e,t){var n=0;for(;e>0;--e){if(!t&&isNaN(parseInt(peek(),16))){return parseInt(n,16)||""}var i=next(true);if(isNaN(parseInt(i,16)))parse_error("Invalid hex-character pattern in string");n+=i}return parseInt(n,16)}var E=with_eof_error("Unterminated string constant",function(){const e=r.pos;var t=next(),n=[];for(;;){var i=next(true,true);if(i=="\\")i=read_escaped_char(true,true);else if(i=="\r"||i=="\n")parse_error("Unterminated string constant");else if(i==t)break;n.push(i)}var a=token("string",n.join(""));s=r.text.slice(e,r.pos);a.quote=t;return a});var g=with_eof_error("Unterminated template",function(e){if(e){r.template_braces.push(r.brace_counter)}var t="",n="",i,a;next(true,true);while((i=next(true,true))!="`"){if(i=="\r"){if(peek()=="\n")++r.pos;i="\n"}else if(i=="$"&&peek()=="{"){next(true,true);r.brace_counter++;a=token(e?"template_head":"template_substitution",t);s=n;u=false;return a}n+=i;if(i=="\\"){var c=r.pos;var l=o&&(o.type==="name"||o.type==="punc"&&(o.value===")"||o.value==="]"));i=read_escaped_char(true,!l,true);n+=r.text.substr(c,r.pos-c)}t+=i}r.template_braces.pop();a=token(e?"template_head":"template_substitution",t);s=n;u=true;return a});function skip_line_comment(e){var t=r.regex_allowed;var n=find_eol(),i;if(n==-1){i=r.text.substr(r.pos);r.pos=r.text.length}else{i=r.text.substring(r.pos,n);r.pos=n}r.col=r.tokcol+(r.pos-r.tokpos);r.comments_before.push(token(e,i,true));r.regex_allowed=t;return next_token}var v=with_eof_error("Unterminated multiline comment",function(){var e=r.regex_allowed;var t=find("*/",true);var n=r.text.substring(r.pos,t).replace(/\r\n|\r|\u2028|\u2029/g,"\n");forward(get_full_char_length(n)+2);r.comments_before.push(token("comment2",n,true));r.newline_before=r.newline_before||n.includes("\n");r.regex_allowed=e;return next_token});var S=with_eof_error("Unterminated identifier name",function(){var e=[],t,n=false;var i=function(){n=true;next();if(peek()!=="u"){parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}")}return read_escaped_char(false,true)};if((t=peek())==="\\"){t=i();if(!is_identifier_start(t)){parse_error("First identifier char is an invalid identifier char")}}else if(is_identifier_start(t)){next()}else{return""}e.push(t);while((t=peek())!=null){if((t=peek())==="\\"){t=i();if(!is_identifier_char(t)){parse_error("Invalid escaped identifier char")}}else{if(!is_identifier_char(t)){break}next()}e.push(t)}const r=e.join("");if(f.has(r)&&n){parse_error("Escaped characters are not allowed in keywords")}return r});var C=with_eof_error("Unterminated regular expression",function(e){var t=false,n,i=false;while(n=next(true))if(k.has(n)){parse_error("Unexpected line terminator")}else if(t){e+="\\"+n;t=false}else if(n=="["){i=true;e+=n}else if(n=="]"&&i){i=false;e+=n}else if(n=="/"&&!i){break}else if(n=="\\"){t=true}else{e+=n}const r=S();return token("regexp","/"+e+"/"+r)});function read_operator(e){function grow(e){if(!peek())return e;var t=e+peek();if(b.has(t)){next();return grow(t)}else{return e}}return token("operator",grow(e||next()))}function handle_slash(){next();switch(peek()){case"/":next();return skip_line_comment("comment1");case"*":next();return v()}return r.regex_allowed?C(""):read_operator("/")}function handle_eq_sign(){next();if(peek()===">"){next();return token("arrow","=>")}else{return read_operator("=")}}function handle_dot(){next();if(is_digit(peek().charCodeAt(0))){return read_num(".")}if(peek()==="."){next();next();return token("expand","...")}return token("punc",".")}function read_word(){var e=S();if(a)return token("name",e);return l.has(e)?token("atom",e):!c.has(e)?token("name",e):b.has(e)?token("operator",e):token("keyword",e)}function read_private_word(){next();return token("privatename",S())}function with_eof_error(e,t){return function(n){try{return t(n)}catch(t){if(t===x)parse_error(e);else throw t}}}function next_token(e){if(e!=null)return C(e);if(i&&r.pos==0&&looking_at("#!")){start_token();forward(2);skip_line_comment("comment5")}for(;;){skip_whitespace();start_token();if(n){if(looking_at("\x3c!--")){forward(4);skip_line_comment("comment3");continue}if(looking_at("--\x3e")&&r.newline_before){forward(3);skip_line_comment("comment4");continue}}var t=peek();if(!t)return token("eof");var a=t.charCodeAt(0);switch(a){case 34:case 39:return E();case 46:return handle_dot();case 47:{var o=handle_slash();if(o===next_token)continue;return o}case 61:return handle_eq_sign();case 63:{if(!is_option_chain_op())break;next();next();return token("punc","?.")}case 96:return g(true);case 123:r.brace_counter++;break;case 125:r.brace_counter--;if(r.template_braces.length>0&&r.template_braces[r.template_braces.length-1]===r.brace_counter)return g(false);break}if(is_digit(a))return read_num();if(A.has(t))return token("punc",next());if(_.has(t))return read_operator();if(a==92||is_identifier_start(t))return read_word();if(a==35)return read_private_word();break}parse_error("Unexpected character '"+t+"'")}next_token.next=next;next_token.peek=peek;next_token.context=function(e){if(e)r=e;return r};next_token.add_directive=function(e){r.directive_stack[r.directive_stack.length-1].push(e);if(r.directives[e]===undefined){r.directives[e]=1}else{r.directives[e]++}};next_token.push_directives_stack=function(){r.directive_stack.push([])};next_token.pop_directives_stack=function(){var e=r.directive_stack[r.directive_stack.length-1];for(var t=0;t0};return next_token}var F=makePredicate(["typeof","void","delete","--","++","!","~","-","+"]);var O=makePredicate(["--","++"]);var w=makePredicate(["=","+=","-=","??=","&&=","||=","/=","*=","**=","%=",">>=","<<=",">>>=","|=","^=","&="]);var M=makePredicate(["??=","&&=","||="]);var N=function(e,t){for(var n=0;n","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],{});var I=makePredicate(["atom","num","big_int","string","regexp","name"]);function parse(e,t){const n=new WeakMap;t=defaults(t,{bare_returns:false,ecma:null,expression:false,filename:null,html5_comments:true,module:false,shebang:true,strict:false,toplevel:null},true);var i={input:typeof e=="string"?tokenizer(e,t.filename,t.html5_comments,t.shebang):e,token:null,prev:null,peeked:null,in_function:0,in_async:-1,in_generator:-1,in_directives:true,in_loop:0,labels:[]};i.token=next();function is(e,t){return is_token(i.token,e,t)}function peek(){return i.peeked||(i.peeked=i.input())}function next(){i.prev=i.token;if(!i.peeked)peek();i.token=i.peeked;i.peeked=null;i.in_directives=i.in_directives&&(i.token.type=="string"||is("punc",";"));return i.token}function prev(){return i.prev}function croak(e,t,n,r){var a=i.input.context();js_error(e,a.filename,t!=null?t:a.tokline,n!=null?n:a.tokcol,r!=null?r:a.tokpos)}function token_error(e,t){croak(t,e.line,e.col)}function unexpected(e){if(e==null)e=i.token;token_error(e,"Unexpected token: "+e.type+" ("+e.value+")")}function expect_token(e,t){if(is(e,t)){return next()}token_error(i.token,"Unexpected token "+i.token.type+" «"+i.token.value+"»"+", expected "+e+" «"+t+"»")}function expect(e){return expect_token("punc",e)}function has_newline_before(e){return e.nlb||!e.comments_before.every(e=>!e.nlb)}function can_insert_semicolon(){return!t.strict&&(is("eof")||is("punc","}")||has_newline_before(i.token))}function is_in_generator(){return i.in_generator===i.in_function}function is_in_async(){return i.in_async===i.in_function}function can_await(){return i.in_async===i.in_function||i.in_function===0&&i.input.has_directive("use strict")}function semicolon(e){if(is("punc",";"))next();else if(!e&&!can_insert_semicolon())unexpected()}function parenthesised(){expect("(");var e=k(true);expect(")");return e}function embed_tokens(e){return function _embed_tokens_wrapper(...t){const n=i.token;const r=e(...t);r.start=n;r.end=prev();return r}}function handle_regexp(){if(is("operator","/")||is("operator","/=")){i.peeked=null;i.token=i.input(i.token.value.substr(1))}}var r=embed_tokens(function statement(e,n,r){handle_regexp();switch(i.token.type){case"string":if(i.in_directives){var a=peek();if(!s.includes("\\")&&(is_token(a,"punc",";")||is_token(a,"punc","}")||has_newline_before(a)||is_token(a,"eof"))){i.input.add_directive(i.token.value)}else{i.in_directives=false}}var u=i.in_directives,f=simple_statement();return u&&f.body instanceof Xt?new X(f.body):f;case"template_head":case"num":case"big_int":case"regexp":case"operator":case"atom":return simple_statement();case"name":if(i.token.value=="async"&&is_token(peek(),"keyword","function")){next();next();if(n){croak("functions are not allowed as the body of a loop")}return o(pe,false,true,e)}if(i.token.value=="import"&&!is_token(peek(),"punc","(")&&!is_token(peek(),"punc",".")){next();var _=import_();semicolon();return _}return is_token(peek(),"punc",":")?labeled_statement():simple_statement();case"punc":switch(i.token.value){case"{":return new q({start:i.token,body:block_(),end:prev()});case"[":case"(":return simple_statement();case";":i.in_directives=false;next();return new Y;default:unexpected()}case"keyword":switch(i.token.value){case"break":next();return break_cont(ye);case"continue":next();return break_cont(ke);case"debugger":next();semicolon();return new G;case"do":next();var h=in_loop(statement);expect_token("keyword","while");var d=parenthesised();semicolon(true);return new J({body:h,condition:d});case"while":next();return new ee({condition:parenthesised(),body:in_loop(function(){return statement(false,true)})});case"for":next();return for_();case"class":next();if(n){croak("classes are not allowed as the body of a loop")}if(r){croak("classes are not allowed as the body of an if")}return class_(Et,e);case"function":next();if(n){croak("functions are not allowed as the body of a loop")}return o(pe,false,false,e);case"if":next();return if_();case"return":if(i.in_function==0&&!t.bare_returns)croak("'return' outside of function");next();var m=null;if(is("punc",";")){next()}else if(!can_insert_semicolon()){m=k(true);semicolon()}return new ve({value:m});case"switch":next();return new Ce({expression:parenthesised(),body:in_loop(switch_body_)});case"throw":next();if(has_newline_before(i.token))croak("Illegal newline after 'throw'");var m=k(true);semicolon();return new De({value:m});case"try":next();return try_();case"var":next();var _=c();semicolon();return _;case"let":next();var _=l();semicolon();return _;case"const":next();var _=p();semicolon();return _;case"with":if(i.input.has_directive("use strict")){croak("Strict mode may not include a with statement")}next();return new re({expression:parenthesised(),body:statement()});case"export":if(!is_token(peek(),"punc","(")){next();var _=export_();if(is("punc",";"))semicolon();return _}}}unexpected()});function labeled_statement(){var e=as_symbol(Pt);if(e.name==="await"&&is_in_async()){token_error(i.prev,"await cannot be used as label inside async function")}if(i.labels.some(t=>t.name===e.name)){croak("Label "+e.name+" defined twice")}expect(":");i.labels.push(e);var t=r();i.labels.pop();if(!(t instanceof Z)){e.references.forEach(function(t){if(t instanceof ke){t=t.label.start;croak("Continue label `"+e.name+"` refers to non-IterationStatement.",t.line,t.col,t.pos)}})}return new $({body:t,label:e})}function simple_statement(e){return new H({body:(e=k(true),semicolon(),e)})}function break_cont(e){var t=null,n;if(!can_insert_semicolon()){t=as_symbol(Ut,true)}if(t!=null){n=i.labels.find(e=>e.name===t.name);if(!n)croak("Undefined label "+t.name);t.thedef=n}else if(i.in_loop==0)croak(e.TYPE+" not inside a loop or switch");semicolon();var r=new e({label:t});if(n)n.references.push(r);return r}function for_(){var e="`for await` invalid in this context";var t=i.token;if(t.type=="name"&&t.value=="await"){if(!can_await()){token_error(t,e)}next()}else{t=false}expect("(");var n=null;if(!is("punc",";")){n=is("keyword","var")?(next(),c(true)):is("keyword","let")?(next(),l(true)):is("keyword","const")?(next(),p(true)):k(true,true);var r=is("operator","in");var a=is("name","of");if(t&&!a){token_error(t,e)}if(r||a){if(n instanceof Ne){if(n.definitions.length>1)token_error(n.start,"Only one variable declaration allowed in for..in loop")}else if(!(is_assignable(n)||(n=to_destructuring(n))instanceof _e)){token_error(n.start,"Invalid left-hand side in for..in loop")}next();if(r){return for_in(n)}else{return for_of(n,!!t)}}}else if(t){token_error(t,e)}return regular_for(n)}function regular_for(e){expect(";");var t=is("punc",";")?null:k(true);expect(";");var n=is("punc",")")?null:k(true);expect(")");return new te({init:e,condition:t,step:n,body:in_loop(function(){return r(false,true)})})}function for_of(e,t){var n=e instanceof Ne?e.definitions[0].name:null;var i=k(true);expect(")");return new ie({await:t,init:e,name:n,object:i,body:in_loop(function(){return r(false,true)})})}function for_in(e){var t=k(true);expect(")");return new ne({init:e,object:t,body:in_loop(function(){return r(false,true)})})}var a=function(e,t,n){if(has_newline_before(i.token)){croak("Unexpected newline before arrow (=>)")}expect_token("arrow","=>");var r=_function_body(is("punc","{"),false,n);var a=r instanceof Array&&r.length?r[r.length-1].end:r instanceof Array?e:r.end;return new fe({start:e,end:a,async:n,argnames:t,body:r})};var o=function(e,t,n,i){var r=e===pe;var a=is("operator","*");if(a){next()}var o=is("name")?as_symbol(r?Ct:Ft):null;if(r&&!o){if(i){e=le}else{unexpected()}}if(o&&e!==ce&&!(o instanceof bt))unexpected(prev());var s=[];var u=_function_body(true,a||t,n,o,s);return new e({start:s.start,end:u.end,is_generator:a,async:n,name:o,argnames:s,body:u})};function track_used_binding_identifiers(e,t){var n=new Set;var i=false;var r=false;var a=false;var o=!!t;var s={add_parameter:function(t){if(n.has(t.value)){if(i===false){i=t}s.check_strict()}else{n.add(t.value);if(e){switch(t.value){case"arguments":case"eval":case"yield":if(o){token_error(t,"Unexpected "+t.value+" identifier as parameter inside strict mode")}break;default:if(f.has(t.value)){unexpected()}}}}},mark_default_assignment:function(e){if(r===false){r=e}},mark_spread:function(e){if(a===false){a=e}},mark_strict_mode:function(){o=true},is_strict:function(){return r!==false||a!==false||o},check_strict:function(){if(s.is_strict()&&i!==false){token_error(i,"Parameter "+i.value+" was used already")}}};return s}function parameters(e){var t=track_used_binding_identifiers(true,i.input.has_directive("use strict"));expect("(");while(!is("punc",")")){var n=parameter(t);e.push(n);if(!is("punc",")")){expect(",")}if(n instanceof se){break}}next()}function parameter(e,t){var n;var r=false;if(e===undefined){e=track_used_binding_identifiers(true,i.input.has_directive("use strict"))}if(is("expand","...")){r=i.token;e.mark_spread(i.token);next()}n=binding_element(e,t);if(is("operator","=")&&r===false){e.mark_default_assignment(i.token);next();n=new it({start:n.start,left:n,operator:"=",right:k(false),end:i.token})}if(r!==false){if(!is("punc",")")){unexpected()}n=new se({start:r,expression:n,end:r})}e.check_strict();return n}function binding_element(e,t){var n=[];var r=true;var a=false;var o;var s=i.token;if(e===undefined){e=track_used_binding_identifiers(false,i.input.has_directive("use strict"))}t=t===undefined?At:t;if(is("punc","[")){next();while(!is("punc","]")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("punc")){switch(i.token.value){case",":n.push(new Qt({start:i.token,end:i.token}));continue;case"]":break;case"[":case"{":n.push(binding_element(e,t));break;default:unexpected()}}else if(is("name")){e.add_parameter(i.token);n.push(as_symbol(t))}else{croak("Invalid function parameter")}if(is("operator","=")&&a===false){e.mark_default_assignment(i.token);next();n[n.length-1]=new it({start:n[n.length-1].start,left:n[n.length-1],operator:"=",right:k(false),end:i.token})}if(a){if(!is("punc","]")){croak("Rest element must be last element")}n[n.length-1]=new se({start:o,expression:n[n.length-1],end:o})}}expect("]");e.check_strict();return new _e({start:s,names:n,is_array:true,end:prev()})}else if(is("punc","{")){next();while(!is("punc","}")){if(r){r=false}else{expect(",")}if(is("expand","...")){a=true;o=i.token;e.mark_spread(i.token);next()}if(is("name")&&(is_token(peek(),"punc")||is_token(peek(),"operator"))&&[",","}","="].includes(peek().value)){e.add_parameter(i.token);var u=prev();var c=as_symbol(t);if(a){n.push(new se({start:o,expression:c,end:c.end}))}else{n.push(new st({start:u,key:c.name,value:c,end:c.end}))}}else if(is("punc","}")){continue}else{var l=i.token;var f=as_property_name();if(f===null){unexpected(prev())}else if(prev().type==="name"&&!is("punc",":")){n.push(new st({start:prev(),key:f,value:new t({start:prev(),name:f,end:prev()}),end:prev()}))}else{expect(":");n.push(new st({start:l,quote:l.quote,key:f,value:binding_element(e,t),end:prev()}))}}if(a){if(!is("punc","}")){croak("Rest element must be last element")}}else if(is("operator","=")){e.mark_default_assignment(i.token);next();n[n.length-1].value=new it({start:n[n.length-1].value.start,left:n[n.length-1].value,operator:"=",right:k(false),end:i.token})}}expect("}");e.check_strict();return new _e({start:s,names:n,is_array:false,end:prev()})}else if(is("name")){e.add_parameter(i.token);return as_symbol(t)}else{croak("Invalid function parameter")}}function params_or_seq_(e,t){var n;var r;var a;var o=[];expect("(");while(!is("punc",")")){if(n)unexpected(n);if(is("expand","...")){n=i.token;if(t)r=i.token;next();o.push(new se({start:prev(),expression:k(),end:i.token}))}else{o.push(k())}if(!is("punc",")")){expect(",");if(is("punc",")")){a=prev();if(t)r=a}}}expect(")");if(e&&is("arrow","=>")){if(n&&a)unexpected(a)}else if(r){unexpected(r)}return o}function _function_body(e,t,n,r,a){var o=i.in_loop;var s=i.labels;var u=i.in_generator;var c=i.in_async;++i.in_function;if(t)i.in_generator=i.in_function;if(n)i.in_async=i.in_function;if(a)parameters(a);if(e)i.in_directives=true;i.in_loop=0;i.labels=[];if(e){i.input.push_directives_stack();var l=block_();if(r)_verify_symbol(r);if(a)a.forEach(_verify_symbol);i.input.pop_directives_stack()}else{var l=[new ve({start:i.token,value:k(false),end:i.token})]}--i.in_function;i.in_loop=o;i.labels=s;i.in_generator=u;i.in_async=c;return l}function _await_expression(){if(!can_await()){croak("Unexpected await expression outside async function",i.prev.line,i.prev.col,i.prev.pos)}return new Se({start:prev(),end:i.token,expression:v(true)})}function _yield_expression(){if(!is_in_generator()){croak("Unexpected yield expression outside generator function",i.prev.line,i.prev.col,i.prev.pos)}var e=i.token;var t=false;var n=true;if(can_insert_semicolon()||is("punc")&&S.has(i.token.value)){n=false}else if(is("operator","*")){t=true;next()}return new Te({start:e,is_star:t,expression:n?k():null,end:prev()})}function if_(){var e=parenthesised(),t=r(false,false,true),n=null;if(is("keyword","else")){next();n=r(false,false,true)}return new Ae({condition:e,body:t,alternative:n})}function block_(){expect("{");var e=[];while(!is("punc","}")){if(is("eof"))unexpected();e.push(r())}next();return e}function switch_body_(){expect("{");var e=[],t=null,n=null,a;while(!is("punc","}")){if(is("eof"))unexpected();if(is("keyword","case")){if(n)n.end=prev();t=[];n=new Fe({start:(a=i.token,next(),a),expression:k(true),body:t});e.push(n);expect(":")}else if(is("keyword","default")){if(n)n.end=prev();t=[];n=new xe({start:(a=i.token,next(),expect(":"),a),body:t});e.push(n)}else{if(!t)unexpected();t.push(r())}}if(n)n.end=prev();next();return e}function try_(){var e=block_(),t=null,n=null;if(is("keyword","catch")){var r=i.token;next();if(is("punc","{")){var a=null}else{expect("(");var a=parameter(undefined,Mt);expect(")")}t=new we({start:r,argname:a,body:block_(),end:prev()})}if(is("keyword","finally")){var r=i.token;next();n=new Me({start:r,body:block_(),end:prev()})}if(!t&&!n)croak("Missing catch/finally blocks");return new Oe({body:e,bcatch:t,bfinally:n})}function vardefs(e,t){var n=[];var r;for(;;){var a=t==="var"?yt:t==="const"?St:t==="let"?Tt:null;if(is("punc","{")||is("punc","[")){r=new Be({start:i.token,name:binding_element(undefined,a),value:is("operator","=")?(expect_token("operator","="),k(false,e)):null,end:prev()})}else{r=new Be({start:i.token,name:as_symbol(a),value:is("operator","=")?(next(),k(false,e)):!e&&t==="const"?croak("Missing initializer in const declaration"):null,end:prev()});if(r.name.name=="import")croak("Unexpected token: import")}n.push(r);if(!is("punc",","))break;next()}return n}var c=function(e){return new Ie({start:prev(),definitions:vardefs(e,"var"),end:prev()})};var l=function(e){return new Pe({start:prev(),definitions:vardefs(e,"let"),end:prev()})};var p=function(e){return new Le({start:prev(),definitions:vardefs(e,"const"),end:prev()})};var _=function(e){var t=i.token;expect_token("operator","new");if(is("punc",".")){next();expect_token("name","target");return g(new Dt({start:t,end:prev()}),e)}var n=h(false),r;if(is("punc","(")){next();r=expr_list(")",true)}else{r=[]}var a=new Xe({start:t,expression:n,args:r,end:prev()});annotate(a);return g(a,e)};function as_atom_node(){var e=i.token,t;switch(e.type){case"name":t=_make_symbol(Lt);break;case"num":t=new Ht({start:e,end:e,value:e.value,raw:s});break;case"big_int":t=new Wt({start:e,end:e,value:e.value});break;case"string":t=new Xt({start:e,end:e,value:e.value,quote:e.quote});break;case"regexp":const[n,i,r]=e.value.match(/^\/(.*)\/(\w*)$/);t=new qt({start:e,end:e,value:{source:i,flags:r}});break;case"atom":switch(e.value){case"false":t=new tn({start:e,end:e});break;case"true":t=new nn({start:e,end:e});break;case"null":t=new jt({start:e,end:e});break}break}next();return t}function to_fun_args(e,t){var n=function(e,t){if(t){return new it({start:e.start,left:e,operator:"=",right:t,end:t.end})}return e};if(e instanceof at){return n(new _e({start:e.start,end:e.end,is_array:false,names:e.properties.map(e=>to_fun_args(e))}),t)}else if(e instanceof st){e.value=to_fun_args(e.value);return n(e,t)}else if(e instanceof Qt){return e}else if(e instanceof _e){e.names=e.names.map(e=>to_fun_args(e));return n(e,t)}else if(e instanceof Lt){return n(new At({name:e.name,start:e.start,end:e.end}),t)}else if(e instanceof se){e.expression=to_fun_args(e.expression);return n(e,t)}else if(e instanceof rt){return n(new _e({start:e.start,end:e.end,is_array:true,names:e.elements.map(e=>to_fun_args(e))}),t)}else if(e instanceof nt){return n(to_fun_args(e.left,e.right),t)}else if(e instanceof it){e.left=to_fun_args(e.left);return e}else{croak("Invalid function parameter",e.start.line,e.start.col)}}var h=function(e,t){if(is("operator","new")){return _(e)}if(is("operator","import")){return import_meta()}var r=i.token;var s;var u=is("name","async")&&(s=peek()).value!="["&&s.type!="arrow"&&as_atom_node();if(is("punc")){switch(i.token.value){case"(":if(u&&!e)break;var c=params_or_seq_(t,!u);if(t&&is("arrow","=>")){return a(r,c.map(e=>to_fun_args(e)),!!u)}var l=u?new Ge({expression:u,args:c}):c.length==1?c[0]:new He({expressions:c});if(l.start){const e=r.comments_before.length;n.set(r,e);l.start.comments_before.unshift(...r.comments_before);r.comments_before=l.start.comments_before;if(e==0&&r.comments_before.length>0){var f=r.comments_before[0];if(!f.nlb){f.nlb=r.nlb;r.nlb=false}}r.comments_after=l.start.comments_after}l.start=r;var p=prev();if(l.end){p.comments_before=l.end.comments_before;l.end.comments_after.push(...p.comments_after);p.comments_after=l.end.comments_after}l.end=p;if(l instanceof Ge)annotate(l);return g(l,e);case"[":return g(d(),e);case"{":return g(E(),e)}if(!u)unexpected()}if(t&&is("name")&&is_token(peek(),"arrow")){var h=new At({name:i.token.value,start:r,end:r});next();return a(r,[h],!!u)}if(is("keyword","function")){next();var m=o(le,false,!!u);m.start=r;m.end=prev();return g(m,e)}if(u)return g(u,e);if(is("keyword","class")){next();var v=class_(gt);v.start=r;v.end=prev();return g(v,e)}if(is("template_head")){return g(template_string(),e)}if(I.has(i.token.type)){return g(as_atom_node(),e)}unexpected()};function template_string(){var e=[],t=i.token;e.push(new me({start:i.token,raw:s,value:i.token.value,end:i.token}));while(!u){next();handle_regexp();e.push(k(true));e.push(new me({start:i.token,raw:s,value:i.token.value,end:i.token}))}next();return new de({start:t,segments:e,end:i.token})}function expr_list(e,t,n){var r=true,a=[];while(!is("punc",e)){if(r)r=false;else expect(",");if(t&&is("punc",e))break;if(is("punc",",")&&n){a.push(new Qt({start:i.token,end:i.token}))}else if(is("expand","...")){next();a.push(new se({start:prev(),expression:k(),end:i.token}))}else{a.push(k(false))}}next();return a}var d=embed_tokens(function(){expect("[");return new rt({elements:expr_list("]",!t.strict,true)})});var m=embed_tokens((e,t)=>{return o(ce,e,t)});var E=embed_tokens(function object_or_destructuring_(){var e=i.token,n=true,r=[];expect("{");while(!is("punc","}")){if(n)n=false;else expect(",");if(!t.strict&&is("punc","}"))break;e=i.token;if(e.type=="expand"){next();r.push(new se({start:e,expression:k(false),end:prev()}));continue}var a=as_property_name();var o;if(!is("punc",":")){var s=concise_method_or_getset(a,e);if(s){r.push(s);continue}o=new Lt({start:prev(),name:a,end:prev()})}else if(a===null){unexpected(prev())}else{next();o=k(false)}if(is("operator","=")){next();o=new nt({start:e,left:o,operator:"=",right:k(false),logical:false,end:prev()})}r.push(new st({start:e,quote:e.quote,key:a instanceof z?a:""+a,value:o,end:prev()}))}next();return new at({properties:r})});function class_(e,t){var n,r,a,o,s=[];i.input.push_directives_stack();i.input.add_directive("use strict");if(i.token.type=="name"&&i.token.value!="extends"){a=as_symbol(e===Et?Ot:wt)}if(e===Et&&!a){if(t){e=gt}else{unexpected()}}if(i.token.value=="extends"){next();o=k(true)}expect("{");while(is("punc",";")){next()}while(!is("punc","}")){n=i.token;r=concise_method_or_getset(as_property_name(),n,true);if(!r){unexpected()}s.push(r);while(is("punc",";")){next()}}i.input.pop_directives_stack();next();return new e({start:n,name:a,extends:o,properties:s,end:prev()})}function concise_method_or_getset(e,t,n){const i=(e,n=Rt)=>{if(typeof e==="string"||typeof e==="number"){return new n({start:t,name:""+e,end:prev()})}else if(e===null){unexpected()}return e};const r=()=>!is("punc","(")&&!is("punc",",")&&!is("punc","}")&&!is("operator","=");var a=false;var o=false;var s=false;var u=false;var c=null;if(n&&e==="static"&&r()){o=true;e=as_property_name()}if(e==="async"&&r()){a=true;e=as_property_name()}if(prev().type==="operator"&&prev().value==="*"){s=true;e=as_property_name()}if((e==="get"||e==="set")&&r()){c=e;e=as_property_name()}if(prev().type==="privatename"){u=true}const l=prev();if(c!=null){if(!u){const n=c==="get"?ft:lt;e=i(e);return new n({start:t,static:o,key:e,quote:e instanceof Rt?l.quote:undefined,value:m(),end:prev()})}else{const n=c==="get"?ct:ut;return new n({start:t,static:o,key:i(e),value:m(),end:prev()})}}if(is("punc","(")){e=i(e);const n=u?_t:pt;var f=new n({start:t,static:o,is_generator:s,async:a,key:e,quote:e instanceof Rt?l.quote:undefined,value:m(s,a),end:prev()});return f}if(n){const n=i(e,xt);const r=n instanceof xt?l.quote:undefined;const a=u?mt:dt;if(is("operator","=")){next();return new a({start:t,static:o,quote:r,key:n,value:k(false),end:prev()})}else if(is("name")||is("privatename")||is("operator","*")||is("punc",";")||is("punc","}")){return new a({start:t,static:o,quote:r,key:n,end:prev()})}}}function import_(){var e=prev();var t;var n;if(is("name")){t=as_symbol(Nt)}if(is("punc",",")){next()}n=map_names(true);if(n||t){expect_token("name","from")}var r=i.token;if(r.type!=="string"){unexpected()}next();return new Ue({start:e,imported_name:t,imported_names:n,module_name:new Xt({start:r,value:r.value,quote:r.quote,end:r}),end:i.token})}function import_meta(){var e=i.token;expect_token("operator","import");expect_token("punc",".");expect_token("name","meta");return g(new ze({start:e,end:prev()}),false)}function map_name(e){function make_symbol(e){return new e({name:as_property_name(),start:prev(),end:prev()})}var t=e?It:Vt;var n=e?Nt:Bt;var r=i.token;var a;var o;if(e){a=make_symbol(t)}else{o=make_symbol(n)}if(is("name","as")){next();if(e){o=make_symbol(n)}else{a=make_symbol(t)}}else if(e){o=new n(a)}else{a=new t(o)}return new Ve({start:r,foreign_name:a,name:o,end:prev()})}function map_nameAsterisk(e,t){var n=e?It:Vt;var r=e?Nt:Bt;var a=i.token;var o;var s=prev();t=t||new r({name:"*",start:a,end:s});o=new n({name:"*",start:a,end:s});return new Ve({start:a,foreign_name:o,name:t,end:s})}function map_names(e){var t;if(is("punc","{")){next();t=[];while(!is("punc","}")){t.push(map_name(e));if(is("punc",",")){next()}}next()}else if(is("operator","*")){var n;next();if(e&&is("name","as")){next();n=as_symbol(e?Nt:Vt)}t=[map_nameAsterisk(e,n)]}return t}function export_(){var e=i.token;var t;var n;if(is("keyword","default")){t=true;next()}else if(n=map_names(false)){if(is("name","from")){next();var a=i.token;if(a.type!=="string"){unexpected()}next();return new Ke({start:e,is_default:t,exported_names:n,module_name:new Xt({start:a,value:a.value,quote:a.quote,end:a}),end:prev()})}else{return new Ke({start:e,is_default:t,exported_names:n,end:prev()})}}var o;var s;var u;if(is("punc","{")||t&&(is("keyword","class")||is("keyword","function"))&&is_token(peek(),"punc")){s=k(false);semicolon()}else if((o=r(t))instanceof Ne&&t){unexpected(o.start)}else if(o instanceof Ne||o instanceof pe||o instanceof Et){u=o}else if(o instanceof gt||o instanceof le){s=o}else if(o instanceof H){s=o.body}else{unexpected(o.start)}return new Ke({start:e,is_default:t,exported_value:s,exported_definition:u,end:prev()})}function as_property_name(){var e=i.token;switch(e.type){case"punc":if(e.value==="["){next();var t=k(false);expect("]");return t}else unexpected(e);case"operator":if(e.value==="*"){next();return null}if(!["delete","in","instanceof","new","typeof","void"].includes(e.value)){unexpected(e)}case"name":case"privatename":case"string":case"num":case"big_int":case"keyword":case"atom":next();return e.value;default:unexpected(e)}}function as_name(){var e=i.token;if(e.type!="name"&&e.type!="privatename")unexpected();next();return e.value}function _make_symbol(e){var t=i.token.value;return new(t=="this"?zt:t=="super"?Kt:e)({name:String(t),start:i.token,end:i.token})}function _verify_symbol(e){var t=e.name;if(is_in_generator()&&t=="yield"){token_error(e.start,"Yield cannot be used as identifier inside generators")}if(i.input.has_directive("use strict")){if(t=="yield"){token_error(e.start,"Unexpected yield identifier inside strict mode")}if(e instanceof bt&&(t=="arguments"||t=="eval")){token_error(e.start,"Unexpected "+t+" in strict mode")}}}function as_symbol(e,t){if(!is("name")){if(!t)croak("Name expected");return null}var n=_make_symbol(e);_verify_symbol(n);next();return n}function annotate(e){var t=e.start;var i=t.comments_before;const r=n.get(t);var a=r!=null?r:i.length;while(--a>=0){var o=i[a];if(/[@#]__/.test(o.value)){if(/[@#]__PURE__/.test(o.value)){set_annotation(e,an);break}if(/[@#]__INLINE__/.test(o.value)){set_annotation(e,on);break}if(/[@#]__NOINLINE__/.test(o.value)){set_annotation(e,sn);break}}}}var g=function(e,t,n){var i=e.start;if(is("punc",".")){next();const r=is("privatename")?Ye:qe;return g(new r({start:i,expression:e,optional:false,property:as_name(),end:prev()}),t,n)}if(is("punc","[")){next();var r=k(true);expect("]");return g(new je({start:i,expression:e,optional:false,property:r,end:prev()}),t,n)}if(t&&is("punc","(")){next();var a=new Ge({start:i,expression:e,optional:false,args:call_args(),end:prev()});annotate(a);return g(a,true,n)}if(is("punc","?.")){next();let n;if(t&&is("punc","(")){next();const t=new Ge({start:i,optional:true,expression:e,args:call_args(),end:prev()});annotate(t);n=g(t,true,true)}else if(is("name")||is("privatename")){const r=is("privatename")?Ye:qe;n=g(new r({start:i,expression:e,optional:true,property:as_name(),end:prev()}),t,true)}else if(is("punc","[")){next();const r=k(true);expect("]");n=g(new je({start:i,expression:e,optional:true,property:r,end:prev()}),t,true)}if(!n)unexpected();if(n instanceof $e)return n;return new $e({start:i,expression:n,end:prev()})}if(is("template_head")){if(n){unexpected()}return g(new he({start:i,prefix:e,template_string:template_string(),end:prev()}),t)}return e};function call_args(){var e=[];while(!is("punc",")")){if(is("expand","...")){next();e.push(new se({start:prev(),expression:k(false),end:prev()}))}else{e.push(k(false))}if(!is("punc",")")){expect(",")}}next();return e}var v=function(e,t){var n=i.token;if(n.type=="name"&&n.value=="await"&&can_await()){next();return _await_expression()}if(is("operator")&&F.has(n.value)){next();handle_regexp();var r=make_unary(Qe,n,v(e));r.start=n;r.end=prev();return r}var a=h(e,t);while(is("operator")&&O.has(i.token.value)&&!has_newline_before(i.token)){if(a instanceof fe)unexpected();a=make_unary(Je,i.token,a);a.start=n;a.end=i.token;next()}return a};function make_unary(e,t,n){var r=t.value;switch(r){case"++":case"--":if(!is_assignable(n))croak("Invalid use of "+r+" operator",t.line,t.col,t.pos);break;case"delete":if(n instanceof Lt&&i.input.has_directive("use strict"))croak("Calling delete on expression not allowed in strict mode",n.start.line,n.start.col,n.start.pos);break}return new e({operator:r,expression:n})}var D=function(e,t,n){var r=is("operator")?i.token.value:null;if(r=="in"&&n)r=null;if(r=="**"&&e instanceof Qe&&!is_token(e.start,"punc","(")&&e.operator!=="--"&&e.operator!=="++")unexpected(e.start);var a=r!=null?N[r]:null;if(a!=null&&(a>t||r==="**"&&t===a)){next();var o=D(v(true),a,n);return D(new et({start:e.start,left:e,operator:r,right:o,end:o.end}),t,n)}return e};function expr_ops(e){return D(v(true,true),0,e)}var b=function(e){var t=i.token;var n=expr_ops(e);if(is("operator","?")){next();var r=k(false);expect(":");return new tt({start:t,condition:n,consequent:r,alternative:k(false,e),end:prev()})}return n};function is_assignable(e){return e instanceof We||e instanceof Lt}function to_destructuring(e){if(e instanceof at){e=new _e({start:e.start,names:e.properties.map(to_destructuring),is_array:false,end:e.end})}else if(e instanceof rt){var t=[];for(var n=0;n=0;){a+="this."+t[o]+" = props."+t[o]+";"}const s=i&&Object.create(i.prototype);if(s&&s.initialize||n&&n.initialize)a+="this.initialize();";a+="}";a+="this.flags = 0;";a+="}";var u=new Function(a)();if(s){u.prototype=s;u.BASE=i}if(i)i.SUBCLASSES.push(u);u.prototype.CTOR=u;u.prototype.constructor=u;u.PROPS=t||null;u.SELF_PROPS=r;u.SUBCLASSES=[];if(e){u.prototype.TYPE=u.TYPE=e}if(n)for(o in n)if(HOP(n,o)){if(o[0]==="$"){u[o.substr(1)]=n[o]}else{u.prototype[o]=n[o]}}u.DEFMETHOD=function(e,t){this.prototype[e]=t};return u}const P=(e,t)=>Boolean(e.flags&t);const L=(e,t,n)=>{if(n){e.flags|=t}else{e.flags&=~t}};const B=1;const V=2;const U=4;class AST_Token{constructor(e,t,n,i,r,a,o,s,u){this.flags=a?1:0;this.type=e;this.value=t;this.line=n;this.col=i;this.pos=r;this.comments_before=o;this.comments_after=s;this.file=u;Object.seal(this)}get nlb(){return P(this,B)}set nlb(e){L(this,B,e)}get quote(){return!P(this,U)?"":P(this,V)?"'":'"'}set quote(e){L(this,V,e==="'");L(this,U,!!e)}}var z=DEFNODE("Node","start end",{_clone:function(e){if(e){var t=this.clone();return t.transform(new TreeTransformer(function(e){if(e!==t){return e.clone(true)}}))}return new this.CTOR(this)},clone:function(e){return this._clone(e)},$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(e){return e._visit(this)},walk:function(e){return this._walk(e)},_children_backwards:()=>{}},null);var K=DEFNODE("Statement",null,{$documentation:"Base class of all statements"});var G=DEFNODE("Debugger",null,{$documentation:"Represents a debugger statement"},K);var X=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"}},K);var H=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(e){return e._visit(this,function(){this.body._walk(e)})},_children_backwards(e){e(this.body)}},K);function walk_body(e,t){const n=e.body;for(var i=0,r=n.length;i SymbolDef for all variables/functions defined in this scope",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 e=this;while(e.is_block_scope()){e=e.parent_scope}return e},clone:function(e,t){var n=this._clone(e);if(e&&this.variables&&t&&!this._block_scope){n.figure_out_scope({},{toplevel:t,parent_scope:this.parent_scope})}else{if(this.variables)n.variables=new Map(this.variables);if(this.enclosed)n.enclosed=this.enclosed.slice();if(this._block_scope)n._block_scope=this._block_scope}return n},pinned:function(){return this.uses_eval||this.uses_with}},W);var oe=DEFNODE("Toplevel","globals",{$documentation:"The toplevel scope",$propdoc:{globals:"[Map/S] a map of name -> SymbolDef for all undeclared names"},wrap_commonjs:function(e){var t=this.body;var n="(function(exports){'$ORIG';})(typeof "+e+"=='undefined'?("+e+"={}):"+e+");";n=parse(n);n=n.transform(new TreeTransformer(function(e){if(e instanceof X&&e.value=="$ORIG"){return r.splice(t)}}));return n},wrap_enclose:function(e){if(typeof e!="string")e="";var t=e.indexOf(":");if(t<0)t=e.length;var n=this.body;return parse(["(function(",e.slice(0,t),'){"$ORIG"})(',e.slice(t+1),")"].join("")).transform(new TreeTransformer(function(e){if(e instanceof X&&e.value=="$ORIG"){return r.splice(n)}}))}},ae);var se=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(e){return e._visit(this,function(){this.expression.walk(e)})},_children_backwards(e){e(this.expression)}});var ue=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 e=[];for(var t=0;t b)"},ue);var pe=DEFNODE("Defun",null,{$documentation:"A function definition"},ue);var _e=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(e){return e._visit(this,function(){this.names.forEach(function(t){t._walk(e)})})},_children_backwards(e){let t=this.names.length;while(t--)e(this.names[t])},all_symbols:function(){var e=[];this.walk(new TreeWalker(function(t){if(t instanceof vt){e.push(t)}}));return e}});var he=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(e){return e._visit(this,function(){this.prefix._walk(e);this.template_string._walk(e)})},_children_backwards(e){e(this.template_string);e(this.prefix)}});var de=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(e){return e._visit(this,function(){this.segments.forEach(function(t){t._walk(e)})})},_children_backwards(e){let t=this.segments.length;while(t--)e(this.segments[t])}});var me=DEFNODE("TemplateSegment","value raw",{$documentation:"A segment of a template string literal",$propdoc:{value:"Content of the segment",raw:"Raw source of the segment"}});var Ee=DEFNODE("Jump",null,{$documentation:"Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"},K);var ge=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(e){return e._visit(this,this.value&&function(){this.value._walk(e)})},_children_backwards(e){if(this.value)e(this.value)}},Ee);var ve=DEFNODE("Return",null,{$documentation:"A `return` statement"},ge);var De=DEFNODE("Throw",null,{$documentation:"A `throw` statement"},ge);var be=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(e){return e._visit(this,this.label&&function(){this.label._walk(e)})},_children_backwards(e){if(this.label)e(this.label)}},Ee);var ye=DEFNODE("Break",null,{$documentation:"A `break` statement"},be);var ke=DEFNODE("Continue",null,{$documentation:"A `continue` statement"},be);var Se=DEFNODE("Await","expression",{$documentation:"An `await` statement",$propdoc:{expression:"[AST_Node] the mandatory expression being awaited"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e)})},_children_backwards(e){e(this.expression)}});var Te=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(e){return e._visit(this,this.expression&&function(){this.expression._walk(e)})},_children_backwards(e){if(this.expression)e(this.expression)}});var Ae=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(e){return e._visit(this,function(){this.condition._walk(e);this.body._walk(e);if(this.alternative)this.alternative._walk(e)})},_children_backwards(e){if(this.alternative){e(this.alternative)}e(this.body);e(this.condition)}},j);var Ce=DEFNODE("Switch","expression",{$documentation:"A `switch` statement",$propdoc:{expression:"[AST_Node] the `switch` “discriminant”"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},W);var Re=DEFNODE("SwitchBranch",null,{$documentation:"Base class for `switch` branches"},W);var xe=DEFNODE("Default",null,{$documentation:"A `default` switch branch"},Re);var Fe=DEFNODE("Case","expression",{$documentation:"A `case` switch branch",$propdoc:{expression:"[AST_Node] the `case` expression"},_walk:function(e){return e._visit(this,function(){this.expression._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);e(this.expression)}},Re);var Oe=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(e){return e._visit(this,function(){walk_body(this,e);if(this.bcatch)this.bcatch._walk(e);if(this.bfinally)this.bfinally._walk(e)})},_children_backwards(e){if(this.bfinally)e(this.bfinally);if(this.bcatch)e(this.bcatch);let t=this.body.length;while(t--)e(this.body[t])}},W);var we=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(e){return e._visit(this,function(){if(this.argname)this.argname._walk(e);walk_body(this,e)})},_children_backwards(e){let t=this.body.length;while(t--)e(this.body[t]);if(this.argname)e(this.argname)}},W);var Me=DEFNODE("Finally",null,{$documentation:"A `finally` node; only makes sense as part of a `try` statement"},W);var Ne=DEFNODE("Definitions","definitions",{$documentation:"Base class for `var` or `const` nodes (variable declarations/initializations)",$propdoc:{definitions:"[AST_VarDef*] array of variable definitions"},_walk:function(e){return e._visit(this,function(){var t=this.definitions;for(var n=0,i=t.length;n a`"},et);var rt=DEFNODE("Array","elements",{$documentation:"An array literal",$propdoc:{elements:"[AST_Node*] array of elements"},_walk:function(e){return e._visit(this,function(){var t=this.elements;for(var n=0,i=t.length;nt._walk(e))})},_children_backwards(e){let t=this.properties.length;while(t--)e(this.properties[t]);if(this.extends)e(this.extends);if(this.name)e(this.name)}},ae);var dt=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(e){return e._visit(this,function(){if(this.key instanceof z)this.key._walk(e);if(this.value instanceof z)this.value._walk(e)})},_children_backwards(e){if(this.value instanceof z)e(this.value);if(this.key instanceof z)e(this.key)},computed_key(){return!(this.key instanceof xt)}},ot);var mt=DEFNODE("ClassProperty","",{$documentation:"A class property for a private property"},dt);var Et=DEFNODE("DefClass",null,{$documentation:"A class definition"},ht);var gt=DEFNODE("ClassExpression",null,{$documentation:"A class expression."},ht);var vt=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 Dt=DEFNODE("NewTarget",null,{$documentation:"A reference to new.target"});var bt=DEFNODE("SymbolDeclaration","init",{$documentation:"A declaration symbol (symbol in var/const, function name or argument, symbol in catch)"},vt);var yt=DEFNODE("SymbolVar",null,{$documentation:"Symbol defining a variable"},bt);var kt=DEFNODE("SymbolBlockDeclaration",null,{$documentation:"Base class for block-scoped declaration symbols"},bt);var St=DEFNODE("SymbolConst",null,{$documentation:"A constant declaration"},kt);var Tt=DEFNODE("SymbolLet",null,{$documentation:"A block-scoped `let` declaration"},kt);var At=DEFNODE("SymbolFunarg",null,{$documentation:"Symbol naming a function argument"},yt);var Ct=DEFNODE("SymbolDefun",null,{$documentation:"Symbol defining a function"},bt);var Rt=DEFNODE("SymbolMethod",null,{$documentation:"Symbol in an object defining a method"},vt);var xt=DEFNODE("SymbolClassProperty",null,{$documentation:"Symbol for a class property"},vt);var Ft=DEFNODE("SymbolLambda",null,{$documentation:"Symbol naming a function expression"},bt);var Ot=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."},kt);var wt=DEFNODE("SymbolClass",null,{$documentation:"Symbol naming a class's name. Lexically scoped to the class."},bt);var Mt=DEFNODE("SymbolCatch",null,{$documentation:"Symbol naming the exception in catch"},kt);var Nt=DEFNODE("SymbolImport",null,{$documentation:"Symbol referring to an imported name"},kt);var It=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"},vt);var Pt=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}},vt);var Lt=DEFNODE("SymbolRef",null,{$documentation:"Reference to some symbol (not definition/declaration)"},vt);var Bt=DEFNODE("SymbolExport",null,{$documentation:"Symbol referring to a name to export"},Lt);var Vt=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"},vt);var Ut=DEFNODE("LabelRef",null,{$documentation:"Reference to a label symbol"},vt);var zt=DEFNODE("This",null,{$documentation:"The `this` symbol"},vt);var Kt=DEFNODE("Super",null,{$documentation:"The `super` symbol"},zt);var Gt=DEFNODE("Constant",null,{$documentation:"Base class for all constants",getValue:function(){return this.value}});var Xt=DEFNODE("String","value quote",{$documentation:"A string literal",$propdoc:{value:"[string] the contents of this string",quote:"[string] the original quote character"}},Gt);var Ht=DEFNODE("Number","value raw",{$documentation:"A number literal",$propdoc:{value:"[number] the numeric value",raw:"[string] numeric value as string"}},Gt);var Wt=DEFNODE("BigInt","value",{$documentation:"A big int literal",$propdoc:{value:"[string] big int value"}},Gt);var qt=DEFNODE("RegExp","value",{$documentation:"A regexp literal",$propdoc:{value:"[RegExp] the actual regexp"}},Gt);var Yt=DEFNODE("Atom",null,{$documentation:"Base class for atoms"},Gt);var jt=DEFNODE("Null",null,{$documentation:"The `null` atom",value:null},Yt);var $t=DEFNODE("NaN",null,{$documentation:"The impossible value",value:0/0},Yt);var Zt=DEFNODE("Undefined",null,{$documentation:"The `undefined` value",value:function(){}()},Yt);var Qt=DEFNODE("Hole",null,{$documentation:"A hole in an array",value:function(){}()},Yt);var Jt=DEFNODE("Infinity",null,{$documentation:"The `Infinity` value",value:1/0},Yt);var en=DEFNODE("Boolean",null,{$documentation:"Base class for booleans"},Yt);var tn=DEFNODE("False",null,{$documentation:"The `false` atom",value:false},en);var nn=DEFNODE("True",null,{$documentation:"The `true` atom",value:true},en);function walk(e,t,n=[e]){const i=n.push.bind(n);while(n.length){const e=n.pop();const r=t(e,n);if(r){if(r===rn)return true;continue}e._children_backwards(i)}return false}function walk_parent(e,t,n){const i=[e];const r=i.push.bind(i);const a=n?n.slice():[];const o=[];let s;const u={parent:(e=0)=>{if(e===-1){return s}if(n&&e>=a.length){e-=a.length;return n[n.length-(e+1)]}return a[a.length-(1+e)]}};while(i.length){s=i.pop();while(o.length&&i.length==o[o.length-1]){a.pop();o.pop()}const e=t(s,u);if(e){if(e===rn)return true;continue}const n=i.length;s._children_backwards(r);if(i.length>n){a.push(s);o.push(n-1)}}return false}const rn=Symbol("abort walk");class TreeWalker{constructor(e){this.visit=e;this.stack=[];this.directives=Object.create(null)}_visit(e,t){this.push(e);var n=this.visit(e,t?function(){t.call(e)}:noop);if(!n&&t){t.call(e)}this.pop();return n}parent(e){return this.stack[this.stack.length-2-(e||0)]}push(e){if(e instanceof ue){this.directives=Object.create(this.directives)}else if(e instanceof X&&!this.directives[e.value]){this.directives[e.value]=e}else if(e instanceof ht){this.directives=Object.create(this.directives);if(!this.directives["use strict"]){this.directives["use strict"]=e}}this.stack.push(e)}pop(){var e=this.stack.pop();if(e instanceof ue||e instanceof ht){this.directives=Object.getPrototypeOf(this.directives)}}self(){return this.stack[this.stack.length-1]}find_parent(e){var t=this.stack;for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof e)return i}}has_directive(e){var t=this.directives[e];if(t)return t;var n=this.stack[this.stack.length-1];if(n instanceof ae&&n.body){for(var i=0;i=0;){var i=t[n];if(i instanceof $&&i.label.name==e.label.name)return i.body}else for(var n=t.length;--n>=0;){var i=t[n];if(i instanceof Z||e instanceof ye&&i instanceof Ce)return i}}}class TreeTransformer extends TreeWalker{constructor(e,t){super();this.before=e;this.after=t}}const an=1;const on=2;const sn=4;var un=Object.freeze({__proto__:null,AST_Accessor:ce,AST_Array:rt,AST_Arrow:fe,AST_Assign:nt,AST_Atom:Yt,AST_Await:Se,AST_BigInt:Wt,AST_Binary:et,AST_Block:W,AST_BlockStatement:q,AST_Boolean:en,AST_Break:ye,AST_Call:Ge,AST_Case:Fe,AST_Catch:we,AST_Chain:$e,AST_Class:ht,AST_ClassExpression:gt,AST_ClassPrivateProperty:mt,AST_ClassProperty:dt,AST_ConciseMethod:pt,AST_Conditional:tt,AST_Const:Le,AST_Constant:Gt,AST_Continue:ke,AST_Debugger:G,AST_Default:xe,AST_DefaultAssign:it,AST_DefClass:Et,AST_Definitions:Ne,AST_Defun:pe,AST_Destructuring:_e,AST_Directive:X,AST_Do:J,AST_Dot:qe,AST_DotHash:Ye,AST_DWLoop:Q,AST_EmptyStatement:Y,AST_Exit:ge,AST_Expansion:se,AST_Export:Ke,AST_False:tn,AST_Finally:Me,AST_For:te,AST_ForIn:ne,AST_ForOf:ie,AST_Function:le,AST_Hole:Qt,AST_If:Ae,AST_Import:Ue,AST_ImportMeta:ze,AST_Infinity:Jt,AST_IterationStatement:Z,AST_Jump:Ee,AST_Label:Pt,AST_LabeledStatement:$,AST_LabelRef:Ut,AST_Lambda:ue,AST_Let:Pe,AST_LoopControl:be,AST_NameMapping:Ve,AST_NaN:$t,AST_New:Xe,AST_NewTarget:Dt,AST_Node:z,AST_Null:jt,AST_Number:Ht,AST_Object:at,AST_ObjectGetter:ft,AST_ObjectKeyVal:st,AST_ObjectProperty:ot,AST_ObjectSetter:lt,AST_PrefixedTemplateString:he,AST_PrivateGetter:ct,AST_PrivateMethod:_t,AST_PrivateSetter:ut,AST_PropAccess:We,AST_RegExp:qt,AST_Return:ve,AST_Scope:ae,AST_Sequence:He,AST_SimpleStatement:H,AST_Statement:K,AST_StatementWithBody:j,AST_String:Xt,AST_Sub:je,AST_Super:Kt,AST_Switch:Ce,AST_SwitchBranch:Re,AST_Symbol:vt,AST_SymbolBlockDeclaration:kt,AST_SymbolCatch:Mt,AST_SymbolClass:wt,AST_SymbolClassProperty:xt,AST_SymbolConst:St,AST_SymbolDeclaration:bt,AST_SymbolDefClass:Ot,AST_SymbolDefun:Ct,AST_SymbolExport:Bt,AST_SymbolExportForeign:Vt,AST_SymbolFunarg:At,AST_SymbolImport:Nt,AST_SymbolImportForeign:It,AST_SymbolLambda:Ft,AST_SymbolLet:Tt,AST_SymbolMethod:Rt,AST_SymbolRef:Lt,AST_SymbolVar:yt,AST_TemplateSegment:me,AST_TemplateString:de,AST_This:zt,AST_Throw:De,AST_Token:AST_Token,AST_Toplevel:oe,AST_True:nn,AST_Try:Oe,AST_Unary:Ze,AST_UnaryPostfix:Je,AST_UnaryPrefix:Qe,AST_Undefined:Zt,AST_Var:Ie,AST_VarDef:Be,AST_While:ee,AST_With:re,AST_Yield:Te,TreeTransformer:TreeTransformer,TreeWalker:TreeWalker,walk:walk,walk_abort:rn,walk_body:walk_body,walk_parent:walk_parent,_INLINE:on,_NOINLINE:sn,_PURE:an});function def_transform(e,t){e.DEFMETHOD("transform",function(e,n){let i=undefined;e.push(this);if(e.before)i=e.before(this,t,n);if(i===undefined){i=this;t(i,e);if(e.after){const t=e.after(i,n);if(t!==undefined)i=t}}e.pop();return i})}function do_list(e,t){return r(e,function(e){return e.transform(t,true)})}def_transform(z,noop);def_transform($,function(e,t){e.label=e.label.transform(t);e.body=e.body.transform(t)});def_transform(H,function(e,t){e.body=e.body.transform(t)});def_transform(W,function(e,t){e.body=do_list(e.body,t)});def_transform(J,function(e,t){e.body=e.body.transform(t);e.condition=e.condition.transform(t)});def_transform(ee,function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t)});def_transform(te,function(e,t){if(e.init)e.init=e.init.transform(t);if(e.condition)e.condition=e.condition.transform(t);if(e.step)e.step=e.step.transform(t);e.body=e.body.transform(t)});def_transform(ne,function(e,t){e.init=e.init.transform(t);e.object=e.object.transform(t);e.body=e.body.transform(t)});def_transform(re,function(e,t){e.expression=e.expression.transform(t);e.body=e.body.transform(t)});def_transform(ge,function(e,t){if(e.value)e.value=e.value.transform(t)});def_transform(be,function(e,t){if(e.label)e.label=e.label.transform(t)});def_transform(Ae,function(e,t){e.condition=e.condition.transform(t);e.body=e.body.transform(t);if(e.alternative)e.alternative=e.alternative.transform(t)});def_transform(Ce,function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)});def_transform(Fe,function(e,t){e.expression=e.expression.transform(t);e.body=do_list(e.body,t)});def_transform(Oe,function(e,t){e.body=do_list(e.body,t);if(e.bcatch)e.bcatch=e.bcatch.transform(t);if(e.bfinally)e.bfinally=e.bfinally.transform(t)});def_transform(we,function(e,t){if(e.argname)e.argname=e.argname.transform(t);e.body=do_list(e.body,t)});def_transform(Ne,function(e,t){e.definitions=do_list(e.definitions,t)});def_transform(Be,function(e,t){e.name=e.name.transform(t);if(e.value)e.value=e.value.transform(t)});def_transform(_e,function(e,t){e.names=do_list(e.names,t)});def_transform(ue,function(e,t){if(e.name)e.name=e.name.transform(t);e.argnames=do_list(e.argnames,t);if(e.body instanceof z){e.body=e.body.transform(t)}else{e.body=do_list(e.body,t)}});def_transform(Ge,function(e,t){e.expression=e.expression.transform(t);e.args=do_list(e.args,t)});def_transform(He,function(e,t){const n=do_list(e.expressions,t);e.expressions=n.length?n:[new Ht({value:0})]});def_transform(qe,function(e,t){e.expression=e.expression.transform(t)});def_transform(je,function(e,t){e.expression=e.expression.transform(t);e.property=e.property.transform(t)});def_transform($e,function(e,t){e.expression=e.expression.transform(t)});def_transform(Te,function(e,t){if(e.expression)e.expression=e.expression.transform(t)});def_transform(Se,function(e,t){e.expression=e.expression.transform(t)});def_transform(Ze,function(e,t){e.expression=e.expression.transform(t)});def_transform(et,function(e,t){e.left=e.left.transform(t);e.right=e.right.transform(t)});def_transform(tt,function(e,t){e.condition=e.condition.transform(t);e.consequent=e.consequent.transform(t);e.alternative=e.alternative.transform(t)});def_transform(rt,function(e,t){e.elements=do_list(e.elements,t)});def_transform(at,function(e,t){e.properties=do_list(e.properties,t)});def_transform(ot,function(e,t){if(e.key instanceof z){e.key=e.key.transform(t)}if(e.value)e.value=e.value.transform(t)});def_transform(ht,function(e,t){if(e.name)e.name=e.name.transform(t);if(e.extends)e.extends=e.extends.transform(t);e.properties=do_list(e.properties,t)});def_transform(se,function(e,t){e.expression=e.expression.transform(t)});def_transform(Ve,function(e,t){e.foreign_name=e.foreign_name.transform(t);e.name=e.name.transform(t)});def_transform(Ue,function(e,t){if(e.imported_name)e.imported_name=e.imported_name.transform(t);if(e.imported_names)do_list(e.imported_names,t);e.module_name=e.module_name.transform(t)});def_transform(Ke,function(e,t){if(e.exported_definition)e.exported_definition=e.exported_definition.transform(t);if(e.exported_value)e.exported_value=e.exported_value.transform(t);if(e.exported_names)do_list(e.exported_names,t);if(e.module_name)e.module_name=e.module_name.transform(t)});def_transform(de,function(e,t){e.segments=do_list(e.segments,t)});def_transform(he,function(e,t){e.prefix=e.prefix.transform(t);e.template_string=e.template_string.transform(t)});(function(){var e=function(e){var t=true;for(var n=0;n1||e.guardedHandlers&&e.guardedHandlers.length){throw new Error("Multiple catch clauses are not supported.")}return new Oe({start:my_start_token(e),end:my_end_token(e),body:from_moz(e.block).body,bcatch:from_moz(t[0]),bfinally:e.finalizer?new Me(from_moz(e.finalizer)):null})},Property:function(e){var t=e.key;var n={start:my_start_token(t||e.value),end:my_end_token(e.value),key:t.type=="Identifier"?t.name:t.value,value:from_moz(e.value)};if(e.computed){n.key=from_moz(e.key)}if(e.method){n.is_generator=e.value.generator;n.async=e.value.async;if(!e.computed){n.key=new Rt({name:n.key})}else{n.key=from_moz(e.key)}return new pt(n)}if(e.kind=="init"){if(t.type!="Identifier"&&t.type!="Literal"){n.key=from_moz(t)}return new st(n)}if(typeof n.key==="string"||typeof n.key==="number"){n.key=new Rt({name:n.key})}n.value=new ce(n.value);if(e.kind=="get")return new ft(n);if(e.kind=="set")return new lt(n);if(e.kind=="method"){n.async=e.value.async;n.is_generator=e.value.generator;n.quote=e.computed?'"':null;return new pt(n)}},MethodDefinition:function(e){var t={start:my_start_token(e),end:my_end_token(e),key:e.computed?from_moz(e.key):new Rt({name:e.key.name||e.key.value}),value:from_moz(e.value),static:e.static};if(e.kind=="get"){return new ft(t)}if(e.kind=="set"){return new lt(t)}t.is_generator=e.value.generator;t.async=e.value.async;return new pt(t)},FieldDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in FieldDefinition");t=from_moz(e.key)}return new dt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},PropertyDefinition:function(e){let t;if(e.computed){t=from_moz(e.key)}else{if(e.key.type!=="Identifier")throw new Error("Non-Identifier key in PropertyDefinition");t=from_moz(e.key)}return new dt({start:my_start_token(e),end:my_end_token(e),key:t,value:from_moz(e.value),static:e.static})},ArrayExpression:function(e){return new rt({start:my_start_token(e),end:my_end_token(e),elements:e.elements.map(function(e){return e===null?new Qt:from_moz(e)})})},ObjectExpression:function(e){return new at({start:my_start_token(e),end:my_end_token(e),properties:e.properties.map(function(e){if(e.type==="SpreadElement"){return from_moz(e)}e.type="Property";return from_moz(e)})})},SequenceExpression:function(e){return new He({start:my_start_token(e),end:my_end_token(e),expressions:e.expressions.map(from_moz)})},MemberExpression:function(e){return new(e.computed?je:qe)({start:my_start_token(e),end:my_end_token(e),property:e.computed?from_moz(e.property):e.property.name,expression:from_moz(e.object),optional:e.optional||false})},ChainExpression:function(e){return new $e({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.expression)})},SwitchCase:function(e){return new(e.test?Fe:xe)({start:my_start_token(e),end:my_end_token(e),expression:from_moz(e.test),body:e.consequent.map(from_moz)})},VariableDeclaration:function(e){return new(e.kind==="const"?Le:e.kind==="let"?Pe:Ie)({start:my_start_token(e),end:my_end_token(e),definitions:e.declarations.map(from_moz)})},ImportDeclaration:function(e){var t=null;var n=null;e.specifiers.forEach(function(e){if(e.type==="ImportSpecifier"){if(!n){n=[]}n.push(new Ve({start:my_start_token(e),end:my_end_token(e),foreign_name:from_moz(e.imported),name:from_moz(e.local)}))}else if(e.type==="ImportDefaultSpecifier"){t=from_moz(e.local)}else if(e.type==="ImportNamespaceSpecifier"){if(!n){n=[]}n.push(new Ve({start:my_start_token(e),end:my_end_token(e),foreign_name:new It({name:"*"}),name:from_moz(e.local)}))}});return new Ue({start:my_start_token(e),end:my_end_token(e),imported_name:t,imported_names:n,module_name:from_moz(e.source)})},ExportAllDeclaration:function(e){return new Ke({start:my_start_token(e),end:my_end_token(e),exported_names:[new Ve({name:new Vt({name:"*"}),foreign_name:new Vt({name:"*"})})],module_name:from_moz(e.source)})},ExportNamedDeclaration:function(e){return new Ke({start:my_start_token(e),end:my_end_token(e),exported_definition:from_moz(e.declaration),exported_names:e.specifiers&&e.specifiers.length?e.specifiers.map(function(e){return new Ve({foreign_name:from_moz(e.exported),name:from_moz(e.local)})}):null,module_name:from_moz(e.source)})},ExportDefaultDeclaration:function(e){return new Ke({start:my_start_token(e),end:my_end_token(e),exported_value:from_moz(e.declaration),is_default:true})},Literal:function(e){var t=e.value,n={start:my_start_token(e),end:my_end_token(e)};var i=e.regex;if(i&&i.pattern){n.value={source:i.pattern,flags:i.flags};return new qt(n)}else if(i){const i=e.raw||t;const r=i.match(/^\/(.*)\/(\w*)$/);if(!r)throw new Error("Invalid regex source "+i);const[a,o,s]=r;n.value={source:o,flags:s};return new qt(n)}if(t===null)return new jt(n);switch(typeof t){case"string":n.value=t;return new Xt(n);case"number":n.value=t;n.raw=e.raw||t.toString();return new Ht(n);case"boolean":return new(t?nn:tn)(n)}},MetaProperty:function(e){if(e.meta.name==="new"&&e.property.name==="target"){return new Dt({start:my_start_token(e),end:my_end_token(e)})}else if(e.meta.name==="import"&&e.property.name==="meta"){return new ze({start:my_start_token(e),end:my_end_token(e)})}},Identifier:function(e){var t=n[n.length-2];return new(t.type=="LabeledStatement"?Pt:t.type=="VariableDeclarator"&&t.id===e?t.kind=="const"?St:t.kind=="let"?Tt:yt:/Import.*Specifier/.test(t.type)?t.local===e?Nt:It:t.type=="ExportSpecifier"?t.local===e?Bt:Vt:t.type=="FunctionExpression"?t.id===e?Ft:At:t.type=="FunctionDeclaration"?t.id===e?Ct:At:t.type=="ArrowFunctionExpression"?t.params.includes(e)?At:Lt:t.type=="ClassExpression"?t.id===e?wt:Lt:t.type=="Property"?t.key===e&&t.computed||t.value===e?Lt:Rt:t.type=="PropertyDefinition"||t.type==="FieldDefinition"?t.key===e&&t.computed||t.value===e?Lt:xt:t.type=="ClassDeclaration"?t.id===e?Ot:Lt:t.type=="MethodDefinition"?t.computed?Lt:Rt:t.type=="CatchClause"?Mt:t.type=="BreakStatement"||t.type=="ContinueStatement"?Ut:Lt)({start:my_start_token(e),end:my_end_token(e),name:e.name})},BigIntLiteral(e){return new Wt({start:my_start_token(e),end:my_end_token(e),value:e.value})}};t.UpdateExpression=t.UnaryExpression=function To_Moz_Unary(e){var t="prefix"in e?e.prefix:e.type=="UnaryExpression"?true:false;return new(t?Qe:Je)({start:my_start_token(e),end:my_end_token(e),operator:e.operator,expression:from_moz(e.argument)})};t.ClassDeclaration=t.ClassExpression=function From_Moz_Class(e){return new(e.type==="ClassDeclaration"?Et:gt)({start:my_start_token(e),end:my_end_token(e),name:from_moz(e.id),extends:from_moz(e.superClass),properties:e.body.body.map(from_moz)})};map("EmptyStatement",Y);map("BlockStatement",q,"body@body");map("IfStatement",Ae,"test>condition, consequent>body, alternate>alternative");map("LabeledStatement",$,"label>label, body>body");map("BreakStatement",ye,"label>label");map("ContinueStatement",ke,"label>label");map("WithStatement",re,"object>expression, body>body");map("SwitchStatement",Ce,"discriminant>expression, cases@body");map("ReturnStatement",ve,"argument>value");map("ThrowStatement",De,"argument>value");map("WhileStatement",ee,"test>condition, body>body");map("DoWhileStatement",J,"test>condition, body>body");map("ForStatement",te,"init>init, test>condition, update>step, body>body");map("ForInStatement",ne,"left>init, right>object, body>body");map("ForOfStatement",ie,"left>init, right>object, body>body, await=await");map("AwaitExpression",Se,"argument>expression");map("YieldExpression",Te,"argument>expression, delegate=is_star");map("DebuggerStatement",G);map("VariableDeclarator",Be,"id>name, init>value");map("CatchClause",we,"param>argname, body%body");map("ThisExpression",zt);map("Super",Kt);map("BinaryExpression",et,"operator=operator, left>left, right>right");map("LogicalExpression",et,"operator=operator, left>left, right>right");map("AssignmentExpression",nt,"operator=operator, left>left, right>right");map("ConditionalExpression",tt,"test>condition, consequent>consequent, alternate>alternative");map("NewExpression",Xe,"callee>expression, arguments@args");map("CallExpression",Ge,"callee>expression, optional=optional, arguments@args");def_to_moz(oe,function To_Moz_Program(e){return to_moz_scope("Program",e)});def_to_moz(se,function To_Moz_Spread(e){return{type:to_moz_in_destructuring()?"RestElement":"SpreadElement",argument:to_moz(e.expression)}});def_to_moz(he,function To_Moz_TaggedTemplateExpression(e){return{type:"TaggedTemplateExpression",tag:to_moz(e.prefix),quasi:to_moz(e.template_string)}});def_to_moz(de,function To_Moz_TemplateLiteral(e){var t=[];var n=[];for(var i=0;i({type:"BigIntLiteral",value:e.value}));en.DEFMETHOD("to_mozilla_ast",Gt.prototype.to_mozilla_ast);jt.DEFMETHOD("to_mozilla_ast",Gt.prototype.to_mozilla_ast);Qt.DEFMETHOD("to_mozilla_ast",function To_Moz_ArrayHole(){return null});W.DEFMETHOD("to_mozilla_ast",q.prototype.to_mozilla_ast);ue.DEFMETHOD("to_mozilla_ast",le.prototype.to_mozilla_ast);function my_start_token(e){var t=e.loc,n=t&&t.start;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.start,false,[],[],t&&t.source)}function my_end_token(e){var t=e.loc,n=t&&t.end;var i=e.range;return new AST_Token("","",n&&n.line||0,n&&n.column||0,i?i[0]:e.end,false,[],[],t&&t.source)}function map(e,n,i){var r="function From_Moz_"+e+"(M){\n";r+="return new U2."+n.name+"({\n"+"start: my_start_token(M),\n"+"end: my_end_token(M)";var a="function To_Moz_"+e+"(M){\n";a+="return {\n"+"type: "+JSON.stringify(e);if(i)i.split(/\s*,\s*/).forEach(function(e){var t=/([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(e);if(!t)throw new Error("Can't understand property map: "+e);var n=t[1],i=t[2],o=t[3];r+=",\n"+o+": ";a+=",\n"+n+": ";switch(i){case"@":r+="M."+n+".map(from_moz)";a+="M."+o+".map(to_moz)";break;case">":r+="from_moz(M."+n+")";a+="to_moz(M."+o+")";break;case"=":r+="M."+n;a+="M."+o;break;case"%":r+="from_moz(M."+n+").body";a+="to_moz_block(M)";break;default:throw new Error("Can't understand operator in propmap: "+e)}});r+="\n})\n}";a+="\n}\n}";r=new Function("U2","my_start_token","my_end_token","from_moz","return("+r+")")(un,my_start_token,my_end_token,from_moz);a=new Function("to_moz","to_moz_block","to_moz_scope","return("+a+")")(to_moz,to_moz_block,to_moz_scope);t[e]=r;def_to_moz(n,a)}var n=null;function from_moz(e){n.push(e);var i=e!=null?t[e.type](e):null;n.pop();return i}z.from_mozilla_ast=function(e){var t=n;n=[];var i=from_moz(e);n=t;return i};function set_moz_loc(e,t){var n=e.start;var i=e.end;if(!(n&&i)){return t}if(n.pos!=null&&i.endpos!=null){t.range=[n.pos,i.endpos]}if(n.line){t.loc={start:{line:n.line,column:n.col},end:i.endline?{line:i.endline,column:i.endcol}:null};if(n.file){t.loc.source=n.file}}return t}function def_to_moz(e,t){e.DEFMETHOD("to_mozilla_ast",function(e){return set_moz_loc(this,t(this,e))})}var i=null;function to_moz(e){if(i===null){i=[]}i.push(e);var t=e!=null?e.to_mozilla_ast(i[i.length-2]):null;i.pop();if(i.length===0){i=null}return t}function to_moz_in_destructuring(){var e=i.length;while(e--){if(i[e]instanceof _e){return true}}return false}function to_moz_block(e){return{type:"BlockStatement",body:e.body.map(to_moz)}}function to_moz_scope(e,t){var n=t.body.map(to_moz);if(t.body[0]instanceof H&&t.body[0].body instanceof Xt){n.unshift(to_moz(new Y(t.body[0])))}return{type:e,body:n}}})();function first_in_statement(e){let t=e.parent(-1);for(let n=0,i;i=e.parent(n);n++){if(i instanceof K&&i.body===t)return true;if(i instanceof He&&i.expressions[0]===t||i.TYPE==="Call"&&i.expression===t||i instanceof he&&i.prefix===t||i instanceof qe&&i.expression===t||i instanceof je&&i.expression===t||i instanceof tt&&i.condition===t||i instanceof et&&i.left===t||i instanceof Je&&i.expression===t){t=i}else{return false}}}function left_is_object(e){if(e instanceof at)return true;if(e instanceof He)return left_is_object(e.expressions[0]);if(e.TYPE==="Call")return left_is_object(e.expression);if(e instanceof he)return left_is_object(e.prefix);if(e instanceof qe||e instanceof je)return left_is_object(e.expression);if(e instanceof tt)return left_is_object(e.condition);if(e instanceof et)return left_is_object(e.left);if(e instanceof Je)return left_is_object(e.expression);return false}const cn=/^$|[;{][\s\n]*$/;const ln=10;const fn=32;const pn=/[@#]__(PURE|INLINE|NOINLINE)__/g;function is_some_comments(e){return(e.type==="comment2"||e.type==="comment1")&&/@preserve|@lic|@cc_on|^\**!/i.test(e.value)}function OutputStream(e){var t=!e;e=defaults(e,{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(e.shorthand===undefined)e.shorthand=e.ecma>5;var n=return_false;if(e.comments){let t=e.comments;if(typeof e.comments==="string"&&/^\/.*\/[a-zA-Z]*$/.test(e.comments)){var i=e.comments.lastIndexOf("/");t=new RegExp(e.comments.substr(1,i-1),e.comments.substr(i+1))}if(t instanceof RegExp){n=function(e){return e.type!="comment5"&&t.test(e.value)}}else if(typeof t==="function"){n=function(e){return e.type!="comment5"&&t(this,e)}}else if(t==="some"){n=is_some_comments}else{n=return_true}}var r=0;var a=0;var o=1;var s=0;var u="";let c=new Set;var l=e.ascii_only?function(t,n){if(e.ecma>=2015&&!e.safari10){t=t.replace(/[\ud800-\udbff][\udc00-\udfff]/g,function(e){var t=get_full_char_code(e,0).toString(16);return"\\u{"+t+"}"})}return t.replace(/[\u0000-\u001f\u007f-\uffff]/g,function(e){var t=e.charCodeAt(0).toString(16);if(t.length<=2&&!n){while(t.length<2)t="0"+t;return"\\x"+t}else{while(t.length<4)t="0"+t;return"\\u"+t}})}:function(e){return e.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g,function(e,t){if(t){return"\\u"+t.charCodeAt(0).toString(16)}return e})};function make_string(t,n){var i=0,r=0;t=t.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,function(n,a){switch(n){case'"':++i;return'"';case"'":++r;return"'";case"\\":return"\\\\";case"\n":return"\\n";case"\r":return"\\r";case"\t":return"\\t";case"\b":return"\\b";case"\f":return"\\f";case"\v":return e.ie8?"\\x0B":"\\v";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";case"\ufeff":return"\\ufeff";case"\0":return/[0-9]/.test(get_full_char(t,a+1))?"\\x00":"\\0"}return n});function quote_single(){return"'"+t.replace(/\x27/g,"\\'")+"'"}function quote_double(){return'"'+t.replace(/\x22/g,'\\"')+'"'}function quote_template(){return"`"+t.replace(/`/g,"\\`")+"`"}t=l(t);if(n==="`")return quote_template();switch(e.quote_style){case 1:return quote_single();case 2:return quote_double();case 3:return n=="'"?quote_single():quote_double();default:return i>r?quote_single():quote_double()}}function encode_string(t,n){var i=make_string(t,n);if(e.inline_script){i=i.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi,"<\\/$1$2");i=i.replace(/\x3c!--/g,"\\x3c!--");i=i.replace(/--\x3e/g,"--\\x3e")}return i}function make_name(e){e=e.toString();e=l(e,true);return e}function make_indent(t){return" ".repeat(e.indent_start+r-t*e.indent_level)}var f=false;var p=false;var _=false;var h=0;var d=false;var m=false;var E=-1;var g="";var v,D,b=e.source_map&&[];var y=b?function(){b.forEach(function(t){try{let n=!t.name&&t.token.type=="name"?t.token.value:t.name;if(n instanceof vt){n=n.name}e.source_map.add(t.token.file,t.line,t.col,t.token.line,t.token.col,is_basic_identifier_string(n)?n:undefined)}catch(e){}});b=[]}:noop;var k=e.max_line_len?function(){if(a>e.max_line_len){if(h){var t=u.slice(0,h);var n=u.slice(h);if(b){var i=n.length-a;b.forEach(function(e){e.line++;e.col+=i})}u=t+"\n"+n;o++;s++;a=n.length}}if(h){h=0;y()}}:noop;var S=makePredicate("( [ + * / - , . `");function print(t){t=String(t);var n=get_full_char(t,0);if(d&&n){d=false;if(n!=="\n"){print("\n");C()}}if(m&&n){m=false;if(!/[\s;})]/.test(n)){A()}}E=-1;var i=g.charAt(g.length-1);if(_){_=false;if(i===":"&&n==="}"||(!n||!";}".includes(n))&&i!==";"){if(e.semicolons||S.has(n)){u+=";";a++;s++}else{k();if(a>0){u+="\n";s++;o++;a=0}if(/^\s+$/.test(t)){_=true}}if(!e.beautify)p=false}}if(p){if(is_identifier_char(i)&&(is_identifier_char(n)||n=="\\")||n=="/"&&n==i||(n=="+"||n=="-")&&n==g){u+=" ";a++;s++}p=false}if(v){b.push({token:v,name:D,line:o,col:a});v=false;if(!h)y()}u+=t;f=t[t.length-1]=="(";s+=t.length;var r=t.split(/\r?\n/),c=r.length-1;o+=c;a+=r[0].length;if(c>0){k();a=r[c].length}g=t}var T=function(){print("*")};var A=e.beautify?function(){print(" ")}:function(){p=true};var C=e.beautify?function(t){if(e.beautify){print(make_indent(t?.5:0))}}:noop;var R=e.beautify?function(e,t){if(e===true)e=next_indent();var n=r;r=e;var i=t();r=n;return i}:function(e,t){return t()};var x=e.beautify?function(){if(E<0)return print("\n");if(u[E]!="\n"){u=u.slice(0,E)+"\n"+u.slice(E);s++;o++}E++}:e.max_line_len?function(){k();h=u.length}:noop;var F=e.beautify?function(){print(";")}:function(){_=true};function force_semicolon(){_=false;print(";")}function next_indent(){return r+e.indent_level}function with_block(e){var t;print("{");x();R(next_indent(),function(){t=e()});C();print("}");return t}function with_parens(e){print("(");var t=e();print(")");return t}function with_square(e){print("[");var t=e();print("]");return t}function comma(){print(",");A()}function colon(){print(":");A()}var O=b?function(e,t){v=e;D=t}:noop;function get(){if(h){k()}return u}function has_nlb(){let e=u.length-1;while(e>=0){const t=u.charCodeAt(e);if(t===ln){return true}if(t!==fn){return false}e--}return true}function filter_comment(t){if(!e.preserve_annotations){t=t.replace(pn," ")}if(/^\s*$/.test(t)){return""}return t.replace(/(<\s*\/\s*)(script)/i,"<\\/$2")}function prepend_comments(t){var i=this;var r=t.start;if(!r)return;var a=i.printed_comments;const o=t instanceof ge&&t.value;if(r.comments_before&&a.has(r.comments_before)){if(o){r.comments_before=[]}else{return}}var u=r.comments_before;if(!u){u=r.comments_before=[]}a.add(u);if(o){var c=new TreeWalker(function(e){var t=c.parent();if(t instanceof ge||t instanceof et&&t.left===e||t.TYPE=="Call"&&t.expression===e||t instanceof tt&&t.condition===e||t instanceof qe&&t.expression===e||t instanceof He&&t.expressions[0]===e||t instanceof je&&t.expression===e||t instanceof Je){if(!e.start)return;var n=e.start.comments_before;if(n&&!a.has(n)){a.add(n);u=u.concat(n)}}else{return true}});c.push(t);t.value.walk(c)}if(s==0){if(u.length>0&&e.shebang&&u[0].type==="comment5"&&!a.has(u[0])){print("#!"+u.shift().value+"\n");C()}var l=e.preamble;if(l){print(l.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g,"\n"))}}u=u.filter(n,t).filter(e=>!a.has(e));if(u.length==0)return;var f=has_nlb();u.forEach(function(e,t){a.add(e);if(!f){if(e.nlb){print("\n");C();f=true}else if(t>0){A()}}if(/comment[134]/.test(e.type)){var n=filter_comment(e.value);if(n){print("//"+n+"\n");C()}f=true}else if(e.type=="comment2"){var n=filter_comment(e.value);if(n){print("/*"+n+"*/")}f=false}});if(!f){if(r.nlb){print("\n");C()}else{A()}}}function append_comments(e,t){var i=this;var r=e.end;if(!r)return;var a=i.printed_comments;var o=r[t?"comments_before":"comments_after"];if(!o||a.has(o))return;if(!(e instanceof K||o.every(e=>!/comment[134]/.test(e.type))))return;a.add(o);var s=u.length;o.filter(n,e).forEach(function(e,n){if(a.has(e))return;a.add(e);m=false;if(d){print("\n");C();d=false}else if(e.nlb&&(n>0||!has_nlb())){print("\n");C()}else if(n>0||!t){A()}if(/comment[134]/.test(e.type)){const t=filter_comment(e.value);if(t){print("//"+t)}d=true}else if(e.type=="comment2"){const t=filter_comment(e.value);if(t){print("/*"+t+"*/")}m=true}});if(u.length>s)E=s}var w=[];return{get:get,toString:get,indent:C,in_directive:false,use_asm:null,active_scope:null,indentation:function(){return r},current_width:function(){return a-r},should_break:function(){return e.width&&this.current_width()>=e.width},has_parens:function(){return f},newline:x,print:print,star:T,space:A,comma:comma,colon:colon,last:function(){return g},semicolon:F,force_semicolon:force_semicolon,to_utf8:l,print_name:function(e){print(make_name(e))},print_string:function(e,t,n){var i=encode_string(e,t);if(n===true&&!i.includes("\\")){if(!cn.test(u)){force_semicolon()}force_semicolon()}print(i)},print_template_string_chars:function(e){var t=encode_string(e,"`").replace(/\${/g,"\\${");return print(t.substr(1,t.length-2))},encode_string:encode_string,next_indent:next_indent,with_indent:R,with_block:with_block,with_parens:with_parens,with_square:with_square,add_mapping:O,option:function(t){return e[t]},printed_comments:c,prepend_comments:t?noop:prepend_comments,append_comments:t||n===return_false?noop:append_comments,line:function(){return o},col:function(){return a},pos:function(){return s},push_node:function(e){w.push(e)},pop_node:function(){return w.pop()},parent:function(e){return w[w.length-2-(e||0)]}}}(function(){function DEFPRINT(e,t){e.DEFMETHOD("_codegen",t)}z.DEFMETHOD("print",function(e,t){var n=this,i=n._codegen;if(n instanceof ae){e.active_scope=n}else if(!e.use_asm&&n instanceof X&&n.value=="use asm"){e.use_asm=e.active_scope}function doit(){e.prepend_comments(n);n.add_source_map(e);i(n,e);e.append_comments(n)}e.push_node(n);if(t||n.needs_parens(e)){e.with_parens(doit)}else{doit()}e.pop_node();if(n===e.use_asm){e.use_asm=null}});z.DEFMETHOD("_print",z.prototype.print);z.DEFMETHOD("print_to_string",function(e){var t=OutputStream(e);this.print(t);return t.get()});function PARENS(e,t){if(Array.isArray(e)){e.forEach(function(e){PARENS(e,t)})}else{e.DEFMETHOD("needs_parens",t)}}PARENS(z,return_false);PARENS(le,function(e){if(!e.has_parens()&&first_in_statement(e)){return true}if(e.option("webkit")){var t=e.parent();if(t instanceof We&&t.expression===this){return true}}if(e.option("wrap_iife")){var t=e.parent();if(t instanceof Ge&&t.expression===this){return true}}if(e.option("wrap_func_args")){var t=e.parent();if(t instanceof Ge&&t.args.includes(this)){return true}}return false});PARENS(fe,function(e){var t=e.parent();if(e.option("wrap_func_args")&&t instanceof Ge&&t.args.includes(this)){return true}return t instanceof We&&t.expression===this});PARENS(at,function(e){return!e.has_parens()&&first_in_statement(e)});PARENS(gt,first_in_statement);PARENS(Ze,function(e){var t=e.parent();return t instanceof We&&t.expression===this||t instanceof Ge&&t.expression===this||t instanceof et&&t.operator==="**"&&this instanceof Qe&&t.left===this&&this.operator!=="++"&&this.operator!=="--"});PARENS(Se,function(e){var t=e.parent();return t instanceof We&&t.expression===this||t instanceof Ge&&t.expression===this||t instanceof et&&t.operator==="**"&&t.left===this||e.option("safari10")&&t instanceof Qe});PARENS(He,function(e){var t=e.parent();return t instanceof Ge||t instanceof Ze||t instanceof et||t instanceof Be||t instanceof We||t instanceof rt||t instanceof ot||t instanceof tt||t instanceof fe||t instanceof it||t instanceof se||t instanceof ie&&this===t.object||t instanceof Te||t instanceof Ke});PARENS(et,function(e){var t=e.parent();if(t instanceof Ge&&t.expression===this)return true;if(t instanceof Ze)return true;if(t instanceof We&&t.expression===this)return true;if(t instanceof et){const e=t.operator;const n=this.operator;if(n==="??"&&(e==="||"||e==="&&")){return true}if(e==="??"&&(n==="||"||n==="&&")){return true}const i=N[e];const r=N[n];if(i>r||i==r&&(this===t.right||e=="**")){return true}}});PARENS(Te,function(e){var t=e.parent();if(t instanceof et&&t.operator!=="=")return true;if(t instanceof Ge&&t.expression===this)return true;if(t instanceof tt&&t.condition===this)return true;if(t instanceof Ze)return true;if(t instanceof We&&t.expression===this)return true});PARENS(We,function(e){var t=e.parent();if(t instanceof Xe&&t.expression===this){return walk(this,e=>{if(e instanceof ae)return true;if(e instanceof Ge){return rn}})}});PARENS(Ge,function(e){var t=e.parent(),n;if(t instanceof Xe&&t.expression===this||t instanceof Ke&&t.is_default&&this.expression instanceof le)return true;return this.expression instanceof le&&t instanceof We&&t.expression===this&&(n=e.parent(1))instanceof nt&&n.left===t});PARENS(Xe,function(e){var t=e.parent();if(this.args.length===0&&(t instanceof We||t instanceof Ge&&t.expression===this))return true});PARENS(Ht,function(e){var t=e.parent();if(t instanceof We&&t.expression===this){var n=this.getValue();if(n<0||/^0/.test(make_num(n))){return true}}});PARENS(Wt,function(e){var t=e.parent();if(t instanceof We&&t.expression===this){var n=this.getValue();if(n.startsWith("-")){return true}}});PARENS([nt,tt],function(e){var t=e.parent();if(t instanceof Ze)return true;if(t instanceof et&&!(t instanceof nt))return true;if(t instanceof Ge&&t.expression===this)return true;if(t instanceof tt&&t.condition===this)return true;if(t instanceof We&&t.expression===this)return true;if(this instanceof nt&&this.left instanceof _e&&this.left.is_array===false)return true});DEFPRINT(X,function(e,t){t.print_string(e.value,e.quote);t.semicolon()});DEFPRINT(se,function(e,t){t.print("...");e.expression.print(t)});DEFPRINT(_e,function(e,t){t.print(e.is_array?"[":"{");var n=e.names.length;e.names.forEach(function(e,i){if(i>0)t.comma();e.print(t);if(i==n-1&&e instanceof Qt)t.comma()});t.print(e.is_array?"]":"}")});DEFPRINT(G,function(e,t){t.print("debugger");t.semicolon()});function display_body(e,t,n,i){var r=e.length-1;n.in_directive=i;e.forEach(function(e,i){if(n.in_directive===true&&!(e instanceof X||e instanceof Y||e instanceof H&&e.body instanceof Xt)){n.in_directive=false}if(!(e instanceof Y)){n.indent();e.print(n);if(!(i==r&&t)){n.newline();if(t)n.newline()}}if(n.in_directive===true&&e instanceof H&&e.body instanceof Xt){n.in_directive=false}});n.in_directive=false}j.DEFMETHOD("_do_print_body",function(e){force_statement(this.body,e)});DEFPRINT(K,function(e,t){e.body.print(t);t.semicolon()});DEFPRINT(oe,function(e,t){display_body(e.body,true,t,true);t.print("")});DEFPRINT($,function(e,t){e.label.print(t);t.colon();e.body.print(t)});DEFPRINT(H,function(e,t){e.body.print(t);t.semicolon()});function print_braced_empty(e,t){t.print("{");t.with_indent(t.next_indent(),function(){t.append_comments(e,true)});t.print("}")}function print_braced(e,t,n){if(e.body.length>0){t.with_block(function(){display_body(e.body,false,t,n)})}else print_braced_empty(e,t)}DEFPRINT(q,function(e,t){print_braced(e,t)});DEFPRINT(Y,function(e,t){t.semicolon()});DEFPRINT(J,function(e,t){t.print("do");t.space();make_block(e.body,t);t.space();t.print("while");t.space();t.with_parens(function(){e.condition.print(t)});t.semicolon()});DEFPRINT(ee,function(e,t){t.print("while");t.space();t.with_parens(function(){e.condition.print(t)});t.space();e._do_print_body(t)});DEFPRINT(te,function(e,t){t.print("for");t.space();t.with_parens(function(){if(e.init){if(e.init instanceof Ne){e.init.print(t)}else{parenthesize_for_noin(e.init,t,true)}t.print(";");t.space()}else{t.print(";")}if(e.condition){e.condition.print(t);t.print(";");t.space()}else{t.print(";")}if(e.step){e.step.print(t)}});t.space();e._do_print_body(t)});DEFPRINT(ne,function(e,t){t.print("for");if(e.await){t.space();t.print("await")}t.space();t.with_parens(function(){e.init.print(t);t.space();t.print(e instanceof ie?"of":"in");t.space();e.object.print(t)});t.space();e._do_print_body(t)});DEFPRINT(re,function(e,t){t.print("with");t.space();t.with_parens(function(){e.expression.print(t)});t.space();e._do_print_body(t)});ue.DEFMETHOD("_do_print",function(e,t){var n=this;if(!t){if(n.async){e.print("async");e.space()}e.print("function");if(n.is_generator){e.star()}if(n.name){e.space()}}if(n.name instanceof vt){n.name.print(e)}else if(t&&n.name instanceof z){e.with_square(function(){n.name.print(e)})}e.with_parens(function(){n.argnames.forEach(function(t,n){if(n)e.comma();t.print(e)})});e.space();print_braced(n,e,true)});DEFPRINT(ue,function(e,t){e._do_print(t)});DEFPRINT(he,function(e,t){var n=e.prefix;var i=n instanceof ue||n instanceof et||n instanceof tt||n instanceof He||n instanceof Ze||n instanceof qe&&n.expression instanceof at;if(i)t.print("(");e.prefix.print(t);if(i)t.print(")");e.template_string.print(t)});DEFPRINT(de,function(e,t){var n=t.parent()instanceof he;t.print("`");for(var i=0;i");e.space();const r=t.body[0];if(t.body.length===1&&r instanceof ve){const t=r.value;if(!t){e.print("{}")}else if(left_is_object(t)){e.print("(");t.print(e);e.print(")")}else{t.print(e)}}else{print_braced(t,e)}if(i){e.print(")")}});ge.DEFMETHOD("_do_print",function(e,t){e.print(t);if(this.value){e.space();const t=this.value.start.comments_before;if(t&&t.length&&!e.printed_comments.has(t)){e.print("(");this.value.print(e);e.print(")")}else{this.value.print(e)}}e.semicolon()});DEFPRINT(ve,function(e,t){e._do_print(t,"return")});DEFPRINT(De,function(e,t){e._do_print(t,"throw")});DEFPRINT(Te,function(e,t){var n=e.is_star?"*":"";t.print("yield"+n);if(e.expression){t.space();e.expression.print(t)}});DEFPRINT(Se,function(e,t){t.print("await");t.space();var n=e.expression;var i=!(n instanceof Ge||n instanceof Lt||n instanceof We||n instanceof Ze||n instanceof Gt||n instanceof Se||n instanceof at);if(i)t.print("(");e.expression.print(t);if(i)t.print(")")});be.DEFMETHOD("_do_print",function(e,t){e.print(t);if(this.label){e.space();this.label.print(e)}e.semicolon()});DEFPRINT(ye,function(e,t){e._do_print(t,"break")});DEFPRINT(ke,function(e,t){e._do_print(t,"continue")});function make_then(e,t){var n=e.body;if(t.option("braces")||t.option("ie8")&&n instanceof J)return make_block(n,t);if(!n)return t.force_semicolon();while(true){if(n instanceof Ae){if(!n.alternative){make_block(e.body,t);return}n=n.alternative}else if(n instanceof j){n=n.body}else break}force_statement(e.body,t)}DEFPRINT(Ae,function(e,t){t.print("if");t.space();t.with_parens(function(){e.condition.print(t)});t.space();if(e.alternative){make_then(e,t);t.space();t.print("else");t.space();if(e.alternative instanceof Ae)e.alternative.print(t);else force_statement(e.alternative,t)}else{e._do_print_body(t)}});DEFPRINT(Ce,function(e,t){t.print("switch");t.space();t.with_parens(function(){e.expression.print(t)});t.space();var n=e.body.length-1;if(n<0)print_braced_empty(e,t);else t.with_block(function(){e.body.forEach(function(e,i){t.indent(true);e.print(t);if(i0)t.newline()})})});Re.DEFMETHOD("_do_print_body",function(e){e.newline();this.body.forEach(function(t){e.indent();t.print(e);e.newline()})});DEFPRINT(xe,function(e,t){t.print("default:");e._do_print_body(t)});DEFPRINT(Fe,function(e,t){t.print("case");t.space();e.expression.print(t);t.print(":");e._do_print_body(t)});DEFPRINT(Oe,function(e,t){t.print("try");t.space();print_braced(e,t);if(e.bcatch){t.space();e.bcatch.print(t)}if(e.bfinally){t.space();e.bfinally.print(t)}});DEFPRINT(we,function(e,t){t.print("catch");if(e.argname){t.space();t.with_parens(function(){e.argname.print(t)})}t.space();print_braced(e,t)});DEFPRINT(Me,function(e,t){t.print("finally");t.space();print_braced(e,t)});Ne.DEFMETHOD("_do_print",function(e,t){e.print(t);e.space();this.definitions.forEach(function(t,n){if(n)e.comma();t.print(e)});var n=e.parent();var i=n instanceof te||n instanceof ne;var r=!i||n&&n.init!==this;if(r)e.semicolon()});DEFPRINT(Pe,function(e,t){e._do_print(t,"let")});DEFPRINT(Ie,function(e,t){e._do_print(t,"var")});DEFPRINT(Le,function(e,t){e._do_print(t,"const")});DEFPRINT(Ue,function(e,t){t.print("import");t.space();if(e.imported_name){e.imported_name.print(t)}if(e.imported_name&&e.imported_names){t.print(",");t.space()}if(e.imported_names){if(e.imported_names.length===1&&e.imported_names[0].foreign_name.name==="*"){e.imported_names[0].print(t)}else{t.print("{");e.imported_names.forEach(function(n,i){t.space();n.print(t);if(i{if(e instanceof ae)return true;if(e instanceof et&&e.operator=="in"){return rn}})}e.print(t,i)}DEFPRINT(Be,function(e,t){e.name.print(t);if(e.value){t.space();t.print("=");t.space();var n=t.parent(1);var i=n instanceof te||n instanceof ne;parenthesize_for_noin(e.value,t,i)}});DEFPRINT(Ge,function(e,t){e.expression.print(t);if(e instanceof Xe&&e.args.length===0)return;if(e.expression instanceof Ge||e.expression instanceof ue){t.add_mapping(e.start)}if(e.optional)t.print("?.");t.with_parens(function(){e.args.forEach(function(e,n){if(n)t.comma();e.print(t)})})});DEFPRINT(Xe,function(e,t){t.print("new");t.space();Ge.prototype._codegen(e,t)});He.DEFMETHOD("_do_print",function(e){this.expressions.forEach(function(t,n){if(n>0){e.comma();if(e.should_break()){e.newline();e.indent()}}t.print(e)})});DEFPRINT(He,function(e,t){e._do_print(t)});DEFPRINT(qe,function(e,t){var n=e.expression;n.print(t);var i=e.property;var r=f.has(i)?t.option("ie8"):!is_identifier_string(i,t.option("ecma")>=2015||t.option("safari10"));if(e.optional)t.print("?.");if(r){t.print("[");t.add_mapping(e.end);t.print_string(i);t.print("]")}else{if(n instanceof Ht&&n.getValue()>=0){if(!/[xa-f.)]/i.test(t.last())){t.print(".")}}if(!e.optional)t.print(".");t.add_mapping(e.end);t.print_name(i)}});DEFPRINT(Ye,function(e,t){var n=e.expression;n.print(t);var i=e.property;if(e.optional)t.print("?");t.print(".#");t.print_name(i)});DEFPRINT(je,function(e,t){e.expression.print(t);if(e.optional)t.print("?.");t.print("[");e.property.print(t);t.print("]")});DEFPRINT($e,function(e,t){e.expression.print(t)});DEFPRINT(Qe,function(e,t){var n=e.operator;t.print(n);if(/^[a-z]/i.test(n)||/[+-]$/.test(n)&&e.expression instanceof Qe&&/^[+-]/.test(e.expression.operator)){t.space()}e.expression.print(t)});DEFPRINT(Je,function(e,t){e.expression.print(t);t.print(e.operator)});DEFPRINT(et,function(e,t){var n=e.operator;e.left.print(t);if(n[0]==">"&&e.left instanceof Je&&e.left.operator=="--"){t.print(" ")}else{t.space()}t.print(n);if((n=="<"||n=="<<")&&e.right instanceof Qe&&e.right.operator=="!"&&e.right.expression instanceof Qe&&e.right.expression.operator=="--"){t.print(" ")}else{t.space()}e.right.print(t)});DEFPRINT(tt,function(e,t){e.condition.print(t);t.space();t.print("?");t.space();e.consequent.print(t);t.space();t.colon();e.alternative.print(t)});DEFPRINT(rt,function(e,t){t.with_square(function(){var n=e.elements,i=n.length;if(i>0)t.space();n.forEach(function(e,n){if(n)t.comma();e.print(t);if(n===i-1&&e instanceof Qt)t.comma()});if(i>0)t.space()})});DEFPRINT(at,function(e,t){if(e.properties.length>0)t.with_block(function(){e.properties.forEach(function(e,n){if(n){t.print(",");t.newline()}t.indent();e.print(t)});t.newline()});else print_braced_empty(e,t)});DEFPRINT(ht,function(e,t){t.print("class");t.space();if(e.name){e.name.print(t);t.space()}if(e.extends){var n=!(e.extends instanceof Lt)&&!(e.extends instanceof We)&&!(e.extends instanceof gt)&&!(e.extends instanceof le);t.print("extends");if(n){t.print("(")}else{t.space()}e.extends.print(t);if(n){t.print(")")}else{t.space()}}if(e.properties.length>0)t.with_block(function(){e.properties.forEach(function(e,n){if(n){t.newline()}t.indent();e.print(t)});t.newline()});else t.print("{}")});DEFPRINT(Dt,function(e,t){t.print("new.target")});function print_property_name(e,t,n){if(n.option("quote_keys")){return n.print_string(e)}if(""+ +e==e&&e>=0){if(n.option("keep_numbers")){return n.print(e)}return n.print(make_num(e))}var i=f.has(e)?n.option("ie8"):n.option("ecma")<2015||n.option("safari10")?!is_basic_identifier_string(e):!is_identifier_string(e,true);if(i||t&&n.option("keep_quoted_props")){return n.print_string(e,t)}return n.print_name(e)}DEFPRINT(st,function(e,t){function get_name(e){var t=e.definition();return t?t.mangled_name||t.name:e.name}var n=t.option("shorthand");if(n&&e.value instanceof vt&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value)===e.key&&!f.has(e.key)){print_property_name(e.key,e.quote,t)}else if(n&&e.value instanceof it&&e.value.left instanceof vt&&is_identifier_string(e.key,t.option("ecma")>=2015||t.option("safari10"))&&get_name(e.value.left)===e.key){print_property_name(e.key,e.quote,t);t.space();t.print("=");t.space();e.value.right.print(t)}else{if(!(e.key instanceof z)){print_property_name(e.key,e.quote,t)}else{t.with_square(function(){e.key.print(t)})}t.colon();e.value.print(t)}});DEFPRINT(mt,(e,t)=>{if(e.static){t.print("static");t.space()}t.print("#");print_property_name(e.key.name,e.quote,t);if(e.value){t.print("=");e.value.print(t)}t.semicolon()});DEFPRINT(dt,(e,t)=>{if(e.static){t.print("static");t.space()}if(e.key instanceof xt){print_property_name(e.key.name,e.quote,t)}else{t.print("[");e.key.print(t);t.print("]")}if(e.value){t.print("=");e.value.print(t)}t.semicolon()});ot.DEFMETHOD("_print_getter_setter",function(e,t,n){var i=this;if(i.static){n.print("static");n.space()}if(e){n.print(e);n.space()}if(i.key instanceof Rt){if(t)n.print("#");print_property_name(i.key.name,i.quote,n)}else{n.with_square(function(){i.key.print(n)})}i.value._do_print(n,true)});DEFPRINT(lt,function(e,t){e._print_getter_setter("set",false,t)});DEFPRINT(ft,function(e,t){e._print_getter_setter("get",false,t)});DEFPRINT(ut,function(e,t){e._print_getter_setter("set",true,t)});DEFPRINT(ct,function(e,t){e._print_getter_setter("get",true,t)});DEFPRINT(_t,function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,true,t)});DEFPRINT(pt,function(e,t){var n;if(e.is_generator&&e.async){n="async*"}else if(e.is_generator){n="*"}else if(e.async){n="async"}e._print_getter_setter(n,false,t)});vt.DEFMETHOD("_do_print",function(e){var t=this.definition();e.print_name(t?t.mangled_name||t.name:this.name)});DEFPRINT(vt,function(e,t){e._do_print(t)});DEFPRINT(Qt,noop);DEFPRINT(zt,function(e,t){t.print("this")});DEFPRINT(Kt,function(e,t){t.print("super")});DEFPRINT(Gt,function(e,t){t.print(e.getValue())});DEFPRINT(Xt,function(e,t){t.print_string(e.getValue(),e.quote,t.in_directive)});DEFPRINT(Ht,function(e,t){if((t.option("keep_numbers")||t.use_asm)&&e.raw){t.print(e.raw)}else{t.print(make_num(e.getValue()))}});DEFPRINT(Wt,function(e,t){t.print(e.getValue()+"n")});const e=/(<\s*\/\s*script)/i;const t=(e,t)=>t.replace("/","\\/");DEFPRINT(qt,function(n,i){let{source:r,flags:a}=n.getValue();r=regexp_source_fix(r);a=a?sort_regexp_flags(a):"";r=r.replace(e,t);i.print(i.to_utf8(`/${r}/${a}`));const o=i.parent();if(o instanceof et&&/^\w/.test(o.operator)&&o.left===n){i.print(" ")}});function force_statement(e,t){if(t.option("braces")){make_block(e,t)}else{if(!e||e instanceof Y)t.force_semicolon();else e.print(t)}}function best_of(e){var t=e[0],n=t.length;for(var i=1;i{return e===null&&t===null||e.TYPE===t.TYPE&&e.shallow_cmp(t)};const hn=(e,t)=>{if(!_n(e,t))return false;const n=[e];const i=[t];const r=n.push.bind(n);const a=i.push.bind(i);while(n.length&&i.length){const e=n.pop();const t=i.pop();if(!_n(e,t))return false;e._children_backwards(r);t._children_backwards(a);if(n.length!==i.length){return false}}return n.length==0&&i.length==0};const dn=e=>{const t=Object.keys(e).map(t=>{if(e[t]==="eq"){return`this.${t} === other.${t}`}else if(e[t]==="exist"){return`(this.${t} == null ? other.${t} == null : this.${t} === other.${t})`}else{throw new Error(`mkshallow: Unexpected instruction: ${e[t]}`)}}).join(" && ");return new Function("other","return "+t)};const mn=()=>true;z.prototype.shallow_cmp=function(){throw new Error("did not find a shallow_cmp function for "+this.constructor.name)};G.prototype.shallow_cmp=mn;X.prototype.shallow_cmp=dn({value:"eq"});H.prototype.shallow_cmp=mn;W.prototype.shallow_cmp=mn;Y.prototype.shallow_cmp=mn;$.prototype.shallow_cmp=dn({"label.name":"eq"});J.prototype.shallow_cmp=mn;ee.prototype.shallow_cmp=mn;te.prototype.shallow_cmp=dn({init:"exist",condition:"exist",step:"exist"});ne.prototype.shallow_cmp=mn;ie.prototype.shallow_cmp=mn;re.prototype.shallow_cmp=mn;oe.prototype.shallow_cmp=mn;se.prototype.shallow_cmp=mn;ue.prototype.shallow_cmp=dn({is_generator:"eq",async:"eq"});_e.prototype.shallow_cmp=dn({is_array:"eq"});he.prototype.shallow_cmp=mn;de.prototype.shallow_cmp=mn;me.prototype.shallow_cmp=dn({value:"eq"});Ee.prototype.shallow_cmp=mn;be.prototype.shallow_cmp=mn;Se.prototype.shallow_cmp=mn;Te.prototype.shallow_cmp=dn({is_star:"eq"});Ae.prototype.shallow_cmp=dn({alternative:"exist"});Ce.prototype.shallow_cmp=mn;Re.prototype.shallow_cmp=mn;Oe.prototype.shallow_cmp=dn({bcatch:"exist",bfinally:"exist"});we.prototype.shallow_cmp=dn({argname:"exist"});Me.prototype.shallow_cmp=mn;Ne.prototype.shallow_cmp=mn;Be.prototype.shallow_cmp=dn({value:"exist"});Ve.prototype.shallow_cmp=mn;Ue.prototype.shallow_cmp=dn({imported_name:"exist",imported_names:"exist"});ze.prototype.shallow_cmp=mn;Ke.prototype.shallow_cmp=dn({exported_definition:"exist",exported_value:"exist",exported_names:"exist",module_name:"eq",is_default:"eq"});Ge.prototype.shallow_cmp=mn;He.prototype.shallow_cmp=mn;We.prototype.shallow_cmp=mn;$e.prototype.shallow_cmp=mn;qe.prototype.shallow_cmp=dn({property:"eq"});Ye.prototype.shallow_cmp=dn({property:"eq"});Ze.prototype.shallow_cmp=dn({operator:"eq"});et.prototype.shallow_cmp=dn({operator:"eq"});tt.prototype.shallow_cmp=mn;rt.prototype.shallow_cmp=mn;at.prototype.shallow_cmp=mn;ot.prototype.shallow_cmp=mn;st.prototype.shallow_cmp=dn({key:"eq"});lt.prototype.shallow_cmp=dn({static:"eq"});ft.prototype.shallow_cmp=dn({static:"eq"});pt.prototype.shallow_cmp=dn({static:"eq",is_generator:"eq",async:"eq"});ht.prototype.shallow_cmp=dn({name:"exist",extends:"exist"});dt.prototype.shallow_cmp=dn({static:"eq"});vt.prototype.shallow_cmp=dn({name:"eq"});Dt.prototype.shallow_cmp=mn;zt.prototype.shallow_cmp=mn;Kt.prototype.shallow_cmp=mn;Xt.prototype.shallow_cmp=dn({value:"eq"});Ht.prototype.shallow_cmp=dn({value:"eq"});Wt.prototype.shallow_cmp=dn({value:"eq"});qt.prototype.shallow_cmp=function(e){return this.value.flags===e.value.flags&&this.value.source===e.value.source};Yt.prototype.shallow_cmp=mn;const En=1<<0;const gn=1<<1;let vn=null;let Dn=null;class SymbolDef{constructor(e,t,n){this.name=t.name;this.orig=[t];this.init=n;this.eliminated=0;this.assignments=0;this.scope=e;this.replaced=0;this.global=false;this.export=0;this.mangled_name=null;this.undeclared=false;this.id=SymbolDef.next_id++;this.chained=false;this.direct_access=false;this.escaped=0;this.recursive_refs=0;this.references=[];this.should_replace=undefined;this.single_use=false;this.fixed=false;Object.seal(this)}fixed_value(){if(!this.fixed||this.fixed instanceof z)return this.fixed;return this.fixed()}unmangleable(e){if(!e)e={};if(vn&&vn.has(this.id)&&keep_name(e.keep_fnames,this.orig[0].name))return true;return this.global&&!e.toplevel||this.export&En||this.undeclared||!e.eval&&this.scope.pinned()||(this.orig[0]instanceof Ft||this.orig[0]instanceof Ct)&&keep_name(e.keep_fnames,this.orig[0].name)||this.orig[0]instanceof Rt||(this.orig[0]instanceof wt||this.orig[0]instanceof Ot)&&keep_name(e.keep_classnames,this.orig[0].name)}mangle(e){const t=e.cache&&e.cache.props;if(this.global&&t&&t.has(this.name)){this.mangled_name=t.get(this.name)}else if(!this.mangled_name&&!this.unmangleable(e)){var n=this.scope;var i=this.orig[0];if(e.ie8&&i instanceof Ft)n=n.parent_scope;const r=redefined_catch_def(this);this.mangled_name=r?r.mangled_name||r.name:n.next_mangled(e,this);if(this.global&&t){t.set(this.name,this.mangled_name)}}}}SymbolDef.next_id=1;function redefined_catch_def(e){if(e.orig[0]instanceof Mt&&e.scope.is_block_scope()){return e.scope.get_defun_scope().variables.get(e.name)}}ae.DEFMETHOD("figure_out_scope",function(e,{parent_scope:t=null,toplevel:n=this}={}){e=defaults(e,{cache:null,ie8:false,safari10:false});if(!(n instanceof oe)){throw new Error("Invalid toplevel scope")}var i=this.parent_scope=t;var r=new Map;var a=null;var o=null;var s=[];var u=new TreeWalker((t,n)=>{if(t.is_block_scope()){const r=i;t.block_scope=i=new ae(t);i._block_scope=true;const a=t instanceof we?r.parent_scope:r;i.init_scope_vars(a);i.uses_with=r.uses_with;i.uses_eval=r.uses_eval;if(e.safari10){if(t instanceof te||t instanceof ne){s.push(i)}}if(t instanceof Ce){const e=i;i=r;t.expression.walk(u);i=e;for(let e=0;e{if(e===t)return true;if(t instanceof kt){return e instanceof Ft}return!(e instanceof Tt||e instanceof St)})){js_error(`"${t.name}" is redeclared`,t.start.file,t.start.line,t.start.col,t.start.pos)}if(!(t instanceof At))mark_export(h,2);if(a!==i){t.mark_enclosed();var h=i.find_variable(t);if(t.thedef!==h){t.thedef=h;t.reference()}}}else if(t instanceof Ut){var d=r.get(t.name);if(!d)throw new Error(string_template("Undefined label {name} [{line},{col}]",{name:t.name,line:t.start.line,col:t.start.col}));t.thedef=d}if(!(i instanceof oe)&&(t instanceof Ke||t instanceof Ue)){js_error(`"${t.TYPE}" statement may only appear at the top level`,t.start.file,t.start.line,t.start.col,t.start.pos)}});this.walk(u);function mark_export(e,t){if(o){var n=0;do{t++}while(u.parent(n++)!==o)}var i=u.parent(t);if(e.export=i instanceof Ke?En:0){var r=i.exported_definition;if((r instanceof pe||r instanceof Et)&&i.is_default){e.export=gn}}}const c=this instanceof oe;if(c){this.globals=new Map}var u=new TreeWalker(e=>{if(e instanceof be&&e.label){e.label.thedef.references.push(e);return true}if(e instanceof Lt){var t=e.name;if(t=="eval"&&u.parent()instanceof Ge){for(var i=e.scope;i&&!i.uses_eval;i=i.parent_scope){i.uses_eval=true}}var r;if(u.parent()instanceof Ve&&u.parent(1).module_name||!(r=e.scope.find_variable(t))){r=n.def_global(e);if(e instanceof Bt)r.export=En}else if(r.scope instanceof ue&&t=="arguments"){r.scope.uses_arguments=true}e.thedef=r;e.reference();if(e.scope.is_block_scope()&&!(r.orig[0]instanceof kt)){e.scope=e.scope.get_defun_scope()}return true}var a;if(e instanceof Mt&&(a=redefined_catch_def(e.definition()))){var i=e.scope;while(i){push_uniq(i.enclosed,a);if(i===a.scope)break;i=i.parent_scope}}});this.walk(u);if(e.ie8||e.safari10){walk(this,e=>{if(e instanceof Mt){var t=e.name;var i=e.thedef.references;var r=e.scope.get_defun_scope();var a=r.find_variable(t)||n.globals.get(t)||r.def_variable(e);i.forEach(function(e){e.thedef=a;e.reference()});e.thedef=a;e.reference();return true}})}if(e.safari10){for(const e of s){e.parent_scope.variables.forEach(function(t){push_uniq(e.enclosed,t)})}}});oe.DEFMETHOD("def_global",function(e){var t=this.globals,n=e.name;if(t.has(n)){return t.get(n)}else{var i=new SymbolDef(this,e);i.undeclared=true;i.global=true;t.set(n,i);return i}});ae.DEFMETHOD("init_scope_vars",function(e){this.variables=new Map;this.uses_with=false;this.uses_eval=false;this.parent_scope=e;this.enclosed=[];this.cname=-1});ae.DEFMETHOD("conflicting_def",function(e){return this.enclosed.find(t=>t.name===e)||this.variables.has(e)||this.parent_scope&&this.parent_scope.conflicting_def(e)});ae.DEFMETHOD("conflicting_def_shallow",function(e){return this.enclosed.find(t=>t.name===e)||this.variables.has(e)});ae.DEFMETHOD("add_child_scope",function(e){if(e.parent_scope===this)return;e.parent_scope=this;const t=(()=>{const e=[];let t=this;do{e.push(t)}while(t=t.parent_scope);e.reverse();return e})();const n=new Set(e.enclosed);const i=[];for(const e of t){i.forEach(t=>push_uniq(e.enclosed,t));for(const t of e.variables.values()){if(n.has(t)){push_uniq(i,t);push_uniq(e.enclosed,t)}}}});function find_scopes_visible_from(e){const t=new Set;for(const n of new Set(e)){(function bubble_up(e){if(e==null||t.has(e))return;t.add(e);bubble_up(e.parent_scope)})(n)}return[...t]}ae.DEFMETHOD("create_symbol",function(e,{source:t,tentative_name:n,scope:i,conflict_scopes:r=[i],init:a=null}={}){let o;r=find_scopes_visible_from(r);if(n){n=o=n.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/gi,"_");let e=0;while(r.find(e=>e.conflicting_def_shallow(o))){o=n+"$"+e++}}if(!o){throw new Error("No symbol name could be generated in create_symbol()")}const s=make_node(e,t,{name:o,scope:i});this.def_variable(s,a||null);s.mark_enclosed();return s});z.DEFMETHOD("is_block_scope",return_false);ht.DEFMETHOD("is_block_scope",return_false);ue.DEFMETHOD("is_block_scope",return_false);oe.DEFMETHOD("is_block_scope",return_false);Re.DEFMETHOD("is_block_scope",return_false);W.DEFMETHOD("is_block_scope",return_true);ae.DEFMETHOD("is_block_scope",function(){return this._block_scope||false});Z.DEFMETHOD("is_block_scope",return_true);ue.DEFMETHOD("init_scope_vars",function(){ae.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false;this.def_variable(new At({name:"arguments",start:this.start,end:this.end}))});fe.DEFMETHOD("init_scope_vars",function(){ae.prototype.init_scope_vars.apply(this,arguments);this.uses_arguments=false});vt.DEFMETHOD("mark_enclosed",function(){var e=this.definition();var t=this.scope;while(t){push_uniq(t.enclosed,e);if(t===e.scope)break;t=t.parent_scope}});vt.DEFMETHOD("reference",function(){this.definition().references.push(this);this.mark_enclosed()});ae.DEFMETHOD("find_variable",function(e){if(e instanceof vt)e=e.name;return this.variables.get(e)||this.parent_scope&&this.parent_scope.find_variable(e)});ae.DEFMETHOD("def_function",function(e,t){var n=this.def_variable(e,t);if(!n.init||n.init instanceof pe)n.init=t;return n});ae.DEFMETHOD("def_variable",function(e,t){var n=this.variables.get(e.name);if(n){n.orig.push(e);if(n.init&&(n.scope!==e.scope||n.init instanceof le)){n.init=t}}else{n=new SymbolDef(this,e,t);this.variables.set(e.name,n);n.global=!this.parent_scope}return e.thedef=n});function next_mangled(e,t){var n=e.enclosed;e:while(true){var i=bn(++e.cname);if(f.has(i))continue;if(t.reserved.has(i))continue;if(Dn&&Dn.has(i))continue e;for(let e=n.length;--e>=0;){const r=n[e];const a=r.mangled_name||r.unmangleable(t)&&r.name;if(i==a)continue e}return i}}ae.DEFMETHOD("next_mangled",function(e){return next_mangled(this,e)});oe.DEFMETHOD("next_mangled",function(e){let t;const n=this.mangled_names;do{t=next_mangled(this,e)}while(n.has(t));return t});le.DEFMETHOD("next_mangled",function(e,t){var n=t.orig[0]instanceof At&&this.name&&this.name.definition();var i=n?n.mangled_name||n.name:null;while(true){var r=next_mangled(this,e);if(!i||i!=r)return r}});vt.DEFMETHOD("unmangleable",function(e){var t=this.definition();return!t||t.unmangleable(e)});Pt.DEFMETHOD("unmangleable",return_false);vt.DEFMETHOD("unreferenced",function(){return!this.definition().references.length&&!this.scope.pinned()});vt.DEFMETHOD("definition",function(){return this.thedef});vt.DEFMETHOD("global",function(){return this.thedef.global});oe.DEFMETHOD("_default_mangler_options",function(e){e=defaults(e,{eval:false,ie8:false,keep_classnames:false,keep_fnames:false,module:false,reserved:[],toplevel:false});if(e.module)e.toplevel=true;if(!Array.isArray(e.reserved)&&!(e.reserved instanceof Set)){e.reserved=[]}e.reserved=new Set(e.reserved);e.reserved.add("arguments");return e});oe.DEFMETHOD("mangle_names",function(e){e=this._default_mangler_options(e);var t=-1;var n=[];if(e.keep_fnames){vn=new Set}const i=this.mangled_names=new Set;if(e.cache){this.globals.forEach(collect);if(e.cache.props){e.cache.props.forEach(function(e){i.add(e)})}}var r=new TreeWalker(function(i,r){if(i instanceof $){var a=t;r();t=a;return true}if(i instanceof ae){i.variables.forEach(collect);return}if(i.is_block_scope()){i.block_scope.variables.forEach(collect);return}if(vn&&i instanceof Be&&i.value instanceof ue&&!i.value.name&&keep_name(e.keep_fnames,i.name.name)){vn.add(i.name.definition().id);return}if(i instanceof Pt){let e;do{e=bn(++t)}while(f.has(e));i.mangled_name=e;return true}if(!(e.ie8||e.safari10)&&i instanceof Mt){n.push(i.definition());return}});this.walk(r);if(e.keep_fnames||e.keep_classnames){Dn=new Set;n.forEach(t=>{if(t.name.length<6&&t.unmangleable(e)){Dn.add(t.name)}})}n.forEach(t=>{t.mangle(e)});vn=null;Dn=null;function collect(t){const i=!e.reserved.has(t.name)&&!(t.export&En);if(i){n.push(t)}}});oe.DEFMETHOD("find_colliding_names",function(e){const t=e.cache&&e.cache.props;const n=new Set;e.reserved.forEach(to_avoid);this.globals.forEach(add_def);this.walk(new TreeWalker(function(e){if(e instanceof ae)e.variables.forEach(add_def);if(e instanceof Mt)add_def(e.definition())}));return n;function to_avoid(e){n.add(e)}function add_def(n){var i=n.name;if(n.global&&t&&t.has(i))i=t.get(i);else if(!n.unmangleable(e))return;to_avoid(i)}});oe.DEFMETHOD("expand_names",function(e){bn.reset();bn.sort();e=this._default_mangler_options(e);var t=this.find_colliding_names(e);var n=0;this.globals.forEach(rename);this.walk(new TreeWalker(function(e){if(e instanceof ae)e.variables.forEach(rename);if(e instanceof Mt)rename(e.definition())}));function next_name(){var e;do{e=bn(n++)}while(t.has(e)||f.has(e));return e}function rename(t){if(t.global&&e.cache)return;if(t.unmangleable(e))return;if(e.reserved.has(t.name))return;const n=redefined_catch_def(t);const i=t.name=n?n.name:next_name();t.orig.forEach(function(e){e.name=i});t.references.forEach(function(e){e.name=i})}});z.DEFMETHOD("tail_node",return_this);He.DEFMETHOD("tail_node",function(){return this.expressions[this.expressions.length-1]});oe.DEFMETHOD("compute_char_frequency",function(e){e=this._default_mangler_options(e);try{z.prototype.print=function(t,n){this._print(t,n);if(this instanceof vt&&!this.unmangleable(e)){bn.consider(this.name,-1)}else if(e.properties){if(this instanceof Ye){bn.consider("#"+this.property,-1)}else if(this instanceof qe){bn.consider(this.property,-1)}else if(this instanceof je){skip_string(this.property)}}};bn.consider(this.print_to_string(),1)}finally{z.prototype.print=z.prototype._print}bn.sort();function skip_string(e){if(e instanceof Xt){bn.consider(e.value,-1)}else if(e instanceof tt){skip_string(e.consequent);skip_string(e.alternative)}else if(e instanceof He){skip_string(e.tail_node())}}});const bn=(()=>{const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");const t="0123456789".split("");let n;let i;function reset(){i=new Map;e.forEach(function(e){i.set(e,0)});t.forEach(function(e){i.set(e,0)})}base54.consider=function(e,t){for(var n=e.length;--n>=0;){i.set(e[n],i.get(e[n])+t)}};function compare(e,t){return i.get(t)-i.get(e)}base54.sort=function(){n=mergeSort(e,compare).concat(mergeSort(t,compare))};base54.reset=reset;reset();function base54(e){var t="",i=54;e++;do{e--;t+=n[e%i];e=Math.floor(e/i);i=64}while(e>0);return t}return base54})();let yn=undefined;z.prototype.size=function(e,t){yn=e&&e.mangle_options;let n=0;walk_parent(this,(e,t)=>{n+=e._size(t);if(e instanceof fe&&e.is_braceless()){n+=e.body[0].value._size(t);return true}},t||e&&e.stack);yn=undefined;return n};z.prototype._size=(()=>0);G.prototype._size=(()=>8);X.prototype._size=function(){return 2+this.value.length};const kn=e=>e.length&&e.length-1;W.prototype._size=function(){return 2+kn(this.body)};oe.prototype._size=function(){return kn(this.body)};Y.prototype._size=(()=>1);$.prototype._size=(()=>2);J.prototype._size=(()=>9);ee.prototype._size=(()=>7);te.prototype._size=(()=>8);ne.prototype._size=(()=>8);re.prototype._size=(()=>6);se.prototype._size=(()=>3);const Sn=e=>(e.is_generator?1:0)+(e.async?6:0);ce.prototype._size=function(){return Sn(this)+4+kn(this.argnames)+kn(this.body)};le.prototype._size=function(e){const t=!!first_in_statement(e);return t*2+Sn(this)+12+kn(this.argnames)+kn(this.body)};pe.prototype._size=function(){return Sn(this)+13+kn(this.argnames)+kn(this.body)};fe.prototype._size=function(){let e=2+kn(this.argnames);if(!(this.argnames.length===1&&this.argnames[0]instanceof vt)){e+=2}const t=this.is_braceless()?0:kn(this.body)+2;return Sn(this)+e+t};_e.prototype._size=(()=>2);de.prototype._size=function(){return 2+Math.floor(this.segments.length/2)*3};me.prototype._size=function(){return this.value.length};ve.prototype._size=function(){return this.value?7:6};De.prototype._size=(()=>6);ye.prototype._size=function(){return this.label?6:5};ke.prototype._size=function(){return this.label?9:8};Ae.prototype._size=(()=>4);Ce.prototype._size=function(){return 8+kn(this.body)};Fe.prototype._size=function(){return 5+kn(this.body)};xe.prototype._size=function(){return 8+kn(this.body)};Oe.prototype._size=function(){return 3+kn(this.body)};we.prototype._size=function(){let e=7+kn(this.body);if(this.argname){e+=2}return e};Me.prototype._size=function(){return 7+kn(this.body)};const Tn=(e,t)=>e+kn(t.definitions);Ie.prototype._size=function(){return Tn(4,this)};Pe.prototype._size=function(){return Tn(4,this)};Le.prototype._size=function(){return Tn(6,this)};Be.prototype._size=function(){return this.value?1:0};Ve.prototype._size=function(){return this.name?4:0};Ue.prototype._size=function(){let e=6;if(this.imported_name)e+=1;if(this.imported_name||this.imported_names)e+=5;if(this.imported_names){e+=2+kn(this.imported_names)}return e};ze.prototype._size=(()=>11);Ke.prototype._size=function(){let e=7+(this.is_default?8:0);if(this.exported_value){e+=this.exported_value._size()}if(this.exported_names){e+=2+kn(this.exported_names)}if(this.module_name){e+=5}return e};Ge.prototype._size=function(){if(this.optional){return 4+kn(this.args)}return 2+kn(this.args)};Xe.prototype._size=function(){return 6+kn(this.args)};He.prototype._size=function(){return kn(this.expressions)};qe.prototype._size=function(){if(this.optional){return this.property.length+2}return this.property.length+1};Ye.prototype._size=function(){if(this.optional){return this.property.length+3}return this.property.length+2};je.prototype._size=function(){return this.optional?4:2};Ze.prototype._size=function(){if(this.operator==="typeof")return 7;if(this.operator==="void")return 5;return this.operator.length};et.prototype._size=function(e){if(this.operator==="in")return 4;let t=this.operator.length;if((this.operator==="+"||this.operator==="-")&&this.right instanceof Ze&&this.right.operator===this.operator){t+=1}if(this.needs_parens(e)){t+=2}return t};tt.prototype._size=(()=>3);rt.prototype._size=function(){return 2+kn(this.elements)};at.prototype._size=function(e){let t=2;if(first_in_statement(e)){t+=2}return t+kn(this.properties)};const An=e=>typeof e==="string"?e.length:0;st.prototype._size=function(){return An(this.key)+1};const Cn=e=>e?7:0;ft.prototype._size=function(){return 5+Cn(this.static)+An(this.key)};lt.prototype._size=function(){return 5+Cn(this.static)+An(this.key)};pt.prototype._size=function(){return Cn(this.static)+An(this.key)+Sn(this)};_t.prototype._size=function(){return pt.prototype._size.call(this)+1};ct.prototype._size=ut.prototype._size=function(){return pt.prototype._size.call(this)+4};ht.prototype._size=function(){return(this.name?8:7)+(this.extends?8:0)};dt.prototype._size=function(){return Cn(this.static)+(typeof this.key==="string"?this.key.length+2:0)+(this.value?1:0)};mt.prototype._size=function(){return dt.prototype._size.call(this)+1};vt.prototype._size=function(){return!yn||this.definition().unmangleable(yn)?this.name.length:1};xt.prototype._size=function(){return this.name.length};Lt.prototype._size=bt.prototype._size=function(){const{name:e,thedef:t}=this;if(t&&t.global)return e.length;if(e==="arguments")return 9;return vt.prototype._size.call(this)};Dt.prototype._size=(()=>10);It.prototype._size=function(){return this.name.length};Vt.prototype._size=function(){return this.name.length};zt.prototype._size=(()=>4);Kt.prototype._size=(()=>5);Xt.prototype._size=function(){return this.value.length+2};Ht.prototype._size=function(){const{value:e}=this;if(e===0)return 1;if(e>0&&Math.floor(e)===e){return Math.floor(Math.log10(e)+1)}return e.toString().length};Wt.prototype._size=function(){return this.value.length};qt.prototype._size=function(){return this.value.toString().length};jt.prototype._size=(()=>4);$t.prototype._size=(()=>3);Zt.prototype._size=(()=>6);Qt.prototype._size=(()=>0);Jt.prototype._size=(()=>8);nn.prototype._size=(()=>4);tn.prototype._size=(()=>5);Se.prototype._size=(()=>6);Te.prototype._size=(()=>6);const Rn=1;const xn=2;const Fn=4;const On=8;const wn=16;const Mn=32;const Nn=256;const In=512;const Pn=1024;const Ln=Nn|In|Pn;const Bn=(e,t)=>e.flags&t;const Vn=(e,t)=>{e.flags|=t};const Un=(e,t)=>{e.flags&=~t};class Compressor extends TreeWalker{constructor(e,{false_by_default:t=false,mangle_options:n=false}){super();if(e.defaults!==undefined&&!e.defaults)t=true;this.options=defaults(e,{arguments:false,arrows:!t,booleans:!t,booleans_as_integers:false,collapse_vars:!t,comparisons:!t,computed_props:!t,conditionals:!t,dead_code:!t,defaults:true,directives:!t,drop_console:false,drop_debugger:!t,ecma:5,evaluate:!t,expression:false,global_defs:false,hoist_funs:false,hoist_props:!t,hoist_vars:false,ie8:false,if_return:!t,inline:!t,join_vars:!t,keep_classnames:false,keep_fargs:true,keep_fnames:false,keep_infinity:false,loops:!t,module:false,negate_iife:!t,passes:1,properties:!t,pure_getters:!t&&"strict",pure_funcs:null,reduce_funcs:!t,reduce_vars:!t,sequences:!t,side_effects:!t,switches:!t,top_retain:null,toplevel:!!(e&&e["top_retain"]),typeofs:!t,unsafe:false,unsafe_arrows:false,unsafe_comps:false,unsafe_Function:false,unsafe_math:false,unsafe_symbols:false,unsafe_methods:false,unsafe_proto:false,unsafe_regexp:false,unsafe_undefined:false,unused:!t,warnings:false},true);var i=this.options["global_defs"];if(typeof i=="object")for(var r in i){if(r[0]==="@"&&HOP(i,r)){i[r.slice(1)]=parse(i[r],{expression:true})}}if(this.options["inline"]===true)this.options["inline"]=3;var a=this.options["pure_funcs"];if(typeof a=="function"){this.pure_funcs=a}else{this.pure_funcs=a?function(e){return!a.includes(e.expression.print_to_string())}:return_true}var o=this.options["top_retain"];if(o instanceof RegExp){this.top_retain=function(e){return o.test(e.name)}}else if(typeof o=="function"){this.top_retain=o}else if(o){if(typeof o=="string"){o=o.split(/,/)}this.top_retain=function(e){return o.includes(e.name)}}if(this.options["module"]){this.directives["use strict"]=true;this.options["toplevel"]=true}var s=this.options["toplevel"];this.toplevel=typeof s=="string"?{funcs:/funcs/.test(s),vars:/vars/.test(s)}:{funcs:s,vars:s};var u=this.options["sequences"];this.sequences_limit=u==1?800:u|0;this.evaluated_regexps=new Map;this._toplevel=undefined;this.mangle_options=n}option(e){return this.options[e]}exposed(e){if(e.export)return true;if(e.global)for(var t=0,n=e.orig.length;t0||this.option("reduce_vars")){this._toplevel.reset_opt_flags(this)}this._toplevel=this._toplevel.transform(this);if(t>1){let e=0;walk(this._toplevel,()=>{e++});if(e=0){r.body[o]=r.body[o].transform(i)}}else if(r instanceof Ae){r.body=r.body.transform(i);if(r.alternative){r.alternative=r.alternative.transform(i)}}else if(r instanceof re){r.body=r.body.transform(i)}return r});n.transform(i)});function read_property(e,t){t=get_value(t);if(t instanceof z)return;var n;if(e instanceof rt){var i=e.elements;if(t=="length")return make_node_from_constant(i.length,e);if(typeof t=="number"&&t in i)n=i[t]}else if(e instanceof at){t=""+t;var r=e.properties;for(var a=r.length;--a>=0;){var o=r[a];if(!(o instanceof st))return;if(!n&&r[a].key===t)n=r[a].value}}return n instanceof Lt&&n.fixed_value()||n}function is_modified(e,t,n,i,r,a){var o=t.parent(r);var s=is_lhs(n,o);if(s)return s;if(!a&&o instanceof Ge&&o.expression===n&&!(i instanceof fe)&&!(i instanceof ht)&&!o.is_callee_pure(e)&&(!(i instanceof le)||!(o instanceof Xe)&&i.contains_this())){return true}if(o instanceof rt){return is_modified(e,t,o,o,r+1)}if(o instanceof st&&n===o.value){var u=t.parent(r+1);return is_modified(e,t,u,u,r+2)}if(o instanceof We&&o.expression===n){var c=read_property(i,o.property);return!a&&is_modified(e,t,o,c,r+1)}}(function(e){e(z,noop);function reset_def(e,t){t.assignments=0;t.chained=false;t.direct_access=false;t.escaped=0;t.recursive_refs=0;t.references=[];t.single_use=undefined;if(t.scope.pinned()){t.fixed=false}else if(t.orig[0]instanceof St||!e.exposed(t)){t.fixed=t.init}else{t.fixed=false}}function reset_variables(e,t,n){n.variables.forEach(function(n){reset_def(t,n);if(n.fixed===null){e.defs_to_safe_ids.set(n.id,e.safe_ids);mark(e,n,true)}else if(n.fixed){e.loop_ids.set(n.id,e.in_loop);mark(e,n,true)}})}function reset_block_variables(e,t){if(t.block_scope)t.block_scope.variables.forEach(t=>{reset_def(e,t)})}function push(e){e.safe_ids=Object.create(e.safe_ids)}function pop(e){e.safe_ids=Object.getPrototypeOf(e.safe_ids)}function mark(e,t,n){e.safe_ids[t.id]=n}function safe_to_read(e,t){if(t.single_use=="m")return false;if(e.safe_ids[t.id]){if(t.fixed==null){var n=t.orig[0];if(n instanceof At||n.name=="arguments")return false;t.fixed=make_node(Zt,n)}return true}return t.fixed instanceof pe}function safe_to_assign(e,t,n,i){if(t.fixed===undefined)return true;let r;if(t.fixed===null&&(r=e.defs_to_safe_ids.get(t.id))){r[t.id]=false;e.defs_to_safe_ids.delete(t.id);return true}if(!HOP(e.safe_ids,t.id))return false;if(!safe_to_read(e,t))return false;if(t.fixed===false)return false;if(t.fixed!=null&&(!i||t.references.length>t.assignments))return false;if(t.fixed instanceof pe){return i instanceof z&&t.fixed.parent_scope===n}return t.orig.every(e=>{return!(e instanceof St||e instanceof Ct||e instanceof Ft)})}function ref_once(e,t,n){return t.option("unused")&&!n.scope.pinned()&&n.references.length-n.recursive_refs==1&&e.loop_ids.get(n.id)===e.in_loop}function is_immutable(e){if(!e)return false;return e.is_constant()||e instanceof ue||e instanceof zt}function mark_escaped(e,t,n,i,r,a=0,o=1){var s=e.parent(a);if(r){if(r.is_constant())return;if(r instanceof gt)return}if(s instanceof nt&&(s.operator==="="||s.logical)&&i===s.right||s instanceof Ge&&(i!==s.expression||s instanceof Xe)||s instanceof ge&&i===s.value&&i.scope!==t.scope||s instanceof Be&&i===s.value||s instanceof Te&&i===s.value&&i.scope!==t.scope){if(o>1&&!(r&&r.is_constant_expression(n)))o=1;if(!t.escaped||t.escaped>o)t.escaped=o;return}else if(s instanceof rt||s instanceof Se||s instanceof et&&Gn.has(s.operator)||s instanceof tt&&i!==s.condition||s instanceof se||s instanceof He&&i===s.tail_node()){mark_escaped(e,t,n,s,s,a+1,o)}else if(s instanceof st&&i===s.value){var u=e.parent(a+1);mark_escaped(e,t,n,u,u,a+2,o)}else if(s instanceof We&&i===s.expression){r=read_property(r,s.property);mark_escaped(e,t,n,s,r,a+1,o+1);if(r)return}if(a>0)return;if(s instanceof He&&i!==s.tail_node())return;if(s instanceof H)return;t.direct_access=true}const t=e=>walk(e,e=>{if(!(e instanceof vt))return;var t=e.definition();if(!t)return;if(e instanceof Lt)t.references.push(e);t.fixed=false});e(ce,function(e,t,n){push(e);reset_variables(e,n,this);t();pop(e);return true});e(nt,function(e,n,i){var r=this;if(r.left instanceof _e){t(r.left);return}const a=()=>{if(r.logical){r.left.walk(e);push(e);r.right.walk(e);pop(e);return true}};var o=r.left;if(!(o instanceof Lt))return a();var s=o.definition();var u=safe_to_assign(e,s,o.scope,r.right);s.assignments++;if(!u)return a();var c=s.fixed;if(!c&&r.operator!="="&&!r.logical)return a();var l=r.operator=="=";var f=l?r.right:r;if(is_modified(i,e,r,f,0))return a();s.references.push(o);if(!r.logical){if(!l)s.chained=true;s.fixed=l?function(){return r.right}:function(){return make_node(et,r,{operator:r.operator.slice(0,-1),left:c instanceof z?c:c(),right:r.right})}}if(r.logical){mark(e,s,false);push(e);r.right.walk(e);pop(e);return true}mark(e,s,false);r.right.walk(e);mark(e,s,true);mark_escaped(e,s,o.scope,r,f,0,1);return true});e(et,function(e){if(!Gn.has(this.operator))return;this.left.walk(e);push(e);this.right.walk(e);pop(e);return true});e(W,function(e,t,n){reset_block_variables(n,this)});e(Fe,function(e){push(e);this.expression.walk(e);pop(e);push(e);walk_body(this,e);pop(e);return true});e(ht,function(e,t){Un(this,wn);push(e);t();pop(e);return true});e(tt,function(e){this.condition.walk(e);push(e);this.consequent.walk(e);pop(e);push(e);this.alternative.walk(e);pop(e);return true});e($e,function(e,t){const n=e.safe_ids;t();e.safe_ids=n;return true});e(Ge,function(e){this.expression.walk(e);if(this.optional){push(e)}for(const t of this.args)t.walk(e);return true});e(We,function(e){if(!this.optional)return;this.expression.walk(e);push(e);if(this.property instanceof z)this.property.walk(e);return true});e(xe,function(e,t){push(e);t();pop(e);return true});function mark_lambda(e,t,n){Un(this,wn);push(e);reset_variables(e,n,this);if(this.uses_arguments){t();pop(e);return}var i;if(!this.name&&(i=e.parent())instanceof Ge&&i.expression===this&&!i.args.some(e=>e instanceof se)&&this.argnames.every(e=>e instanceof vt)){this.argnames.forEach((t,n)=>{if(!t.definition)return;var r=t.definition();if(r.orig.length>1)return;if(r.fixed===undefined&&(!this.uses_arguments||e.has_directive("use strict"))){r.fixed=function(){return i.args[n]||make_node(Zt,i)};e.loop_ids.set(r.id,e.in_loop);mark(e,r,true)}else{r.fixed=false}})}t();pop(e);return true}e(ue,mark_lambda);e(J,function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);if(has_break_or_continue(this)){pop(e);push(e)}this.condition.walk(e);pop(e);e.in_loop=i;return true});e(te,function(e,t,n){reset_block_variables(n,this);if(this.init)this.init.walk(e);const i=e.in_loop;e.in_loop=this;push(e);if(this.condition)this.condition.walk(e);this.body.walk(e);if(this.step){if(has_break_or_continue(this)){pop(e);push(e)}this.step.walk(e)}pop(e);e.in_loop=i;return true});e(ne,function(e,n,i){reset_block_variables(i,this);t(this.init);this.object.walk(e);const r=e.in_loop;e.in_loop=this;push(e);this.body.walk(e);pop(e);e.in_loop=r;return true});e(Ae,function(e){this.condition.walk(e);push(e);this.body.walk(e);pop(e);if(this.alternative){push(e);this.alternative.walk(e);pop(e)}return true});e($,function(e){push(e);this.body.walk(e);pop(e);return true});e(Mt,function(){this.definition().fixed=false});e(Lt,function(e,t,n){var i=this.definition();i.references.push(this);if(i.references.length==1&&!i.fixed&&i.orig[0]instanceof Ct){e.loop_ids.set(i.id,e.in_loop)}var r;if(i.fixed===undefined||!safe_to_read(e,i)){i.fixed=false}else if(i.fixed){r=this.fixed_value();if(r instanceof ue&&recursive_ref(e,i)){i.recursive_refs++}else if(r&&!n.exposed(i)&&ref_once(e,n,i)){i.single_use=r instanceof ue&&!r.pinned()||r instanceof ht||i.scope===this.scope&&r.is_constant_expression()}else{i.single_use=false}if(is_modified(n,e,this,r,0,is_immutable(r))){if(i.single_use){i.single_use="m"}else{i.fixed=false}}}mark_escaped(e,i,this.scope,this,r,0,1)});e(oe,function(e,t,n){this.globals.forEach(function(e){reset_def(n,e)});reset_variables(e,n,this)});e(Oe,function(e,t,n){reset_block_variables(n,this);push(e);walk_body(this,e);pop(e);if(this.bcatch){push(e);this.bcatch.walk(e);pop(e)}if(this.bfinally)this.bfinally.walk(e);return true});e(Ze,function(e){var t=this;if(t.operator!=="++"&&t.operator!=="--")return;var n=t.expression;if(!(n instanceof Lt))return;var i=n.definition();var r=safe_to_assign(e,i,n.scope,true);i.assignments++;if(!r)return;var a=i.fixed;if(!a)return;i.references.push(n);i.chained=true;i.fixed=function(){return make_node(et,t,{operator:t.operator.slice(0,-1),left:make_node(Qe,t,{operator:"+",expression:a instanceof z?a:a()}),right:make_node(Ht,t,{value:1})})};mark(e,i,true);return true});e(Be,function(e,n){var i=this;if(i.name instanceof _e){t(i.name);return}var r=i.name.definition();if(i.value){if(safe_to_assign(e,r,i.name.scope,i.value)){r.fixed=function(){return i.value};e.loop_ids.set(r.id,e.in_loop);mark(e,r,false);n();mark(e,r,true);return true}else{r.fixed=false}}});e(ee,function(e,t,n){reset_block_variables(n,this);const i=e.in_loop;e.in_loop=this;push(e);t();pop(e);e.in_loop=i;return true})})(function(e,t){e.DEFMETHOD("reduce_vars",t)});oe.DEFMETHOD("reset_opt_flags",function(e){const t=this;const n=e.option("reduce_vars");const i=new TreeWalker(function(r,a){Un(r,Ln);if(n){if(e.top_retain&&r instanceof pe&&i.parent()===t){Vn(r,Pn)}return r.reduce_vars(i,a,e)}});i.safe_ids=Object.create(null);i.in_loop=null;i.loop_ids=new Map;i.defs_to_safe_ids=new Map;t.walk(i)});vt.DEFMETHOD("fixed_value",function(){var e=this.thedef.fixed;if(!e||e instanceof z)return e;return e()});Lt.DEFMETHOD("is_immutable",function(){var e=this.definition().orig;return e.length==1&&e[0]instanceof Ft});function is_func_expr(e){return e instanceof fe||e instanceof le}function is_lhs_read_only(e){if(e instanceof zt)return true;if(e instanceof Lt)return e.definition().orig[0]instanceof Ft;if(e instanceof We){e=e.expression;if(e instanceof Lt){if(e.is_immutable())return false;e=e.fixed_value()}if(!e)return true;if(e instanceof qt)return false;if(e instanceof Gt)return true;return is_lhs_read_only(e)}return false}function is_ref_of(e,t){if(!(e instanceof Lt))return false;var n=e.definition().orig;for(var i=n.length;--i>=0;){if(n[i]instanceof t)return true}}function find_scope(e){for(let t=0;;t++){const n=e.parent(t);if(n instanceof oe)return n;if(n instanceof ue)return n;if(n.block_scope)return n.block_scope}}function find_variable(e,t){var n,i=0;while(n=e.parent(i++)){if(n instanceof ae)break;if(n instanceof we&&n.argname){n=n.argname.definition().scope;break}}return n.find_variable(t)}function make_sequence(e,t){if(t.length==1)return t[0];if(t.length==0)throw new Error("trying to create a sequence with length zero!");return make_node(He,e,{expressions:t.reduce(merge_sequence,[])})}function make_node_from_constant(e,t){switch(typeof e){case"string":return make_node(Xt,t,{value:e});case"number":if(isNaN(e))return make_node($t,t);if(isFinite(e)){return 1/e<0?make_node(Qe,t,{operator:"-",expression:make_node(Ht,t,{value:-e})}):make_node(Ht,t,{value:e})}return e<0?make_node(Qe,t,{operator:"-",expression:make_node(Jt,t)}):make_node(Jt,t);case"boolean":return make_node(e?nn:tn,t);case"undefined":return make_node(Zt,t);default:if(e===null){return make_node(jt,t,{value:null})}if(e instanceof RegExp){return make_node(qt,t,{value:{source:regexp_source_fix(e.source),flags:e.flags}})}throw new Error(string_template("Can't handle constant of type: {type}",{type:typeof e}))}}function maintain_this_binding(e,t,n){if(e instanceof Qe&&e.operator=="delete"||e instanceof Ge&&e.expression===t&&(n instanceof We||n instanceof Lt&&n.name=="eval")){return make_sequence(t,[make_node(Ht,t,{value:0}),n])}return n}function merge_sequence(e,t){if(t instanceof He){e.push(...t.expressions)}else{e.push(t)}return e}function as_statement_array(e){if(e===null)return[];if(e instanceof q)return e.body;if(e instanceof Y)return[];if(e instanceof K)return[e];throw new Error("Can't convert thing to statement array")}function is_empty(e){if(e===null)return true;if(e instanceof Y)return true;if(e instanceof q)return e.body.length==0;return false}function can_be_evicted_from_block(e){return!(e instanceof Et||e instanceof pe||e instanceof Pe||e instanceof Le||e instanceof Ke||e instanceof Ue)}function loop_body(e){if(e instanceof Z){return e.body instanceof q?e.body:e}return e}function is_iife_call(e){if(e.TYPE!="Call")return false;return e.expression instanceof le||is_iife_call(e.expression)}function is_undeclared_ref(e){return e instanceof Lt&&e.definition().undeclared}var zn=makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");Lt.DEFMETHOD("is_declared",function(e){return!this.definition().undeclared||e.option("unsafe")&&zn.has(this.name)});var Kn=makePredicate("Infinity NaN undefined");function is_identifier_atom(e){return e instanceof Jt||e instanceof $t||e instanceof Zt}function tighten_body(e,t){var n,i;var a=t.find_parent(ae).get_defun_scope();find_loop_scope_try();var o,s=10;do{o=false;eliminate_spurious_blocks(e);if(t.option("dead_code")){eliminate_dead_code(e,t)}if(t.option("if_return")){handle_if_return(e,t)}if(t.sequences_limit>0){sequencesize(e,t);sequencesize_2(e,t)}if(t.option("join_vars")){join_consecutive_vars(e)}if(t.option("collapse_vars")){collapse(e,t)}}while(o&&s-- >0);function find_loop_scope_try(){var e=t.self(),r=0;do{if(e instanceof we||e instanceof Me){r++}else if(e instanceof Z){n=true}else if(e instanceof ae){a=e;break}else if(e instanceof Oe){i=true}}while(e=t.parent(r++))}function collapse(e,t){if(a.pinned())return e;var s;var u=[];var c=e.length;var l=new TreeTransformer(function(e){if(A)return e;if(!T){if(e!==p[_])return e;_++;if(_1)||e instanceof Z&&!(e instanceof te)||e instanceof be||e instanceof Oe||e instanceof re||e instanceof Te||e instanceof Ke||e instanceof ht||n instanceof te&&e!==n.init||!y&&(e instanceof Lt&&!e.is_declared(t)&&!jn.has(e))||e instanceof Lt&&n instanceof Ge&&has_annotation(n,sn)){A=true;return e}if(!E&&(!D||!y)&&(n instanceof et&&Gn.has(n.operator)&&n.left!==e||n instanceof tt&&n.condition!==e||n instanceof Ae&&n.condition!==e)){E=n}if(R&&!(e instanceof bt)&&g.equivalent_to(e)){if(E){A=true;return e}if(is_lhs(e,n)){if(d)C++;return e}else{C++;if(d&&h instanceof Be)return e}o=A=true;if(h instanceof Je){return make_node(Qe,h,h)}if(h instanceof Be){var r=h.name.definition();var a=h.value;if(r.references.length-r.replaced==1&&!t.exposed(r)){r.replaced++;if(S&&is_identifier_atom(a)){return a.transform(t)}else{return maintain_this_binding(n,e,a)}}return make_node(nt,h,{operator:"=",logical:false,left:make_node(Lt,h.name,h.name),right:a})}Un(h,Mn);return h}var s;if(e instanceof Ge||e instanceof ge&&(b||g instanceof We||may_modify(g))||e instanceof We&&(b||e.expression.may_throw_on_access(t))||e instanceof Lt&&(v.get(e.name)||b&&may_modify(e))||e instanceof Be&&e.value&&(v.has(e.name.name)||b&&may_modify(e.name))||(s=is_lhs(e.left,e))&&(s instanceof We||v.has(s.name))||k&&(i?e.has_side_effects(t):side_effects_external(e))){m=e;if(e instanceof ae)A=true}return handle_custom_scan_order(e)},function(e){if(A)return;if(m===e)A=true;if(E===e)E=null});var f=new TreeTransformer(function(e){if(A)return e;if(!T){if(e!==p[_])return e;_++;if(_=0){if(c==0&&t.option("unused"))extract_args();var p=[];extract_candidates(e[c]);while(u.length>0){p=u.pop();var _=0;var h=p[p.length-1];var d=null;var m=null;var E=null;var g=get_lhs(h);if(!g||is_lhs_read_only(g)||g.has_side_effects(t))continue;var v=get_lvalues(h);var D=is_lhs_local(g);if(g instanceof Lt)v.set(g.name,false);var b=value_has_side_effects(h);var y=replace_all_symbols();var k=h.may_throw(t);var S=h.name instanceof At;var T=S;var A=false,C=0,R=!s||!T;if(!R){for(var x=t.self().argnames.lastIndexOf(h.name)+1;!A&&xC)C=false;else{A=false;_=0;T=S;for(var F=c;!A&&F!(e instanceof se))){var i=t.has_directive("use strict");if(i&&!member(i,n.body))i=false;var r=n.argnames.length;s=e.args.slice(r);var a=new Set;for(var o=r;--o>=0;){var c=n.argnames[o];var l=e.args[o];const r=c.definition&&c.definition();const p=r&&r.orig.length>1;if(p)continue;s.unshift(make_node(Be,c,{name:c,value:l}));if(a.has(c.name))continue;a.add(c.name);if(c instanceof se){var f=e.args.slice(o);if(f.every(e=>!has_overlapping_symbol(n,e,i))){u.unshift([make_node(Be,c,{name:c.expression,value:make_node(rt,e,{elements:f})})])}}else{if(!l){l=make_node(Zt,c).transform(t)}else if(l instanceof ue&&l.pinned()||has_overlapping_symbol(n,l,i)){l=null}if(l)u.unshift([make_node(Be,c,{name:c,value:l})])}}}}function extract_candidates(e){p.push(e);if(e instanceof nt){if(!e.left.has_side_effects(t)&&!(e.right instanceof $e)){u.push(p.slice())}extract_candidates(e.right)}else if(e instanceof et){extract_candidates(e.left);extract_candidates(e.right)}else if(e instanceof Ge&&!has_annotation(e,sn)){extract_candidates(e.expression);e.args.forEach(extract_candidates)}else if(e instanceof Fe){extract_candidates(e.expression)}else if(e instanceof tt){extract_candidates(e.condition);extract_candidates(e.consequent);extract_candidates(e.alternative)}else if(e instanceof Ne){var n=e.definitions.length;var i=n-200;if(i<0)i=0;for(;i1&&!(e.name instanceof At)||(i>1?mangleable_var(e):!t.exposed(n))){return make_node(Lt,e.name,e.name)}}else{const t=e instanceof nt?e.left:e.expression;return!is_ref_of(t,St)&&!is_ref_of(t,Tt)&&t}}function get_rvalue(e){if(e instanceof nt){return e.right}else{return e.value}}function get_lvalues(e){var n=new Map;if(e instanceof Ze)return n;var i=new TreeWalker(function(e){var r=e;while(r instanceof We)r=r.expression;if(r instanceof Lt||r instanceof zt){n.set(r.name,n.get(r.name)||is_modified(t,i,e,e,0))}});get_rvalue(e).walk(i);return n}function remove_candidate(n){if(n.name instanceof At){var i=t.parent(),a=t.self().argnames;var o=a.indexOf(n.name);if(o<0){i.args.length=Math.min(i.args.length,a.length-1)}else{var s=i.args;if(s[o])s[o]=make_node(Ht,s[o],{value:0})}return true}var u=false;return e[c].transform(new TreeTransformer(function(e,t,i){if(u)return e;if(e===n||e.body===n){u=true;if(e instanceof Be){e.value=e.name instanceof St?make_node(Zt,e.value):null;return e}return i?r.skip:null}},function(e){if(e instanceof He)switch(e.expressions.length){case 0:return null;case 1:return e.expressions[0]}}))}function is_lhs_local(e){while(e instanceof We)e=e.expression;return e instanceof Lt&&e.definition().scope===a&&!(n&&(v.has(e.name)||h instanceof Ze||h instanceof nt&&!h.logical&&h.operator!="="))}function value_has_side_effects(e){if(e instanceof Ze)return Xn.has(e.operator);return get_rvalue(e).has_side_effects(t)}function replace_all_symbols(){if(b)return false;if(d)return true;if(g instanceof Lt){var e=g.definition();if(e.references.length-e.replaced==(h instanceof Be?1:2)){return true}}return false}function may_modify(e){if(!e.definition)return true;var t=e.definition();if(t.orig.length==1&&t.orig[0]instanceof Ct)return false;if(t.scope.get_defun_scope()!==a)return true;return!t.references.every(e=>{var t=e.scope.get_defun_scope();if(t.TYPE=="Scope")t=t.parent_scope;return t===a})}function side_effects_external(e,t){if(e instanceof nt)return side_effects_external(e.left,true);if(e instanceof Ze)return side_effects_external(e.expression,true);if(e instanceof Be)return e.value&&side_effects_external(e.value);if(t){if(e instanceof qe)return side_effects_external(e.expression,true);if(e instanceof je)return side_effects_external(e.expression,true);if(e instanceof Lt)return e.definition().scope!==a}return false}}function eliminate_spurious_blocks(e){var t=[];for(var n=0;n=0;){var s=e[a];var u=next_index(a);var c=e[u];if(r&&!c&&s instanceof ve){if(!s.value){o=true;e.splice(a,1);continue}if(s.value instanceof Qe&&s.value.operator=="void"){o=true;e[a]=make_node(H,s,{body:s.value.expression});continue}}if(s instanceof Ae){var l=aborts(s.body);if(can_merge_flow(l)){if(l.label){remove(l.label.thedef.references,l)}o=true;s=s.clone();s.condition=s.condition.negate(t);var f=as_statement_array_with_return(s.body,l);s.body=make_node(q,s,{body:as_statement_array(s.alternative).concat(extract_functions())});s.alternative=make_node(q,s,{body:f});e[a]=s.transform(t);continue}var l=aborts(s.alternative);if(can_merge_flow(l)){if(l.label){remove(l.label.thedef.references,l)}o=true;s=s.clone();s.body=make_node(q,s.body,{body:as_statement_array(s.body).concat(extract_functions())});var f=as_statement_array_with_return(s.alternative,l);s.alternative=make_node(q,s.alternative,{body:f});e[a]=s.transform(t);continue}}if(s instanceof Ae&&s.body instanceof ve){var p=s.body.value;if(!p&&!s.alternative&&(r&&!c||c instanceof ve&&!c.value)){o=true;e[a]=make_node(H,s.condition,{body:s.condition});continue}if(p&&!s.alternative&&c instanceof ve&&c.value){o=true;s=s.clone();s.alternative=c;e[a]=s.transform(t);e.splice(u,1);continue}if(p&&!s.alternative&&(!c&&r&&i||c instanceof ve)){o=true;s=s.clone();s.alternative=c||make_node(ve,s,{value:null});e[a]=s.transform(t);if(c)e.splice(u,1);continue}var _=e[prev_index(a)];if(t.option("sequences")&&r&&!s.alternative&&_ instanceof Ae&&_.body instanceof ve&&next_index(u)==e.length&&c instanceof H){o=true;s=s.clone();s.alternative=make_node(q,c,{body:[c,make_node(ve,c,{value:null})]});e[a]=s.transform(t);e.splice(u,1);continue}}}function has_multiple_if_returns(e){var t=0;for(var n=e.length;--n>=0;){var i=e[n];if(i instanceof Ae&&i.body instanceof ve){if(++t>1)return true}}return false}function is_return_void(e){return!e||e instanceof Qe&&e.operator=="void"}function can_merge_flow(i){if(!i)return false;for(var o=a+1,s=e.length;o=0;){var i=e[n];if(!(i instanceof Ie&&declarations_only(i))){break}}return n}}function eliminate_dead_code(e,t){var n;var i=t.self();for(var r=0,a=0,s=e.length;r!e.value)}function sequencesize(e,t){if(e.length<2)return;var n=[],i=0;function push_seq(){if(!n.length)return;var t=make_sequence(n[0],n);e[i++]=make_node(H,t,{body:t});n=[]}for(var r=0,a=e.length;r=t.sequences_limit)push_seq();var u=s.body;if(n.length>0)u=u.drop_side_effect_free(t);if(u)merge_sequence(n,u)}else if(s instanceof Ne&&declarations_only(s)||s instanceof pe){e[i++]=s}else{push_seq();e[i++]=s}}push_seq();e.length=i;if(i!=a)o=true}function to_simple_statement(e,t){if(!(e instanceof q))return e;var n=null;for(var i=0,r=e.body.length;i{if(e instanceof ae)return true;if(e instanceof et&&e.operator==="in"){return rn}});if(!e){if(a.init)a.init=cons_seq(a.init);else{a.init=i.body;n--;o=true}}}}else if(a instanceof ne){if(!(a.init instanceof Le)&&!(a.init instanceof Pe)){a.object=cons_seq(a.object)}}else if(a instanceof Ae){a.condition=cons_seq(a.condition)}else if(a instanceof Ce){a.expression=cons_seq(a.expression)}else if(a instanceof re){a.expression=cons_seq(a.expression)}}if(t.option("conditionals")&&a instanceof Ae){var s=[];var u=to_simple_statement(a.body,s);var c=to_simple_statement(a.alternative,s);if(u!==false&&c!==false&&s.length>0){var l=s.length;s.push(make_node(Ae,a,{condition:a.condition,body:u||make_node(Y,a.body),alternative:c}));s.unshift(n,1);[].splice.apply(e,s);r+=l;n+=l+1;i=null;o=true;continue}}e[n++]=a;i=a instanceof H?a:null}e.length=n}function join_object_assignments(e,n){if(!(e instanceof Ne))return;var i=e.definitions[e.definitions.length-1];if(!(i.value instanceof at))return;var r;if(n instanceof nt&&!n.logical){r=[n]}else if(n instanceof He){r=n.expressions.slice()}if(!r)return;var o=false;do{var s=r[0];if(!(s instanceof nt))break;if(s.operator!="=")break;if(!(s.left instanceof We))break;var u=s.left.expression;if(!(u instanceof Lt))break;if(i.name.name!=u.name)break;if(!s.right.is_constant_expression(a))break;var c=s.left.property;if(c instanceof z){c=c.evaluate(t)}if(c instanceof z)break;c=""+c;var l=t.option("ecma")<2015&&t.has_directive("use strict")?function(e){return e.key!=c&&(e.key&&e.key.name!=c)}:function(e){return e.key&&e.key.name!=c};if(!i.value.properties.every(l))break;var f=i.value.properties.filter(function(e){return e.key===c})[0];if(!f){i.value.properties.push(make_node(st,s,{key:c,value:s.right}))}else{f.value=new He({start:f.start,expressions:[f.value.clone(),s.right.clone()],end:f.end})}r.shift();o=true}while(r.length);return o&&r}function join_consecutive_vars(e){var t;for(var n=0,i=-1,r=e.length;n{if(i instanceof Ie){i.remove_initializers();n.push(i);return true}if(i instanceof pe&&(i===t||!e.has_directive("use strict"))){n.push(i===t?i:make_node(Ie,i,{definitions:[make_node(Be,i,{name:make_node(yt,i.name,i.name),value:null})]}));return true}if(i instanceof Ke||i instanceof Ue){n.push(i);return true}if(i instanceof ae){return true}})}function get_value(e){if(e instanceof Gt){return e.getValue()}if(e instanceof Qe&&e.operator=="void"&&e.expression instanceof Gt){return}return e}function is_undefined(e,t){return Bn(e,On)||e instanceof Zt||e instanceof Qe&&e.operator=="void"&&!e.expression.has_side_effects(t)}(function(e){z.DEFMETHOD("may_throw_on_access",function(e){return!e.option("pure_getters")||this._dot_throw(e)});function is_strict(e){return/strict/.test(e.option("pure_getters"))}e(z,is_strict);e(jt,return_true);e(Zt,return_true);e(Gt,return_false);e(rt,return_false);e(at,function(e){if(!is_strict(e))return false;for(var t=this.properties.length;--t>=0;)if(this.properties[t]._dot_throw(e))return true;return false});e(ht,return_false);e(ot,return_false);e(ft,return_true);e(se,function(e){return this.expression._dot_throw(e)});e(le,return_false);e(fe,return_false);e(Je,return_false);e(Qe,function(){return this.operator=="void"});e(et,function(e){return(this.operator=="&&"||this.operator=="||"||this.operator=="??")&&(this.left._dot_throw(e)||this.right._dot_throw(e))});e(nt,function(e){if(this.logical)return true;return this.operator=="="&&this.right._dot_throw(e)});e(tt,function(e){return this.consequent._dot_throw(e)||this.alternative._dot_throw(e)});e(qe,function(e){if(!is_strict(e))return false;if(this.property=="prototype"){return!(this.expression instanceof le||this.expression instanceof ht)}return true});e($e,function(e){return this.expression._dot_throw(e)});e(He,function(e){return this.tail_node()._dot_throw(e)});e(Lt,function(e){if(this.name==="arguments")return false;if(Bn(this,On))return true;if(!is_strict(e))return false;if(is_undeclared_ref(this)&&this.is_declared(e))return false;if(this.is_immutable())return false;var t=this.fixed_value();return!t||t._dot_throw(e)})})(function(e,t){e.DEFMETHOD("_dot_throw",t)});(function(e){const t=makePredicate("! delete");const n=makePredicate("in instanceof == != === !== < <= >= >");e(z,return_false);e(Qe,function(){return t.has(this.operator)});e(et,function(){return n.has(this.operator)||Gn.has(this.operator)&&this.left.is_boolean()&&this.right.is_boolean()});e(tt,function(){return this.consequent.is_boolean()&&this.alternative.is_boolean()});e(nt,function(){return this.operator=="="&&this.right.is_boolean()});e(He,function(){return this.tail_node().is_boolean()});e(nn,return_true);e(tn,return_true)})(function(e,t){e.DEFMETHOD("is_boolean",t)});(function(e){e(z,return_false);e(Ht,return_true);var t=makePredicate("+ - ~ ++ --");e(Ze,function(){return t.has(this.operator)});var n=makePredicate("- * / % & | ^ << >> >>>");e(et,function(e){return n.has(this.operator)||this.operator=="+"&&this.left.is_number(e)&&this.right.is_number(e)});e(nt,function(e){return n.has(this.operator.slice(0,-1))||this.operator=="="&&this.right.is_number(e)});e(He,function(e){return this.tail_node().is_number(e)});e(tt,function(e){return this.consequent.is_number(e)&&this.alternative.is_number(e)})})(function(e,t){e.DEFMETHOD("is_number",t)});(function(e){e(z,return_false);e(Xt,return_true);e(de,return_true);e(Qe,function(){return this.operator=="typeof"});e(et,function(e){return this.operator=="+"&&(this.left.is_string(e)||this.right.is_string(e))});e(nt,function(e){return(this.operator=="="||this.operator=="+=")&&this.right.is_string(e)});e(He,function(e){return this.tail_node().is_string(e)});e(tt,function(e){return this.consequent.is_string(e)&&this.alternative.is_string(e)})})(function(e,t){e.DEFMETHOD("is_string",t)});var Gn=makePredicate("&& || ??");var Xn=makePredicate("delete ++ --");function is_lhs(e,t){if(t instanceof Ze&&Xn.has(t.operator))return t.expression;if(t instanceof nt&&t.left===e)return e}(function(e){function to_node(e,t){if(e instanceof z)return make_node(e.CTOR,t,e);if(Array.isArray(e))return make_node(rt,t,{elements:e.map(function(e){return to_node(e,t)})});if(e&&typeof e=="object"){var n=[];for(var i in e)if(HOP(e,i)){n.push(make_node(st,t,{key:i,value:to_node(e[i],t)}))}return make_node(at,t,{properties:n})}return make_node_from_constant(e,t)}oe.DEFMETHOD("resolve_defines",function(e){if(!e.option("global_defs"))return this;this.figure_out_scope({ie8:e.option("ie8")});return this.transform(new TreeTransformer(function(t){var n=t._find_defs(e,"");if(!n)return;var i=0,r=t,a;while(a=this.parent(i++)){if(!(a instanceof We))break;if(a.expression!==r)break;r=a}if(is_lhs(r,a)){return}return n}))});e(z,noop);e($e,function(e,t){return this.expression._find_defs(e,t)});e(qe,function(e,t){return this.expression._find_defs(e,"."+this.property+t)});e(bt,function(){if(!this.global())return});e(Lt,function(e,t){if(!this.global())return;var n=e.option("global_defs");var i=this.name+t;if(HOP(n,i))return to_node(n[i],this)})})(function(e,t){e.DEFMETHOD("_find_defs",t)});function best_of_expression(e,t){return e.size()>t.size()?t:e}function best_of_statement(e,t){return best_of_expression(make_node(H,e,{body:e}),make_node(H,t,{body:t})).body}function best_of(e,t,n){return(first_in_statement(e)?best_of_statement:best_of_expression)(t,n)}function convert_to_predicate(e){const t=new Map;for(var n of Object.keys(e)){t.set(n,makePredicate(e[n]))}return t}var Hn=["constructor","toString","valueOf"];var Wn=convert_to_predicate({Array:["indexOf","join","lastIndexOf","slice"].concat(Hn),Boolean:Hn,Function:Hn,Number:["toExponential","toFixed","toPrecision"].concat(Hn),Object:Hn,RegExp:["test"].concat(Hn),String:["charAt","charCodeAt","concat","indexOf","italics","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","trim"].concat(Hn)});var qn=convert_to_predicate({Array:["isArray"],Math:["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan","atan2","pow","max","min"],Number:["isFinite","isNaN"],Object:["create","getOwnPropertyDescriptor","getOwnPropertyNames","getPrototypeOf","isExtensible","isFrozen","isSealed","keys"],String:["fromCharCode"]});(function(e){z.DEFMETHOD("evaluate",function(e){if(!e.option("evaluate"))return this;var t=this._eval(e,1);if(!t||t instanceof RegExp)return t;if(typeof t=="function"||typeof t=="object")return this;return t});var t=makePredicate("! ~ - + void");z.DEFMETHOD("is_constant",function(){if(this instanceof Gt){return!(this instanceof qt)}else{return this instanceof Qe&&this.expression instanceof Gt&&t.has(this.operator)}});e(K,function(){throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]",this.start))});e(ue,return_this);e(ht,return_this);e(z,return_this);e(Gt,function(){return this.getValue()});e(Wt,return_this);e(qt,function(e){let t=e.evaluated_regexps.get(this);if(t===undefined){try{t=(0,eval)(this.print_to_string())}catch(e){t=null}e.evaluated_regexps.set(this,t)}return t||this});e(de,function(){if(this.segments.length!==1)return this;return this.segments[0].value});e(le,function(e){if(e.option("unsafe")){var t=function(){};t.node=this;t.toString=(()=>this.print_to_string());return t}return this});e(rt,function(e,t){if(e.option("unsafe")){var n=[];for(var i=0,r=this.elements.length;itypeof e==="object"||typeof e==="function"||typeof e==="symbol";e(et,function(e,t){if(!i.has(this.operator))t++;var n=this.left._eval(e,t);if(n===this.left)return this;var o=this.right._eval(e,t);if(o===this.right)return this;var s;if(n!=null&&o!=null&&r.has(this.operator)&&a(n)&&a(o)&&typeof n===typeof o){return this}switch(this.operator){case"&&":s=n&&o;break;case"||":s=n||o;break;case"??":s=n!=null?n:o;break;case"|":s=n|o;break;case"&":s=n&o;break;case"^":s=n^o;break;case"+":s=n+o;break;case"*":s=n*o;break;case"**":s=Math.pow(n,o);break;case"/":s=n/o;break;case"%":s=n%o;break;case"-":s=n-o;break;case"<<":s=n<>":s=n>>o;break;case">>>":s=n>>>o;break;case"==":s=n==o;break;case"===":s=n===o;break;case"!=":s=n!=o;break;case"!==":s=n!==o;break;case"<":s=n":s=n>o;break;case">=":s=n>=o;break;default:return this}if(isNaN(s)&&e.find_parent(re)){return this}return s});e(tt,function(e,t){var n=this.condition._eval(e,t);if(n===this.condition)return this;var i=n?this.consequent:this.alternative;var r=i._eval(e,t);return r===i?this:r});const o=new Set;e(Lt,function(e,t){if(o.has(this))return this;var n=this.fixed_value();if(!n)return this;o.add(this);const i=n._eval(e,t);o.delete(this);if(i===n)return this;if(i&&typeof i=="object"){var r=this.definition().escaped;if(r&&t>r)return this}return i});var s={Array:Array,Math:Math,Number:Number,Object:Object,String:String};var u=convert_to_predicate({Math:["E","LN10","LN2","LOG2E","LOG10E","PI","SQRT1_2","SQRT2"],Number:["MAX_VALUE","MIN_VALUE","NaN","NEGATIVE_INFINITY","POSITIVE_INFINITY"]});const c=new Set(["dotAll","global","ignoreCase","multiline","sticky","unicode"]);e(We,function(e,t){if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")){var n=this.property;if(n instanceof z){n=n._eval(e,t);if(n===this.property)return this}var i=this.expression;var r;if(is_undeclared_ref(i)){var a;var o=i.name==="hasOwnProperty"&&n==="call"&&(a=e.parent()&&e.parent().args)&&(a&&a[0]&&a[0].evaluate(e));o=o instanceof qe?o.expression:o;if(o==null||o.thedef&&o.thedef.undeclared){return this.clone()}var l=u.get(i.name);if(!l||!l.has(n))return this;r=s[i.name]}else{r=i._eval(e,t+1);if(r instanceof RegExp){if(n=="source"){return regexp_source_fix(r.source)}else if(n=="flags"||c.has(n)){return r[n]}}if(!r||r===i||!HOP(r,n))return this;if(typeof r=="function")switch(n){case"name":return r.node.name?r.node.name.name:"";case"length":return r.node.length_property();default:return this}}return r[n]}return this});e($e,function(e,t){const n=this.expression._eval(e,t);return n===this.expression?this:n});e(Ge,function(e,t){var n=this.expression;if(this.optional){const n=this.expression._eval(e,t);if(n==null)return undefined}if(e.option("unsafe")&&n instanceof We){var i=n.property;if(i instanceof z){i=i._eval(e,t);if(i===n.property)return this}var r;var a=n.expression;if(is_undeclared_ref(a)){var o=a.name==="hasOwnProperty"&&i==="call"&&(this.args[0]&&this.args[0].evaluate(e));o=o instanceof qe?o.expression:o;if(o==null||o.thedef&&o.thedef.undeclared){return this.clone()}var u=qn.get(a.name);if(!u||!u.has(i))return this;r=s[a.name]}else{r=a._eval(e,t+1);if(r===a||!r)return this;var c=Wn.get(r.constructor.name);if(!c||!c.has(i))return this}var l=[];for(var f=0,p=this.args.length;f";return n;case"<":n.operator=">=";return n;case">=":n.operator="<";return n;case">":n.operator="<=";return n}}switch(i){case"==":n.operator="!=";return n;case"!=":n.operator="==";return n;case"===":n.operator="!==";return n;case"!==":n.operator="===";return n;case"&&":n.operator="||";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"||":n.operator="&&";n.left=n.left.negate(e,t);n.right=n.right.negate(e);return best(this,n,t);case"??":n.right=n.right.negate(e);return best(this,n,t)}return basic_negation(this)})})(function(e,t){e.DEFMETHOD("negate",function(e,n){return t.call(this,e,n)})});var Yn=makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");Ge.DEFMETHOD("is_callee_pure",function(e){if(e.option("unsafe")){var t=this.expression;var n=this.args&&this.args[0]&&this.args[0].evaluate(e);if(t.expression&&t.expression.name==="hasOwnProperty"&&(n==null||n.thedef&&n.thedef.undeclared)){return false}if(is_undeclared_ref(t)&&Yn.has(t.name))return true;let i;if(t instanceof qe&&is_undeclared_ref(t.expression)&&(i=qn.get(t.expression.name))&&i.has(t.property)){return true}}return!!has_annotation(this,an)||!e.pure_funcs(this)});z.DEFMETHOD("is_call_pure",return_false);qe.DEFMETHOD("is_call_pure",function(e){if(!e.option("unsafe"))return;const t=this.expression;let n;if(t instanceof rt){n=Wn.get("Array")}else if(t.is_boolean()){n=Wn.get("Boolean")}else if(t.is_number(e)){n=Wn.get("Number")}else if(t instanceof qt){n=Wn.get("RegExp")}else if(t.is_string(e)){n=Wn.get("String")}else if(!this.may_throw_on_access(e)){n=Wn.get("Object")}return n&&n.has(this.property)});const jn=new Set(["Number","String","Array","Object","Function","Promise"]);(function(e){e(z,return_true);e(Y,return_false);e(Gt,return_false);e(zt,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].has_side_effects(t))return true;return false}e(W,function(e){return any(this.body,e)});e(Ge,function(e){if(!this.is_callee_pure(e)&&(!this.expression.is_call_pure(e)||this.expression.has_side_effects(e))){return true}return any(this.args,e)});e(Ce,function(e){return this.expression.has_side_effects(e)||any(this.body,e)});e(Fe,function(e){return this.expression.has_side_effects(e)||any(this.body,e)});e(Oe,function(e){return any(this.body,e)||this.bcatch&&this.bcatch.has_side_effects(e)||this.bfinally&&this.bfinally.has_side_effects(e)});e(Ae,function(e){return this.condition.has_side_effects(e)||this.body&&this.body.has_side_effects(e)||this.alternative&&this.alternative.has_side_effects(e)});e($,function(e){return this.body.has_side_effects(e)});e(H,function(e){return this.body.has_side_effects(e)});e(ue,return_false);e(ht,function(e){if(this.extends&&this.extends.has_side_effects(e)){return true}return any(this.properties,e)});e(et,function(e){return this.left.has_side_effects(e)||this.right.has_side_effects(e)});e(nt,return_true);e(tt,function(e){return this.condition.has_side_effects(e)||this.consequent.has_side_effects(e)||this.alternative.has_side_effects(e)});e(Ze,function(e){return Xn.has(this.operator)||this.expression.has_side_effects(e)});e(Lt,function(e){return!this.is_declared(e)&&!jn.has(this.name)});e(xt,return_false);e(bt,return_false);e(at,function(e){return any(this.properties,e)});e(ot,function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.value&&this.value.has_side_effects(e)});e(dt,function(e){return this.computed_key()&&this.key.has_side_effects(e)||this.static&&this.value&&this.value.has_side_effects(e)});e(pt,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(ft,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(lt,function(e){return this.computed_key()&&this.key.has_side_effects(e)});e(rt,function(e){return any(this.elements,e)});e(qe,function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)});e(je,function(e){if(this.optional&&is_nullish(this.expression,e)){return false}return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.has_side_effects(e)||this.property.has_side_effects(e)});e($e,function(e){return this.expression.has_side_effects(e)});e(He,function(e){return any(this.expressions,e)});e(Ne,function(e){return any(this.definitions,e)});e(Be,function(){return this.value});e(me,return_false);e(de,function(e){return any(this.segments,e)})})(function(e,t){e.DEFMETHOD("has_side_effects",t)});(function(e){e(z,return_true);e(Gt,return_false);e(Y,return_false);e(ue,return_false);e(bt,return_false);e(zt,return_false);function any(e,t){for(var n=e.length;--n>=0;)if(e[n].may_throw(t))return true;return false}e(ht,function(e){if(this.extends&&this.extends.may_throw(e))return true;return any(this.properties,e)});e(rt,function(e){return any(this.elements,e)});e(nt,function(e){if(this.right.may_throw(e))return true;if(!e.has_directive("use strict")&&this.operator=="="&&this.left instanceof Lt){return false}return this.left.may_throw(e)});e(et,function(e){return this.left.may_throw(e)||this.right.may_throw(e)});e(W,function(e){return any(this.body,e)});e(Ge,function(e){if(this.optional&&is_nullish(this.expression,e))return false;if(any(this.args,e))return true;if(this.is_callee_pure(e))return false;if(this.expression.may_throw(e))return true;return!(this.expression instanceof ue)||any(this.expression.body,e)});e(Fe,function(e){return this.expression.may_throw(e)||any(this.body,e)});e(tt,function(e){return this.condition.may_throw(e)||this.consequent.may_throw(e)||this.alternative.may_throw(e)});e(Ne,function(e){return any(this.definitions,e)});e(Ae,function(e){return this.condition.may_throw(e)||this.body&&this.body.may_throw(e)||this.alternative&&this.alternative.may_throw(e)});e($,function(e){return this.body.may_throw(e)});e(at,function(e){return any(this.properties,e)});e(ot,function(e){return this.value?this.value.may_throw(e):false});e(dt,function(e){return this.computed_key()&&this.key.may_throw(e)||this.static&&this.value&&this.value.may_throw(e)});e(pt,function(e){return this.computed_key()&&this.key.may_throw(e)});e(ft,function(e){return this.computed_key()&&this.key.may_throw(e)});e(lt,function(e){return this.computed_key()&&this.key.may_throw(e)});e(ve,function(e){return this.value&&this.value.may_throw(e)});e(He,function(e){return any(this.expressions,e)});e(H,function(e){return this.body.may_throw(e)});e(qe,function(e){return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)});e(je,function(e){if(this.optional&&is_nullish(this.expression,e))return false;return!this.optional&&this.expression.may_throw_on_access(e)||this.expression.may_throw(e)||this.property.may_throw(e)});e($e,function(e){return this.expression.may_throw(e)});e(Ce,function(e){return this.expression.may_throw(e)||any(this.body,e)});e(Lt,function(e){return!this.is_declared(e)&&!jn.has(this.name)});e(xt,return_false);e(Oe,function(e){return this.bcatch?this.bcatch.may_throw(e):any(this.body,e)||this.bfinally&&this.bfinally.may_throw(e)});e(Ze,function(e){if(this.operator=="typeof"&&this.expression instanceof Lt)return false;return this.expression.may_throw(e)});e(Be,function(e){if(!this.value)return false;return this.value.may_throw(e)})})(function(e,t){e.DEFMETHOD("may_throw",t)});(function(e){function all_refs_local(e){let t=true;walk(this,n=>{if(n instanceof Lt){if(Bn(this,wn)){t=false;return rn}var i=n.definition();if(member(i,this.enclosed)&&!this.variables.has(i.name)){if(e){var r=e.find_variable(n);if(i.undeclared?!r:r===i){t="f";return true}}t=false;return rn}return true}if(n instanceof zt&&this instanceof fe){t=false;return rn}});return t}e(z,return_false);e(Gt,return_true);e(ht,function(e){if(this.extends&&!this.extends.is_constant_expression(e)){return false}for(const t of this.properties){if(t.computed_key()&&!t.key.is_constant_expression(e)){return false}if(t.static&&t.value&&!t.value.is_constant_expression(e)){return false}}return all_refs_local.call(this,e)});e(ue,all_refs_local);e(Ze,function(){return this.expression.is_constant_expression()});e(et,function(){return this.left.is_constant_expression()&&this.right.is_constant_expression()});e(rt,function(){return this.elements.every(e=>e.is_constant_expression())});e(at,function(){return this.properties.every(e=>e.is_constant_expression())});e(ot,function(){return!!(!(this.key instanceof z)&&this.value&&this.value.is_constant_expression())})})(function(e,t){e.DEFMETHOD("is_constant_expression",t)});function aborts(e){return e&&e.aborts()}(function(e){e(K,return_null);e(Ee,return_this);function block_aborts(){for(var e=0;e{if(e instanceof bt){const n=e.definition();if((t||n.global)&&!o.has(n.id)){o.set(n.id,n)}}})}if(n.value){if(n.name instanceof _e){n.walk(f)}else{var r=n.name.definition();map_add(c,r.id,n.value);if(!r.chained&&n.name.fixed_value()===n.value){s.set(r.id,n)}}if(n.value.has_side_effects(e)){n.value.walk(f)}}});return true}return scan_ref_scoped(r,a)});t.walk(f);f=new TreeWalker(scan_ref_scoped);o.forEach(function(e){var t=c.get(e.id);if(t)t.forEach(function(e){e.walk(f)})});var p=new TreeTransformer(function before(c,f,_){var h=p.parent();if(i){const e=a(c);if(e instanceof Lt){var d=e.definition();var m=o.has(d.id);if(c instanceof nt){if(!m||s.has(d.id)&&s.get(d.id)!==c){return maintain_this_binding(h,c,c.right.transform(p))}}else if(!m)return _?r.skip:make_node(Ht,c,{value:0})}}if(l!==t)return;var d;if(c.name&&(c instanceof gt&&!keep_name(e.option("keep_classnames"),(d=c.name.definition()).name)||c instanceof le&&!keep_name(e.option("keep_fnames"),(d=c.name.definition()).name))){if(!o.has(d.id)||d.orig.length>1)c.name=null}if(c instanceof ue&&!(c instanceof ce)){var E=!e.option("keep_fargs");for(var g=c.argnames,v=g.length;--v>=0;){var D=g[v];if(D instanceof se){D=D.expression}if(D instanceof it){D=D.left}if(!(D instanceof _e)&&!o.has(D.definition().id)){Vn(D,Rn);if(E){g.pop()}}else{E=false}}}if((c instanceof pe||c instanceof Et)&&c!==t){const t=c.name.definition();let i=t.global&&!n||o.has(t.id);if(!i){t.eliminated++;if(c instanceof Et){const t=c.drop_side_effect_free(e);if(t){return make_node(H,c,{body:t})}}return _?r.skip:make_node(Y,c)}}if(c instanceof Ne&&!(h instanceof ne&&h.init===c)){var b=!(h instanceof oe)&&!(c instanceof Ie);var y=[],k=[],S=[];var T=[];c.definitions.forEach(function(t){if(t.value)t.value=t.value.transform(p);var n=t.name instanceof _e;var r=n?new SymbolDef(null,{name:""}):t.name.definition();if(b&&r.global)return S.push(t);if(!(i||b)||n&&(t.name.names.length||t.name.is_array||e.option("pure_getters")!=true)||o.has(r.id)){if(t.value&&s.has(r.id)&&s.get(r.id)!==t){t.value=t.value.drop_side_effect_free(e)}if(t.name instanceof yt){var a=u.get(r.id);if(a.length>1&&(!t.value||r.orig.indexOf(t.name)>r.eliminated)){if(t.value){var l=make_node(Lt,t.name,t.name);r.references.push(l);var f=make_node(nt,t,{operator:"=",logical:false,left:l,right:t.value});if(s.get(r.id)===t){s.set(r.id,f)}T.push(f.transform(p))}remove(a,t);r.eliminated++;return}}if(t.value){if(T.length>0){if(S.length>0){T.push(t.value);t.value=make_sequence(t.value,T)}else{y.push(make_node(H,c,{body:make_sequence(c,T)}))}T=[]}S.push(t)}else{k.push(t)}}else if(r.orig[0]instanceof Mt){var _=t.value&&t.value.drop_side_effect_free(e);if(_)T.push(_);t.value=null;k.push(t)}else{var _=t.value&&t.value.drop_side_effect_free(e);if(_){T.push(_)}r.eliminated++}});if(k.length>0||S.length>0){c.definitions=k.concat(S);y.push(c)}if(T.length>0){y.push(make_node(H,c,{body:make_sequence(c,T)}))}switch(y.length){case 0:return _?r.skip:make_node(Y,c);case 1:return y[0];default:return _?r.splice(y):make_node(q,c,{body:y})}}if(c instanceof te){f(c,this);var A;if(c.init instanceof q){A=c.init;c.init=A.body.pop();A.body.push(c)}if(c.init instanceof H){c.init=c.init.body}else if(is_empty(c.init)){c.init=null}return!A?c:_?r.splice(A.body):A}if(c instanceof $&&c.body instanceof te){f(c,this);if(c.body instanceof q){var A=c.body;c.body=A.body.pop();A.body.push(c);return _?r.splice(A.body):A}return c}if(c instanceof q){f(c,this);if(_&&c.body.every(can_be_evicted_from_block)){return r.splice(c.body)}return c}if(c instanceof ae){const e=l;l=c;f(c,this);l=e;return c}});t.transform(p);function scan_ref_scoped(e,n){var i;const r=a(e);if(r instanceof Lt&&!is_ref_of(e.left,kt)&&t.variables.get(r.name)===(i=r.definition())){if(e instanceof nt){e.right.walk(f);if(!i.chained&&e.left.fixed_value()===e.right){s.set(i.id,e)}}return true}if(e instanceof Lt){i=e.definition();if(!o.has(i.id)){o.set(i.id,i);if(i.orig[0]instanceof Mt){const e=i.scope.is_block_scope()&&i.scope.get_defun_scope().variables.get(i.name);if(e)o.set(e.id,e)}}return true}if(e instanceof ae){var u=l;l=e;n();l=u;return true}}});ae.DEFMETHOD("hoist_declarations",function(e){var t=this;if(e.has_directive("use asm"))return t;if(!Array.isArray(t.body))return t;var n=e.option("hoist_funs");var i=e.option("hoist_vars");if(n||i){var r=[];var a=[];var o=new Map,s=0,u=0;walk(t,e=>{if(e instanceof ae&&e!==t)return true;if(e instanceof Ie){++u;return true}});i=i&&u>1;var c=new TreeTransformer(function before(u){if(u!==t){if(u instanceof X){r.push(u);return make_node(Y,u)}if(n&&u instanceof pe&&!(c.parent()instanceof Ke)&&c.parent()===t){a.push(u);return make_node(Y,u)}if(i&&u instanceof Ie&&!u.definitions.some(e=>e.name instanceof _e)){u.definitions.forEach(function(e){o.set(e.name.name,e);++s});var l=u.to_assignments(e);var f=c.parent();if(f instanceof ne&&f.init===u){if(l==null){var p=u.definitions[0].name;return make_node(Lt,p,p)}return l}if(f instanceof te&&f.init===u){return l}if(!l)return make_node(Y,u);return make_node(H,u,{body:l})}if(u instanceof ae)return u}});t=t.transform(c);if(s>0){var l=[];const e=t instanceof ue;const n=e?t.args_as_names():null;o.forEach((t,i)=>{if(e&&n.some(e=>e.name===t.name.name)){o.delete(i)}else{t=t.clone();t.value=null;l.push(t);o.set(i,t)}});if(l.length>0){for(var f=0;fe instanceof se||e.computed_key())){s(o,this);const e=new Map;const n=[];l.properties.forEach(({key:i,value:r})=>{const s=find_scope(a);const c=t.create_symbol(u.CTOR,{source:u,scope:s,conflict_scopes:new Set([s,...u.definition().references.map(e=>e.scope)]),tentative_name:u.name+"_"+i});e.set(String(i),c.definition());n.push(make_node(Be,o,{name:c,value:r}))});i.set(c.id,e);return r.splice(n)}}else if(o instanceof We&&o.expression instanceof Lt){const e=i.get(o.expression.definition().id);if(e){const t=e.get(String(get_value(o.property)));const n=make_node(Lt,o,{name:t.name,scope:o.expression.scope,thedef:t});n.reference({});return n}}});return t.transform(a)});(function(e){function trim(e,t,n){var i=e.length;if(!i)return null;var r=[],a=false;for(var o=0;o0){o[0].body=a.concat(o[0].body)}e.body=o;while(n=o[o.length-1]){var h=n.body[n.body.length-1];if(h instanceof ye&&t.loopcontrol_target(h)===e)n.body.pop();if(n.body.length||n instanceof Fe&&(s||n.expression.has_side_effects(t)))break;if(o.pop()===s)s=null}if(o.length==0){return make_node(q,e,{body:a.concat(make_node(H,e.expression,{body:e.expression}))}).optimize(t)}if(o.length==1&&(o[0]===u||o[0]===s)){var d=false;var m=new TreeWalker(function(t){if(d||t instanceof ue||t instanceof H)return true;if(t instanceof ye&&m.loopcontrol_target(t)===e)d=true});e.walk(m);if(!d){var E=o[0].body.slice();var f=o[0].expression;if(f)E.unshift(make_node(H,f,{body:f}));E.unshift(make_node(H,e.expression,{body:e.expression}));return make_node(q,e,{body:E}).optimize(t)}}return e;function eliminate_branch(e,n){if(n&&!aborts(n)){n.body=n.body.concat(e.body)}else{trim_unreachable_code(t,e,a)}}});def_optimize(Oe,function(e,t){tighten_body(e.body,t);if(e.bcatch&&e.bfinally&&e.bfinally.body.every(is_empty))e.bfinally=null;if(t.option("dead_code")&&e.body.every(is_empty)){var n=[];if(e.bcatch){trim_unreachable_code(t,e.bcatch,n)}if(e.bfinally)n.push(...e.bfinally.body);return make_node(q,e,{body:n}).optimize(t)}return e});Ne.DEFMETHOD("remove_initializers",function(){var e=[];this.definitions.forEach(function(t){if(t.name instanceof bt){t.value=null;e.push(t)}else{walk(t.name,n=>{if(n instanceof bt){e.push(make_node(Be,t,{name:n,value:null}))}})}});this.definitions=e});Ne.DEFMETHOD("to_assignments",function(e){var t=e.option("reduce_vars");var n=[];for(const e of this.definitions){if(e.value){var i=make_node(Lt,e.name,e.name);n.push(make_node(nt,e,{operator:"=",logical:false,left:i,right:e.value}));if(t)i.definition().fixed=false}else if(e.value){var r=make_node(Be,e,{name:e.name,value:e.value});var a=make_node(Ie,e,{definitions:[r]});n.push(a)}const o=e.name.definition();o.eliminated++;o.replaced--}if(n.length==0)return null;return make_sequence(this,n)});def_optimize(Ne,function(e){if(e.definitions.length==0)return make_node(Y,e);return e});def_optimize(Be,function(e,t){if(e.name instanceof Tt&&e.value!=null&&is_undefined(e.value,t)){e.value=null}return e});def_optimize(Ue,function(e){return e});function retain_top_func(e,t){return t.top_retain&&e instanceof pe&&Bn(e,Pn)&&e.name&&t.top_retain(e.name)}def_optimize(Ge,function(e,t){var n=e.expression;var i=n;inline_array_like_spread(e.args);var r=e.args.every(e=>!(e instanceof se));if(t.option("reduce_vars")&&i instanceof Lt&&!has_annotation(e,sn)){const e=i.fixed_value();if(!retain_top_func(e,t)){i=e}}if(e.optional&&is_nullish(i,t)){return make_node(Zt,e)}var a=i instanceof ue;if(a&&i.pinned())return e;if(t.option("unused")&&r&&a&&!i.uses_arguments){var o=0,s=0;for(var u=0,c=e.args.length;u=i.argnames.length;if(f||Bn(i.argnames[u],Rn)){var l=e.args[u].drop_side_effect_free(t);if(l){e.args[o++]=l}else if(!f){e.args[o++]=make_node(Ht,e.args[u],{value:0});continue}}else{e.args[o++]=e.args[u]}s=o}e.args.length=s}if(t.option("unsafe")){if(is_undeclared_ref(n))switch(n.name){case"Array":if(e.args.length!=1){return make_node(rt,e,{elements:e.args}).optimize(t)}else if(e.args[0]instanceof Ht&&e.args[0].value<=11){const t=[];for(let n=0;n=1&&e.args.length<=2&&e.args.every(e=>{var n=e.evaluate(t);p.push(n);return e!==n})){let[n,i]=p;n=regexp_source_fix(new RegExp(n).source);const r=make_node(qt,e,{value:{source:n,flags:i}});if(r._eval(t)!==r){return r}}break}else if(n instanceof qe)switch(n.property){case"toString":if(e.args.length==0&&!n.expression.may_throw_on_access(t)){return make_node(et,e,{left:make_node(Xt,e,{value:""}),operator:"+",right:n.expression}).optimize(t)}break;case"join":if(n.expression instanceof rt)e:{var _;if(e.args.length>0){_=e.args[0].evaluate(t);if(_===e.args[0])break e}var h=[];var d=[];for(var u=0,c=n.expression.elements.length;u0){h.push(make_node(Xt,e,{value:d.join(_)}));d.length=0}h.push(m)}}if(d.length>0){h.push(make_node(Xt,e,{value:d.join(_)}))}if(h.length==0)return make_node(Xt,e,{value:""});if(h.length==1){if(h[0].is_string(t)){return h[0]}return make_node(et,h[0],{operator:"+",left:make_node(Xt,e,{value:""}),right:h[0]})}if(_==""){var g;if(h[0].is_string(t)||h[1].is_string(t)){g=h.shift()}else{g=make_node(Xt,e,{value:""})}return h.reduce(function(e,t){return make_node(et,t,{operator:"+",left:e,right:t})},g).optimize(t)}var l=e.clone();l.expression=l.expression.clone();l.expression.expression=l.expression.expression.clone();l.expression.expression.elements=h;return best_of(t,e,l)}break;case"charAt":if(n.expression.is_string(t)){var v=e.args[0];var D=v?v.evaluate(t):0;if(D!==v){return make_node(je,n,{expression:n.expression,property:make_node_from_constant(D|0,v||n)}).optimize(t)}}break;case"apply":if(e.args.length==2&&e.args[1]instanceof rt){var b=e.args[1].elements.slice();b.unshift(e.args[0]);return make_node(Ge,e,{expression:make_node(qe,n,{expression:n.expression,optional:false,property:"call"}),args:b}).optimize(t)}break;case"call":var y=n.expression;if(y instanceof Lt){y=y.fixed_value()}if(y instanceof ue&&!y.contains_this()){return(e.args.length?make_sequence(this,[e.args[0],make_node(Ge,e,{expression:n.expression,args:e.args.slice(1)})]):make_node(Ge,e,{expression:n.expression,args:[]})).optimize(t)}break}}if(t.option("unsafe_Function")&&is_undeclared_ref(n)&&n.name=="Function"){if(e.args.length==0)return make_node(le,e,{argnames:[],body:[]}).optimize(t);if(e.args.every(e=>e instanceof Xt)){try{var k="n(function("+e.args.slice(0,-1).map(function(e){return e.value}).join(",")+"){"+e.args[e.args.length-1].value+"})";var S=parse(k);var T={ie8:t.option("ie8")};S.figure_out_scope(T);var A=new Compressor(t.options,{mangle_options:t.mangle_options});S=S.transform(A);S.figure_out_scope(T);bn.reset();S.compute_char_frequency(T);S.mangle_names(T);var C;walk(S,e=>{if(is_func_expr(e)){C=e;return rn}});var k=OutputStream();q.prototype._codegen.call(C,C,k);e.args=[make_node(Xt,e,{value:C.argnames.map(function(e){return e.print_to_string()}).join(",")}),make_node(Xt,e.args[e.args.length-1],{value:k.get().replace(/^{|}$/g,"")})];return e}catch(e){if(!(e instanceof JS_Parse_Error)){throw e}}}}var R=a&&i.body[0];var x=a&&!i.is_generator&&!i.async;var F=x&&t.option("inline")&&!e.is_callee_pure(t);if(F&&R instanceof ve){let n=R.value;if(!n||n.is_constant_expression()){if(n){n=n.clone(true)}else{n=make_node(Zt,e)}const i=e.args.concat(n);return make_sequence(e,i).optimize(t)}if(i.argnames.length===1&&i.argnames[0]instanceof At&&e.args.length<2&&n instanceof Lt&&n.name===i.argnames[0].name){const n=(e.args[0]||make_node(Zt)).optimize(t);let i;if(n instanceof We&&(i=t.parent())instanceof Ge&&i.expression===e){return make_sequence(e,[make_node(Ht,e,{value:0}),n])}return n}}if(F){var O,w,M=-1;let a;let o;let s;if(r&&!i.uses_arguments&&!(t.parent()instanceof ht)&&!(i.name&&i instanceof le)&&(o=can_flatten_body(R))&&(n===i||has_annotation(e,on)||t.option("unused")&&(a=n.definition()).references.length==1&&!recursive_ref(t,a)&&i.is_constant_expression(n.scope))&&!has_annotation(e,an|sn)&&!i.contains_this()&&can_inject_symbols()&&(s=find_scope(t))&&!scope_encloses_variables_in_this_scope(s,i)&&!function in_default_assign(){let e=0;let n;while(n=t.parent(e++)){if(n instanceof it)return true;if(n instanceof W)break}return false}()&&!(O instanceof ht)){Vn(i,Nn);s.add_child_scope(i);return make_sequence(e,flatten_fn(o)).optimize(t)}}if(F&&has_annotation(e,on)){Vn(i,Nn);i=make_node(i.CTOR===pe?le:i.CTOR,i,i);i.figure_out_scope({},{parent_scope:find_scope(t),toplevel:t.get_toplevel()});return make_node(Ge,e,{expression:i,args:e.args}).optimize(t)}const N=x&&t.option("side_effects")&&i.body.every(is_empty);if(N){var b=e.args.concat(make_node(Zt,e));return make_sequence(e,b).optimize(t)}if(t.option("negate_iife")&&t.parent()instanceof H&&is_iife_call(e)){return e.negate(t,true)}var I=e.evaluate(t);if(I!==e){I=make_node_from_constant(I,e).optimize(t);return best_of(t,I,e)}return e;function return_value(t){if(!t)return make_node(Zt,e);if(t instanceof ve){if(!t.value)return make_node(Zt,e);return t.value.clone(true)}if(t instanceof H){return make_node(Qe,t,{operator:"void",expression:t.body.clone(true)})}}function can_flatten_body(e){var n=i.body;var r=n.length;if(t.option("inline")<3){return r==1&&return_value(e)}e=null;for(var a=0;a!e.value)){return false}}else if(e){return false}else if(!(o instanceof Y)){e=o}}return return_value(e)}function can_inject_args(e,t){for(var n=0,r=i.argnames.length;n=0;){var s=a.definitions[o].name;if(s instanceof _e||e.has(s.name)||Kn.has(s.name)||O.conflicting_def(s.name)){return false}if(w)w.push(s.definition())}}return true}function can_inject_symbols(){var e=new Set;do{O=t.parent(++M);if(O.is_block_scope()&&O.block_scope){O.block_scope.variables.forEach(function(t){e.add(t.name)})}if(O instanceof we){if(O.argname){e.add(O.argname.name)}}else if(O instanceof Z){w=[]}else if(O instanceof Lt){if(O.fixed_value()instanceof ae)return false}}while(!(O instanceof ae));var n=!(O instanceof oe)||t.toplevel.vars;var r=t.option("inline");if(!can_inject_vars(e,r>=3&&n))return false;if(!can_inject_args(e,r>=2&&n))return false;return!w||w.length==0||!is_reachable(i,w)}function append_var(t,n,i,r){var a=i.definition();const o=O.variables.has(i.name);if(!o){O.variables.set(i.name,a);O.enclosed.push(a);t.push(make_node(Be,i,{name:i,value:null}))}var s=make_node(Lt,i,i);a.references.push(s);if(r)n.push(make_node(nt,e,{operator:"=",logical:false,left:s,right:r.clone()}))}function flatten_args(t,n){var r=i.argnames.length;for(var a=e.args.length;--a>=r;){n.push(e.args[a])}for(a=r;--a>=0;){var o=i.argnames[a];var s=e.args[a];if(Bn(o,Rn)||!o.name||O.conflicting_def(o.name)){if(s)n.push(s)}else{var u=make_node(yt,o,o);o.definition().orig.push(u);if(!s&&w)s=make_node(Zt,e);append_var(t,n,u,s)}}t.reverse();n.reverse()}function flatten_vars(e,t){var n=t.length;for(var r=0,a=i.body.length;re.name!=l.name)){var f=i.variables.get(l.name);var p=make_node(Lt,l,l);f.references.push(p);t.splice(n++,0,make_node(nt,c,{operator:"=",logical:false,left:p,right:make_node(Zt,l)}))}}}}function flatten_fn(e){var n=[];var r=[];flatten_args(n,r);flatten_vars(n,r);r.push(e);if(n.length){const e=O.body.indexOf(t.parent(M-1))+1;O.body.splice(e,0,make_node(Ie,i,{definitions:n}))}return r.map(e=>e.clone(true))}});def_optimize(Xe,function(e,t){if(t.option("unsafe")&&is_undeclared_ref(e.expression)&&["Object","RegExp","Function","Error","Array"].includes(e.expression.name))return make_node(Ge,e,e).transform(t);return e});def_optimize(He,function(e,t){if(!t.option("side_effects"))return e;var n=[];filter_for_side_effects();var i=n.length-1;trim_right_for_undefined();if(i==0){e=maintain_this_binding(t.parent(),t.self(),n[0]);if(!(e instanceof He))e=e.optimize(t);return e}e.expressions=n;return e;function filter_for_side_effects(){var i=first_in_statement(t);var r=e.expressions.length-1;e.expressions.forEach(function(e,a){if(a0&&is_undefined(n[i],t))i--;if(i0){var n=this.clone();n.right=make_sequence(this.right,t.slice(a));t=t.slice(0,a);t.push(n);return make_sequence(this,t).optimize(e)}}}return this});var Qn=makePredicate("== === != !== * & | ^");function is_object(e){return e instanceof rt||e instanceof ue||e instanceof at||e instanceof ht}def_optimize(et,function(e,t){function reversible(){return e.left.is_constant()||e.right.is_constant()||!e.left.has_side_effects(t)&&!e.right.has_side_effects(t)}function reverse(t){if(reversible()){if(t)e.operator=t;var n=e.left;e.left=e.right;e.right=n}}if(Qn.has(e.operator)){if(e.right.is_constant()&&!e.left.is_constant()){if(!(e.left instanceof et&&N[e.left.operator]>=N[e.operator])){reverse()}}}e=e.lift_sequences(t);if(t.option("comparisons"))switch(e.operator){case"===":case"!==":var n=true;if(e.left.is_string(t)&&e.right.is_string(t)||e.left.is_number(t)&&e.right.is_number(t)||e.left.is_boolean()&&e.right.is_boolean()||e.left.equivalent_to(e.right)){e.operator=e.operator.substr(0,2)}case"==":case"!=":if(!n&&is_undefined(e.left,t)){e.left=make_node(jt,e.left)}else if(t.option("typeofs")&&e.left instanceof Xt&&e.left.value=="undefined"&&e.right instanceof Qe&&e.right.operator=="typeof"){var i=e.right.expression;if(i instanceof Lt?i.is_declared(t):!(i instanceof We&&t.option("ie8"))){e.right=i;e.left=make_node(Zt,e.left).optimize(t);if(e.operator.length==2)e.operator+="="}}else if(e.left instanceof Lt&&e.right instanceof Lt&&e.left.definition()===e.right.definition()&&is_object(e.left.fixed_value())){return make_node(e.operator[0]=="="?nn:tn,e)}break;case"&&":case"||":var r=e.left;if(r.operator==e.operator){r=r.right}if(r instanceof et&&r.operator==(e.operator=="&&"?"!==":"===")&&e.right instanceof et&&r.operator==e.right.operator&&(is_undefined(r.left,t)&&e.right.left instanceof jt||r.left instanceof jt&&is_undefined(e.right.left,t))&&!r.right.has_side_effects(t)&&r.right.equivalent_to(e.right.right)){var a=make_node(et,e,{operator:r.operator.slice(0,-1),left:make_node(jt,e),right:r.right});if(r!==e.left){a=make_node(et,e,{operator:e.operator,left:e.left.left,right:a})}return a}break}if(e.operator=="+"&&t.in_boolean_context()){var o=e.left.evaluate(t);var s=e.right.evaluate(t);if(o&&typeof o=="string"){return make_sequence(e,[e.right,make_node(nn,e)]).optimize(t)}if(s&&typeof s=="string"){return make_sequence(e,[e.left,make_node(nn,e)]).optimize(t)}}if(t.option("comparisons")&&e.is_boolean()){if(!(t.parent()instanceof et)||t.parent()instanceof nt){var u=make_node(Qe,e,{operator:"!",expression:e.negate(t,first_in_statement(t))});e=best_of(t,e,u)}if(t.option("unsafe_comps")){switch(e.operator){case"<":reverse(">");break;case"<=":reverse(">=");break}}}if(e.operator=="+"){if(e.right instanceof Xt&&e.right.getValue()==""&&e.left.is_string(t)){return e.left}if(e.left instanceof Xt&&e.left.getValue()==""&&e.right.is_string(t)){return e.right}if(e.left instanceof et&&e.left.operator=="+"&&e.left.left instanceof Xt&&e.left.left.getValue()==""&&e.right.is_string(t)){e.left=e.left.right;return e}}if(t.option("evaluate")){switch(e.operator){case"&&":var o=Bn(e.left,xn)?true:Bn(e.left,Fn)?false:e.left.evaluate(t);if(!o){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}else if(!(o instanceof z)){return make_sequence(e,[e.left,e.right]).optimize(t)}var s=e.right.evaluate(t);if(!s){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(tn,e)]).optimize(t)}else{Vn(e,Fn)}}else if(!(s instanceof z)){var c=t.parent();if(c.operator=="&&"&&c.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}if(e.left.operator=="||"){var l=e.left.right.evaluate(t);if(!l)return make_node(tt,e,{condition:e.left.left,consequent:e.right,alternative:e.left.right}).optimize(t)}break;case"||":var o=Bn(e.left,xn)?true:Bn(e.left,Fn)?false:e.left.evaluate(t);if(!o){return make_sequence(e,[e.left,e.right]).optimize(t)}else if(!(o instanceof z)){return maintain_this_binding(t.parent(),t.self(),e.left).optimize(t)}var s=e.right.evaluate(t);if(!s){var c=t.parent();if(c.operator=="||"&&c.left===t.self()||t.in_boolean_context()){return e.left.optimize(t)}}else if(!(s instanceof z)){if(t.in_boolean_context()){return make_sequence(e,[e.left,make_node(nn,e)]).optimize(t)}else{Vn(e,xn)}}if(e.left.operator=="&&"){var l=e.left.right.evaluate(t);if(l&&!(l instanceof z))return make_node(tt,e,{condition:e.left.left,consequent:e.left.right,alternative:e.right}).optimize(t)}break;case"??":if(is_nullish(e.left,t)){return e.right}var o=e.left.evaluate(t);if(!(o instanceof z)){return o==null?e.right:e.left}if(t.in_boolean_context()){const n=e.right.evaluate(t);if(!(n instanceof z)&&!n){return e.left}}}var f=true;switch(e.operator){case"+":if(e.right instanceof Gt&&e.left instanceof et&&e.left.operator=="+"&&e.left.is_string(t)){var p=make_node(et,e,{operator:"+",left:e.left.right,right:e.right});var _=p.optimize(t);if(p!==_){e=make_node(et,e,{operator:"+",left:e.left.left,right:_})}}if(e.left instanceof et&&e.left.operator=="+"&&e.left.is_string(t)&&e.right instanceof et&&e.right.operator=="+"&&e.right.is_string(t)){var p=make_node(et,e,{operator:"+",left:e.left.right,right:e.right.left});var h=p.optimize(t);if(p!==h){e=make_node(et,e,{operator:"+",left:make_node(et,e.left,{operator:"+",left:e.left.left,right:h}),right:e.right.right})}}if(e.right instanceof Qe&&e.right.operator=="-"&&e.left.is_number(t)){e=make_node(et,e,{operator:"-",left:e.left,right:e.right.expression});break}if(e.left instanceof Qe&&e.left.operator=="-"&&reversible()&&e.right.is_number(t)){e=make_node(et,e,{operator:"-",left:e.right,right:e.left.expression});break}if(e.left instanceof de){var d=e.left;var _=e.right.evaluate(t);if(_!=e.right){d.segments[d.segments.length-1].value+=String(_);return d}}if(e.right instanceof de){var _=e.right;var d=e.left.evaluate(t);if(d!=e.left){_.segments[0].value=String(d)+_.segments[0].value;return _}}if(e.left instanceof de&&e.right instanceof de){var d=e.left;var m=d.segments;var _=e.right;m[m.length-1].value+=_.segments[0].value;for(var E=1;E<_.segments.length;E++){m.push(_.segments[E])}return d}case"*":f=t.option("unsafe_math");case"&":case"|":case"^":if(e.left.is_number(t)&&e.right.is_number(t)&&reversible()&&!(e.left instanceof et&&e.left.operator!=e.operator&&N[e.left.operator]>=N[e.operator])){var g=make_node(et,e,{operator:e.operator,left:e.right,right:e.left});if(e.right instanceof Gt&&!(e.left instanceof Gt)){e=best_of(t,g,e)}else{e=best_of(t,e,g)}}if(f&&e.is_number(t)){if(e.right instanceof et&&e.right.operator==e.operator){e=make_node(et,e,{operator:e.operator,left:make_node(et,e.left,{operator:e.operator,left:e.left,right:e.right.left,start:e.left.start,end:e.right.left.end}),right:e.right.right})}if(e.right instanceof Gt&&e.left instanceof et&&e.left.operator==e.operator){if(e.left.left instanceof Gt){e=make_node(et,e,{operator:e.operator,left:make_node(et,e.left,{operator:e.operator,left:e.left.left,right:e.right,start:e.left.left.start,end:e.right.end}),right:e.left.right})}else if(e.left.right instanceof Gt){e=make_node(et,e,{operator:e.operator,left:make_node(et,e.left,{operator:e.operator,left:e.left.right,right:e.right,start:e.left.right.start,end:e.right.end}),right:e.left.left})}}if(e.left instanceof et&&e.left.operator==e.operator&&e.left.right instanceof Gt&&e.right instanceof et&&e.right.operator==e.operator&&e.right.left instanceof Gt){e=make_node(et,e,{operator:e.operator,left:make_node(et,e.left,{operator:e.operator,left:make_node(et,e.left.left,{operator:e.operator,left:e.left.right,right:e.right.left,start:e.left.right.start,end:e.right.left.end}),right:e.left.left}),right:e.right.right})}}}}if(e.right instanceof et&&e.right.operator==e.operator&&(Gn.has(e.operator)||e.operator=="+"&&(e.right.left.is_string(t)||e.left.is_string(t)&&e.right.right.is_string(t)))){e.left=make_node(et,e.left,{operator:e.operator,left:e.left.transform(t),right:e.right.left.transform(t)});e.right=e.right.right.transform(t);return e.transform(t)}var v=e.evaluate(t);if(v!==e){v=make_node_from_constant(v,e).optimize(t);return best_of(t,v,e)}return e});def_optimize(Bt,function(e){return e});function recursive_ref(e,t){var n;for(var i=0;n=e.parent(i);i++){if(n instanceof ue||n instanceof ht){var r=n.name;if(r&&r.definition()===t)break}}return n}function within_array_or_object_literal(e){var t,n=0;while(t=e.parent(n++)){if(t instanceof K)return false;if(t instanceof rt||t instanceof st||t instanceof at){return true}}return false}def_optimize(Lt,function(e,t){if(!t.option("ie8")&&is_undeclared_ref(e)&&!t.find_parent(re)){switch(e.name){case"undefined":return make_node(Zt,e).optimize(t);case"NaN":return make_node($t,e).optimize(t);case"Infinity":return make_node(Jt,e).optimize(t)}}const n=t.parent();if(t.option("reduce_vars")&&is_lhs(e,n)!==e){const a=e.definition();const o=find_scope(t);if(t.top_retain&&a.global&&t.top_retain(a)){a.fixed=false;a.single_use=false;return e}let s=e.fixed_value();let u=a.single_use&&!(n instanceof Ge&&n.is_callee_pure(t)||has_annotation(n,sn))&&!(n instanceof Ke&&s instanceof ue&&s.name);if(u&&s instanceof z){u=!s.has_side_effects(t)&&!s.may_throw(t)}if(u&&(s instanceof ue||s instanceof ht)){if(retain_top_func(s,t)){u=false}else if(a.scope!==e.scope&&(a.escaped==1||Bn(s,wn)||within_array_or_object_literal(t)||!t.option("reduce_funcs"))){u=false}else if(recursive_ref(t,a)){u=false}else if(a.scope!==e.scope||a.orig[0]instanceof At){u=s.is_constant_expression(e.scope);if(u=="f"){var i=e.scope;do{if(i instanceof pe||is_func_expr(i)){Vn(i,wn)}}while(i=i.parent_scope)}}}if(u&&s instanceof ue){u=a.scope===e.scope&&!scope_encloses_variables_in_this_scope(o,s)||n instanceof Ge&&n.expression===e&&!scope_encloses_variables_in_this_scope(o,s)&&!(s.name&&s.name.definition().recursive_refs>0)}if(u&&s){if(s instanceof Et){Vn(s,Nn);s=make_node(gt,s,s)}if(s instanceof pe){Vn(s,Nn);s=make_node(le,s,s)}if(a.recursive_refs>0&&s.name instanceof Ct){const e=s.name.definition();let t=s.variables.get(s.name.name);let n=t&&t.orig[0];if(!(n instanceof Ft)){n=make_node(Ft,s.name,s.name);n.scope=s;s.name=n;t=s.def_function(n)}walk(s,n=>{if(n instanceof Lt&&n.definition()===e){n.thedef=t;t.references.push(n)}})}if((s instanceof ue||s instanceof ht)&&s.parent_scope!==o){s=s.clone(true,t.get_toplevel());o.add_child_scope(s)}return s.optimize(t)}if(s){let n;if(s instanceof zt){if(!(a.orig[0]instanceof At)&&a.references.every(e=>a.scope===e.scope)){n=s}}else{var r=s.evaluate(t);if(r!==s&&(t.option("unsafe_regexp")||!(r instanceof RegExp))){n=make_node_from_constant(r,s)}}if(n){const i=e.size(t);const r=n.size(t);let o=0;if(t.option("unused")&&!t.exposed(a)){o=(i+2+r)/(a.references.length-a.assignments)}if(r<=i+o){return n}}}}return e});function scope_encloses_variables_in_this_scope(e,t){for(const n of t.enclosed){if(t.variables.has(n.name)){continue}const i=e.find_variable(n.name);if(i){if(i===n)continue;return true}}return false}function is_atomic(e,t){return e instanceof Lt||e.TYPE===t.TYPE}def_optimize(Zt,function(e,t){if(t.option("unsafe_undefined")){var n=find_variable(t,"undefined");if(n){var i=make_node(Lt,e,{name:"undefined",scope:n.scope,thedef:n});Vn(i,On);return i}}var r=is_lhs(t.self(),t.parent());if(r&&is_atomic(r,e))return e;return make_node(Qe,e,{operator:"void",expression:make_node(Ht,e,{value:0})})});def_optimize(Jt,function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&is_atomic(n,e))return e;if(t.option("keep_infinity")&&!(n&&!is_atomic(n,e))&&!find_variable(t,"Infinity")){return e}return make_node(et,e,{operator:"/",left:make_node(Ht,e,{value:1}),right:make_node(Ht,e,{value:0})})});def_optimize($t,function(e,t){var n=is_lhs(t.self(),t.parent());if(n&&!is_atomic(n,e)||find_variable(t,"NaN")){return make_node(et,e,{operator:"/",left:make_node(Ht,e,{value:0}),right:make_node(Ht,e,{value:0})})}return e});function is_reachable(e,t){const n=e=>{if(e instanceof Lt&&member(e.definition(),t)){return rn}};return walk_parent(e,(t,i)=>{if(t instanceof ae&&t!==e){var r=i.parent();if(r instanceof Ge&&r.expression===t)return;if(walk(t,n))return rn;return true}})}const Jn=makePredicate("+ - / * % >> << >>> | ^ &");const ei=makePredicate("* | ^ &");def_optimize(nt,function(e,t){if(e.logical){return e.lift_sequences(t)}var n;if(t.option("dead_code")&&e.left instanceof Lt&&(n=e.left.definition()).scope===t.find_parent(ue)){var i=0,r,a=e;do{r=a;a=t.parent(i++);if(a instanceof ge){if(in_try(i,a))break;if(is_reachable(n.scope,[n]))break;if(e.operator=="=")return e.right;n.fixed=false;return make_node(et,e,{operator:e.operator.slice(0,-1),left:e.left,right:e.right}).optimize(t)}}while(a instanceof et&&a.right===r||a instanceof He&&a.tail_node()===r)}e=e.lift_sequences(t);if(e.operator=="="&&e.left instanceof Lt&&e.right instanceof et){if(e.right.left instanceof Lt&&e.right.left.name==e.left.name&&Jn.has(e.right.operator)){e.operator=e.right.operator+"=";e.right=e.right.right}else if(e.right.right instanceof Lt&&e.right.right.name==e.left.name&&ei.has(e.right.operator)&&!e.right.left.has_side_effects(t)){e.operator=e.right.operator+"=";e.right=e.right.left}}return e;function in_try(n,i){var r=e.right;e.right=make_node(jt,r);var a=i.may_throw(t);e.right=r;var o=e.left.definition().scope;var s;while((s=t.parent(n++))!==o){if(s instanceof Oe){if(s.bfinally)return true;if(a&&s.bcatch)return true}}}});def_optimize(it,function(e,t){if(!t.option("evaluate")){return e}var n=e.right.evaluate(t);if(n===undefined){e=e.left}else if(n!==e.right){n=make_node_from_constant(n,e.right);e.right=best_of_expression(n,e.right)}return e});function is_nullish(e,t){let n;return e instanceof jt||is_undefined(e,t)||e instanceof Lt&&(n=e.definition().fixed)instanceof z&&is_nullish(n,t)||e instanceof We&&e.optional&&is_nullish(e.expression,t)||e instanceof Ge&&e.optional&&is_nullish(e.expression,t)||e instanceof $e&&is_nullish(e.expression,t)}function is_nullish_check(e,t,n){if(t.may_throw(n))return false;let i;if(e instanceof et&&e.operator==="=="&&((i=is_nullish(e.left,n)&&e.left)||(i=is_nullish(e.right,n)&&e.right))&&(i===e.left?e.right:e.left).equivalent_to(t)){return true}if(e instanceof et&&e.operator==="||"){let i;let r;const a=e=>{if(!(e instanceof et&&(e.operator==="==="||e.operator==="=="))){return false}let a=0;let o;if(e.left instanceof jt){a++;i=e;o=e.right}if(e.right instanceof jt){a++;i=e;o=e.left}if(is_undefined(e.left,n)){a++;r=e;o=e.right}if(is_undefined(e.right,n)){a++;r=e;o=e.left}if(a!==1){return false}if(!o.equivalent_to(t)){return false}return true};if(!a(e.left))return false;if(!a(e.right))return false;if(i&&r&&i!==r){return true}}return false}def_optimize(tt,function(e,t){if(!t.option("conditionals"))return e;if(e.condition instanceof He){var n=e.condition.expressions.slice();e.condition=n.pop();n.push(e);return make_sequence(e,n)}var i=e.condition.evaluate(t);if(i!==e.condition){if(i){return maintain_this_binding(t.parent(),t.self(),e.consequent)}else{return maintain_this_binding(t.parent(),t.self(),e.alternative)}}var r=i.negate(t,first_in_statement(t));if(best_of(t,i,r)===r){e=make_node(tt,e,{condition:r,consequent:e.alternative,alternative:e.consequent})}var a=e.condition;var o=e.consequent;var s=e.alternative;if(a instanceof Lt&&o instanceof Lt&&a.definition()===o.definition()){return make_node(et,e,{operator:"||",left:a,right:s})}if(o instanceof nt&&s instanceof nt&&o.operator===s.operator&&o.logical===s.logical&&o.left.equivalent_to(s.left)&&(!e.condition.has_side_effects(t)||o.operator=="="&&!o.left.has_side_effects(t))){return make_node(nt,e,{operator:o.operator,left:o.left,logical:o.logical,right:make_node(tt,e,{condition:e.condition,consequent:o.right,alternative:s.right})})}var u;if(o instanceof Ge&&s.TYPE===o.TYPE&&o.args.length>0&&o.args.length==s.args.length&&o.expression.equivalent_to(s.expression)&&!e.condition.has_side_effects(t)&&!o.expression.has_side_effects(t)&&typeof(u=single_arg_diff())=="number"){var c=o.clone();c.args[u]=make_node(tt,e,{condition:e.condition,consequent:o.args[u],alternative:s.args[u]});return c}if(s instanceof tt&&o.equivalent_to(s.consequent)){return make_node(tt,e,{condition:make_node(et,e,{operator:"||",left:a,right:s.condition}),consequent:o,alternative:s.alternative}).optimize(t)}if(t.option("ecma")>=2020&&is_nullish_check(a,s,t)){return make_node(et,e,{operator:"??",left:s,right:o}).optimize(t)}if(s instanceof He&&o.equivalent_to(s.expressions[s.expressions.length-1])){return make_sequence(e,[make_node(et,e,{operator:"||",left:a,right:make_sequence(e,s.expressions.slice(0,-1))}),o]).optimize(t)}if(s instanceof et&&s.operator=="&&"&&o.equivalent_to(s.right)){return make_node(et,e,{operator:"&&",left:make_node(et,e,{operator:"||",left:a,right:s.left}),right:o}).optimize(t)}if(o instanceof tt&&o.alternative.equivalent_to(s)){return make_node(tt,e,{condition:make_node(et,e,{left:e.condition,operator:"&&",right:o.condition}),consequent:o.consequent,alternative:s})}if(o.equivalent_to(s)){return make_sequence(e,[e.condition,o]).optimize(t)}if(o instanceof et&&o.operator=="||"&&o.right.equivalent_to(s)){return make_node(et,e,{operator:"||",left:make_node(et,e,{operator:"&&",left:e.condition,right:o.left}),right:s}).optimize(t)}var l=t.in_boolean_context();if(is_true(e.consequent)){if(is_false(e.alternative)){return booleanize(e.condition)}return make_node(et,e,{operator:"||",left:booleanize(e.condition),right:e.alternative})}if(is_false(e.consequent)){if(is_true(e.alternative)){return booleanize(e.condition.negate(t))}return make_node(et,e,{operator:"&&",left:booleanize(e.condition.negate(t)),right:e.alternative})}if(is_true(e.alternative)){return make_node(et,e,{operator:"||",left:booleanize(e.condition.negate(t)),right:e.consequent})}if(is_false(e.alternative)){return make_node(et,e,{operator:"&&",left:booleanize(e.condition),right:e.consequent})}return e;function booleanize(e){if(e.is_boolean())return e;return make_node(Qe,e,{operator:"!",expression:e.negate(t)})}function is_true(e){return e instanceof nn||l&&e instanceof Gt&&e.getValue()||e instanceof Qe&&e.operator=="!"&&e.expression instanceof Gt&&!e.expression.getValue()}function is_false(e){return e instanceof tn||l&&e instanceof Gt&&!e.getValue()||e instanceof Qe&&e.operator=="!"&&e.expression instanceof Gt&&e.expression.getValue()}function single_arg_diff(){var e=o.args;var t=s.args;for(var n=0,i=e.length;n=2015;var i=this.expression;if(i instanceof at){var r=i.properties;for(var a=r.length;--a>=0;){var o=r[a];if(""+(o instanceof pt?o.key.name:o.key)==e){const e=r.every(e=>(e instanceof st||n&&e instanceof pt&&!e.is_generator)&&!e.computed_key());if(!e)return;if(!safe_to_flatten(o.value,t))return;return make_node(je,this,{expression:make_node(rt,i,{elements:r.map(function(e){var t=e.value;if(t instanceof ce){t=make_node(le,t,t)}var n=e.key;if(n instanceof z&&!(n instanceof Rt)){return make_sequence(e,[n,t])}return t})}),property:make_node(Ht,this,{value:a})})}}}});def_optimize(je,function(e,t){var n=e.expression;var i=e.property;if(t.option("properties")){var r=i.evaluate(t);if(r!==i){if(typeof r=="string"){if(r=="undefined"){r=undefined}else{var a=parseFloat(r);if(a.toString()==r){r=a}}}i=e.property=best_of_expression(i,make_node_from_constant(r,i).transform(t));var o=""+r;if(is_basic_identifier_string(o)&&o.length<=i.size()+1){return make_node(qe,e,{expression:n,optional:e.optional,property:o,quote:i.quote}).optimize(t)}}}var s;e:if(t.option("arguments")&&n instanceof Lt&&n.name=="arguments"&&n.definition().orig.length==1&&(s=n.scope)instanceof ue&&s.uses_arguments&&!(s instanceof fe)&&i instanceof Ht){var u=i.getValue();var c=new Set;var l=s.argnames;for(var f=0;f1){_=null}}else if(!_&&!t.option("keep_fargs")&&u=s.argnames.length){_=s.create_symbol(At,{source:s,scope:s,tentative_name:"argument_"+s.argnames.length});s.argnames.push(_)}}if(_){var d=make_node(Lt,e,_);d.reference({});Un(_,Rn);return d}}if(is_lhs(e,t.parent()))return e;if(r!==i){var m=e.flatten_object(o,t);if(m){n=e.expression=m.expression;i=e.property=m.property}}if(t.option("properties")&&t.option("side_effects")&&i instanceof Ht&&n instanceof rt){var u=i.getValue();var E=n.elements;var g=E[u];e:if(safe_to_flatten(g,t)){var v=true;var D=[];for(var b=E.length;--b>u;){var a=E[b].drop_side_effect_free(t);if(a){D.unshift(a);if(v&&a.has_side_effects(t))v=false}}if(g instanceof se)break e;g=g instanceof Qt?make_node(Zt,g):g;if(!v)D.unshift(g);while(--b>=0){var a=E[b];if(a instanceof se)break e;a=a.drop_side_effect_free(t);if(a)D.unshift(a);else u--}if(v){D.push(g);return make_sequence(e,D).optimize(t)}else return make_node(je,e,{expression:make_node(rt,n,{elements:D}),property:make_node(Ht,i,{value:u})})}}var y=e.evaluate(t);if(y!==e){y=make_node_from_constant(y,e).optimize(t);return best_of(t,y,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node(Zt,e)}return e});def_optimize($e,function(e,t){e.expression=e.expression.optimize(t);return e});ue.DEFMETHOD("contains_this",function(){return walk(this,e=>{if(e instanceof zt)return rn;if(e!==this&&e instanceof ae&&!(e instanceof fe)){return true}})});def_optimize(qe,function(e,t){const n=t.parent();if(is_lhs(e,n))return e;if(t.option("unsafe_proto")&&e.expression instanceof qe&&e.expression.property=="prototype"){var i=e.expression.expression;if(is_undeclared_ref(i))switch(i.name){case"Array":e.expression=make_node(rt,e.expression,{elements:[]});break;case"Function":e.expression=make_node(le,e.expression,{argnames:[],body:[]});break;case"Number":e.expression=make_node(Ht,e.expression,{value:0});break;case"Object":e.expression=make_node(at,e.expression,{properties:[]});break;case"RegExp":e.expression=make_node(qt,e.expression,{value:{source:"t",flags:""}});break;case"String":e.expression=make_node(Xt,e.expression,{value:""});break}}if(!(n instanceof Ge)||!has_annotation(n,sn)){const n=e.flatten_object(e.property,t);if(n)return n.optimize(t)}let r=e.evaluate(t);if(r!==e){r=make_node_from_constant(r,e).optimize(t);return best_of(t,r,e)}if(e.optional&&is_nullish(e.expression,t)){return make_node(Zt,e)}return e});function literals_in_boolean_context(e,t){if(t.in_boolean_context()){return best_of(t,e,make_sequence(e,[e,make_node(nn,e)]).optimize(t))}return e}function inline_array_like_spread(e){for(var t=0;te instanceof Qt)){e.splice(t,1,...i.elements);t--}}}}def_optimize(rt,function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_array_like_spread(e.elements);return e});function inline_object_prop_spread(e,t){for(var n=0;ne instanceof st)){e.splice(n,1,...r.properties);n--}else if(r instanceof Gt&&!(r instanceof Xt)){e.splice(n,1)}else if(is_nullish(r,t)){e.splice(n,1)}}}}def_optimize(at,function(e,t){var n=literals_in_boolean_context(e,t);if(n!==e){return n}inline_object_prop_spread(e.properties,t);return e});def_optimize(qt,literals_in_boolean_context);def_optimize(ve,function(e,t){if(e.value&&is_undefined(e.value,t)){e.value=null}return e});def_optimize(fe,opt_AST_Lambda);def_optimize(le,function(e,t){e=opt_AST_Lambda(e,t);if(t.option("unsafe_arrows")&&t.option("ecma")>=2015&&!e.name&&!e.is_generator&&!e.uses_arguments&&!e.pinned()){const n=walk(e,e=>{if(e instanceof zt)return rn});if(!n)return make_node(fe,e,e).optimize(t)}return e});def_optimize(ht,function(e){return e});def_optimize(Te,function(e,t){if(e.expression&&!e.is_star&&is_undefined(e.expression,t)){e.expression=null}return e});def_optimize(de,function(e,t){if(!t.option("evaluate")||t.parent()instanceof he){return e}var n=[];for(var i=0;i=2015&&(!(n instanceof RegExp)||n.test(e.key+""))){var i=e.key;var r=e.value;var a=r instanceof fe&&Array.isArray(r.body)&&!r.contains_this();if((a||r instanceof le)&&!r.name){return make_node(pt,e,{async:r.async,is_generator:r.is_generator,key:i instanceof z?i:make_node(Rt,e,{name:i}),value:make_node(ce,r,r),quote:e.quote})}}return e});def_optimize(_e,function(e,t){if(t.option("pure_getters")==true&&t.option("unused")&&!e.is_array&&Array.isArray(e.names)&&!is_destructuring_export_decl(t)&&!(e.names[e.names.length-1]instanceof se)){var n=[];for(var i=0;i1)throw new Error("inline source map only works with singular input");t.sourceMap.content=read_source_map(e[a])}}}r=t.parse.toplevel}if(i&&t.mangle.properties.keep_quoted!=="strict"){reserve_quoted_keys(r,i)}if(t.wrap){r=r.wrap_commonjs(t.wrap)}if(t.enclose){r=r.wrap_enclose(t.enclose)}if(n)n.rename=Date.now();if(n)n.compress=Date.now();if(t.compress){r=new Compressor(t.compress,{mangle_options:t.mangle}).compress(r)}if(n)n.scope=Date.now();if(t.mangle)r.figure_out_scope(t.mangle);if(n)n.mangle=Date.now();if(t.mangle){bn.reset();r.compute_char_frequency(t.mangle);r.mangle_names(t.mangle)}if(n)n.properties=Date.now();if(t.mangle&&t.mangle.properties){r=mangle_properties(r,t.mangle.properties)}if(n)n.format=Date.now();var o={};if(t.format.ast){o.ast=r}if(t.format.spidermonkey){o.ast=r.to_mozilla_ast()}if(!HOP(t.format,"code")||t.format.code){if(t.sourceMap){t.format.source_map=await SourceMap({file:t.sourceMap.filename,orig:t.sourceMap.content,root:t.sourceMap.root});if(t.sourceMap.includeSources){if(e instanceof oe){throw new Error("original source content unavailable")}else for(var a in e)if(HOP(e,a)){t.format.source_map.get().setSourceContent(a,e[a])}}}delete t.format.ast;delete t.format.code;delete t.format.spidermonkey;var s=OutputStream(t.format);r.print(s);o.code=s.get();if(t.sourceMap){if(t.sourceMap.asObject){o.map=t.format.source_map.get().toJSON()}else{o.map=t.format.source_map.toString()}if(t.sourceMap.url=="inline"){var u=typeof o.map==="object"?JSON.stringify(o.map):o.map;o.code+="\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,"+ii(u)}else if(t.sourceMap.url){o.code+="\n//# sourceMappingURL="+t.sourceMap.url}}}if(t.nameCache&&t.mangle){if(t.mangle.cache)t.nameCache.vars=cache_to_json(t.mangle.cache);if(t.mangle.properties&&t.mangle.properties.cache){t.nameCache.props=cache_to_json(t.mangle.properties.cache)}}if(t.format&&t.format.source_map){t.format.source_map.destroy()}if(n){n.end=Date.now();o.timings={parse:.001*(n.rename-n.parse),rename:.001*(n.compress-n.rename),compress:.001*(n.scope-n.compress),scope:.001*(n.mangle-n.scope),mangle:.001*(n.properties-n.mangle),properties:.001*(n.format-n.properties),format:.001*(n.end-n.format),total:.001*(n.end-n.start)}}return o}async function run_cli({program:e,packageJson:t,fs:i,path:r}){const a=new Set(["cname","parent_scope","scope","uses_eval","uses_with"]);var o={};var s={compress:false,mangle:false};const u=await _default_options();e.version(t.name+" "+t.version);e.parseArgv=e.parse;e.parse=undefined;if(process.argv.includes("ast"))e.helpInformation=describe_ast;else if(process.argv.includes("options"))e.helpInformation=function(){var e=[];for(var t in u){e.push("--"+(t==="sourceMap"?"source-map":t)+" options:");e.push(format_object(u[t]));e.push("")}return e.join("\n")};e.option("-p, --parse ","Specify parser options.",parse_js());e.option("-c, --compress [options]","Enable compressor/specify compressor options.",parse_js());e.option("-m, --mangle [options]","Mangle names/specify mangler options.",parse_js());e.option("--mangle-props [options]","Mangle properties/specify mangler options.",parse_js());e.option("-f, --format [options]","Format options.",parse_js());e.option("-b, --beautify [options]","Alias for --format.",parse_js());e.option("-o, --output ","Output file (default STDOUT).");e.option("--comments [filter]","Preserve copyright comments in the output.");e.option("--config-file ","Read minify() options from JSON file.");e.option("-d, --define [=value]","Global definitions.",parse_js("define"));e.option("--ecma ","Specify ECMAScript release: 5, 2015, 2016 or 2017...");e.option("-e, --enclose [arg[,...][:value[,...]]]","Embed output in a big function with configurable arguments and values.");e.option("--ie8","Support non-standard Internet Explorer 8.");e.option("--keep-classnames","Do not mangle/drop class names.");e.option("--keep-fnames","Do not mangle/drop function names. Useful for code relying on Function.prototype.name.");e.option("--module","Input is an ES6 module");e.option("--name-cache ","File to hold mangled name mappings.");e.option("--rename","Force symbol expansion.");e.option("--no-rename","Disable symbol expansion.");e.option("--safari10","Support non-standard Safari 10.");e.option("--source-map [options]","Enable source map/specify source map options.",parse_js());e.option("--timings","Display operations run time on STDERR.");e.option("--toplevel","Compress and/or mangle variables in toplevel scope.");e.option("--wrap ","Embed everything as a function with “exports” corresponding to “name” globally.");e.arguments("[files...]").parseArgv(process.argv);if(e.configFile){s=JSON.parse(read_file(e.configFile))}if(!e.output&&e.sourceMap&&e.sourceMap.url!="inline"){fatal("ERROR: cannot write source map to STDOUT")}["compress","enclose","ie8","mangle","module","safari10","sourceMap","toplevel","wrap"].forEach(function(t){if(t in e){s[t]=e[t]}});if("ecma"in e){if(e.ecma!=(e.ecma|0))fatal("ERROR: ecma must be an integer");const t=e.ecma|0;if(t>5&&t<2015)s.ecma=t+2009;else s.ecma=t}if(e.format||e.beautify){const t=e.format||e.beautify;s.format=typeof t==="object"?t:{}}if(e.comments){if(typeof s.format!="object")s.format={};s.format.comments=typeof e.comments=="string"?e.comments=="false"?false:e.comments:"some"}if(e.define){if(typeof s.compress!="object")s.compress={};if(typeof s.compress.global_defs!="object")s.compress.global_defs={};for(var c in e.define){s.compress.global_defs[c]=e.define[c]}}if(e.keepClassnames){s.keep_classnames=true}if(e.keepFnames){s.keep_fnames=true}if(e.mangleProps){if(e.mangleProps.domprops){delete e.mangleProps.domprops}else{if(typeof e.mangleProps!="object")e.mangleProps={};if(!Array.isArray(e.mangleProps.reserved))e.mangleProps.reserved=[]}if(typeof s.mangle!="object")s.mangle={};s.mangle.properties=e.mangleProps}if(e.nameCache){s.nameCache=JSON.parse(read_file(e.nameCache,"{}"))}if(e.output=="ast"){s.format={ast:true,code:false}}if(e.parse){if(!e.parse.acorn&&!e.parse.spidermonkey){s.parse=e.parse}else if(e.sourceMap&&e.sourceMap.content=="inline"){fatal("ERROR: inline source map only works with built-in parser")}}if(~e.rawArgs.indexOf("--rename")){s.rename=true}else if(!e.rename){s.rename=false}let l=e=>e;if(typeof e.sourceMap=="object"&&"base"in e.sourceMap){l=function(){var t=e.sourceMap.base;delete s.sourceMap.base;return function(e){return r.relative(t,e)}}()}let f;if(s.files&&s.files.length){f=s.files;delete s.files}else if(e.args.length){f=e.args}if(f){simple_glob(f).forEach(function(e){o[l(e)]=read_file(e)})}else{await new Promise(e=>{var t=[];process.stdin.setEncoding("utf8");process.stdin.on("data",function(e){t.push(e)}).on("end",function(){o=[t.join("")];e()});process.stdin.resume()})}await run_cli();function convert_ast(e){return z.from_mozilla_ast(Object.keys(o).reduce(e,null))}async function run_cli(){var t=e.sourceMap&&e.sourceMap.content;if(t&&t!=="inline"){s.sourceMap.content=read_file(t,t)}if(e.timings)s.timings=true;try{if(e.parse){if(e.parse.acorn){o=convert_ast(function(t,i){return n(89).parse(o[i],{ecmaVersion:2018,locations:true,program:t,sourceFile:i,sourceType:s.module||e.parse.module?"module":"script"})})}else if(e.parse.spidermonkey){o=convert_ast(function(e,t){var n=JSON.parse(o[t]);if(!e)return n;e.body=e.body.concat(n.body);return e})}}}catch(e){fatal(e)}let r;try{r=await minify(o,s)}catch(e){if(e.name=="SyntaxError"){print_error("Parse error at "+e.filename+":"+e.line+","+e.col);var u=e.col;var c=o[e.filename].split(/\r?\n/);var l=c[e.line-1];if(!l&&!u){l=c[e.line-2];u=l.length}if(l){var f=70;if(u>f){l=l.slice(u-f);u=f}print_error(l.slice(0,80));print_error(l.slice(0,u).replace(/\S/g," ")+"^")}}if(e.defs){print_error("Supported options:");print_error(format_object(e.defs))}fatal(e);return}if(e.output=="ast"){if(!s.compress&&!s.mangle){r.ast.figure_out_scope({})}console.log(JSON.stringify(r.ast,function(e,t){if(t)switch(e){case"thedef":return symdef(t);case"enclosed":return t.length?t.map(symdef):undefined;case"variables":case"globals":return t.size?collect_from_map(t,symdef):undefined}if(a.has(e))return;if(t instanceof AST_Token)return;if(t instanceof Map)return;if(t instanceof z){var n={_class:"AST_"+t.TYPE};if(t.block_scope){n.variables=t.block_scope.variables;n.enclosed=t.block_scope.enclosed}t.CTOR.PROPS.forEach(function(e){n[e]=t[e]});return n}return t},2))}else if(e.output=="spidermonkey"){try{const e=await minify(r.code,{compress:false,mangle:false,format:{ast:true,code:false}});console.log(JSON.stringify(e.ast.to_mozilla_ast(),null,2))}catch(e){fatal(e);return}}else if(e.output){i.writeFileSync(e.output,r.code);if(s.sourceMap&&s.sourceMap.url!=="inline"&&r.map){i.writeFileSync(e.output+".map",r.map)}}else{console.log(r.code)}if(e.nameCache){i.writeFileSync(e.nameCache,JSON.stringify(s.nameCache))}if(r.timings)for(var p in r.timings){print_error("- "+p+": "+r.timings[p].toFixed(3)+"s")}}function fatal(e){if(e instanceof Error)e=e.stack.replace(/^\S*?Error:/,"ERROR:");print_error(e);process.exit(1)}function simple_glob(e){if(Array.isArray(e)){return[].concat.apply([],e.map(simple_glob))}if(e&&e.match(/[*?]/)){var t=r.dirname(e);try{var n=i.readdirSync(t)}catch(e){}if(n){var a="^"+r.basename(e).replace(/[.+^$[\]\\(){}]/g,"\\$&").replace(/\*/g,"[^/\\\\]*").replace(/\?/g,"[^/\\\\]")+"$";var o=process.platform==="win32"?"i":"";var s=new RegExp(a,o);var u=n.filter(function(e){return s.test(e)}).map(function(e){return r.join(t,e)});if(u.length)return u}}return[e]}function read_file(e,t){try{return i.readFileSync(e,"utf8")}catch(e){if((e.code=="ENOENT"||e.code=="ENAMETOOLONG")&&t!=null)return t;fatal(e)}}function parse_js(e){return function(t,n){n=n||{};try{walk(parse(t,{expression:true}),t=>{if(t instanceof nt){var i=t.left.print_to_string();var r=t.right;if(e){n[i]=r}else if(r instanceof rt){n[i]=r.elements.map(to_string)}else if(r instanceof qt){r=r.value;n[i]=new RegExp(r.source,r.flags)}else{n[i]=to_string(r)}return true}if(t instanceof vt||t instanceof We){var i=t.print_to_string();n[i]=true;return true}if(!(t instanceof He))throw t;function to_string(e){return e instanceof Gt?e.getValue():e.print_to_string({quote_keys:true})}})}catch(i){if(e){fatal("Error parsing arguments for '"+e+"': "+t)}else{n[t]=null}}return n}}function symdef(e){var t=1e6+e.id+" "+e.name;if(e.mangled_name)t+=" "+e.mangled_name;return t}function collect_from_map(e,t){var n=[];e.forEach(function(e){n.push(t(e))});return n}function format_object(e){var t=[];var n="";Object.keys(e).map(function(t){if(n.length!/^\$/.test(e));if(n.length>0){e.space();e.with_parens(function(){n.forEach(function(t,n){if(n)e.space();e.print(t)})})}if(t.documentation){e.space();e.print_string(t.documentation)}if(t.SUBCLASSES.length>0){e.space();e.with_block(function(){t.SUBCLASSES.forEach(function(t){e.indent();doitem(t);e.newline()})})}}doitem(z);return e+"\n"}}async function _default_options(){const e={};Object.keys(infer_options({0:0})).forEach(t=>{const n=infer_options({[t]:{0:0}});if(n)e[t]=n});return e}async function infer_options(e){try{await minify("",e)}catch(e){return e.defs}}e._default_options=_default_options;e._run_cli=run_cli;e.minify=minify})},241:e=>{"use strict";e.exports=require("next/dist/compiled/source-map")}};var t={};function __nccwpck_require__(n){if(t[n]){return t[n].exports}var i=t[n]={exports:{}};var r=true;try{e[n].call(i.exports,i,i.exports,__nccwpck_require__);r=false}finally{if(r)delete t[n]}return i.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(633)})(); \ No newline at end of file diff --git a/packages/next/compiled/webpack/bundle4.js b/packages/next/compiled/webpack/bundle4.js index 28a0e9476888468..4fae85994872825 100644 --- a/packages/next/compiled/webpack/bundle4.js +++ b/packages/next/compiled/webpack/bundle4.js @@ -51821,7 +51821,207 @@ module.exports = function normalize(path) { /***/ }), -/***/ 53024: +/***/ 4870: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; + + +var isExtendable = __webpack_require__(29502); +var forIn = __webpack_require__(43086); + +function mixinDeep(target, objects) { + var len = arguments.length, i = 0; + while (++i < len) { + var obj = arguments[i]; + if (isObject(obj)) { + forIn(obj, copy, target); + } + } + return target; +} + +/** + * Copy properties from the source object to the + * target object. + * + * @param {*} `val` + * @param {String} `key` + */ + +function copy(val, key) { + if (!isValidKey(key)) { + return; + } + + var obj = this[key]; + if (isObject(val) && isObject(obj)) { + mixinDeep(obj, val); + } else { + this[key] = val; + } +} + +/** + * Returns true if `val` is an object or function. + * + * @param {any} val + * @return {Boolean} + */ + +function isObject(val) { + return isExtendable(val) && !Array.isArray(val); +} + +/** + * Returns true if `key` is a valid key to use when extending objects. + * + * @param {String} `key` + * @return {Boolean} + */ + +function isValidKey(key) { + return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; +}; + +/** + * Expose `mixinDeep` + */ + +module.exports = mixinDeep; + + +/***/ }), + +/***/ 29502: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isPlainObject = __webpack_require__(81064); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; + + +/***/ }), + +/***/ 50998: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +var path = __webpack_require__(85622); +var fs = __webpack_require__(35747); +var _0777 = parseInt('0777', 8); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + if (path.dirname(p) === p) return cb(er); + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; + + +/***/ }), + +/***/ 57925: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -51832,18 +52032,17 @@ module.exports = function normalize(path) { */ var util = __webpack_require__(31669); -var braces = __webpack_require__(50559); var toRegex = __webpack_require__(51279); -var extend = __webpack_require__(3767); +var extend = __webpack_require__(69148); /** * Local dependencies */ -var compilers = __webpack_require__(26113); -var parsers = __webpack_require__(14086); -var cache = __webpack_require__(34743); -var utils = __webpack_require__(63976); +var compilers = __webpack_require__(4756); +var parsers = __webpack_require__(5333); +var cache = __webpack_require__(58250); +var utils = __webpack_require__(41340); var MAX_LENGTH = 1024 * 64; /** @@ -51851,10 +52050,10 @@ var MAX_LENGTH = 1024 * 64; * glob patterns to use for matching. * * ```js - * var mm = require('micromatch'); - * mm(list, patterns[, options]); + * var nm = require('nanomatch'); + * nm(list, patterns[, options]); * - * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * console.log(nm(['a.js', 'a.txt'], ['*.js'])); * //=> [ 'a.js' ] * ``` * @param {Array} `list` A list of strings to match @@ -51865,7 +52064,7 @@ var MAX_LENGTH = 1024 * 64; * @api public */ -function micromatch(list, patterns, options) { +function nanomatch(list, patterns, options) { patterns = utils.arrayify(patterns); list = utils.arrayify(list); @@ -51875,9 +52074,10 @@ function micromatch(list, patterns, options) { } if (len === 1) { - return micromatch.match(list, patterns[0], options); + return nanomatch.match(list, patterns[0], options); } + var negated = false; var omit = []; var keep = []; var idx = -1; @@ -51886,9 +52086,22 @@ function micromatch(list, patterns, options) { var pattern = patterns[idx]; if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { - omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options)); + omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options)); + negated = true; } else { - keep.push.apply(keep, micromatch.match(list, pattern, options)); + keep.push.apply(keep, nanomatch.match(list, pattern, options)); + } + } + + // minimatch.match parity + if (negated && keep.length === 0) { + if (options && options.unixify === false) { + keep = list.slice(); + } else { + var unixify = utils.unixify(options); + for (var i = 0; i < list.length; i++) { + keep.push(unixify(list[i])); + } } } @@ -51904,10 +52117,10 @@ function micromatch(list, patterns, options) { * Similar to the main function, but `pattern` must be a string. * * ```js - * var mm = require('micromatch'); - * mm.match(list, pattern[, options]); + * var nm = require('nanomatch'); + * nm.match(list, pattern[, options]); * - * console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); + * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); * //=> ['a.a', 'a.aa'] * ``` * @param {Array} `list` Array of strings to match @@ -51917,13 +52130,13 @@ function micromatch(list, patterns, options) { * @api public */ -micromatch.match = function(list, pattern, options) { +nanomatch.match = function(list, pattern, options) { if (Array.isArray(pattern)) { throw new TypeError('expected pattern to be a string'); } var unixify = utils.unixify(options); - var isMatch = memoize('match', pattern, options, micromatch.matcher); + var isMatch = memoize('match', pattern, options, nanomatch.matcher); var matches = []; list = utils.arrayify(list); @@ -51953,7 +52166,7 @@ micromatch.match = function(list, pattern, options) { // if `opts.ignore` was defined, diff ignored list if (options.ignore) { - matches = micromatch.not(matches, options.ignore, options); + matches = nanomatch.not(matches, options.ignore, options); } return options.nodupes !== false ? utils.unique(matches) : matches; @@ -51963,12 +52176,12 @@ micromatch.match = function(list, pattern, options) { * Returns true if the specified `string` matches the given glob `pattern`. * * ```js - * var mm = require('micromatch'); - * mm.isMatch(string, pattern[, options]); + * var nm = require('nanomatch'); + * nm.isMatch(string, pattern[, options]); * - * console.log(mm.isMatch('a.a', '*.a')); + * console.log(nm.isMatch('a.a', '*.a')); * //=> true - * console.log(mm.isMatch('a.b', '*.a')); + * console.log(nm.isMatch('a.b', '*.a')); * //=> false * ``` * @param {String} `string` String to match @@ -51978,12 +52191,12 @@ micromatch.match = function(list, pattern, options) { * @api public */ -micromatch.isMatch = function(str, pattern, options) { +nanomatch.isMatch = function(str, pattern, options) { if (typeof str !== 'string') { throw new TypeError('expected a string: "' + util.inspect(str) + '"'); } - if (isEmptyString(str) || isEmptyString(pattern)) { + if (utils.isEmptyString(str) || utils.isEmptyString(pattern)) { return false; } @@ -51992,21 +52205,21 @@ micromatch.isMatch = function(str, pattern, options) { return true; } - var isMatch = memoize('isMatch', pattern, options, micromatch.matcher); + var isMatch = memoize('isMatch', pattern, options, nanomatch.matcher); return isMatch(str); }; /** - * Returns true if some of the strings in the given `list` match any of the + * Returns true if some of the elements in the given `list` match any of the * given glob `patterns`. * * ```js - * var mm = require('micromatch'); - * mm.some(list, patterns[, options]); + * var nm = require('nanomatch'); + * nm.some(list, patterns[, options]); * - * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // true - * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * console.log(nm.some(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. @@ -52016,33 +52229,35 @@ micromatch.isMatch = function(str, pattern, options) { * @api public */ -micromatch.some = function(list, patterns, options) { +nanomatch.some = function(list, patterns, options) { if (typeof list === 'string') { list = [list]; } + for (var i = 0; i < list.length; i++) { - if (micromatch(list[i], patterns, options).length === 1) { + if (nanomatch(list[i], patterns, options).length === 1) { return true; } } + return false; }; /** - * Returns true if every string in the given `list` matches - * any of the given glob `patterns`. + * Returns true if every element in the given `list` matches + * at least one of the given glob `patterns`. * * ```js - * var mm = require('micromatch'); - * mm.every(list, patterns[, options]); + * var nm = require('nanomatch'); + * nm.every(list, patterns[, options]); * - * console.log(mm.every('foo.js', ['foo.js'])); + * console.log(nm.every('foo.js', ['foo.js'])); * // true - * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * console.log(nm.every(['foo.js', 'bar.js'], ['*.js'])); * // true - * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // false - * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * console.log(nm.every(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` * @param {String|Array} `list` The string or array of strings to test. @@ -52052,15 +52267,17 @@ micromatch.some = function(list, patterns, options) { * @api public */ -micromatch.every = function(list, patterns, options) { +nanomatch.every = function(list, patterns, options) { if (typeof list === 'string') { list = [list]; } + for (var i = 0; i < list.length; i++) { - if (micromatch(list[i], patterns, options).length !== 1) { + if (nanomatch(list[i], patterns, options).length !== 1) { return false; } } + return true; }; @@ -52069,12 +52286,12 @@ micromatch.every = function(list, patterns, options) { * match the specified `string`. * * ```js - * var mm = require('micromatch'); - * mm.any(string, patterns[, options]); + * var nm = require('nanomatch'); + * nm.any(string, patterns[, options]); * - * console.log(mm.any('a.a', ['b.*', '*.a'])); + * console.log(nm.any('a.a', ['b.*', '*.a'])); * //=> true - * console.log(mm.any('a.a', 'b.*')); + * console.log(nm.any('a.a', 'b.*')); * //=> false * ``` * @param {String|Array} `str` The string to test. @@ -52084,12 +52301,12 @@ micromatch.every = function(list, patterns, options) { * @api public */ -micromatch.any = function(str, patterns, options) { +nanomatch.any = function(str, patterns, options) { if (typeof str !== 'string') { throw new TypeError('expected a string: "' + util.inspect(str) + '"'); } - if (isEmptyString(str) || isEmptyString(patterns)) { + if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { return false; } @@ -52098,7 +52315,7 @@ micromatch.any = function(str, patterns, options) { } for (var i = 0; i < patterns.length; i++) { - if (micromatch.isMatch(str, patterns[i], options)) { + if (nanomatch.isMatch(str, patterns[i], options)) { return true; } } @@ -52106,23 +52323,23 @@ micromatch.any = function(str, patterns, options) { }; /** - * Returns true if **all** of the given `patterns` match - * the specified string. + * Returns true if **all** of the given `patterns` + * match the specified string. * * ```js - * var mm = require('micromatch'); - * mm.all(string, patterns[, options]); + * var nm = require('nanomatch'); + * nm.all(string, patterns[, options]); * - * console.log(mm.all('foo.js', ['foo.js'])); + * console.log(nm.all('foo.js', ['foo.js'])); * // true * - * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * console.log(nm.all('foo.js', ['*.js', '!foo.js'])); * // false * - * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * console.log(nm.all('foo.js', ['*.js', 'foo.js'])); * // true * - * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); * // true * ``` * @param {String|Array} `str` The string to test. @@ -52132,15 +52349,17 @@ micromatch.any = function(str, patterns, options) { * @api public */ -micromatch.all = function(str, patterns, options) { +nanomatch.all = function(str, patterns, options) { if (typeof str !== 'string') { throw new TypeError('expected a string: "' + util.inspect(str) + '"'); } + if (typeof patterns === 'string') { patterns = [patterns]; } + for (var i = 0; i < patterns.length; i++) { - if (!micromatch.isMatch(str, patterns[i], options)) { + if (!nanomatch.isMatch(str, patterns[i], options)) { return false; } } @@ -52151,10 +52370,10 @@ micromatch.all = function(str, patterns, options) { * Returns a list of strings that _**do not match any**_ of the given `patterns`. * * ```js - * var mm = require('micromatch'); - * mm.not(list, patterns[, options]); + * var nm = require('nanomatch'); + * nm.not(list, patterns[, options]); * - * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a')); * //=> ['b.b', 'c.c'] * ``` * @param {Array} `list` Array of strings to match. @@ -52164,17 +52383,16 @@ micromatch.all = function(str, patterns, options) { * @api public */ -micromatch.not = function(list, patterns, options) { +nanomatch.not = function(list, patterns, options) { var opts = extend({}, options); var ignore = opts.ignore; delete opts.ignore; - var unixify = utils.unixify(opts); - list = utils.arrayify(list).map(unixify); + list = utils.arrayify(list); - var matches = utils.diff(list, micromatch(list, patterns, opts)); + var matches = utils.diff(list, nanomatch(list, patterns, opts)); if (ignore) { - matches = utils.diff(matches, micromatch(list, ignore)); + matches = utils.diff(matches, nanomatch(list, ignore)); } return opts.nodupes !== false ? utils.unique(matches) : matches; @@ -52185,12 +52403,12 @@ micromatch.not = function(list, patterns, options) { * to [.isMatch](#isMatch) but the pattern can match any part of the string. * * ```js - * var mm = require('micromatch'); - * mm.contains(string, pattern[, options]); + * var nm = require('nanomatch'); + * nm.contains(string, pattern[, options]); * - * console.log(mm.contains('aa/bb/cc', '*b')); + * console.log(nm.contains('aa/bb/cc', '*b')); * //=> true - * console.log(mm.contains('aa/bb/cc', '*d')); + * console.log(nm.contains('aa/bb/cc', '*d')); * //=> false * ``` * @param {String} `str` The string to match. @@ -52200,13 +52418,13 @@ micromatch.not = function(list, patterns, options) { * @api public */ -micromatch.contains = function(str, patterns, options) { +nanomatch.contains = function(str, patterns, options) { if (typeof str !== 'string') { throw new TypeError('expected a string: "' + util.inspect(str) + '"'); } if (typeof patterns === 'string') { - if (isEmptyString(str) || isEmptyString(patterns)) { + if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { return false; } @@ -52221,7 +52439,7 @@ micromatch.contains = function(str, patterns, options) { } var opts = extend({}, options, {contains: true}); - return micromatch.any(str, patterns, opts); + return nanomatch.any(str, patterns, opts); }; /** @@ -52231,7 +52449,7 @@ micromatch.contains = function(str, patterns, options) { * @api private */ -micromatch.matchBase = function(pattern, options) { +nanomatch.matchBase = function(pattern, options) { if (pattern && pattern.indexOf('/') !== -1 || !options) return false; return options.basename === true || options.matchBase === true; }; @@ -52242,11 +52460,11 @@ micromatch.matchBase = function(pattern, options) { * use [glob-object][] instead. * * ```js - * var mm = require('micromatch'); - * mm.matchKeys(object, patterns[, options]); + * var nm = require('nanomatch'); + * nm.matchKeys(object, patterns[, options]); * * var obj = { aa: 'a', ab: 'b', ac: 'c' }; - * console.log(mm.matchKeys(obj, '*b')); + * console.log(nm.matchKeys(obj, '*b')); * //=> { ab: 'b' } * ``` * @param {Object} `object` The object with keys to filter. @@ -52256,11 +52474,11 @@ micromatch.matchBase = function(pattern, options) { * @api public */ -micromatch.matchKeys = function(obj, patterns, options) { +nanomatch.matchKeys = function(obj, patterns, options) { if (!utils.isObject(obj)) { throw new TypeError('expected the first argument to be an object'); } - var keys = micromatch(Object.keys(obj), patterns, options); + var keys = nanomatch(Object.keys(obj), patterns, options); return utils.pick(obj, keys); }; @@ -52270,10 +52488,10 @@ micromatch.matchKeys = function(obj, patterns, options) { * true if the string is a match. * * ```js - * var mm = require('micromatch'); - * mm.matcher(pattern[, options]); + * var nm = require('nanomatch'); + * nm.matcher(pattern[, options]); * - * var isMatch = mm.matcher('*.!(*a)'); + * var isMatch = nm.matcher('*.!(*a)'); * console.log(isMatch('a.a')); * //=> false * console.log(isMatch('a.b')); @@ -52285,7 +52503,13 @@ micromatch.matchKeys = function(obj, patterns, options) { * @api public */ -micromatch.matcher = function matcher(pattern, options) { +nanomatch.matcher = function matcher(pattern, options) { + if (utils.isEmptyString(pattern)) { + return function() { + return false; + }; + } + if (Array.isArray(pattern)) { return compose(pattern, options, matcher); } @@ -52309,10 +52533,10 @@ micromatch.matcher = function matcher(pattern, options) { } // if pattern is a glob string - var re = micromatch.makeRe(pattern, options); + var re = nanomatch.makeRe(pattern, options); // if `options.matchBase` or `options.basename` is defined - if (micromatch.matchBase(pattern, options)) { + if (nanomatch.matchBase(pattern, options)) { return utils.matchBasename(re, options); } @@ -52332,25 +52556,25 @@ micromatch.matcher = function matcher(pattern, options) { }; } - var fn = test(re); - Object.defineProperty(fn, 'result', { - configurable: true, - enumerable: false, - value: re.result - }); - return fn; + // create matcher function + var matcherFn = test(re); + // set result object from compiler on matcher function, + // as a non-enumerable property. useful for debugging + utils.define(matcherFn, 'result', re.result); + return matcherFn; }; /** - * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * Returns an array of matches captured by `pattern` in `string, or + * `null` if the pattern did not match. * * ```js - * var mm = require('micromatch'); - * mm.capture(pattern, string[, options]); + * var nm = require('nanomatch'); + * nm.capture(pattern, string[, options]); * - * console.log(mm.capture('test/*.js', 'test/foo.js')); + * console.log(nm.capture('test/*.js', 'test/foo.js')); * //=> ['foo'] - * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * console.log(nm.capture('test/*.js', 'foo/bar.css')); * //=> null * ``` * @param {String} `pattern` Glob pattern to use for matching. @@ -52360,8 +52584,8 @@ micromatch.matcher = function matcher(pattern, options) { * @api public */ -micromatch.capture = function(pattern, str, options) { - var re = micromatch.makeRe(pattern, extend({capture: true}, options)); +nanomatch.capture = function(pattern, str, options) { + var re = nanomatch.makeRe(pattern, extend({capture: true}, options)); var unixify = utils.unixify(options); function match() { @@ -52383,10 +52607,10 @@ micromatch.capture = function(pattern, str, options) { * Create a regular expression from the given glob `pattern`. * * ```js - * var mm = require('micromatch'); - * mm.makeRe(pattern[, options]); + * var nm = require('nanomatch'); + * nm.makeRe(pattern[, options]); * - * console.log(mm.makeRe('*.js')); + * console.log(nm.makeRe('*.js')); * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ * ``` * @param {String} `pattern` A glob pattern to convert to regex. @@ -52395,7 +52619,11 @@ micromatch.capture = function(pattern, str, options) { * @api public */ -micromatch.makeRe = function(pattern, options) { +nanomatch.makeRe = function(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; + } + if (typeof pattern !== 'string') { throw new TypeError('expected pattern to be a string'); } @@ -52405,20 +52633,10 @@ micromatch.makeRe = function(pattern, options) { } function makeRe() { - var result = micromatch.create(pattern, options); - var ast_array = []; - var output = result.map(function(obj) { - obj.ast.state = obj.state; - ast_array.push(obj.ast); - return obj.output; - }); - - var regex = toRegex(output.join('|'), options); - Object.defineProperty(regex, 'result', { - configurable: true, - enumerable: false, - value: ast_array - }); + var opts = utils.extend({wrap: false}, options); + var result = nanomatch.create(pattern, opts); + var regex = toRegex(result.output, opts); + utils.define(regex, 'result', result); return regex; } @@ -52426,58 +52644,15 @@ micromatch.makeRe = function(pattern, options) { }; /** - * Expand the given brace `pattern`. - * - * ```js - * var mm = require('micromatch'); - * console.log(mm.braces('foo/{a,b}/bar')); - * //=> ['foo/(a|b)/bar'] - * - * console.log(mm.braces('foo/{a,b}/bar', {expand: true})); - * //=> ['foo/(a|b)/bar'] - * ``` - * @param {String} `pattern` String with brace pattern to expand. - * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. - * @return {Array} - * @api public - */ - -micromatch.braces = function(pattern, options) { - if (typeof pattern !== 'string' && !Array.isArray(pattern)) { - throw new TypeError('expected pattern to be an array or string'); - } - - function expand() { - if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) { - return utils.arrayify(pattern); - } - return braces(pattern, options); - } - - return memoize('braces', pattern, options, expand); -}; - -/** - * Proxy to the [micromatch.braces](#method), for parity with - * minimatch. - */ - -micromatch.braceExpand = function(pattern, options) { - var opts = extend({}, options, {expand: true}); - return micromatch.braces(pattern, opts); -}; - -/** - * Parses the given glob `pattern` and returns an array of abstract syntax - * trees (ASTs), with the compiled `output` and optional source `map` on - * each AST. + * Parses the given glob `pattern` and returns an object with the compiled `output` + * and optional source `map`. * * ```js - * var mm = require('micromatch'); - * mm.create(pattern[, options]); + * var nm = require('nanomatch'); + * nm.create(pattern[, options]); * - * console.log(mm.create('abc/*.js')); - * // [{ options: { source: 'string', sourcemap: true }, + * console.log(nm.create('abc/*.js')); + * // { options: { source: 'string', sourcemap: true }, * // state: {}, * // compilers: * // { ... }, @@ -52499,7 +52674,7 @@ micromatch.braceExpand = function(pattern, options) { * // position: { line: 1, column: 28 }, * // content: {}, * // files: {}, - * // idx: 6 }] + * // idx: 6 } * ``` * @param {String} `pattern` Glob pattern to parse and compile. * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed. @@ -52507,32 +52682,24 @@ micromatch.braceExpand = function(pattern, options) { * @api public */ -micromatch.create = function(pattern, options) { - return memoize('create', pattern, options, function() { - function create(str, opts) { - return micromatch.compile(micromatch.parse(str, opts), opts); - } - - pattern = micromatch.braces(pattern, options); - var len = pattern.length; - var idx = -1; - var res = []; - - while (++idx < len) { - res.push(create(pattern[idx], options)); - } - return res; - }); +nanomatch.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + function create() { + return nanomatch.compile(nanomatch.parse(pattern, options), options); + } + return memoize('create', pattern, options, create); }; /** * Parse the given `str` with the given `options`. * * ```js - * var mm = require('micromatch'); - * mm.parse(pattern[, options]); + * var nm = require('nanomatch'); + * nm.parse(pattern[, options]); * - * var ast = mm.parse('a/{b,c}/d'); + * var ast = nm.parse('a/{b,c}/d'); * console.log(ast); * // { type: 'root', * // errors: [], @@ -52554,7 +52721,7 @@ micromatch.create = function(pattern, options) { * @api public */ -micromatch.parse = function(pattern, options) { +nanomatch.parse = function(pattern, options) { if (typeof pattern !== 'string') { throw new TypeError('expected a string'); } @@ -52576,11 +52743,11 @@ micromatch.parse = function(pattern, options) { * Compile the given `ast` or string with the given `options`. * * ```js - * var mm = require('micromatch'); - * mm.compile(ast[, options]); + * var nm = require('nanomatch'); + * nm.compile(ast[, options]); * - * var ast = mm.parse('a/{b,c}/d'); - * console.log(mm.compile(ast)); + * var ast = nm.parse('a/{b,c}/d'); + * console.log(nm.compile(ast)); * // { options: { source: 'string' }, * // state: {}, * // compilers: @@ -52602,39 +52769,33 @@ micromatch.parse = function(pattern, options) { * @api public */ -micromatch.compile = function(ast, options) { +nanomatch.compile = function(ast, options) { if (typeof ast === 'string') { - ast = micromatch.parse(ast, options); + ast = nanomatch.parse(ast, options); } - return memoize('compile', ast.input, options, function() { + function compile() { var snapdragon = utils.instantiate(ast, options); compilers(snapdragon, options); return snapdragon.compile(ast, options); - }); + } + + return memoize('compile', ast.input, options, compile); }; /** * Clear the regex cache. * * ```js - * mm.clearCache(); + * nm.clearCache(); * ``` * @api public */ -micromatch.clearCache = function() { - micromatch.cache.caches = {}; +nanomatch.clearCache = function() { + nanomatch.cache.__data__ = {}; }; -/** - * Returns true if the given value is effectively an empty string - */ - -function isEmptyString(val) { - return String(val) === '' || String(val) === './'; -} - /** * Compose a matcher function with the given patterns. * This allows matcher functions to be compiled once and @@ -52689,24 +52850,24 @@ function memoize(type, pattern, options, fn) { } /** - * Expose compiler, parser and cache on `micromatch` + * Expose compiler, parser and cache on `nanomatch` */ -micromatch.compilers = compilers; -micromatch.parsers = parsers; -micromatch.caches = cache.caches; +nanomatch.compilers = compilers; +nanomatch.parsers = parsers; +nanomatch.cache = cache; /** - * Expose `micromatch` + * Expose `nanomatch` * @type {Function} */ -module.exports = micromatch; +module.exports = nanomatch; /***/ }), -/***/ 34743: +/***/ 58250: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { module.exports = new (__webpack_require__(49908))(); @@ -52714,17156 +52875,17542 @@ module.exports = new (__webpack_require__(49908))(); /***/ }), -/***/ 26113: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 4756: +/***/ (function(module) { "use strict"; -var nanomatch = __webpack_require__(57925); -var extglob = __webpack_require__(66675); - -module.exports = function(snapdragon) { - var compilers = snapdragon.compiler.compilers; - var opts = snapdragon.options; - - // register nanomatch compilers - snapdragon.use(nanomatch.compilers); +/** +* Nanomatch compilers +*/ - // get references to some specific nanomatch compilers before they - // are overridden by the extglob and/or custom compilers - var escape = compilers.escape; - var qmark = compilers.qmark; - var slash = compilers.slash; - var star = compilers.star; - var text = compilers.text; - var plus = compilers.plus; - var dot = compilers.dot; +module.exports = function(nanomatch, options) { + function slash() { + if (options && typeof options.slash === 'string') { + return options.slash; + } + if (options && typeof options.slash === 'function') { + return options.slash.call(nanomatch); + } + return '\\\\/'; + } - // register extglob compilers or escape exglobs if disabled - if (opts.extglob === false || opts.noext === true) { - snapdragon.compiler.use(escapeExtglobs); - } else { - snapdragon.use(extglob.compilers); + function star() { + if (options && typeof options.star === 'string') { + return options.star; + } + if (options && typeof options.star === 'function') { + return options.star.call(nanomatch); + } + return '[^' + slash() + ']*?'; } - snapdragon.use(function() { - this.options.star = this.options.star || function(/*node*/) { - return '[^\\\\/]*?'; - }; - }); + var ast = nanomatch.ast = nanomatch.parser.ast; + ast.state = nanomatch.parser.state; + nanomatch.compiler.state = ast.state; + nanomatch.compiler - // custom micromatch compilers - snapdragon.compiler + /** + * Negation / escaping + */ - // reset referenced compiler - .set('dot', dot) - .set('escape', escape) - .set('plus', plus) - .set('slash', slash) - .set('qmark', qmark) - .set('star', star) - .set('text', text); -}; + .set('not', function(node) { + var prev = this.prev(); + if (this.options.nonegate === true || prev.type !== 'bos') { + return this.emit('\\' + node.val, node); + } + return this.emit(node.val, node); + }) + .set('escape', function(node) { + if (this.options.unescape && /^[-\w_.]/.test(node.val)) { + return this.emit(node.val, node); + } + return this.emit('\\' + node.val, node); + }) + .set('quoted', function(node) { + return this.emit(node.val, node); + }) -function escapeExtglobs(compiler) { - compiler.set('paren', function(node) { - var val = ''; - visit(node, function(tok) { - if (tok.val) val += (/^\W/.test(tok.val) ? '\\' : '') + tok.val; - }); - return this.emit(val, node); - }); + /** + * Regex + */ - /** - * Visit `node` with the given `fn` - */ + .set('dollar', function(node) { + if (node.parent.type === 'bracket') { + return this.emit(node.val, node); + } + return this.emit('\\' + node.val, node); + }) - function visit(node, fn) { - return node.nodes ? mapVisit(node.nodes, fn) : fn(node); - } + /** + * Dot: "." + */ - /** - * Map visit over array of `nodes`. - */ + .set('dot', function(node) { + if (node.dotfiles === true) this.dotfiles = true; + return this.emit('\\' + node.val, node); + }) - function mapVisit(nodes, fn) { - var len = nodes.length; - var idx = -1; - while (++idx < len) { - visit(nodes[idx], fn); - } - } -} + /** + * Slashes: "/" and "\" + */ + .set('backslash', function(node) { + return this.emit(node.val, node); + }) + .set('slash', function(node, nodes, i) { + var val = '[' + slash() + ']'; + var parent = node.parent; + var prev = this.prev(); -/***/ }), + // set "node.hasSlash" to true on all ancestor parens nodes + while (parent.type === 'paren' && !parent.hasSlash) { + parent.hasSlash = true; + parent = parent.parent; + } -/***/ 14086: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (prev.addQmark) { + val += '?'; + } -"use strict"; + // word boundary + if (node.rest.slice(0, 2) === '\\b') { + return this.emit(val, node); + } + // globstars + if (node.parsed === '**' || node.parsed === './**') { + this.output = '(?:' + this.output; + return this.emit(val + ')?', node); + } -var extglob = __webpack_require__(66675); -var nanomatch = __webpack_require__(57925); -var regexNot = __webpack_require__(30931); -var toRegex = __webpack_require__(51279); -var not; + // negation + if (node.parsed === '!**' && this.options.nonegate !== true) { + return this.emit(val + '?\\b', node); + } + return this.emit(val, node); + }) -/** - * Characters to use in negation regex (we want to "not" match - * characters that are matched by other parsers) - */ + /** + * Square brackets + */ -var TEXT = '([!@*?+]?\\(|\\)|\\[:?(?=.*?:?\\])|:?\\]|[*+?!^$.\\\\/])+'; -var createNotRegex = function(opts) { - return not || (not = textRegex(TEXT)); -}; + .set('bracket', function(node) { + var close = node.close; + var open = !node.escaped ? '[' : '\\['; + var negated = node.negated; + var inner = node.inner; + var val = node.val; -/** - * Parsers - */ + if (node.escaped === true) { + inner = inner.replace(/\\?(\W)/g, '\\$1'); + negated = ''; + } -module.exports = function(snapdragon) { - var parsers = snapdragon.parser.parsers; + if (inner === ']-') { + inner = '\\]\\-'; + } - // register nanomatch parsers - snapdragon.use(nanomatch.parsers); + if (negated && inner.indexOf('.') === -1) { + inner += '.'; + } + if (negated && inner.indexOf('/') === -1) { + inner += '/'; + } - // get references to some specific nanomatch parsers before they - // are overridden by the extglob and/or parsers - var escape = parsers.escape; - var slash = parsers.slash; - var qmark = parsers.qmark; - var plus = parsers.plus; - var star = parsers.star; - var dot = parsers.dot; + val = open + negated + inner + close; + return this.emit(val, node); + }) - // register extglob parsers - snapdragon.use(extglob.parsers); + /** + * Square: "[.]" (only matches a single character in brackets) + */ - // custom micromatch parsers - snapdragon.parser - .use(function() { - // override "notRegex" created in nanomatch parser - this.notRegex = /^\!+(?!\()/; + .set('square', function(node) { + var val = (/^\W/.test(node.val) ? '\\' : '') + node.val; + return this.emit(val, node); }) - // reset the referenced parsers - .capture('escape', escape) - .capture('slash', slash) - .capture('qmark', qmark) - .capture('star', star) - .capture('plus', plus) - .capture('dot', dot) /** - * Override `text` parser + * Question mark: "?" */ - .capture('text', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(createNotRegex(this.options)); - if (!m || !m[0]) return; + .set('qmark', function(node) { + var prev = this.prev(); + // don't use "slash" variable so that we always avoid + // matching backslashes and slashes with a qmark + var val = '[^.\\\\/]'; + if (this.options.dot || (prev.type !== 'bos' && prev.type !== 'slash')) { + val = '[^\\\\/]'; + } - // escape regex boundary characters and simple brackets - var val = m[0].replace(/([[\]^$])/g, '\\$1'); + if (node.parsed.slice(-1) === '(') { + var ch = node.rest.charAt(0); + if (ch === '!' || ch === '=' || ch === ':') { + return this.emit(node.val, node); + } + } - return pos({ - type: 'text', - val: val - }); - }); -}; + if (node.val.length > 1) { + val += '{' + node.val.length + '}'; + } + return this.emit(val, node); + }) -/** - * Create text regex - */ + /** + * Plus + */ -function textRegex(pattern) { - var notStr = regexNot.create(pattern, {contains: true, strictClose: false}); - var prefix = '(?:[\\^]|\\\\|'; - return toRegex(prefix + notStr + ')', {strictClose: false}); -} + .set('plus', function(node) { + var prev = node.parsed.slice(-1); + if (prev === ']' || prev === ')') { + return this.emit(node.val, node); + } + if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) { + return this.emit('\\+', node); + } + var ch = this.output.slice(-1); + if (/\w/.test(ch) && !node.inside) { + return this.emit('+\\+?', node); + } + return this.emit('+', node); + }) + /** + * globstar: '**' + */ -/***/ }), + .set('globstar', function(node, nodes, i) { + if (!this.output) { + this.state.leadingGlobstar = true; + } -/***/ 63976: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + var prev = this.prev(); + var before = this.prev(2); + var next = this.next(); + var after = this.next(2); + var type = prev.type; + var val = node.val; -"use strict"; + if (prev.type === 'slash' && next.type === 'slash') { + if (before.type === 'text') { + this.output += '?'; + if (after.type !== 'text') { + this.output += '\\b'; + } + } + } -var utils = module.exports; -var path = __webpack_require__(85622); + var parsed = node.parsed; + if (parsed.charAt(0) === '!') { + parsed = parsed.slice(1); + } -/** - * Module dependencies - */ + var isInside = node.isInside.paren || node.isInside.brace; + if (parsed && type !== 'slash' && type !== 'bos' && !isInside) { + val = star(); + } else { + val = this.options.dot !== true + ? '(?:(?!(?:[' + slash() + ']|^)\\.).)*?' + : '(?:(?!(?:[' + slash() + ']|^)(?:\\.{1,2})($|[' + slash() + ']))(?!\\.{2}).)*?'; + } -var Snapdragon = __webpack_require__(79285); -utils.define = __webpack_require__(35851); -utils.diff = __webpack_require__(9455); -utils.extend = __webpack_require__(3767); -utils.pick = __webpack_require__(38509); -utils.typeOf = __webpack_require__(19613); -utils.unique = __webpack_require__(19009); + if ((type === 'slash' || type === 'bos') && this.options.dot !== true) { + val = '(?!\\.)' + val; + } -/** - * Returns true if the platform is windows, or `path.sep` is `\\`. - * This is defined as a function to allow `path.sep` to be set in unit tests, - * or by the user, if there is a reason to do so. - * @return {Boolean} - */ + if (prev.type === 'slash' && next.type === 'slash' && before.type !== 'text') { + if (after.type === 'text' || after.type === 'star') { + node.addQmark = true; + } + } -utils.isWindows = function() { - return path.sep === '\\' || process.platform === 'win32'; -}; + if (this.options.capture) { + val = '(' + val + ')'; + } -/** - * Get the `Snapdragon` instance to use - */ + return this.emit(val, node); + }) -utils.instantiate = function(ast, options) { - var snapdragon; - // if an instance was created by `.parse`, use that instance - if (utils.typeOf(ast) === 'object' && ast.snapdragon) { - snapdragon = ast.snapdragon; - // if the user supplies an instance on options, use that instance - } else if (utils.typeOf(options) === 'object' && options.snapdragon) { - snapdragon = options.snapdragon; - // create a new instance - } else { - snapdragon = new Snapdragon(options); - } + /** + * Star: "*" + */ - utils.define(snapdragon, 'parse', function(str, options) { - var parsed = Snapdragon.prototype.parse.apply(this, arguments); - parsed.input = str; + .set('star', function(node, nodes, i) { + var prior = nodes[i - 2] || {}; + var prev = this.prev(); + var next = this.next(); + var type = prev.type; - // escape unmatched brace/bracket/parens - var last = this.parser.stack.pop(); - if (last && this.options.strictErrors !== true) { - var open = last.nodes[0]; - var inner = last.nodes[1]; - if (last.type === 'bracket') { - if (inner.val.charAt(0) === '[') { - inner.val = '\\' + inner.val; + function isStart(n) { + return n.type === 'bos' || n.type === 'slash'; + } + + if (this.output === '' && this.options.contains !== true) { + this.output = '(?![' + slash() + '])'; + } + + if (type === 'bracket' && this.options.bash === false) { + var str = next && next.type === 'bracket' ? star() : '*?'; + if (!prev.nodes || prev.nodes[1].type !== 'posix') { + return this.emit(str, node); } + } - } else { - open.val = '\\' + open.val; - var sibling = open.parent.nodes[1]; - if (sibling.type === 'star') { - sibling.loose = true; + var prefix = !this.dotfiles && type !== 'text' && type !== 'escape' + ? (this.options.dot ? '(?!(?:^|[' + slash() + '])\\.{1,2}(?:$|[' + slash() + ']))' : '(?!\\.)') + : ''; + + if (isStart(prev) || (isStart(prior) && type === 'not')) { + if (prefix !== '(?!\\.)') { + prefix += '(?!(\\.{2}|\\.[' + slash() + ']))(?=.)'; + } else { + prefix += '(?=.)'; } + } else if (prefix === '(?!\\.)') { + prefix = ''; } - } - // add non-enumerable parser reference - utils.define(parsed, 'parser', this.parser); - return parsed; - }); + if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) { + this.output = '(?!\\.)' + this.output; + } - return snapdragon; -}; + var output = prefix + star(); + if (this.options.capture) { + output = '(' + output + ')'; + } -/** - * Create the key to use for memoization. The key is generated - * by iterating over the options and concatenating key-value pairs - * to the pattern string. - */ - -utils.createKey = function(pattern, options) { - if (utils.typeOf(options) !== 'object') { - return pattern; - } - var val = pattern; - var keys = Object.keys(options); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - val += ';' + key + '=' + String(options[key]); - } - return val; -}; + return this.emit(output, node); + }) -/** - * Cast `val` to an array - * @return {Array} - */ + /** + * Text + */ -utils.arrayify = function(val) { - if (typeof val === 'string') return [val]; - return val ? (Array.isArray(val) ? val : [val]) : []; -}; + .set('text', function(node) { + return this.emit(node.val, node); + }) -/** - * Return true if `val` is a non-empty string - */ + /** + * End-of-string + */ -utils.isString = function(val) { - return typeof val === 'string'; -}; + .set('eos', function(node) { + var prev = this.prev(); + var val = node.val; -/** - * Return true if `val` is a non-empty string - */ + this.output = '(?:\\.[' + slash() + '](?=.))?' + this.output; + if (this.state.metachar && prev.type !== 'qmark' && prev.type !== 'slash') { + val += (this.options.contains ? '[' + slash() + ']?' : '(?:[' + slash() + ']|$)'); + } -utils.isObject = function(val) { - return utils.typeOf(val) === 'object'; -}; + return this.emit(val, node); + }); -/** - * Returns true if the given `str` has special characters - */ + /** + * Allow custom compilers to be passed on options + */ -utils.hasSpecialChars = function(str) { - return /(?:(?:(^|\/)[!.])|[*?+()|\[\]{}]|[+@]\()/.test(str); + if (options && typeof options.compilers === 'function') { + options.compilers(nanomatch.compiler); + } }; -/** - * Escape regex characters in the given string - */ - -utils.escapeRegex = function(str) { - return str.replace(/[-[\]{}()^$|*+?.\\\/\s]/g, '\\$&'); -}; -/** - * Normalize slashes in the given filepath. - * - * @param {String} `filepath` - * @return {String} - */ -utils.toPosixPath = function(str) { - return str.replace(/\\+/g, '/'); -}; +/***/ }), -/** - * Strip backslashes before special characters in a string. - * - * @param {String} `str` - * @return {String} - */ +/***/ 5333: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -utils.unescape = function(str) { - return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); -}; +"use strict"; -/** - * Strip the prefix from a filepath - * @param {String} `fp` - * @return {String} - */ -utils.stripPrefix = function(str) { - if (str.charAt(0) !== '.') { - return str; - } - var ch = str.charAt(1); - if (utils.isSlash(ch)) { - return str.slice(2); - } - return str; -}; +var regexNot = __webpack_require__(30931); +var toRegex = __webpack_require__(51279); /** - * Returns true if the given str is an escaped or - * unescaped path character + * Characters to use in negation regex (we want to "not" match + * characters that are matched by other parsers) */ -utils.isSlash = function(str) { - return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; -}; +var cached; +var NOT_REGEX = '[\\[!*+?$^"\'.\\\\/]+'; +var not = createTextRegex(NOT_REGEX); /** - * Returns a function that returns true if the given - * pattern matches or contains a `filepath` - * - * @param {String} `pattern` - * @return {Function} + * Nanomatch parsers */ -utils.matchPath = function(pattern, options) { - return (options && options.contains) - ? utils.containsPattern(pattern, options) - : utils.equalsPattern(pattern, options); -}; +module.exports = function(nanomatch, options) { + var parser = nanomatch.parser; + var opts = parser.options; -/** - * Returns true if the given (original) filepath or unixified path are equal - * to the given pattern. - */ + parser.state = { + slashes: 0, + paths: [] + }; -utils._equals = function(filepath, unixPath, pattern) { - return pattern === filepath || pattern === unixPath; -}; + parser.ast.state = parser.state; + parser -/** - * Returns true if the given (original) filepath or unixified path contain - * the given pattern. - */ + /** + * Beginning-of-string + */ -utils._contains = function(filepath, unixPath, pattern) { - return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; -}; + .capture('prefix', function() { + if (this.parsed) return; + var m = this.match(/^\.[\\/]/); + if (!m) return; + this.state.strictOpen = !!this.options.strictOpen; + this.state.addPrefix = true; + }) -/** - * Returns a function that returns true if the given - * pattern is the same as a given `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ + /** + * Escape: "\\." + */ -utils.equalsPattern = function(pattern, options) { - var unixify = utils.unixify(options); - options = options || {}; + .capture('escape', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^(?:\\(.)|([$^]))/); + if (!m) return; - return function fn(filepath) { - var equal = utils._equals(filepath, unixify(filepath), pattern); - if (equal === true || options.nocase !== true) { - return equal; - } - var lower = filepath.toLowerCase(); - return utils._equals(lower, unixify(lower), pattern); - }; -}; + return pos({ + type: 'escape', + val: m[2] || m[1] + }); + }) -/** - * Returns a function that returns true if the given - * pattern contains a `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ + /** + * Quoted strings + */ -utils.containsPattern = function(pattern, options) { - var unixify = utils.unixify(options); - options = options || {}; + .capture('quoted', function() { + var pos = this.position(); + var m = this.match(/^["']/); + if (!m) return; - return function(filepath) { - var contains = utils._contains(filepath, unixify(filepath), pattern); - if (contains === true || options.nocase !== true) { - return contains; - } - var lower = filepath.toLowerCase(); - return utils._contains(lower, unixify(lower), pattern); - }; -}; + var quote = m[0]; + if (this.input.indexOf(quote) === -1) { + return pos({ + type: 'escape', + val: quote + }); + } -/** - * Returns a function that returns true if the given - * regex matches the `filename` of a file path. - * - * @param {RegExp} `re` Matching regex - * @return {Function} - */ + var tok = advanceTo(this.input, quote); + this.consume(tok.len); -utils.matchBasename = function(re) { - return function(filepath) { - return re.test(path.basename(filepath)); - }; -}; + return pos({ + type: 'quoted', + val: tok.esc + }); + }) -/** - * Determines the filepath to return based on the provided options. - * @return {any} - */ + /** + * Negations: "!" + */ -utils.value = function(str, unixify, options) { - if (options && options.unixify === false) { - return str; - } - return unixify(str); -}; + .capture('not', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(this.notRegex || /^!+/); + if (!m) return; + var val = m[0]; -/** - * Returns a function that normalizes slashes in a string to forward - * slashes, strips `./` from beginning of paths, and optionally unescapes - * special characters. - * @return {Function} - */ + var isNegated = (val.length % 2) === 1; + if (parsed === '' && !isNegated) { + val = ''; + } -utils.unixify = function(options) { - options = options || {}; - return function(filepath) { - if (utils.isWindows() || options.unixify === true) { - filepath = utils.toPosixPath(filepath); - } - if (options.stripPrefix !== false) { - filepath = utils.stripPrefix(filepath); - } - if (options.unescape === true) { - filepath = utils.unescape(filepath); - } - return filepath; - }; -}; + // if nothing has been parsed, we know `!` is at the start, + // so we need to wrap the result in a negation regex + if (parsed === '' && isNegated && this.options.nonegate !== true) { + this.bos.val = '(?!^(?:'; + this.append = ')$).*'; + val = ''; + } + return pos({ + type: 'not', + val: val + }); + }) + /** + * Dot: "." + */ -/***/ }), + .capture('dot', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\.+/); + if (!m) return; -/***/ 50559: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + var val = m[0]; + this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/'); -"use strict"; + return pos({ + type: 'dot', + dotfiles: this.state.dot, + val: val + }); + }) + /** + * Plus: "+" + */ -/** - * Module dependencies - */ + .capture('plus', /^\+(?!\()/) -var toRegex = __webpack_require__(51279); -var unique = __webpack_require__(19009); -var extend = __webpack_require__(92845); + /** + * Question mark: "?" + */ -/** - * Local dependencies - */ + .capture('qmark', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\?+(?!\()/); + if (!m) return; -var compilers = __webpack_require__(90808); -var parsers = __webpack_require__(46362); -var Braces = __webpack_require__(12638); -var utils = __webpack_require__(38640); -var MAX_LENGTH = 1024 * 64; -var cache = {}; + this.state.metachar = true; + this.state.qmark = true; -/** - * Convert the given `braces` pattern into a regex-compatible string. By default, only one string is generated for every input string. Set `options.expand` to true to return an array of patterns (similar to Bash or minimatch. Before using `options.expand`, it's recommended that you read the [performance notes](#performance)). - * - * ```js - * var braces = require('braces'); - * console.log(braces('{a,b,c}')); - * //=> ['(a|b|c)'] - * - * console.log(braces('{a,b,c}', {expand: true})); - * //=> ['a', 'b', 'c'] - * ``` - * @param {String} `str` - * @param {Object} `options` - * @return {String} - * @api public - */ + return pos({ + type: 'qmark', + parsed: parsed, + val: m[0] + }); + }) -function braces(pattern, options) { - var key = utils.createKey(String(pattern), options); - var arr = []; + /** + * Globstar: "**" + */ - var disabled = options && options.cache === false; - if (!disabled && cache.hasOwnProperty(key)) { - return cache[key]; - } + .capture('globstar', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\*{2}(?![*(])(?=[,)/]|$)/); + if (!m) return; - if (Array.isArray(pattern)) { - for (var i = 0; i < pattern.length; i++) { - arr.push.apply(arr, braces.create(pattern[i], options)); - } - } else { - arr = braces.create(pattern, options); - } + var type = opts.noglobstar !== true ? 'globstar' : 'star'; + var node = pos({type: type, parsed: parsed}); + this.state.metachar = true; - if (options && options.nodupes === true) { - arr = unique(arr); - } + while (this.input.slice(0, 4) === '/**/') { + this.input = this.input.slice(3); + } - if (!disabled) { - cache[key] = arr; - } - return arr; -} + node.isInside = { + brace: this.isInside('brace'), + paren: this.isInside('paren') + }; -/** - * Expands a brace pattern into an array. This method is called by the main [braces](#braces) function when `options.expand` is true. Before using this method it's recommended that you read the [performance notes](#performance)) and advantages of using [.optimize](#optimize) instead. - * - * ```js - * var braces = require('braces'); - * console.log(braces.expand('a/{b,c}/d')); - * //=> ['a/b/d', 'a/c/d']; - * ``` - * @param {String} `pattern` Brace pattern - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ + if (type === 'globstar') { + this.state.globstar = true; + node.val = '**'; -braces.expand = function(pattern, options) { - return braces.create(pattern, extend({}, options, {expand: true})); -}; + } else { + this.state.star = true; + node.val = '*'; + } -/** - * Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default. - * - * ```js - * var braces = require('braces'); - * console.log(braces.expand('a/{b,c}/d')); - * //=> ['a/(b|c)/d'] - * ``` - * @param {String} `pattern` Brace pattern - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ + return node; + }) -braces.optimize = function(pattern, options) { - return braces.create(pattern, options); -}; + /** + * Star: "*" + */ -/** - * Processes a brace pattern and returns either an expanded array (if `options.expand` is true), a highly optimized regex-compatible string. This method is called by the main [braces](#braces) function. - * - * ```js - * var braces = require('braces'); - * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) - * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' - * ``` - * @param {String} `pattern` Brace pattern - * @param {Object} `options` - * @return {Array} Returns an array of expanded values. - * @api public - */ + .capture('star', function() { + var pos = this.position(); + var starRe = /^(?:\*(?![*(])|[*]{3,}(?!\()|[*]{2}(?![(/]|$)|\*(?=\*\())/; + var m = this.match(starRe); + if (!m) return; -braces.create = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); - } + this.state.metachar = true; + this.state.star = true; + return pos({ + type: 'star', + val: m[0] + }); + }) - var maxLength = (options && options.maxLength) || MAX_LENGTH; - if (pattern.length >= maxLength) { - throw new Error('expected pattern to be less than ' + maxLength + ' characters'); - } + /** + * Slash: "/" + */ - function create() { - if (pattern === '' || pattern.length < 3) { - return [pattern]; - } + .capture('slash', function() { + var pos = this.position(); + var m = this.match(/^\//); + if (!m) return; - if (utils.isEmptySets(pattern)) { - return []; - } + this.state.slashes++; + return pos({ + type: 'slash', + val: m[0] + }); + }) - if (utils.isQuotedString(pattern)) { - return [pattern.slice(1, -1)]; - } + /** + * Backslash: "\\" + */ - var proto = new Braces(options); - var result = !options || options.expand !== true - ? proto.optimize(pattern, options) - : proto.expand(pattern, options); + .capture('backslash', function() { + var pos = this.position(); + var m = this.match(/^\\(?![*+?(){}[\]'"])/); + if (!m) return; - // get the generated pattern(s) - var arr = result.output; + var val = m[0]; - // filter out empty strings if specified - if (options && options.noempty === true) { - arr = arr.filter(Boolean); - } + if (this.isInside('bracket')) { + val = '\\'; + } else if (val.length > 1) { + val = '\\\\'; + } - // filter out duplicates if specified - if (options && options.nodupes === true) { - arr = unique(arr); - } + return pos({ + type: 'backslash', + val: val + }); + }) - Object.defineProperty(arr, 'result', { - enumerable: false, - value: result - }); + /** + * Square: "[.]" + */ - return arr; - } + .capture('square', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^\[([^!^\\])\]/); + if (!m) return; - return memoize('create', pattern, options, create); -}; + return pos({ + type: 'square', + val: m[1] + }); + }) -/** - * Create a regular expression from the given string `pattern`. - * - * ```js - * var braces = require('braces'); - * - * console.log(braces.makeRe('id-{200..300}')); - * //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/ - * ``` - * @param {String} `pattern` The pattern to convert to regex. - * @param {Object} `options` - * @return {RegExp} - * @api public - */ + /** + * Brackets: "[...]" (basic, this can be overridden by other parsers) + */ -braces.makeRe = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); - } + .capture('bracket', function() { + var pos = this.position(); + var m = this.match(/^(?:\[([!^]?)([^\]]+|\]-)(\]|[^*+?]+)|\[)/); + if (!m) return; - var maxLength = (options && options.maxLength) || MAX_LENGTH; - if (pattern.length >= maxLength) { - throw new Error('expected pattern to be less than ' + maxLength + ' characters'); - } + var val = m[0]; + var negated = m[1] ? '^' : ''; + var inner = (m[2] || '').replace(/\\\\+/, '\\\\'); + var close = m[3] || ''; - function makeRe() { - var arr = braces(pattern, options); - var opts = extend({strictErrors: false}, options); - return toRegex(arr, opts); - } + if (m[2] && inner.length < m[2].length) { + val = val.replace(/\\\\+/, '\\\\'); + } - return memoize('makeRe', pattern, options, makeRe); -}; + var esc = this.input.slice(0, 2); + if (inner === '' && esc === '\\]') { + inner += esc; + this.consume(2); -/** - * Parse the given `str` with the given `options`. - * - * ```js - * var braces = require('braces'); - * var ast = braces.parse('a/{b,c}/d'); - * console.log(ast); - * // { type: 'root', - * // errors: [], - * // input: 'a/{b,c}/d', - * // nodes: - * // [ { type: 'bos', val: '' }, - * // { type: 'text', val: 'a/' }, - * // { type: 'brace', - * // nodes: - * // [ { type: 'brace.open', val: '{' }, - * // { type: 'text', val: 'b,c' }, - * // { type: 'brace.close', val: '}' } ] }, - * // { type: 'text', val: '/d' }, - * // { type: 'eos', val: '' } ] } - * ``` - * @param {String} `pattern` Brace pattern to parse - * @param {Object} `options` - * @return {Object} Returns an AST - * @api public - */ + var str = this.input; + var idx = -1; + var ch; -braces.parse = function(pattern, options) { - var proto = new Braces(options); - return proto.parse(pattern, options); -}; + while ((ch = str[++idx])) { + this.consume(1); + if (ch === ']') { + close = ch; + break; + } + inner += ch; + } + } -/** - * Compile the given `ast` or string with the given `options`. - * - * ```js - * var braces = require('braces'); - * var ast = braces.parse('a/{b,c}/d'); - * console.log(braces.compile(ast)); - * // { options: { source: 'string' }, - * // state: {}, - * // compilers: - * // { eos: [Function], - * // noop: [Function], - * // bos: [Function], - * // brace: [Function], - * // 'brace.open': [Function], - * // text: [Function], - * // 'brace.close': [Function] }, - * // output: [ 'a/(b|c)/d' ], - * // ast: - * // { ... }, - * // parsingErrors: [] } - * ``` - * @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first. - * @param {Object} `options` - * @return {Object} Returns an object that has an `output` property with the compiled string. - * @api public - */ + return pos({ + type: 'bracket', + val: val, + escaped: close !== ']', + negated: negated, + inner: inner, + close: close + }); + }) -braces.compile = function(ast, options) { - var proto = new Braces(options); - return proto.compile(ast, options); -}; + /** + * Text + */ -/** - * Clear the regex cache. - * - * ```js - * braces.clearCache(); - * ``` - * @api public - */ + .capture('text', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(not); + if (!m || !m[0]) return; -braces.clearCache = function() { - cache = braces.cache = {}; + return pos({ + type: 'text', + val: m[0] + }); + }); + + /** + * Allow custom parsers to be passed on options + */ + + if (options && typeof options.parsers === 'function') { + options.parsers(nanomatch.parser); + } }; /** - * Memoize a generated regex or function. A unique key is generated - * from the method name, pattern, and user-defined options. Set - * options.memoize to false to disable. + * Advance to the next non-escaped character */ -function memoize(type, pattern, options, fn) { - var key = utils.createKey(type + ':' + pattern, options); - var disabled = options && options.cache === false; - if (disabled) { - braces.clearCache(); - return fn(pattern, options); - } +function advanceTo(input, endChar) { + var ch = input.charAt(0); + var tok = { len: 1, val: '', esc: '' }; + var idx = 0; - if (cache.hasOwnProperty(key)) { - return cache[key]; + function advance() { + if (ch !== '\\') { + tok.esc += '\\' + ch; + tok.val += ch; + } + + ch = input.charAt(++idx); + tok.len++; + + if (ch === '\\') { + advance(); + advance(); + } } - var res = fn(pattern, options); - cache[key] = res; - return res; + while (ch && ch !== endChar) { + advance(); + } + return tok; } /** - * Expose `Braces` constructor and methods - * @type {Function} + * Create text regex */ -braces.Braces = Braces; -braces.compilers = compilers; -braces.parsers = parsers; -braces.cache = cache; +function createTextRegex(pattern) { + if (cached) return cached; + var opts = {contains: true, strictClose: false}; + var not = regexNot.create(pattern, opts); + var re = toRegex('^(?:[*]\\((?=.)|' + not + ')', opts); + return (cached = re); +} /** - * Expose `braces` - * @type {Function} + * Expose negation string */ -module.exports = braces; +module.exports.not = NOT_REGEX; /***/ }), -/***/ 12638: +/***/ 41340: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -var extend = __webpack_require__(92845); +var utils = module.exports; +var path = __webpack_require__(85622); + +/** + * Module dependencies + */ + +var isWindows = __webpack_require__(8025)(); var Snapdragon = __webpack_require__(79285); -var compilers = __webpack_require__(90808); -var parsers = __webpack_require__(46362); -var utils = __webpack_require__(38640); +utils.define = __webpack_require__(18918); +utils.diff = __webpack_require__(9455); +utils.extend = __webpack_require__(69148); +utils.pick = __webpack_require__(38509); +utils.typeOf = __webpack_require__(42556); +utils.unique = __webpack_require__(19009); /** - * Customize Snapdragon parser and renderer + * Returns true if the given value is effectively an empty string */ -function Braces(options) { - this.options = extend({}, options); -} +utils.isEmptyString = function(val) { + return String(val) === '' || String(val) === './'; +}; /** - * Initialize braces + * Returns true if the platform is windows, or `path.sep` is `\\`. + * This is defined as a function to allow `path.sep` to be set in unit tests, + * or by the user, if there is a reason to do so. + * @return {Boolean} */ -Braces.prototype.init = function(options) { - if (this.isInitialized) return; - this.isInitialized = true; - var opts = utils.createOptions({}, this.options, options); - this.snapdragon = this.options.snapdragon || new Snapdragon(opts); - this.compiler = this.snapdragon.compiler; - this.parser = this.snapdragon.parser; +utils.isWindows = function() { + return path.sep === '\\' || isWindows === true; +}; - compilers(this.snapdragon, opts); - parsers(this.snapdragon, opts); +/** + * Return the last element from an array + */ - /** - * Call Snapdragon `.parse` method. When AST is returned, we check to - * see if any unclosed braces are left on the stack and, if so, we iterate - * over the stack and correct the AST so that compilers are called in the correct - * order and unbalance braces are properly escaped. - */ +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; - utils.define(this.snapdragon, 'parse', function(pattern, options) { - var parsed = Snapdragon.prototype.parse.apply(this, arguments); - this.parser.ast.input = pattern; +/** + * Get the `Snapdragon` instance to use + */ - var stack = this.parser.stack; - while (stack.length) { - addParent({type: 'brace.close', val: ''}, stack.pop()); - } +utils.instantiate = function(ast, options) { + var snapdragon; + // if an instance was created by `.parse`, use that instance + if (utils.typeOf(ast) === 'object' && ast.snapdragon) { + snapdragon = ast.snapdragon; + // if the user supplies an instance on options, use that instance + } else if (utils.typeOf(options) === 'object' && options.snapdragon) { + snapdragon = options.snapdragon; + // create a new instance + } else { + snapdragon = new Snapdragon(options); + } - function addParent(node, parent) { - utils.define(node, 'parent', parent); - parent.nodes.push(node); + utils.define(snapdragon, 'parse', function(str, options) { + var parsed = Snapdragon.prototype.parse.call(this, str, options); + parsed.input = str; + + // escape unmatched brace/bracket/parens + var last = this.parser.stack.pop(); + if (last && this.options.strictErrors !== true) { + var open = last.nodes[0]; + var inner = last.nodes[1]; + if (last.type === 'bracket') { + if (inner.val.charAt(0) === '[') { + inner.val = '\\' + inner.val; + } + + } else { + open.val = '\\' + open.val; + var sibling = open.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; + } + } } // add non-enumerable parser reference utils.define(parsed, 'parser', this.parser); return parsed; }); + + return snapdragon; }; /** - * Decorate `.parse` method + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. */ -Braces.prototype.parse = function(ast, options) { - if (ast && typeof ast === 'object' && ast.nodes) return ast; - this.init(options); - return this.snapdragon.parse(ast, options); +utils.createKey = function(pattern, options) { + if (typeof options === 'undefined') { + return pattern; + } + var key = pattern; + for (var prop in options) { + if (options.hasOwnProperty(prop)) { + key += ';' + prop + '=' + String(options[prop]); + } + } + return key; }; /** - * Decorate `.compile` method + * Cast `val` to an array + * @return {Array} */ -Braces.prototype.compile = function(ast, options) { - if (typeof ast === 'string') { - ast = this.parse(ast, options); - } else { - this.init(options); - } - return this.snapdragon.compile(ast, options); +utils.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; }; /** - * Expand + * Return true if `val` is a non-empty string */ -Braces.prototype.expand = function(pattern) { - var ast = this.parse(pattern, {expand: true}); - return this.compile(ast, {expand: true}); +utils.isString = function(val) { + return typeof val === 'string'; }; /** - * Optimize + * Return true if `val` is a non-empty string */ -Braces.prototype.optimize = function(pattern) { - var ast = this.parse(pattern, {optimize: true}); - return this.compile(ast, {optimize: true}); +utils.isRegex = function(val) { + return utils.typeOf(val) === 'regexp'; }; /** - * Expose `Braces` + * Return true if `val` is a non-empty string */ -module.exports = Braces; +utils.isObject = function(val) { + return utils.typeOf(val) === 'object'; +}; +/** + * Escape regex characters in the given string + */ -/***/ }), +utils.escapeRegex = function(str) { + return str.replace(/[-[\]{}()^$|*+?.\\/\s]/g, '\\$&'); +}; -/***/ 90808: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * Combines duplicate characters in the provided `input` string. + * @param {String} `input` + * @returns {String} + */ -"use strict"; +utils.combineDupes = function(input, patterns) { + patterns = utils.arrayify(patterns).join('|').split('|'); + patterns = patterns.map(function(s) { + return s.replace(/\\?([+*\\/])/g, '\\$1'); + }); + var substr = patterns.join('|'); + var regex = new RegExp('(' + substr + ')(?=\\1)', 'g'); + return input.replace(regex, ''); +}; +/** + * Returns true if the given `str` has special characters + */ -var utils = __webpack_require__(38640); +utils.hasSpecialChars = function(str) { + return /(?:(?:(^|\/)[!.])|[*?+()|[\]{}]|[+@]\()/.test(str); +}; -module.exports = function(braces, options) { - braces.compiler +/** + * Normalize slashes in the given filepath. + * + * @param {String} `filepath` + * @return {String} + */ - /** - * bos - */ +utils.toPosixPath = function(str) { + return str.replace(/\\+/g, '/'); +}; - .set('bos', function() { - if (this.output) return; - this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : []; - this.ast.count = 1; - }) +/** + * Strip backslashes before special characters in a string. + * + * @param {String} `str` + * @return {String} + */ - /** - * Square brackets - */ +utils.unescape = function(str) { + return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); +}; - .set('bracket', function(node) { - var close = node.close; - var open = !node.escaped ? '[' : '\\['; - var negated = node.negated; - var inner = node.inner; +/** + * Strip the drive letter from a windows filepath + * @param {String} `fp` + * @return {String} + */ - inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\'); - if (inner === ']-') { - inner = '\\]\\-'; - } +utils.stripDrive = function(fp) { + return utils.isWindows() ? fp.replace(/^[a-z]:[\\/]+?/i, '/') : fp; +}; - if (negated && inner.indexOf('.') === -1) { - inner += '.'; - } - if (negated && inner.indexOf('/') === -1) { - inner += '/'; - } +/** + * Strip the prefix from a filepath + * @param {String} `fp` + * @return {String} + */ - var val = open + negated + inner + close; - var queue = node.parent.queue; - var last = utils.arrayify(queue.pop()); +utils.stripPrefix = function(str) { + if (str.charAt(0) === '.' && (str.charAt(1) === '/' || str.charAt(1) === '\\')) { + return str.slice(2); + } + return str; +}; - queue.push(utils.join(last, val)); - queue.push.apply(queue, []); - }) +/** + * Returns true if `str` is a common character that doesn't need + * to be processed to be used for matching. + * @param {String} `str` + * @return {Boolean} + */ - /** - * Brace - */ +utils.isSimpleChar = function(str) { + return str.trim() === '' || str === '.'; +}; - .set('brace', function(node) { - node.queue = isEscaped(node) ? [node.val] : []; - node.count = 1; - return this.mapVisit(node.nodes); - }) +/** + * Returns true if the given str is an escaped or + * unescaped path character + */ - /** - * Open - */ +utils.isSlash = function(str) { + return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; +}; - .set('brace.open', function(node) { - node.parent.open = node.val; - }) +/** + * Returns a function that returns true if the given + * pattern matches or contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - /** - * Inner - */ +utils.matchPath = function(pattern, options) { + return (options && options.contains) + ? utils.containsPattern(pattern, options) + : utils.equalsPattern(pattern, options); +}; - .set('text', function(node) { - var queue = node.parent.queue; - var escaped = node.escaped; - var segs = [node.val]; +/** + * Returns true if the given (original) filepath or unixified path are equal + * to the given pattern. + */ - if (node.optimize === false) { - options = utils.extend({}, options, {optimize: false}); - } +utils._equals = function(filepath, unixPath, pattern) { + return pattern === filepath || pattern === unixPath; +}; - if (node.multiplier > 1) { - node.parent.count *= node.multiplier; - } +/** + * Returns true if the given (original) filepath or unixified path contain + * the given pattern. + */ - if (options.quantifiers === true && utils.isQuantifier(node.val)) { - escaped = true; +utils._contains = function(filepath, unixPath, pattern) { + return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; +}; - } else if (node.val.length > 1) { - if (isType(node.parent, 'brace') && !isEscaped(node)) { - var expanded = utils.expand(node.val, options); - segs = expanded.segs; +/** + * Returns a function that returns true if the given + * pattern is the same as a given `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - if (expanded.isOptimized) { - node.parent.isOptimized = true; - } +utils.equalsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; - // if nothing was expanded, we probably have a literal brace - if (!segs.length) { - var val = (expanded.val || node.val); - if (options.unescape !== false) { - // unescape unexpanded brace sequence/set separators - val = val.replace(/\\([,.])/g, '$1'); - // strip quotes - val = val.replace(/["'`]/g, ''); - } + return function fn(filepath) { + var equal = utils._equals(filepath, unixify(filepath), pattern); + if (equal === true || options.nocase !== true) { + return equal; + } + var lower = filepath.toLowerCase(); + return utils._equals(lower, unixify(lower), pattern); + }; +}; - segs = [val]; - escaped = true; - } - } +/** + * Returns a function that returns true if the given + * pattern contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - } else if (node.val === ',') { - if (options.expand) { - node.parent.queue.push(['']); - segs = ['']; - } else { - segs = ['|']; - } - } else { - escaped = true; - } +utils.containsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; - if (escaped && isType(node.parent, 'brace')) { - if (node.parent.nodes.length <= 4 && node.parent.count === 1) { - node.parent.escaped = true; - } else if (node.parent.length <= 3) { - node.parent.escaped = true; - } - } + return function(filepath) { + var contains = utils._contains(filepath, unixify(filepath), pattern); + if (contains === true || options.nocase !== true) { + return contains; + } + var lower = filepath.toLowerCase(); + return utils._contains(lower, unixify(lower), pattern); + }; +}; - if (!hasQueue(node.parent)) { - node.parent.queue = segs; - return; - } +/** + * Returns a function that returns true if the given + * regex matches the `filename` of a file path. + * + * @param {RegExp} `re` Matching regex + * @return {Function} + */ - var last = utils.arrayify(queue.pop()); - if (node.parent.count > 1 && options.expand) { - last = multiply(last, node.parent.count); - node.parent.count = 1; - } +utils.matchBasename = function(re) { + return function(filepath) { + return re.test(filepath) || re.test(path.basename(filepath)); + }; +}; - queue.push(utils.join(utils.flatten(last), segs.shift())); - queue.push.apply(queue, segs); - }) +/** + * Returns the given value unchanced. + * @return {any} + */ - /** - * Close - */ +utils.identity = function(val) { + return val; +}; - .set('brace.close', function(node) { - var queue = node.parent.queue; - var prev = node.parent.parent; - var last = prev.queue.pop(); - var open = node.parent.open; - var close = node.val; +/** + * Determines the filepath to return based on the provided options. + * @return {any} + */ - if (open && close && isOptimized(node, options)) { - open = '('; - close = ')'; - } +utils.value = function(str, unixify, options) { + if (options && options.unixify === false) { + return str; + } + if (options && typeof options.unixify === 'function') { + return options.unixify(str); + } + return unixify(str); +}; - // if a close brace exists, and the previous segment is one character - // don't wrap the result in braces or parens - var ele = utils.last(queue); - if (node.parent.count > 1 && options.expand) { - ele = multiply(queue.pop(), node.parent.count); - node.parent.count = 1; - queue.push(ele); - } +/** + * Returns a function that normalizes slashes in a string to forward + * slashes, strips `./` from beginning of paths, and optionally unescapes + * special characters. + * @return {Function} + */ - if (close && typeof ele === 'string' && ele.length === 1) { - open = ''; - close = ''; - } +utils.unixify = function(options) { + var opts = options || {}; + return function(filepath) { + if (opts.stripPrefix !== false) { + filepath = utils.stripPrefix(filepath); + } + if (opts.unescape === true) { + filepath = utils.unescape(filepath); + } + if (opts.unixify === true || utils.isWindows()) { + filepath = utils.toPosixPath(filepath); + } + return filepath; + }; +}; - if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) { - queue.push(utils.join(open, queue.pop() || '')); - queue = utils.flatten(utils.join(queue, close)); - } - if (typeof last === 'undefined') { - prev.queue = [queue]; - } else { - prev.queue.push(utils.flatten(utils.join(last, queue))); - } - }) +/***/ }), - /** - * eos - */ +/***/ 18918: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - .set('eos', function(node) { - if (this.input) return; +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015-2018, Jon Schlinkert. + * Released under the MIT License. + */ - if (options.optimize !== false) { - this.output = utils.last(utils.flatten(this.ast.queue)); - } else if (Array.isArray(utils.last(this.ast.queue))) { - this.output = utils.flatten(this.ast.queue.pop()); - } else { - this.output = utils.flatten(this.ast.queue); - } - if (node.parent.count > 1 && options.expand) { - this.output = multiply(this.output, node.parent.count); - } - this.output = utils.arrayify(this.output); - this.ast.queue = []; - }); +var isobject = __webpack_require__(96667); +var isDescriptor = __webpack_require__(44133); +var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) + ? Reflect.defineProperty + : Object.defineProperty; + +module.exports = function defineProperty(obj, key, val) { + if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { + throw new TypeError('expected an object, function, or array'); + } + + if (typeof key !== 'string') { + throw new TypeError('expected "key" to be a string'); + } + + if (isDescriptor(val)) { + define(obj, key, val); + return obj; + } + define(obj, key, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); + + return obj; }; -/** - * Multiply the segments in the current brace level - */ -function multiply(queue, n, options) { - return utils.flatten(utils.repeat(utils.arrayify(queue), n)); -} +/***/ }), -/** - * Return true if `node` is escaped - */ +/***/ 69148: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function isEscaped(node) { - return node.escaped === true; -} +"use strict"; -/** - * Returns true if regex parens should be used for sets. If the parent `type` - * is not `brace`, then we're on a root node, which means we should never - * expand segments and open/close braces should be `{}` (since this indicates - * a brace is missing from the set) - */ -function isOptimized(node, options) { - if (node.parent.isOptimized) return true; - return isType(node.parent, 'brace') - && !isEscaped(node.parent) - && options.expand !== true; -} +var isExtendable = __webpack_require__(61781); +var assignSymbols = __webpack_require__(64353); -/** - * Returns true if the value in `node` should be wrapped in a literal brace. - * @return {Boolean} - */ +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; +}; -function isLiteralBrace(node, options) { - return isEscaped(node.parent) || options.optimize !== false; +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } } -/** - * Returns true if the given `node` does not have an inner value. - * @return {Boolean} - */ +function isString(val) { + return (val && typeof val === 'string'); +} -function noInner(node, type) { - if (node.parent.queue.length === 1) { - return true; +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; } - var nodes = node.parent.nodes; - return nodes.length === 3 - && isType(nodes[0], 'brace.open') - && !isType(nodes[1], 'text') - && isType(nodes[2], 'brace.close'); + return obj; } -/** - * Returns true if the given `node` is the given `type` - * @return {Boolean} - */ - -function isType(node, type) { - return typeof node !== 'undefined' && node.type === type; +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); } /** - * Returns true if the given `node` has a non-empty queue. - * @return {Boolean} + * Returns true if the given `key` is an own property of `obj`. */ -function hasQueue(node) { - return Array.isArray(node.queue) && node.queue.length; +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); } /***/ }), -/***/ 46362: +/***/ 61781: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ -var Node = __webpack_require__(12579); -var utils = __webpack_require__(38640); - -/** - * Braces parsers - */ -module.exports = function(braces, options) { - braces.parser - .set('bos', function() { - if (!this.parsed) { - this.ast = this.nodes[0] = new Node(this.ast); - } - }) +var isPlainObject = __webpack_require__(81064); - /** - * Character parsers - */ +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; - .set('escape', function() { - var pos = this.position(); - var m = this.match(/^(?:\\(.)|\$\{)/); - if (!m) return; - var prev = this.prev(); - var last = utils.last(prev.nodes); +/***/ }), - var node = pos(new Node({ - type: 'text', - multiplier: 1, - val: m[0] - })); +/***/ 8025: +/***/ (function(module, exports) { - if (node.val === '\\\\') { - return node; - } +/*! + * is-windows + * + * Copyright © 2015-2018, Jon Schlinkert. + * Released under the MIT License. + */ - if (node.val === '${') { - var str = this.input; - var idx = -1; - var ch; +(function(factory) { + if (exports && typeof exports === 'object' && "object" !== 'undefined') { + module.exports = factory(); + } else if (typeof define === 'function' && define.amd) { + define([], factory); + } else if (typeof window !== 'undefined') { + window.isWindows = factory(); + } else if (typeof global !== 'undefined') { + global.isWindows = factory(); + } else if (typeof self !== 'undefined') { + self.isWindows = factory(); + } else { + this.isWindows = factory(); + } +})(function() { + 'use strict'; + return function isWindows() { + return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE)); + }; +}); - while ((ch = str[++idx])) { - this.consume(1); - node.val += ch; - if (ch === '\\') { - node.val += str[++idx]; - continue; - } - if (ch === '}') { - break; - } - } - } - if (this.options.unescape !== false) { - node.val = node.val.replace(/\\([{}])/g, '$1'); - } +/***/ }), - if (last.val === '"' && this.input.charAt(0) === '"') { - last.val = node.val; - this.consume(1); - return; - } +/***/ 42556: +/***/ (function(module) { - return concatNodes.call(this, pos, node, prev, options); - }) +var toString = Object.prototype.toString; - /** - * Brackets: "[...]" (basic, this is overridden by - * other parsers in more advanced implementations) - */ +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; - .set('bracket', function() { - var isInside = this.isInside('brace'); - var pos = this.position(); - var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]-)(\]|[^*+?]+)|\[)/); - if (!m) return; + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } - var prev = this.prev(); - var val = m[0]; - var negated = m[1] ? '^' : ''; - var inner = m[2] || ''; - var close = m[3] || ''; + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; - if (isInside && prev.type === 'brace') { - prev.text = prev.text || ''; - prev.text += val; - } + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; - var esc = this.input.slice(0, 2); - if (inner === '' && esc === '\\]') { - inner += esc; - this.consume(2); + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; - var str = this.input; - var idx = -1; - var ch; + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; - while ((ch = str[++idx])) { - this.consume(1); - if (ch === ']') { - close = ch; - break; - } - inner += ch; - } - } + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; - return pos(new Node({ - type: 'bracket', - val: val, - escaped: close !== ']', - negated: negated, - inner: inner, - close: close - })); - }) + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } - /** - * Empty braces (we capture these early to - * speed up processing in the compiler) - */ + if (isGeneratorObj(val)) { + return 'generator'; + } - .set('multiplier', function() { - var isInside = this.isInside('brace'); - var pos = this.position(); - var m = this.match(/^\{((?:,|\{,+\})+)\}/); - if (!m) return; + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } - this.multiplier = true; - var prev = this.prev(); - var val = m[0]; + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; - if (isInside && prev.type === 'brace') { - prev.text = prev.text || ''; - prev.text += val; - } +function ctorName(val) { + return typeof val.constructor === 'function' ? val.constructor.name : null; +} - var node = pos(new Node({ - type: 'text', - multiplier: 1, - match: m, - val: val - })); +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} - return concatNodes.call(this, pos, node, prev, options); - }) +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} - /** - * Open - */ +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} - .set('brace.open', function() { - var pos = this.position(); - var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/); - if (!m) return; +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} - var prev = this.prev(); - var last = utils.last(prev.nodes); +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} - // if the last parsed character was an extglob character - // we need to _not optimize_ the brace pattern because - // it might be mistaken for an extglob by a downstream parser - if (last && last.val && isExtglobChar(last.val.slice(-1))) { - last.optimize = false; - } +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} - var open = pos(new Node({ - type: 'brace.open', - val: m[0] - })); +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} - var node = pos(new Node({ - type: 'brace', - nodes: [] - })); +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ - node.push(open); - prev.push(node); - this.push('brace', node); - }) +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} - /** - * Close - */ - .set('brace.close', function() { - var pos = this.position(); - var m = this.match(/^\}/); - if (!m || !m[0]) return; +/***/ }), - var brace = this.pop('brace'); - var node = pos(new Node({ - type: 'brace.close', - val: m[0] - })); +/***/ 31368: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (!this.isType(brace, 'brace')) { - if (this.options.strict) { - throw new Error('missing opening "{"'); - } - node.type = 'text'; - node.multiplier = 0; - node.escaped = true; - return node; - } +"use strict"; - var prev = this.prev(); - var last = utils.last(prev.nodes); - if (last.text) { - var lastNode = utils.last(last.nodes); - if (lastNode.val === ')' && /[!@*?+]\(/.test(last.text)) { - var open = last.nodes[0]; - var text = last.nodes[1]; - if (open.type === 'brace.open' && text && text.type === 'text') { - text.optimize = false; - } - } - } - if (brace.nodes.length > 2) { - var first = brace.nodes[1]; - if (first.type === 'text' && first.val === ',') { - brace.nodes.splice(1, 1); - brace.nodes.push(first); - } - } +var typeOf = __webpack_require__(48865); +var copyDescriptor = __webpack_require__(3605); +var define = __webpack_require__(5477); - brace.push(node); - }) +/** + * Copy static properties, prototype properties, and descriptors from one object to another. + * + * ```js + * function App() {} + * var proto = App.prototype; + * App.prototype.set = function() {}; + * App.prototype.get = function() {}; + * + * var obj = {}; + * copy(obj, proto); + * ``` + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String|Array} `omit` One or more properties to omit + * @return {Object} + * @api public + */ - /** - * Capture boundary characters - */ +function copy(receiver, provider, omit) { + if (!isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); + } + if (!isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); + } - .set('boundary', function() { - var pos = this.position(); - var m = this.match(/^[$^](?!\{)/); - if (!m) return; - return pos(new Node({ - type: 'text', - val: m[0] - })); - }) + var props = nativeKeys(provider); + var keys = Object.keys(provider); + var len = props.length; + omit = arrayify(omit); - /** - * One or zero, non-comma characters wrapped in braces - */ + while (len--) { + var key = props[len]; - .set('nobrace', function() { - var isInside = this.isInside('brace'); - var pos = this.position(); - var m = this.match(/^\{[^,]?\}/); - if (!m) return; + if (has(keys, key)) { + define(receiver, key, provider[key]); + } else if (!(key in receiver) && !has(omit, key)) { + copyDescriptor(receiver, provider, key); + } + } +}; - var prev = this.prev(); - var val = m[0]; +/** + * Return true if the given value is an object or function + */ - if (isInside && prev.type === 'brace') { - prev.text = prev.text || ''; - prev.text += val; - } +function isObject(val) { + return typeOf(val) === 'object' || typeof val === 'function'; +} - return pos(new Node({ - type: 'text', - multiplier: 0, - val: val - })); - }) +/** + * Returns true if an array has any of the given elements, or an + * object has any of the give keys. + * + * ```js + * has(['a', 'b', 'c'], 'c'); + * //=> true + * + * has(['a', 'b', 'c'], ['c', 'z']); + * //=> true + * + * has({a: 'b', c: 'd'}, ['c', 'z']); + * //=> true + * ``` + * @param {Object} `obj` + * @param {String|Array} `val` + * @return {Boolean} + */ - /** - * Text - */ +function has(obj, val) { + val = arrayify(val); + var len = val.length; - .set('text', function() { - var isInside = this.isInside('brace'); - var pos = this.position(); - var m = this.match(/^((?!\\)[^${}[\]])+/); - if (!m) return; + if (isObject(obj)) { + for (var key in obj) { + if (val.indexOf(key) > -1) { + return true; + } + } - var prev = this.prev(); - var val = m[0]; + var keys = nativeKeys(obj); + return has(keys, val); + } - if (isInside && prev.type === 'brace') { - prev.text = prev.text || ''; - prev.text += val; + if (Array.isArray(obj)) { + var arr = obj; + while (len--) { + if (arr.indexOf(val[len]) > -1) { + return true; } + } + return false; + } - var node = pos(new Node({ - type: 'text', - multiplier: 1, - val: val - })); - - return concatNodes.call(this, pos, node, prev, options); - }); -}; + throw new TypeError('expected an array or object.'); +} /** - * Returns true if the character is an extglob character. + * Cast the given value to an array. + * + * ```js + * arrayify('foo'); + * //=> ['foo'] + * + * arrayify(['foo']); + * //=> ['foo'] + * ``` + * + * @param {String|Array} `val` + * @return {Array} */ -function isExtglobChar(ch) { - return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+'; +function arrayify(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; } /** - * Combine text nodes, and calculate empty sets (`{,,}`) - * @param {Function} `pos` Function to calculate node position - * @param {Object} `node` AST node - * @return {Object} + * Returns true if a value has a `contructor` + * + * ```js + * hasConstructor({}); + * //=> true + * + * hasConstructor(Object.create(null)); + * //=> false + * ``` + * @param {Object} `value` + * @return {Boolean} */ -function concatNodes(pos, node, parent, options) { - node.orig = node.val; - var prev = this.prev(); - var last = utils.last(prev.nodes); - var isEscaped = false; - - if (node.val.length > 1) { - var a = node.val.charAt(0); - var b = node.val.slice(-1); - - isEscaped = (a === '"' && b === '"') - || (a === "'" && b === "'") - || (a === '`' && b === '`'); - } +function hasConstructor(val) { + return isObject(val) && typeof val.constructor !== 'undefined'; +} - if (isEscaped && options.unescape !== false) { - node.val = node.val.slice(1, node.val.length - 1); - node.escaped = true; - } +/** + * Get the native `ownPropertyNames` from the constructor of the + * given `object`. An empty array is returned if the object does + * not have a constructor. + * + * ```js + * nativeKeys({a: 'b', b: 'c', c: 'd'}) + * //=> ['a', 'b', 'c'] + * + * nativeKeys(function(){}) + * //=> ['length', 'caller'] + * ``` + * + * @param {Object} `obj` Object that has a `constructor`. + * @return {Array} Array of keys. + */ - if (node.match) { - var match = node.match[1]; - if (!match || match.indexOf('}') === -1) { - match = node.match[0]; - } +function nativeKeys(val) { + if (!hasConstructor(val)) return []; + return Object.getOwnPropertyNames(val); +} - // replace each set with a single "," - var val = match.replace(/\{/g, ',').replace(/\}/g, ''); - node.multiplier *= val.length; - node.val = ''; - } +/** + * Expose `copy` + */ - var simpleText = last.type === 'text' - && last.multiplier === 1 - && node.multiplier === 1 - && node.val; +module.exports = copy; - if (simpleText) { - last.val += node.val; - return; - } +/** + * Expose `copy.has` for tests + */ - prev.push(node); -} +module.exports.has = has; /***/ }), -/***/ 38640: +/***/ 59248: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/*! + * object-visit + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ -var splitString = __webpack_require__(33218); -var utils = module.exports; -/** - * Module dependencies - */ +var isObject = __webpack_require__(96667); -utils.extend = __webpack_require__(92845); -utils.flatten = __webpack_require__(27299); -utils.isObject = __webpack_require__(96667); -utils.fillRange = __webpack_require__(82593); -utils.repeat = __webpack_require__(69523); -utils.unique = __webpack_require__(19009); +module.exports = function visit(thisArg, method, target, val) { + if (!isObject(thisArg) && typeof thisArg !== 'function') { + throw new Error('object-visit expects `thisArg` to be an object.'); + } -utils.define = function(obj, key, val) { - Object.defineProperty(obj, key, { - writable: true, - configurable: true, - enumerable: false, - value: val - }); -}; - -/** - * Returns true if the given string contains only empty brace sets. - */ - -utils.isEmptySets = function(str) { - return /^(?:\{,\})+$/.test(str); -}; - -/** - * Returns true if the given string contains only empty brace sets. - */ - -utils.isQuotedString = function(str) { - var open = str.charAt(0); - if (open === '\'' || open === '"' || open === '`') { - return str.slice(-1) === open; + if (typeof method !== 'string') { + throw new Error('object-visit expects `method` name to be a string'); } - return false; -}; - -/** - * Create the key to use for memoization. The unique key is generated - * by iterating over the options and concatenating key-value pairs - * to the pattern string. - */ -utils.createKey = function(pattern, options) { - var id = pattern; - if (typeof options === 'undefined') { - return id; - } - var keys = Object.keys(options); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - id += ';' + key + '=' + String(options[key]); + if (typeof thisArg[method] !== 'function') { + return thisArg; } - return id; -}; -/** - * Normalize options - */ + var args = [].slice.call(arguments, 3); + target = target || {}; -utils.createOptions = function(options) { - var opts = utils.extend.apply(null, arguments); - if (typeof opts.expand === 'boolean') { - opts.optimize = !opts.expand; - } - if (typeof opts.optimize === 'boolean') { - opts.expand = !opts.optimize; - } - if (opts.optimize === true) { - opts.makeRe = true; + for (var key in target) { + var arr = [key, target[key]].concat(args); + thisArg[method].apply(thisArg, arr); } - return opts; + return thisArg; }; -/** - * Join patterns in `a` to patterns in `b` - */ - -utils.join = function(a, b, options) { - options = options || {}; - a = utils.arrayify(a); - b = utils.arrayify(b); - - if (!a.length) return b; - if (!b.length) return a; - - var len = a.length; - var idx = -1; - var arr = []; - - while (++idx < len) { - var val = a[idx]; - if (Array.isArray(val)) { - for (var i = 0; i < val.length; i++) { - val[i] = utils.join(val[i], b, options); - } - arr.push(val); - continue; - } - - for (var j = 0; j < b.length; j++) { - var bval = b[j]; - - if (Array.isArray(bval)) { - arr.push(utils.join(val, bval, options)); - } else { - arr.push(val + bval); - } - } - } - return arr; -}; -/** - * Split the given string on `,` if not escaped. - */ +/***/ }), -utils.split = function(str, options) { - var opts = utils.extend({sep: ','}, options); - if (typeof opts.keepQuotes !== 'boolean') { - opts.keepQuotes = true; - } - if (opts.unescape === false) { - opts.keepEscaping = true; - } - return splitString(str, opts, utils.escapeBrackets(opts)); -}; +/***/ 38509: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * Expand ranges or sets in the given `pattern`. +"use strict"; +/*! + * object.pick * - * @param {String} `str` - * @param {Object} `options` - * @return {Object} + * Copyright (c) 2014-2015 Jon Schlinkert, contributors. + * Licensed under the MIT License */ -utils.expand = function(str, options) { - var opts = utils.extend({rangeLimit: 10000}, options); - var segs = utils.split(str, opts); - var tok = { segs: segs }; - - if (utils.isQuotedString(str)) { - return tok; - } - - if (opts.rangeLimit === true) { - opts.rangeLimit = 10000; - } - if (segs.length > 1) { - if (opts.optimize === false) { - tok.val = segs[0]; - return tok; - } - tok.segs = utils.stringifyArray(tok.segs); - } else if (segs.length === 1) { - var arr = str.split('..'); +var isObject = __webpack_require__(96667); - if (arr.length === 1) { - tok.val = tok.segs[tok.segs.length - 1] || tok.val || str; - tok.segs = []; - return tok; - } +module.exports = function pick(obj, keys) { + if (!isObject(obj) && typeof obj !== 'function') { + return {}; + } - if (arr.length === 2 && arr[0] === arr[1]) { - tok.escaped = true; - tok.val = arr[0]; - tok.segs = []; - return tok; + var res = {}; + if (typeof keys === 'string') { + if (keys in obj) { + res[keys] = obj[keys]; } + return res; + } - if (arr.length > 1) { - if (opts.optimize !== false) { - opts.optimize = true; - delete opts.expand; - } - - if (opts.optimize !== true) { - var min = Math.min(arr[0], arr[1]); - var max = Math.max(arr[0], arr[1]); - var step = arr[2] || 1; - - if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) { - throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); - } - } - - arr.push(opts); - tok.segs = utils.fillRange.apply(null, arr); - - if (!tok.segs.length) { - tok.escaped = true; - tok.val = str; - return tok; - } - - if (opts.optimize === true) { - tok.segs = utils.stringifyArray(tok.segs); - } + var len = keys.length; + var idx = -1; - if (tok.segs === '') { - tok.val = str; - } else { - tok.val = tok.segs[0]; - } - return tok; + while (++idx < len) { + var key = keys[idx]; + if (key in obj) { + res[key] = obj[key]; } - } else { - tok.val = str; } - return tok; + return res; }; -/** - * Ensure commas inside brackets and parens are not split. - * @param {Object} `tok` Token from the `split-string` module - * @return {undefined} - */ - -utils.escapeBrackets = function(options) { - return function(tok) { - if (tok.escaped && tok.val === 'b') { - tok.val = '\\b'; - return; - } - - if (tok.val !== '(' && tok.val !== '[') return; - var opts = utils.extend({}, options); - var brackets = []; - var parens = []; - var stack = []; - var val = tok.val; - var str = tok.str; - var i = tok.idx - 1; - - while (++i < str.length) { - var ch = str[i]; - - if (ch === '\\') { - val += (opts.keepEscaping === false ? '' : ch) + str[++i]; - continue; - } - - if (ch === '(') { - parens.push(ch); - stack.push(ch); - } - - if (ch === '[') { - brackets.push(ch); - stack.push(ch); - } - - if (ch === ')') { - parens.pop(); - stack.pop(); - if (!stack.length) { - val += ch; - break; - } - } - if (ch === ']') { - brackets.pop(); - stack.pop(); - if (!stack.length) { - val += ch; - break; - } - } - val += ch; - } +/***/ }), - tok.split = false; - tok.val = val.slice(1); - tok.idx = i; - }; -}; +/***/ 27255: +/***/ (function(module) { -/** - * Returns true if the given string looks like a regex quantifier - * @return {Boolean} +/*! + * pascalcase + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. */ -utils.isQuantifier = function(str) { - return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str); -}; +function pascalcase(str) { + if (typeof str !== 'string') { + throw new TypeError('expected a string.'); + } + str = str.replace(/([A-Z])/g, ' $1'); + if (str.length === 1) { return str.toUpperCase(); } + str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase(); + str = str.charAt(0).toUpperCase() + str.slice(1); + return str.replace(/[\W_]+(\w|$)/g, function (_, ch) { + return ch.toUpperCase(); + }); +} -/** - * Cast `val` to an array. - * @param {*} `val` - */ +module.exports = pascalcase; -utils.stringifyArray = function(arr) { - return [utils.arrayify(arr).join('|')]; -}; -/** - * Cast `val` to an array. - * @param {*} `val` - */ +/***/ }), -utils.arrayify = function(arr) { - if (typeof arr === 'undefined') { - return []; - } - if (typeof arr === 'string') { - return [arr]; - } - return arr; -}; +/***/ 88412: +/***/ (function(module) { -/** - * Returns true if the given `str` is a non-empty string - * @return {Boolean} - */ +"use strict"; -utils.isString = function(str) { - return str != null && typeof str === 'string'; -}; /** - * Get the last element from `array` - * @param {Array} `array` - * @return {*} + * POSIX character classes */ -utils.last = function(arr, n) { - return arr[arr.length - (n || 1)]; -}; - -utils.escapeRegex = function(str) { - return str.replace(/\\?([!^*?()[\]{}+?/])/g, '\\$1'); +module.exports = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' }; /***/ }), -/***/ 92845: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 58404: +/***/ (function(module) { "use strict"; -var isObject = __webpack_require__(4585); - -module.exports = function extend(o/*, objects*/) { - if (!isObject(o)) { o = {}; } - - var len = arguments.length; - for (var i = 1; i < len; i++) { - var obj = arguments[i]; +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process +} - if (isObject(obj)) { - assign(o, obj); - } +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); } - return o; -}; - -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); } } -/** - * Returns true if the given `key` is an own property of `obj`. - */ - -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} /***/ }), -/***/ 4585: +/***/ 59570: /***/ (function(module) { -"use strict"; /*! - * is-extendable - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + * prr + * (c) 2013 Rod Vagg + * https://github.com/rvagg/prr + * License: MIT + */ + +(function (name, context, definition) { + if ( true && module.exports) + module.exports = definition() + else + context[name] = definition() +})('prr', this, function() { + + var setProperty = typeof Object.defineProperty == 'function' + ? function (obj, key, options) { + Object.defineProperty(obj, key, options) + return obj + } + : function (obj, key, options) { // < es5 + obj[key] = options.value + return obj + } + + , makeOptions = function (value, options) { + var oo = typeof options == 'object' + , os = !oo && typeof options == 'string' + , op = function (p) { + return oo + ? !!options[p] + : os + ? options.indexOf(p[0]) > -1 + : false + } + + return { + enumerable : op('enumerable') + , configurable : op('configurable') + , writable : op('writable') + , value : value + } + } + , prr = function (obj, key, value, options) { + var k + options = makeOptions(value, options) -module.exports = function isExtendable(val) { - return typeof val !== 'undefined' && val !== null - && (typeof val === 'object' || typeof val === 'function'); -}; + if (typeof key == 'object') { + for (k in key) { + if (Object.hasOwnProperty.call(key, k)) { + options.value = key[k] + setProperty(obj, k, options) + } + } + return obj + } + + return setProperty(obj, key, options) + } + return prr +}) /***/ }), -/***/ 35851: +/***/ 79822: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/*! - * define-property - * - * Copyright (c) 2015-2018, Jon Schlinkert. - * Released under the MIT License. - */ +module.exports = __webpack_require__(76417).randomBytes +/***/ }), -var isobject = __webpack_require__(96667); -var isDescriptor = __webpack_require__(44133); -var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) - ? Reflect.defineProperty - : Object.defineProperty; +/***/ 42770: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -module.exports = function defineProperty(obj, key, val) { - if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { - throw new TypeError('expected an object, function, or array'); - } - - if (typeof key !== 'string') { - throw new TypeError('expected "key" to be a string'); - } +"use strict"; +// 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. - if (isDescriptor(val)) { - define(obj, key, val); - return obj; - } +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. - define(obj, key, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); - return obj; -}; +/**/ -/***/ }), +var pna = __webpack_require__(58404); +/**/ -/***/ 3767: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ -"use strict"; +module.exports = Duplex; +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ -var isExtendable = __webpack_require__(98775); -var assignSymbols = __webpack_require__(64353); +var Readable = __webpack_require__(79341); +var Writable = __webpack_require__(78063); -module.exports = Object.assign || function(obj/*, objects*/) { - if (obj === null || typeof obj === 'undefined') { - throw new TypeError('Cannot convert undefined or null to object'); - } - if (!isObject(obj)) { - obj = {}; - } - for (var i = 1; i < arguments.length; i++) { - var val = arguments[i]; - if (isString(val)) { - val = toObject(val); - } - if (isObject(val)) { - assign(obj, val); - assignSymbols(obj, val); - } - } - return obj; -}; +util.inherits(Duplex, Readable); -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } -function isString(val) { - return (val && typeof val === 'string'); +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); } -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; } - return obj; +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); } -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); +function onEndNT(self) { + self.end(); } -/** - * Returns true if the given `key` is an own property of `obj`. - */ +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); -} +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + pna.nextTick(cb, err); +}; /***/ }), -/***/ 82593: +/***/ 60143: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/*! - * fill-range - * - * Copyright (c) 2014-2015, 2017, Jon Schlinkert. - * Released under the MIT License. - */ - +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. -var util = __webpack_require__(31669); -var isNumber = __webpack_require__(87218); -var extend = __webpack_require__(13342); -var repeat = __webpack_require__(6332); -var toRegex = __webpack_require__(11846); -/** - * Return a range of numbers or letters. - * - * @param {String} `start` Start of the range - * @param {String} `stop` End of the range - * @param {String} `step` Increment or decrement to use. - * @param {Function} `fn` Custom function to modify each element in the range. - * @return {Array} - */ -function fillRange(start, stop, step, options) { - if (typeof start === 'undefined') { - return []; - } +module.exports = PassThrough; - if (typeof stop === 'undefined' || start === stop) { - // special case, for handling negative zero - var isString = typeof start === 'string'; - if (isNumber(start) && !toNumber(start)) { - return [isString ? '0' : 0]; - } - return [start]; - } +var Transform = __webpack_require__(62826); - if (typeof step !== 'number' && typeof step !== 'string') { - options = step; - step = undefined; - } +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ - if (typeof options === 'function') { - options = { transform: options }; - } +util.inherits(PassThrough, Transform); - var opts = extend({step: step}, options); - if (opts.step && !isValidNumber(opts.step)) { - if (opts.strictRanges === true) { - throw new TypeError('expected options.step to be a number'); - } - return []; - } +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); - opts.isNumber = isValidNumber(start) && isValidNumber(stop); - if (!opts.isNumber && !isValid(start, stop)) { - if (opts.strictRanges === true) { - throw new RangeError('invalid range arguments: ' + util.inspect([start, stop])); - } - return []; - } + Transform.call(this, options); +} - opts.isPadded = isPadded(start) || isPadded(stop); - opts.toString = opts.stringify - || typeof opts.step === 'string' - || typeof start === 'string' - || typeof stop === 'string' - || !opts.isNumber; +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; - if (opts.isPadded) { - opts.maxLength = Math.max(String(start).length, String(stop).length); - } +/***/ }), - // support legacy minimatch/fill-range options - if (typeof opts.optimize === 'boolean') opts.toRegex = opts.optimize; - if (typeof opts.makeRe === 'boolean') opts.toRegex = opts.makeRe; - return expand(start, stop, opts); -} +/***/ 79341: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function expand(start, stop, options) { - var a = options.isNumber ? toNumber(start) : start.charCodeAt(0); - var b = options.isNumber ? toNumber(stop) : stop.charCodeAt(0); +"use strict"; +// 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 step = Math.abs(toNumber(options.step)) || 1; - if (options.toRegex && step === 1) { - return toRange(a, b, start, stop, options); - } - var zero = {greater: [], lesser: []}; - var asc = a < b; - var arr = new Array(Math.round((asc ? b - a : a - b) / step)); - var idx = 0; - while (asc ? a <= b : a >= b) { - var val = options.isNumber ? a : String.fromCharCode(a); - if (options.toRegex && (val >= 0 || !options.isNumber)) { - zero.greater.push(val); - } else { - zero.lesser.push(Math.abs(val)); - } +/**/ - if (options.isPadded) { - val = zeros(val, options); - } +var pna = __webpack_require__(58404); +/**/ - if (options.toString) { - val = String(val); - } +module.exports = Readable; - if (typeof options.transform === 'function') { - arr[idx++] = options.transform(val, a, b, step, idx, arr, options); - } else { - arr[idx++] = val; - } +/**/ +var isArray = __webpack_require__(21352); +/**/ - if (asc) { - a += step; - } else { - a -= step; - } - } +/**/ +var Duplex; +/**/ - if (options.toRegex === true) { - return toSequence(arr, zero, options); - } - return arr; -} +Readable.ReadableState = ReadableState; -function toRange(a, b, start, stop, options) { - if (options.isPadded) { - return toRegex(start, stop, options); - } +/**/ +var EE = __webpack_require__(28614).EventEmitter; - if (options.isNumber) { - return toRegex(Math.min(a, b), Math.max(a, b), options); - } +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ - var start = String.fromCharCode(Math.min(a, b)); - var stop = String.fromCharCode(Math.max(a, b)); - return '[' + start + '-' + stop + ']'; -} +/**/ +var Stream = __webpack_require__(20681); +/**/ -function toSequence(arr, zeros, options) { - var greater = '', lesser = ''; - if (zeros.greater.length) { - greater = zeros.greater.join('|'); - } - if (zeros.lesser.length) { - lesser = '-(' + zeros.lesser.join('|') + ')'; - } - var res = greater && lesser - ? greater + '|' + lesser - : greater || lesser; +/**/ - if (options.capture) { - return '(' + res + ')'; - } - return res; +var Buffer = __webpack_require__(96788).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); } - -function zeros(val, options) { - if (options.isPadded) { - var str = String(val); - var len = str.length; - var dash = ''; - if (str.charAt(0) === '-') { - dash = '-'; - str = str.slice(1); - } - var diff = options.maxLength - len; - var pad = repeat('0', diff); - val = (dash + pad + str); - } - if (options.stringify) { - return String(val); - } - return val; +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } -function toNumber(val) { - return Number(val) || 0; -} +/**/ -function isPadded(str) { - return /^-?0\d/.test(str); -} +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ -function isValid(min, max) { - return (isValidNumber(min) || isValidLetter(min)) - && (isValidNumber(max) || isValidLetter(max)); +/**/ +var debugUtil = __webpack_require__(31669); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; } +/**/ -function isValidLetter(ch) { - return typeof ch === 'string' && ch.length === 1 && /^\w+$/.test(ch); -} +var BufferList = __webpack_require__(28878); +var destroyImpl = __webpack_require__(87915); +var StringDecoder; -function isValidNumber(n) { - return isNumber(n) && !/\./.test(n); -} +util.inherits(Readable, Stream); -/** - * Expose `fillRange` - * @type {Function} - */ +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; -module.exports = fillRange; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} -/***/ }), +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(42770); -/***/ 13342: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + options = options || {}; -"use strict"; + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; -var isObject = __webpack_require__(27244); + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; -module.exports = function extend(o/*, objects*/) { - if (!isObject(o)) { o = {}; } + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; - var len = arguments.length; - for (var i = 1; i < len; i++) { - var obj = arguments[i]; + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - if (isObject(obj)) { - assign(o, obj); - } - } - return o; -}; + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } - } -} + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; -/** - * Returns true if the given `key` is an own property of `obj`. - */ + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + // has it been destroyed + this.destroyed = false; -/***/ }), + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; -/***/ 27244: -/***/ (function(module) { + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = __webpack_require__(7395)/* .StringDecoder */ .s; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || __webpack_require__(42770); -module.exports = function isExtendable(val) { - return typeof val !== 'undefined' && val !== null - && (typeof val === 'object' || typeof val === 'function'); -}; + if (!(this instanceof Readable)) return new Readable(options); + this._readableState = new ReadableState(options, this); -/***/ }), + // legacy + this.readable = true; -/***/ 98775: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (options) { + if (typeof options.read === 'function') this._read = options.read; -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } -var isPlainObject = __webpack_require__(81064); + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); }; +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; -/***/ }), - -/***/ 19613: -/***/ (function(module) { - -var toString = Object.prototype.toString; - -module.exports = function kindOf(val) { - if (val === void 0) return 'undefined'; - if (val === null) return 'null'; - - var type = typeof val; - if (type === 'boolean') return 'boolean'; - if (type === 'string') return 'string'; - if (type === 'number') return 'number'; - if (type === 'symbol') return 'symbol'; - if (type === 'function') { - return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; } - if (isArray(val)) return 'array'; - if (isBuffer(val)) return 'buffer'; - if (isArguments(val)) return 'arguments'; - if (isDate(val)) return 'date'; - if (isError(val)) return 'error'; - if (isRegexp(val)) return 'regexp'; - - switch (ctorName(val)) { - case 'Symbol': return 'symbol'; - case 'Promise': return 'promise'; - - // Set, Map, WeakSet, WeakMap - case 'WeakMap': return 'weakmap'; - case 'WeakSet': return 'weakset'; - case 'Map': return 'map'; - case 'Set': return 'set'; - - // 8-bit typed arrays - case 'Int8Array': return 'int8array'; - case 'Uint8Array': return 'uint8array'; - case 'Uint8ClampedArray': return 'uint8clampedarray'; - - // 16-bit typed arrays - case 'Int16Array': return 'int16array'; - case 'Uint16Array': return 'uint16array'; + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; - // 32-bit typed arrays - case 'Int32Array': return 'int32array'; - case 'Uint32Array': return 'uint32array'; - case 'Float32Array': return 'float32array'; - case 'Float64Array': return 'float64array'; - } +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; - if (isGeneratorObj(val)) { - return 'generator'; - } +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } - // Non-plain objects - type = toString.call(val); - switch (type) { - case '[object Object]': return 'object'; - // iterators - case '[object Map Iterator]': return 'mapiterator'; - case '[object Set Iterator]': return 'setiterator'; - case '[object String Iterator]': return 'stringiterator'; - case '[object Array Iterator]': return 'arrayiterator'; + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } } - // other - return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); -}; - -function ctorName(val) { - return typeof val.constructor === 'function' ? val.constructor.name : null; + return needMoreData(state); } -function isArray(val) { - if (Array.isArray) return Array.isArray(val); - return val instanceof Array; -} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); -function isError(val) { - return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); } -function isDate(val) { - if (val instanceof Date) return true; - return typeof val.toDateString === 'function' - && typeof val.getDate === 'function' - && typeof val.setDate === 'function'; +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; } -function isRegexp(val) { - if (val instanceof RegExp) return true; - return typeof val.flags === 'string' - && typeof val.ignoreCase === 'boolean' - && typeof val.multiline === 'boolean' - && typeof val.global === 'boolean'; +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } -function isGeneratorFn(name, val) { - return ctorName(name) === 'GeneratorFunction'; -} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; -function isGeneratorObj(val) { - return typeof val.throw === 'function' - && typeof val.return === 'function' - && typeof val.next === 'function'; -} +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __webpack_require__(7395)/* .StringDecoder */ .s; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; -function isArguments(val) { - try { - if (typeof val.length === 'number' && typeof val.callee === 'function') { - return true; - } - } catch (err) { - if (err.message.indexOf('callee') !== -1) { - return true; - } +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; } - return false; + return n; } -/** - * If you need to support Safari 5-7 (8-10 yr-old browser), - * take a look at https://github.com/feross/is-buffer - */ - -function isBuffer(val) { - if (val.constructor && typeof val.constructor.isBuffer === 'function') { - return val.constructor.isBuffer(val); +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } - return false; + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; } +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; -/***/ }), + if (n !== 0) state.emittedReadable = false; -/***/ 11846: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } -"use strict"; -/*! - * to-regex-range - * - * Copyright (c) 2015, 2017, Jon Schlinkert. - * Released under the MIT License. - */ + n = howMuchToRead(n, state); + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. -var repeat = __webpack_require__(6332); -var isNumber = __webpack_require__(87218); -var cache = {}; + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); -function toRegexRange(min, max, options) { - if (isNumber(min) === false) { - throw new RangeError('toRegexRange: first argument is invalid.'); + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); } - if (typeof max === 'undefined' || min === max) { - return String(min); + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); } - if (isNumber(max) === false) { - throw new RangeError('toRegexRange: second argument is invalid.'); - } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; - options = options || {}; - var relax = String(options.relaxZeros); - var shorthand = String(options.shorthand); - var capture = String(options.capture); - var key = min + ':' + max + '=' + relax + shorthand + capture; - if (cache.hasOwnProperty(key)) { - return cache[key].result; + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; } - var a = Math.min(min, max); - var b = Math.max(min, max); + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; - if (Math.abs(a - b) === 1) { - var result = min + '|' + max; - if (options.capture) { - return '(' + result + ')'; - } - return result; + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); } - var isPadded = padding(min) || padding(max); - var positives = []; - var negatives = []; - - var tok = {min: min, max: max, a: a, b: b}; - if (isPadded) { - tok.isPadded = isPadded; - tok.maxLen = String(tok.max).length; - } + if (ret !== null) this.emit('data', ret); - if (a < 0) { - var newMin = b < 0 ? Math.abs(b) : 1; - var newMax = Math.abs(a); - negatives = splitToPatterns(newMin, newMax, tok, options); - a = tok.a = 0; - } + return ret; +}; - if (b >= 0) { - positives = splitToPatterns(a, b, tok, options); +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } } + state.ended = true; - tok.negatives = negatives; - tok.positives = positives; - tok.result = siftPatterns(negatives, positives, options); + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} - if (options.capture && (positives.length + negatives.length) > 1) { - tok.result = '(' + tok.result + ')'; +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); } - - cache[key] = tok; - return tok.result; } -function siftPatterns(neg, pos, options) { - var onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; - var onlyPositive = filterPatterns(pos, neg, '', false, options) || []; - var intersected = filterPatterns(neg, pos, '-?', true, options) || []; - var subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); - return subpatterns.join('|'); +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); } -function splitToRanges(min, max) { - min = Number(min); - max = Number(max); - - var nines = 1; - var stops = [max]; - var stop = +countNines(min, nines); - - while (min <= stop && stop <= max) { - stops = push(stops, stop); - nines += 1; - stop = +countNines(min, nines); - } - - var zeros = 1; - stop = countZeros(max + 1, zeros) - 1; - - while (min < stop && stop <= max) { - stops = push(stops, stop); - zeros += 1; - stop = countZeros(max + 1, zeros) - 1; +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); } - - stops.sort(compare); - return stops; } -/** - * Convert a range to a regex pattern - * @param {Number} `start` - * @param {Number} `stop` - * @return {String} - */ - -function rangeToPattern(start, stop, options) { - if (start === stop) { - return {pattern: String(start), digits: []}; +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; } + state.readingMore = false; +} - var zipped = zip(String(start), String(stop)); - var len = zipped.length, i = -1; +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; - var pattern = ''; - var digits = 0; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; - while (++i < len) { - var numbers = zipped[i]; - var startDigit = numbers[0]; - var stopDigit = numbers[1]; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - if (startDigit === stopDigit) { - pattern += startDigit; + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - } else if (startDigit !== '0' || stopDigit !== '9') { - pattern += toCharacterClass(startDigit, stopDigit); + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); - } else { - digits += 1; + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } } } - if (digits) { - pattern += options.shorthand ? '\\d' : '[0-9]'; + function onend() { + debug('onend'); + dest.end(); } - return { pattern: pattern, digits: [digits] }; -} + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); -function splitToPatterns(min, max, tok, options) { - var ranges = splitToRanges(min, max); - var len = ranges.length; - var idx = -1; + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); - var tokens = []; - var start = min; - var prev; + cleanedUp = true; - while (++idx < len) { - var range = ranges[idx]; - var obj = rangeToPattern(start, range, options); - var zeros = ''; + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - if (!tok.isPadded && prev && prev.pattern === obj.pattern) { - if (prev.digits.length > 1) { - prev.digits.pop(); + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; } - prev.digits.push(obj.digits[0]); - prev.string = prev.pattern + toQuantifier(prev.digits); - start = range + 1; - continue; - } - - if (tok.isPadded) { - zeros = padZeros(range, tok); + src.pause(); } - - obj.string = zeros + obj.pattern + toQuantifier(obj.digits); - tokens.push(obj); - start = range + 1; - prev = obj; } - return tokens; -} - -function filterPatterns(arr, comparison, prefix, intersection, options) { - var res = []; - - for (var i = 0; i < arr.length; i++) { - var tok = arr[i]; - var ele = tok.string; - - if (options.relaxZeros !== false) { - if (prefix === '-' && ele.charAt(0) === '0') { - if (ele.charAt(1) === '{') { - ele = '0*' + ele.replace(/^0\{\d+\}/, ''); - } else { - ele = '0*' + ele.slice(1); - } - } - } + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } - if (!intersection && !contains(comparison, 'string', ele)) { - res.push(prefix + ele); - } + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); - if (intersection && contains(comparison, 'string', ele)) { - res.push(prefix + ele); - } + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - return res; -} + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); -/** - * Zip strings (`for in` can be used on string characters) - */ + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } -function zip(a, b) { - var arr = []; - for (var ch in a) arr.push([a[ch], b[ch]]); - return arr; -} + // tell the dest that it's being piped to + dest.emit('pipe', src); -function compare(a, b) { - return a > b ? 1 : b > a ? -1 : 0; -} + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } -function push(arr, ele) { - if (arr.indexOf(ele) === -1) arr.push(ele); - return arr; -} + return dest; +}; -function contains(arr, key, val) { - for (var i = 0; i < arr.length; i++) { - if (arr[i][key] === val) { - return true; +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); } - } - return false; -} - -function countNines(min, len) { - return String(min).slice(0, -len) + repeat('9', len); + }; } -function countZeros(integer, zeros) { - return integer - (integer % Math.pow(10, zeros)); -} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; -function toQuantifier(digits) { - var start = digits[0]; - var stop = digits[1] ? (',' + digits[1]) : ''; - if (!stop && (!start || start === 1)) { - return ''; - } - return '{' + start + stop + '}'; -} + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; -function toCharacterClass(a, b) { - return '[' + a + ((b - a === 1) ? '' : '-') + b + ']'; -} + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; -function padding(str) { - return /^-?(0+)\d/.exec(str); -} + if (!dest) dest = state.pipes; -function padZeros(val, tok) { - if (tok.isPadded) { - var diff = Math.abs(tok.maxLen - String(val).length); - switch (diff) { - case 0: - return ''; - case 1: - return '0'; - default: { - return '0{' + diff + '}'; - } - } + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; } - return val; -} -/** - * Expose `toRegexRange` - */ + // slow case. multiple pipe destinations. -module.exports = toRegexRange; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } -/***/ }), + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; -/***/ 4870: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; -"use strict"; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; -var isExtendable = __webpack_require__(29502); -var forIn = __webpack_require__(43086); +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); -function mixinDeep(target, objects) { - var len = arguments.length, i = 0; - while (++i < len) { - var obj = arguments[i]; - if (isObject(obj)) { - forIn(obj, copy, target); + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } } } - return target; -} -/** - * Copy properties from the source object to the - * target object. - * - * @param {*} `val` - * @param {String} `key` - */ + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; -function copy(val, key) { - if (!isValidKey(key)) { - return; +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); } + return this; +}; - var obj = this[key]; - if (isObject(val) && isObject(obj)) { - mixinDeep(obj, val); - } else { - this[key] = val; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); } } -/** - * Returns true if `val` is an object or function. - * - * @param {any} val - * @return {Boolean} - */ +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } -function isObject(val) { - return isExtendable(val) && !Array.isArray(val); + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); } -/** - * Returns true if `key` is a valid key to use when extending objects. - * - * @param {String} `key` - * @return {Boolean} - */ - -function isValidKey(key) { - return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; }; -/** - * Expose `mixinDeep` - */ - -module.exports = mixinDeep; - +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} -/***/ }), +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; -/***/ 29502: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + var state = this._readableState; + var paused = false; -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); -var isPlainObject = __webpack_require__(81064); + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); -}; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } -/***/ }), + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } -/***/ 50998: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; -var path = __webpack_require__(85622); -var fs = __webpack_require__(35747); -var _0777 = parseInt('0777', 8); + return this; +}; -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - if (path.dirname(p) === p) return cb(er); - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; +// exposed for testing purposes only. +Readable._fromList = fromList; - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; } -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; } - if (!made) made = null; + ++c; + } + list.length -= c; + return ret; +} - p = path.resolve(p); +function endReadable(stream) { + var state = stream._readableState; - try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} - return made; -}; +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} /***/ }), -/***/ 57925: +/***/ 62826: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. -/** - * Module dependencies - */ -var util = __webpack_require__(31669); -var toRegex = __webpack_require__(51279); -var extend = __webpack_require__(69148); +module.exports = Transform; -/** - * Local dependencies - */ +var Duplex = __webpack_require__(42770); -var compilers = __webpack_require__(4756); -var parsers = __webpack_require__(5333); -var cache = __webpack_require__(58250); -var utils = __webpack_require__(41340); -var MAX_LENGTH = 1024 * 64; +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ -/** - * The main function takes a list of strings and one or more - * glob patterns to use for matching. - * - * ```js - * var nm = require('nanomatch'); - * nm(list, patterns[, options]); - * - * console.log(nm(['a.js', 'a.txt'], ['*.js'])); - * //=> [ 'a.js' ] - * ``` - * @param {Array} `list` A list of strings to match - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array} Returns an array of matches - * @summary false - * @api public - */ +util.inherits(Transform, Duplex); -function nanomatch(list, patterns, options) { - patterns = utils.arrayify(patterns); - list = utils.arrayify(list); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; - var len = patterns.length; - if (list.length === 0 || len === 0) { - return []; - } + var cb = ts.writecb; - if (len === 1) { - return nanomatch.match(list, patterns[0], options); + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); } - var negated = false; - var omit = []; - var keep = []; - var idx = -1; + ts.writechunk = null; + ts.writecb = null; - while (++idx < len) { - var pattern = patterns[idx]; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); - if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { - omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options)); - negated = true; - } else { - keep.push.apply(keep, nanomatch.match(list, pattern, options)); - } - } + cb(er); - // minimatch.match parity - if (negated && keep.length === 0) { - if (options && options.unixify === false) { - keep = list.slice(); - } else { - var unixify = utils.unixify(options); - for (var i = 0; i < list.length; i++) { - keep.push(unixify(list[i])); - } - } + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); } +} - var matches = utils.diff(keep, omit); - if (!options || options.nodupes !== false) { - return utils.unique(matches); - } +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); - return matches; -} + Duplex.call(this, options); -/** - * Similar to the main function, but `pattern` must be a string. - * - * ```js - * var nm = require('nanomatch'); - * nm.match(list, pattern[, options]); - * - * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); - * //=> ['a.a', 'a.aa'] - * ``` - * @param {Array} `list` Array of strings to match - * @param {String} `pattern` Glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array} Returns an array of matches - * @api public - */ + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; -nanomatch.match = function(list, pattern, options) { - if (Array.isArray(pattern)) { - throw new TypeError('expected pattern to be a string'); - } + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - var unixify = utils.unixify(options); - var isMatch = memoize('match', pattern, options, nanomatch.matcher); - var matches = []; + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - list = utils.arrayify(list); - var len = list.length; - var idx = -1; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - while (++idx < len) { - var ele = list[idx]; - if (ele === pattern || isMatch(ele)) { - matches.push(utils.value(ele, unixify, options)); - } + if (typeof options.flush === 'function') this._flush = options.flush; } - // if no options were passed, uniquify results and return - if (typeof options === 'undefined') { - return utils.unique(matches); - } + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} - if (matches.length === 0) { - if (options.failglob === true) { - throw new Error('no matches found for "' + pattern + '"'); - } - if (options.nonull === true || options.nullglob === true) { - return [options.unescape ? utils.unescape(pattern) : pattern]; - } - } +function prefinish() { + var _this = this; - // if `opts.ignore` was defined, diff ignored list - if (options.ignore) { - matches = nanomatch.not(matches, options.ignore, options); + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); } +} - return options.nodupes !== false ? utils.unique(matches) : matches; +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); }; -/** - * Returns true if the specified `string` matches the given glob `pattern`. - * - * ```js - * var nm = require('nanomatch'); - * nm.isMatch(string, pattern[, options]); - * - * console.log(nm.isMatch('a.a', '*.a')); - * //=> true - * console.log(nm.isMatch('a.b', '*.a')); - * //=> false - * ``` - * @param {String} `string` String to match - * @param {String} `pattern` Glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if the string matches the glob pattern. - * @api public - */ +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; -nanomatch.isMatch = function(str, pattern, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } +}; - if (utils.isEmptyString(str) || utils.isEmptyString(pattern)) { - return false; - } +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; - var equals = utils.equalsPattern(options); - if (equals(str)) { - return true; + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; } +}; - var isMatch = memoize('isMatch', pattern, options, nanomatch.matcher); - return isMatch(str); +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); }; -/** - * Returns true if some of the elements in the given `list` match any of the - * given glob `patterns`. - * - * ```js - * var nm = require('nanomatch'); - * nm.some(list, patterns[, options]); - * - * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); - * // true - * console.log(nm.some(['foo.js'], ['*.js', '!foo.js'])); - * // false - * ``` - * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ +function done(stream, er, data) { + if (er) return stream.emit('error', er); -nanomatch.some = function(list, patterns, options) { - if (typeof list === 'string') { - list = [list]; - } + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); - for (var i = 0; i < list.length; i++) { - if (nanomatch(list[i], patterns, options).length === 1) { - return true; - } - } + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); - return false; -}; + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); -/** - * Returns true if every element in the given `list` matches - * at least one of the given glob `patterns`. - * - * ```js - * var nm = require('nanomatch'); - * nm.every(list, patterns[, options]); - * - * console.log(nm.every('foo.js', ['foo.js'])); - * // true - * console.log(nm.every(['foo.js', 'bar.js'], ['*.js'])); - * // true - * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); - * // false - * console.log(nm.every(['foo.js'], ['*.js', '!foo.js'])); - * // false - * ``` - * @param {String|Array} `list` The string or array of strings to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ + return stream.push(null); +} -nanomatch.every = function(list, patterns, options) { - if (typeof list === 'string') { - list = [list]; - } +/***/ }), - for (var i = 0; i < list.length; i++) { - if (nanomatch(list[i], patterns, options).length !== 1) { - return false; - } - } +/***/ 78063: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return true; -}; +"use strict"; +// 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. -/** - * Returns true if **any** of the given glob `patterns` - * match the specified `string`. - * - * ```js - * var nm = require('nanomatch'); - * nm.any(string, patterns[, options]); - * - * console.log(nm.any('a.a', ['b.*', '*.a'])); - * //=> true - * console.log(nm.any('a.a', 'b.*')); - * //=> false - * ``` - * @param {String|Array} `str` The string to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. -nanomatch.any = function(str, patterns, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); - } - if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { - return false; - } - if (typeof patterns === 'string') { - patterns = [patterns]; - } +/**/ - for (var i = 0; i < patterns.length; i++) { - if (nanomatch.isMatch(str, patterns[i], options)) { - return true; - } - } - return false; -}; +var pna = __webpack_require__(58404); +/**/ -/** - * Returns true if **all** of the given `patterns` - * match the specified string. - * - * ```js - * var nm = require('nanomatch'); - * nm.all(string, patterns[, options]); - * - * console.log(nm.all('foo.js', ['foo.js'])); - * // true - * - * console.log(nm.all('foo.js', ['*.js', '!foo.js'])); - * // false - * - * console.log(nm.all('foo.js', ['*.js', 'foo.js'])); - * // true - * - * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); - * // true - * ``` - * @param {String|Array} `str` The string to test. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if any patterns match `str` - * @api public - */ +module.exports = Writable; -nanomatch.all = function(str, patterns, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); - } +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} - if (typeof patterns === 'string') { - patterns = [patterns]; - } +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; - for (var i = 0; i < patterns.length; i++) { - if (!nanomatch.isMatch(str, patterns[i], options)) { - return false; - } - } - return true; -}; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ -/** - * Returns a list of strings that _**do not match any**_ of the given `patterns`. - * - * ```js - * var nm = require('nanomatch'); - * nm.not(list, patterns[, options]); - * - * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a')); - * //=> ['b.b', 'c.c'] - * ``` - * @param {Array} `list` Array of strings to match. - * @param {String|Array} `patterns` One or more glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Array} Returns an array of strings that **do not match** the given patterns. - * @api public - */ +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ -nanomatch.not = function(list, patterns, options) { - var opts = extend({}, options); - var ignore = opts.ignore; - delete opts.ignore; +/**/ +var Duplex; +/**/ - list = utils.arrayify(list); +Writable.WritableState = WritableState; - var matches = utils.diff(list, nanomatch(list, patterns, opts)); - if (ignore) { - matches = utils.diff(matches, nanomatch(list, ignore)); - } +/**/ +var util = Object.create(__webpack_require__(78334)); +util.inherits = __webpack_require__(2989); +/**/ - return opts.nodupes !== false ? utils.unique(matches) : matches; +/**/ +var internalUtil = { + deprecate: __webpack_require__(92262) }; +/**/ -/** - * Returns true if the given `string` contains the given pattern. Similar - * to [.isMatch](#isMatch) but the pattern can match any part of the string. - * - * ```js - * var nm = require('nanomatch'); - * nm.contains(string, pattern[, options]); - * - * console.log(nm.contains('aa/bb/cc', '*b')); - * //=> true - * console.log(nm.contains('aa/bb/cc', '*d')); - * //=> false - * ``` - * @param {String} `str` The string to match. - * @param {String|Array} `patterns` Glob pattern to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns true if the patter matches any part of `str`. - * @api public - */ +/**/ +var Stream = __webpack_require__(20681); +/**/ -nanomatch.contains = function(str, patterns, options) { - if (typeof str !== 'string') { - throw new TypeError('expected a string: "' + util.inspect(str) + '"'); - } +/**/ - if (typeof patterns === 'string') { - if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { - return false; - } +var Buffer = __webpack_require__(96788).Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} - var equals = utils.equalsPattern(patterns, options); - if (equals(str)) { - return true; - } - var contains = utils.containsPattern(patterns, options); - if (contains(str)) { - return true; - } - } +/**/ - var opts = extend({}, options, {contains: true}); - return nanomatch.any(str, patterns, opts); -}; +var destroyImpl = __webpack_require__(87915); -/** - * Returns true if the given pattern and options should enable - * the `matchBase` option. - * @return {Boolean} - * @api private - */ +util.inherits(Writable, Stream); -nanomatch.matchBase = function(pattern, options) { - if (pattern && pattern.indexOf('/') !== -1 || !options) return false; - return options.basename === true || options.matchBase === true; -}; +function nop() {} -/** - * Filter the keys of the given object with the given `glob` pattern - * and `options`. Does not attempt to match nested keys. If you need this feature, - * use [glob-object][] instead. - * - * ```js - * var nm = require('nanomatch'); - * nm.matchKeys(object, patterns[, options]); - * - * var obj = { aa: 'a', ab: 'b', ac: 'c' }; - * console.log(nm.matchKeys(obj, '*b')); - * //=> { ab: 'b' } - * ``` - * @param {Object} `object` The object with keys to filter. - * @param {String|Array} `patterns` One or more glob patterns to use for matching. - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Object} Returns an object with only keys that match the given patterns. - * @api public - */ +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(42770); -nanomatch.matchKeys = function(obj, patterns, options) { - if (!utils.isObject(obj)) { - throw new TypeError('expected the first argument to be an object'); - } - var keys = nanomatch(Object.keys(obj), patterns, options); - return utils.pick(obj, keys); -}; + options = options || {}; -/** - * Returns a memoized matcher function from the given glob `pattern` and `options`. - * The returned function takes a string to match as its only argument and returns - * true if the string is a match. - * - * ```js - * var nm = require('nanomatch'); - * nm.matcher(pattern[, options]); - * - * var isMatch = nm.matcher('*.!(*a)'); - * console.log(isMatch('a.a')); - * //=> false - * console.log(isMatch('a.b')); - * //=> true - * ``` - * @param {String} `pattern` Glob pattern - * @param {Object} `options` See available [options](#options) for changing how matches are performed. - * @return {Function} Returns a matcher function. - * @api public - */ + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; -nanomatch.matcher = function matcher(pattern, options) { - if (utils.isEmptyString(pattern)) { - return function() { - return false; - }; - } + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - if (Array.isArray(pattern)) { - return compose(pattern, options, matcher); - } + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - // if pattern is a regex - if (pattern instanceof RegExp) { - return test(pattern); - } + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; - // if pattern is invalid - if (!utils.isString(pattern)) { - throw new TypeError('expected pattern to be an array, string or regex'); - } + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; - // if pattern is a non-glob string - if (!utils.hasSpecialChars(pattern)) { - if (options && options.nocase === true) { - pattern = pattern.toLowerCase(); - } - return utils.matchPath(pattern, options); - } + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); - // if pattern is a glob string - var re = nanomatch.makeRe(pattern, options); + // if _final has been called + this.finalCalled = false; - // if `options.matchBase` or `options.basename` is defined - if (nanomatch.matchBase(pattern, options)) { - return utils.matchBasename(re, options); - } + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - function test(regex) { - var equals = utils.equalsPattern(options); - var unixify = utils.unixify(options); + // has it been destroyed + this.destroyed = false; - return function(str) { - if (equals(str)) { - return true; - } + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - if (regex.test(unixify(str))) { - return true; - } - return false; - }; - } + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - // create matcher function - var matcherFn = test(re); - // set result object from compiler on matcher function, - // as a non-enumerable property. useful for debugging - utils.define(matcherFn, 'result', re.result); - return matcherFn; -}; + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; -/** - * Returns an array of matches captured by `pattern` in `string, or - * `null` if the pattern did not match. - * - * ```js - * var nm = require('nanomatch'); - * nm.capture(pattern, string[, options]); - * - * console.log(nm.capture('test/*.js', 'test/foo.js')); - * //=> ['foo'] - * console.log(nm.capture('test/*.js', 'foo/bar.css')); - * //=> null - * ``` - * @param {String} `pattern` Glob pattern to use for matching. - * @param {String} `string` String to match - * @param {Object} `options` See available [options](#options) for changing how matches are performed - * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. - * @api public - */ + // a flag to see when we're in the middle of a write. + this.writing = false; -nanomatch.capture = function(pattern, str, options) { - var re = nanomatch.makeRe(pattern, extend({capture: true}, options)); - var unixify = utils.unixify(options); + // when true all writes will be buffered until .uncork() call + this.corked = 0; - function match() { - return function(string) { - var match = re.exec(unixify(string)); - if (!match) { - return null; - } + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - return match.slice(1); - }; - } - - var capture = memoize('capture', pattern, options, match); - return capture(str); -}; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; -/** - * Create a regular expression from the given glob `pattern`. - * - * ```js - * var nm = require('nanomatch'); - * nm.makeRe(pattern[, options]); - * - * console.log(nm.makeRe('*.js')); - * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ - * ``` - * @param {String} `pattern` A glob pattern to convert to regex. - * @param {Object} `options` See available [options](#options) for changing how matches are performed. - * @return {RegExp} Returns a regex created from the given pattern. - * @api public - */ + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; -nanomatch.makeRe = function(pattern, options) { - if (pattern instanceof RegExp) { - return pattern; - } + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - if (typeof pattern !== 'string') { - throw new TypeError('expected pattern to be a string'); - } + // the amount that is being written when _write is called. + this.writelen = 0; - if (pattern.length > MAX_LENGTH) { - throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); - } + this.bufferedRequest = null; + this.lastBufferedRequest = null; - function makeRe() { - var opts = utils.extend({wrap: false}, options); - var result = nanomatch.create(pattern, opts); - var regex = toRegex(result.output, opts); - utils.define(regex, 'result', result); - return regex; - } + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - return memoize('makeRe', pattern, options, makeRe); -}; + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; -/** - * Parses the given glob `pattern` and returns an object with the compiled `output` - * and optional source `map`. - * - * ```js - * var nm = require('nanomatch'); - * nm.create(pattern[, options]); - * - * console.log(nm.create('abc/*.js')); - * // { options: { source: 'string', sourcemap: true }, - * // state: {}, - * // compilers: - * // { ... }, - * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', - * // ast: - * // { type: 'root', - * // errors: [], - * // nodes: - * // [ ... ], - * // dot: false, - * // input: 'abc/*.js' }, - * // parsingErrors: [], - * // map: - * // { version: 3, - * // sources: [ 'string' ], - * // names: [], - * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', - * // sourcesContent: [ 'abc/*.js' ] }, - * // position: { line: 1, column: 28 }, - * // content: {}, - * // files: {}, - * // idx: 6 } - * ``` - * @param {String} `pattern` Glob pattern to parse and compile. - * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed. - * @return {Object} Returns an object with the parsed AST, compiled string and optional source map. - * @api public - */ + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; -nanomatch.create = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); - } - function create() { - return nanomatch.compile(nanomatch.parse(pattern, options), options); - } - return memoize('create', pattern, options, create); -}; + // count buffered requests + this.bufferedRequestCount = 0; -/** - * Parse the given `str` with the given `options`. - * - * ```js - * var nm = require('nanomatch'); - * nm.parse(pattern[, options]); - * - * var ast = nm.parse('a/{b,c}/d'); - * console.log(ast); - * // { type: 'root', - * // errors: [], - * // input: 'a/{b,c}/d', - * // nodes: - * // [ { type: 'bos', val: '' }, - * // { type: 'text', val: 'a/' }, - * // { type: 'brace', - * // nodes: - * // [ { type: 'brace.open', val: '{' }, - * // { type: 'text', val: 'b,c' }, - * // { type: 'brace.close', val: '}' } ] }, - * // { type: 'text', val: '/d' }, - * // { type: 'eos', val: '' } ] } - * ``` - * @param {String} `str` - * @param {Object} `options` - * @return {Object} Returns an AST - * @api public - */ + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} -nanomatch.parse = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; } + return out; +}; - function parse() { - var snapdragon = utils.instantiate(null, options); - parsers(snapdragon, options); +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); - var ast = snapdragon.parse(pattern, options); - utils.define(ast, 'snapdragon', snapdragon); - ast.input = pattern; - return ast; - } +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; - return memoize('parse', pattern, options, parse); -}; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} -/** - * Compile the given `ast` or string with the given `options`. - * - * ```js - * var nm = require('nanomatch'); - * nm.compile(ast[, options]); - * - * var ast = nm.parse('a/{b,c}/d'); - * console.log(nm.compile(ast)); - * // { options: { source: 'string' }, - * // state: {}, - * // compilers: - * // { eos: [Function], - * // noop: [Function], - * // bos: [Function], - * // brace: [Function], - * // 'brace.open': [Function], - * // text: [Function], - * // 'brace.close': [Function] }, - * // output: [ 'a/(b|c)/d' ], - * // ast: - * // { ... }, - * // parsingErrors: [] } - * ``` - * @param {Object|String} `ast` - * @param {Object} `options` - * @return {Object} Returns an object that has an `output` property with the compiled string. - * @api public - */ +function Writable(options) { + Duplex = Duplex || __webpack_require__(42770); -nanomatch.compile = function(ast, options) { - if (typeof ast === 'string') { - ast = nanomatch.parse(ast, options); - } + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. - function compile() { - var snapdragon = utils.instantiate(ast, options); - compilers(snapdragon, options); - return snapdragon.compile(ast, options); + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); } - return memoize('compile', ast.input, options, compile); -}; + this._writableState = new WritableState(options, this); -/** - * Clear the regex cache. - * - * ```js - * nm.clearCache(); - * ``` - * @api public - */ + // legacy. + this.writable = true; -nanomatch.clearCache = function() { - nanomatch.cache.__data__ = {}; -}; + if (options) { + if (typeof options.write === 'function') this._write = options.write; -/** - * Compose a matcher function with the given patterns. - * This allows matcher functions to be compiled once and - * called multiple times. - */ + if (typeof options.writev === 'function') this._writev = options.writev; -function compose(patterns, options, matcher) { - var matchers; + if (typeof options.destroy === 'function') this._destroy = options.destroy; - return memoize('compose', String(patterns), options, function() { - return function(file) { - // delay composition until it's invoked the first time, - // after that it won't be called again - if (!matchers) { - matchers = []; - for (var i = 0; i < patterns.length; i++) { - matchers.push(matcher(patterns[i], options)); - } - } + if (typeof options.final === 'function') this._final = options.final; + } - var len = matchers.length; - while (len--) { - if (matchers[len](file) === true) { - return true; - } - } - return false; - }; - }); + Stream.call(this); } -/** - * Memoize a generated regex or function. A unique key is generated - * from the `type` (usually method name), the `pattern`, and - * user-defined options. - */ +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; -function memoize(type, pattern, options, fn) { - var key = utils.createKey(type + '=' + pattern, options); +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} - if (options && options.cache === false) { - return fn(pattern, options); - } +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; - if (cache.has(type, key)) { - return cache.get(type, key); + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); } - - var val = fn(pattern, options); - cache.set(type, key, val); - return val; + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; } -/** - * Expose compiler, parser and cache on `nanomatch` - */ +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); -nanomatch.compilers = compilers; -nanomatch.parsers = parsers; -nanomatch.cache = cache; + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } -/** - * Expose `nanomatch` - * @type {Function} - */ + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } -module.exports = nanomatch; + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; -/***/ }), + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } -/***/ 58250: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return ret; +}; -module.exports = new (__webpack_require__(49908))(); +Writable.prototype.cork = function () { + var state = this._writableState; + state.corked++; +}; -/***/ }), +Writable.prototype.uncork = function () { + var state = this._writableState; -/***/ 4756: -/***/ (function(module) { + if (state.corked) { + state.corked--; -"use strict"; + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; -/** -* Nanomatch compilers -*/ +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} -module.exports = function(nanomatch, options) { - function slash() { - if (options && typeof options.slash === 'string') { - return options.slash; - } - if (options && typeof options.slash === 'function') { - return options.slash.call(nanomatch); - } - return '\\\\/'; +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; } +}); - function star() { - if (options && typeof options.star === 'string') { - return options.star; - } - if (options && typeof options.star === 'function') { - return options.star.call(nanomatch); +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; } - return '[^' + slash() + ']*?'; } + var len = state.objectMode ? 1 : chunk.length; - var ast = nanomatch.ast = nanomatch.parser.ast; - ast.state = nanomatch.parser.state; - nanomatch.compiler.state = ast.state; - nanomatch.compiler - - /** - * Negation / escaping - */ - - .set('not', function(node) { - var prev = this.prev(); - if (this.options.nonegate === true || prev.type !== 'bos') { - return this.emit('\\' + node.val, node); - } - return this.emit(node.val, node); - }) - .set('escape', function(node) { - if (this.options.unescape && /^[-\w_.]/.test(node.val)) { - return this.emit(node.val, node); - } - return this.emit('\\' + node.val, node); - }) - .set('quoted', function(node) { - return this.emit(node.val, node); - }) + state.length += len; - /** - * Regex - */ + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; - .set('dollar', function(node) { - if (node.parent.type === 'bracket') { - return this.emit(node.val, node); - } - return this.emit('\\' + node.val, node); - }) + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } - /** - * Dot: "." - */ + return ret; +} - .set('dot', function(node) { - if (node.dotfiles === true) this.dotfiles = true; - return this.emit('\\' + node.val, node); - }) +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} - /** - * Slashes: "/" and "\" - */ +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; - .set('backslash', function(node) { - return this.emit(node.val, node); - }) - .set('slash', function(node, nodes, i) { - var val = '[' + slash() + ']'; - var parent = node.parent; - var prev = this.prev(); - - // set "node.hasSlash" to true on all ancestor parens nodes - while (parent.type === 'paren' && !parent.hasSlash) { - parent.hasSlash = true; - parent = parent.parent; - } - - if (prev.addQmark) { - val += '?'; - } - - // word boundary - if (node.rest.slice(0, 2) === '\\b') { - return this.emit(val, node); - } + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} - // globstars - if (node.parsed === '**' || node.parsed === './**') { - this.output = '(?:' + this.output; - return this.emit(val + ')?', node); - } +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} - // negation - if (node.parsed === '!**' && this.options.nonegate !== true) { - return this.emit(val + '?\\b', node); - } - return this.emit(val, node); - }) +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - /** - * Square brackets - */ + onwriteStateUpdate(state); - .set('bracket', function(node) { - var close = node.close; - var open = !node.escaped ? '[' : '\\['; - var negated = node.negated; - var inner = node.inner; - var val = node.val; + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); - if (node.escaped === true) { - inner = inner.replace(/\\?(\W)/g, '\\$1'); - negated = ''; - } + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } - if (inner === ']-') { - inner = '\\]\\-'; - } + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} - if (negated && inner.indexOf('.') === -1) { - inner += '.'; - } - if (negated && inner.indexOf('/') === -1) { - inner += '/'; - } +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} - val = open + negated + inner + close; - return this.emit(val, node); - }) +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} - /** - * Square: "[.]" (only matches a single character in brackets) - */ +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; - .set('square', function(node) { - var val = (/^\W/.test(node.val) ? '\\' : '') + node.val; - return this.emit(val, node); - }) + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; - /** - * Question mark: "?" - */ + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; - .set('qmark', function(node) { - var prev = this.prev(); - // don't use "slash" variable so that we always avoid - // matching backslashes and slashes with a qmark - var val = '[^.\\\\/]'; - if (this.options.dot || (prev.type !== 'bos' && prev.type !== 'slash')) { - val = '[^\\\\/]'; - } + doWrite(stream, state, true, state.length, buffer, '', holder.finish); - if (node.parsed.slice(-1) === '(') { - var ch = node.rest.charAt(0); - if (ch === '!' || ch === '=' || ch === ':') { - return this.emit(node.val, node); - } - } + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - if (node.val.length > 1) { - val += '{' + node.val.length + '}'; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; } - return this.emit(val, node); - }) + } - /** - * Plus - */ + if (entry === null) state.lastBufferedRequest = null; + } - .set('plus', function(node) { - var prev = node.parsed.slice(-1); - if (prev === ']' || prev === ')') { - return this.emit(node.val, node); - } - if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) { - return this.emit('\\+', node); - } - var ch = this.output.slice(-1); - if (/\w/.test(ch) && !node.inside) { - return this.emit('+\\+?', node); - } - return this.emit('+', node); - }) + state.bufferedRequest = entry; + state.bufferProcessing = false; +} - /** - * globstar: '**' - */ +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; - .set('globstar', function(node, nodes, i) { - if (!this.output) { - this.state.leadingGlobstar = true; - } +Writable.prototype._writev = null; - var prev = this.prev(); - var before = this.prev(2); - var next = this.next(); - var after = this.next(2); - var type = prev.type; - var val = node.val; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - if (prev.type === 'slash' && next.type === 'slash') { - if (before.type === 'text') { - this.output += '?'; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - if (after.type !== 'text') { - this.output += '\\b'; - } - } - } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - var parsed = node.parsed; - if (parsed.charAt(0) === '!') { - parsed = parsed.slice(1); - } + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } - var isInside = node.isInside.paren || node.isInside.brace; - if (parsed && type !== 'slash' && type !== 'bos' && !isInside) { - val = star(); - } else { - val = this.options.dot !== true - ? '(?:(?!(?:[' + slash() + ']|^)\\.).)*?' - : '(?:(?!(?:[' + slash() + ']|^)(?:\\.{1,2})($|[' + slash() + ']))(?!\\.{2}).)*?'; - } + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; - if ((type === 'slash' || type === 'bos') && this.options.dot !== true) { - val = '(?!\\.)' + val; - } +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} - if (prev.type === 'slash' && next.type === 'slash' && before.type !== 'text') { - if (after.type === 'text' || after.type === 'star') { - node.addQmark = true; - } - } +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} - if (this.options.capture) { - val = '(' + val + ')'; - } +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} - return this.emit(val, node); - }) +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} - /** - * Star: "*" - */ +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } - .set('star', function(node, nodes, i) { - var prior = nodes[i - 2] || {}; - var prev = this.prev(); - var next = this.next(); - var type = prev.type; + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); - function isStart(n) { - return n.type === 'bos' || n.type === 'slash'; - } +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; - if (this.output === '' && this.options.contains !== true) { - this.output = '(?![' + slash() + '])'; - } +/***/ }), - if (type === 'bracket' && this.options.bash === false) { - var str = next && next.type === 'bracket' ? star() : '*?'; - if (!prev.nodes || prev.nodes[1].type !== 'posix') { - return this.emit(str, node); - } - } +/***/ 28878: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - var prefix = !this.dotfiles && type !== 'text' && type !== 'escape' - ? (this.options.dot ? '(?!(?:^|[' + slash() + '])\\.{1,2}(?:$|[' + slash() + ']))' : '(?!\\.)') - : ''; +"use strict"; - if (isStart(prev) || (isStart(prior) && type === 'not')) { - if (prefix !== '(?!\\.)') { - prefix += '(?!(\\.{2}|\\.[' + slash() + ']))(?=.)'; - } else { - prefix += '(?=.)'; - } - } else if (prefix === '(?!\\.)') { - prefix = ''; - } - if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) { - this.output = '(?!\\.)' + this.output; - } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - var output = prefix + star(); - if (this.options.capture) { - output = '(' + output + ')'; - } +var Buffer = __webpack_require__(96788).Buffer; +var util = __webpack_require__(31669); - return this.emit(output, node); - }) +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} - /** - * Text - */ +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); - .set('text', function(node) { - return this.emit(node.val, node); - }) + this.head = null; + this.tail = null; + this.length = 0; + } - /** - * End-of-string - */ + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; - .set('eos', function(node) { - var prev = this.prev(); - var val = node.val; + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; - this.output = '(?:\\.[' + slash() + '](?=.))?' + this.output; - if (this.state.metachar && prev.type !== 'qmark' && prev.type !== 'slash') { - val += (this.options.contains ? '[' + slash() + ']?' : '(?:[' + slash() + ']|$)'); - } + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; - return this.emit(val, node); - }); + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; - /** - * Allow custom compilers to be passed on options - */ + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; - if (options && typeof options.compilers === 'function') { - options.compilers(nanomatch.compiler); - } -}; + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + return BufferList; +}(); +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; +} /***/ }), -/***/ 5333: +/***/ 87915: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -var regexNot = __webpack_require__(30931); -var toRegex = __webpack_require__(51279); +/**/ -/** - * Characters to use in negation regex (we want to "not" match - * characters that are matched by other parsers) - */ +var pna = __webpack_require__(58404); +/**/ -var cached; -var NOT_REGEX = '[\\[!*+?$^"\'.\\\\/]+'; -var not = createTextRegex(NOT_REGEX); - -/** - * Nanomatch parsers - */ - -module.exports = function(nanomatch, options) { - var parser = nanomatch.parser; - var opts = parser.options; +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; - parser.state = { - slashes: 0, - paths: [] - }; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; - parser.ast.state = parser.state; - parser + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); + } + return this; + } - /** - * Beginning-of-string - */ + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks - .capture('prefix', function() { - if (this.parsed) return; - var m = this.match(/^\.[\\/]/); - if (!m) return; - this.state.strictOpen = !!this.options.strictOpen; - this.state.addPrefix = true; - }) + if (this._readableState) { + this._readableState.destroyed = true; + } - /** - * Escape: "\\." - */ + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } - .capture('escape', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(/^(?:\\(.)|([$^]))/); - if (!m) return; + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); - return pos({ - type: 'escape', - val: m[2] || m[1] - }); - }) + return this; +} - /** - * Quoted strings - */ +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } - .capture('quoted', function() { - var pos = this.position(); - var m = this.match(/^["']/); - if (!m) return; + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} - var quote = m[0]; - if (this.input.indexOf(quote) === -1) { - return pos({ - type: 'escape', - val: quote - }); - } +function emitErrorNT(self, err) { + self.emit('error', err); +} - var tok = advanceTo(this.input, quote); - this.consume(tok.len); +module.exports = { + destroy: destroy, + undestroy: undestroy +}; - return pos({ - type: 'quoted', - val: tok.esc - }); - }) +/***/ }), - /** - * Negations: "!" - */ +/***/ 20681: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - .capture('not', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(this.notRegex || /^!+/); - if (!m) return; - var val = m[0]; +module.exports = __webpack_require__(92413); - var isNegated = (val.length % 2) === 1; - if (parsed === '' && !isNegated) { - val = ''; - } - // if nothing has been parsed, we know `!` is at the start, - // so we need to wrap the result in a negation regex - if (parsed === '' && isNegated && this.options.nonegate !== true) { - this.bos.val = '(?!^(?:'; - this.append = ')$).*'; - val = ''; - } - return pos({ - type: 'not', - val: val - }); - }) +/***/ }), - /** - * Dot: "." - */ +/***/ 96788: +/***/ (function(module, exports, __webpack_require__) { - .capture('dot', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\.+/); - if (!m) return; +/* eslint-disable node/no-deprecated-api */ +var buffer = __webpack_require__(64293) +var Buffer = buffer.Buffer - var val = m[0]; - this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/'); +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} - return pos({ - type: 'dot', - dotfiles: this.state.dot, - val: val - }); - }) +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} - /** - * Plus: "+" - */ +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) - .capture('plus', /^\+(?!\()/) +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} - /** - * Question mark: "?" - */ +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 +} - .capture('qmark', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\?+(?!\()/); - if (!m) return; +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} - this.state.metachar = true; - this.state.qmark = true; +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} - return pos({ - type: 'qmark', - parsed: parsed, - val: m[0] - }); - }) - /** - * Globstar: "**" - */ +/***/ }), - .capture('globstar', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(/^\*{2}(?![*(])(?=[,)/]|$)/); - if (!m) return; +/***/ 7395: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - var type = opts.noglobstar !== true ? 'globstar' : 'star'; - var node = pos({type: type, parsed: parsed}); - this.state.metachar = true; +"use strict"; +// 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. - while (this.input.slice(0, 4) === '/**/') { - this.input = this.input.slice(3); - } - node.isInside = { - brace: this.isInside('brace'), - paren: this.isInside('paren') - }; - if (type === 'globstar') { - this.state.globstar = true; - node.val = '**'; +/**/ - } else { - this.state.star = true; - node.val = '*'; - } +var Buffer = __webpack_require__(96788).Buffer; +/**/ - return node; - }) +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; - /** - * Star: "*" - */ +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; - .capture('star', function() { - var pos = this.position(); - var starRe = /^(?:\*(?![*(])|[*]{3,}(?!\()|[*]{2}(?![(/]|$)|\*(?=\*\())/; - var m = this.match(starRe); - if (!m) return; +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} - this.state.metachar = true; - this.state.star = true; - return pos({ - type: 'star', - val: m[0] - }); - }) +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.s = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} - /** - * Slash: "/" - */ +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; - .capture('slash', function() { - var pos = this.position(); - var m = this.match(/^\//); - if (!m) return; +StringDecoder.prototype.end = utf8End; - this.state.slashes++; - return pos({ - type: 'slash', - val: m[0] - }); - }) +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; - /** - * Backslash: "\\" - */ +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; - .capture('backslash', function() { - var pos = this.position(); - var m = this.match(/^\\(?![*+?(){}[\]'"])/); - if (!m) return; +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} - var val = m[0]; +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} - if (this.isInside('bracket')) { - val = '\\'; - } else if (val.length > 1) { - val = '\\\\'; +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; } + } + } +} - return pos({ - type: 'backslash', - val: val - }); - }) - - /** - * Square: "[.]" - */ +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} - .capture('square', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(/^\[([^!^\\])\]/); - if (!m) return; +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} - return pos({ - type: 'square', - val: m[1] - }); - }) +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} - /** - * Brackets: "[...]" (basic, this can be overridden by other parsers) - */ +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} - .capture('bracket', function() { - var pos = this.position(); - var m = this.match(/^(?:\[([!^]?)([^\]]+|\]-)(\]|[^*+?]+)|\[)/); - if (!m) return; +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} - var val = m[0]; - var negated = m[1] ? '^' : ''; - var inner = (m[2] || '').replace(/\\\\+/, '\\\\'); - var close = m[3] || ''; +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} - if (m[2] && inner.length < m[2].length) { - val = val.replace(/\\\\+/, '\\\\'); - } +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} - var esc = this.input.slice(0, 2); - if (inner === '' && esc === '\\]') { - inner += esc; - this.consume(2); +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} - var str = this.input; - var idx = -1; - var ch; +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} - while ((ch = str[++idx])) { - this.consume(1); - if (ch === ']') { - close = ch; - break; - } - inner += ch; - } - } +/***/ }), - return pos({ - type: 'bracket', - val: val, - escaped: close !== ']', - negated: negated, - inner: inner, - close: close - }); - }) +/***/ 68193: +/***/ (function(module, exports, __webpack_require__) { - /** - * Text - */ +var Stream = __webpack_require__(92413); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = __webpack_require__(79341); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __webpack_require__(78063); + exports.Duplex = __webpack_require__(42770); + exports.Transform = __webpack_require__(62826); + exports.PassThrough = __webpack_require__(60143); +} - .capture('text', function() { - if (this.isInside('bracket')) return; - var pos = this.position(); - var m = this.match(not); - if (!m || !m[0]) return; - return pos({ - type: 'text', - val: m[0] - }); - }); +/***/ }), - /** - * Allow custom parsers to be passed on options - */ +/***/ 30931: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (options && typeof options.parsers === 'function') { - options.parsers(nanomatch.parser); - } -}; +"use strict"; + + +var extend = __webpack_require__(39700); +var safe = __webpack_require__(71217); /** - * Advance to the next non-escaped character + * The main export is a function that takes a `pattern` string and an `options` object. + * + * ```js + & var not = require('regex-not'); + & console.log(not('foo')); + & //=> /^(?:(?!^(?:foo)$).)*$/ + * ``` + * + * @param {String} `pattern` + * @param {Object} `options` + * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`. + * @api public */ -function advanceTo(input, endChar) { - var ch = input.charAt(0); - var tok = { len: 1, val: '', esc: '' }; - var idx = 0; +function toRegex(pattern, options) { + return new RegExp(toRegex.create(pattern, options)); +} - function advance() { - if (ch !== '\\') { - tok.esc += '\\' + ch; - tok.val += ch; - } +/** + * Create a regex-compatible string from the given `pattern` and `options`. + * + * ```js + & var not = require('regex-not'); + & console.log(not.create('foo')); + & //=> '^(?:(?!^(?:foo)$).)*$' + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {String} + * @api public + */ - ch = input.charAt(++idx); - tok.len++; +toRegex.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } - if (ch === '\\') { - advance(); - advance(); - } + var opts = extend({}, options); + if (opts.contains === true) { + opts.strictNegate = false; } - while (ch && ch !== endChar) { - advance(); + var open = opts.strictOpen !== false ? '^' : ''; + var close = opts.strictClose !== false ? '$' : ''; + var endChar = opts.endChar ? opts.endChar : '+'; + var str = pattern; + + if (opts.strictNegate === false) { + str = '(?:(?!(?:' + pattern + ')).)' + endChar; + } else { + str = '(?:(?!^(?:' + pattern + ')$).)' + endChar; } - return tok; -} -/** - * Create text regex - */ + var res = open + str + close; + if (opts.safe === true && safe(res) === false) { + throw new Error('potentially unsafe regular expression: ' + res); + } -function createTextRegex(pattern) { - if (cached) return cached; - var opts = {contains: true, strictClose: false}; - var not = regexNot.create(pattern, opts); - var re = toRegex('^(?:[*]\\((?=.)|' + not + ')', opts); - return (cached = re); -} + return res; +}; /** - * Expose negation string + * Expose `toRegex` */ -module.exports.not = NOT_REGEX; +module.exports = toRegex; /***/ }), -/***/ 41340: +/***/ 39700: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -var utils = module.exports; -var path = __webpack_require__(85622); +var isExtendable = __webpack_require__(93295); +var assignSymbols = __webpack_require__(64353); -/** - * Module dependencies - */ +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; +}; -var isWindows = __webpack_require__(8025)(); -var Snapdragon = __webpack_require__(79285); -utils.define = __webpack_require__(18918); -utils.diff = __webpack_require__(9455); -utils.extend = __webpack_require__(69148); -utils.pick = __webpack_require__(38509); -utils.typeOf = __webpack_require__(42556); -utils.unique = __webpack_require__(19009); +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} -/** - * Returns true if the given value is effectively an empty string - */ +function isString(val) { + return (val && typeof val === 'string'); +} -utils.isEmptyString = function(val) { - return String(val) === '' || String(val) === './'; -}; +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} + +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} /** - * Returns true if the platform is windows, or `path.sep` is `\\`. - * This is defined as a function to allow `path.sep` to be set in unit tests, - * or by the user, if there is a reason to do so. - * @return {Boolean} + * Returns true if the given `key` is an own property of `obj`. */ -utils.isWindows = function() { - return path.sep === '\\' || isWindows === true; -}; +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} -/** - * Return the last element from an array - */ +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} -utils.last = function(arr, n) { - return arr[arr.length - (n || 1)]; -}; -/** - * Get the `Snapdragon` instance to use - */ +/***/ }), -utils.instantiate = function(ast, options) { - var snapdragon; - // if an instance was created by `.parse`, use that instance - if (utils.typeOf(ast) === 'object' && ast.snapdragon) { - snapdragon = ast.snapdragon; - // if the user supplies an instance on options, use that instance - } else if (utils.typeOf(options) === 'object' && options.snapdragon) { - snapdragon = options.snapdragon; - // create a new instance - } else { - snapdragon = new Snapdragon(options); - } +/***/ 93295: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - utils.define(snapdragon, 'parse', function(str, options) { - var parsed = Snapdragon.prototype.parse.call(this, str, options); - parsed.input = str; +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ - // escape unmatched brace/bracket/parens - var last = this.parser.stack.pop(); - if (last && this.options.strictErrors !== true) { - var open = last.nodes[0]; - var inner = last.nodes[1]; - if (last.type === 'bracket') { - if (inner.val.charAt(0) === '[') { - inner.val = '\\' + inner.val; - } - } else { - open.val = '\\' + open.val; - var sibling = open.parent.nodes[1]; - if (sibling.type === 'star') { - sibling.loose = true; - } - } - } - // add non-enumerable parser reference - utils.define(parsed, 'parser', this.parser); - return parsed; - }); +var isPlainObject = __webpack_require__(81064); - return snapdragon; +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); }; -/** - * Create the key to use for memoization. The key is generated - * by iterating over the options and concatenating key-value pairs - * to the pattern string. - */ -utils.createKey = function(pattern, options) { - if (typeof options === 'undefined') { - return pattern; - } - var key = pattern; - for (var prop in options) { - if (options.hasOwnProperty(prop)) { - key += ';' + prop + '=' + String(options[prop]); - } - } - return key; -}; +/***/ }), -/** - * Cast `val` to an array - * @return {Array} +/***/ 69523: +/***/ (function(module) { + +"use strict"; +/*! + * repeat-element + * + * Copyright (c) 2015-present, Jon Schlinkert. + * Licensed under the MIT license. */ -utils.arrayify = function(val) { - if (typeof val === 'string') return [val]; - return val ? (Array.isArray(val) ? val : [val]) : []; -}; -/** - * Return true if `val` is a non-empty string - */ -utils.isString = function(val) { - return typeof val === 'string'; -}; +module.exports = function repeat(ele, num) { + var arr = new Array(num); -/** - * Return true if `val` is a non-empty string - */ + for (var i = 0; i < num; i++) { + arr[i] = ele; + } -utils.isRegex = function(val) { - return utils.typeOf(val) === 'regexp'; + return arr; }; -/** - * Return true if `val` is a non-empty string - */ -utils.isObject = function(val) { - return utils.typeOf(val) === 'object'; -}; +/***/ }), -/** - * Escape regex characters in the given string +/***/ 6332: +/***/ (function(module) { + +"use strict"; +/*! + * repeat-string + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. */ -utils.escapeRegex = function(str) { - return str.replace(/[-[\]{}()^$|*+?.\\/\s]/g, '\\$&'); -}; + /** - * Combines duplicate characters in the provided `input` string. - * @param {String} `input` - * @returns {String} + * Results cache */ -utils.combineDupes = function(input, patterns) { - patterns = utils.arrayify(patterns).join('|').split('|'); - patterns = patterns.map(function(s) { - return s.replace(/\\?([+*\\/])/g, '\\$1'); - }); - var substr = patterns.join('|'); - var regex = new RegExp('(' + substr + ')(?=\\1)', 'g'); - return input.replace(regex, ''); -}; +var res = ''; +var cache; /** - * Returns true if the given `str` has special characters + * Expose `repeat` */ -utils.hasSpecialChars = function(str) { - return /(?:(?:(^|\/)[!.])|[*?+()|[\]{}]|[+@]\()/.test(str); -}; +module.exports = repeat; /** - * Normalize slashes in the given filepath. + * Repeat the given `string` the specified `number` + * of times. * - * @param {String} `filepath` - * @return {String} + * **Example:** + * + * ```js + * var repeat = require('repeat-string'); + * repeat('A', 5); + * //=> AAAAA + * ``` + * + * @param {String} `string` The string to repeat + * @param {Number} `number` The number of times to repeat the string + * @return {String} Repeated string + * @api public */ -utils.toPosixPath = function(str) { - return str.replace(/\\+/g, '/'); -}; - -/** - * Strip backslashes before special characters in a string. - * - * @param {String} `str` - * @return {String} - */ - -utils.unescape = function(str) { - return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); -}; +function repeat(str, num) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } -/** - * Strip the drive letter from a windows filepath - * @param {String} `fp` - * @return {String} - */ + // cover common, quick use cases + if (num === 1) return str; + if (num === 2) return str + str; -utils.stripDrive = function(fp) { - return utils.isWindows() ? fp.replace(/^[a-z]:[\\/]+?/i, '/') : fp; -}; + var max = str.length * num; + if (cache !== str || typeof cache === 'undefined') { + cache = str; + res = ''; + } else if (res.length >= max) { + return res.substr(0, max); + } -/** - * Strip the prefix from a filepath - * @param {String} `fp` - * @return {String} - */ + while (max > res.length && num > 1) { + if (num & 1) { + res += str; + } -utils.stripPrefix = function(str) { - if (str.charAt(0) === '.' && (str.charAt(1) === '/' || str.charAt(1) === '\\')) { - return str.slice(2); + num >>= 1; + str += str; } - return str; -}; - -/** - * Returns true if `str` is a common character that doesn't need - * to be processed to be used for matching. - * @param {String} `str` - * @return {Boolean} - */ -utils.isSimpleChar = function(str) { - return str.trim() === '' || str === '.'; -}; + res += str; + res = res.substr(0, max); + return res; +} -/** - * Returns true if the given str is an escaped or - * unescaped path character - */ -utils.isSlash = function(str) { - return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; -}; +/***/ }), -/** - * Returns a function that returns true if the given - * pattern matches or contains a `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ +/***/ 25622: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -utils.matchPath = function(pattern, options) { - return (options && options.contains) - ? utils.containsPattern(pattern, options) - : utils.equalsPattern(pattern, options); -}; +var util = __webpack_require__(10265); +var types = __webpack_require__(40432); +var sets = __webpack_require__(28135); +var positions = __webpack_require__(54771); -/** - * Returns true if the given (original) filepath or unixified path are equal - * to the given pattern. - */ -utils._equals = function(filepath, unixPath, pattern) { - return pattern === filepath || pattern === unixPath; -}; +module.exports = function(regexpStr) { + var i = 0, l, c, + start = { type: types.ROOT, stack: []}, -/** - * Returns true if the given (original) filepath or unixified path contain - * the given pattern. - */ + // Keep track of last clause/group and stack. + lastGroup = start, + last = start.stack, + groupStack = []; -utils._contains = function(filepath, unixPath, pattern) { - return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; -}; -/** - * Returns a function that returns true if the given - * pattern is the same as a given `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ + var repeatErr = function(i) { + util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1)); + }; -utils.equalsPattern = function(pattern, options) { - var unixify = utils.unixify(options); - options = options || {}; + // Decode a few escaped characters. + var str = util.strToChars(regexpStr); + l = str.length; - return function fn(filepath) { - var equal = utils._equals(filepath, unixify(filepath), pattern); - if (equal === true || options.nocase !== true) { - return equal; - } - var lower = filepath.toLowerCase(); - return utils._equals(lower, unixify(lower), pattern); - }; -}; + // Iterate through each character in string. + while (i < l) { + c = str[i++]; -/** - * Returns a function that returns true if the given - * pattern contains a `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ + switch (c) { + // Handle escaped characters, inclues a few sets. + case '\\': + c = str[i++]; -utils.containsPattern = function(pattern, options) { - var unixify = utils.unixify(options); - options = options || {}; + switch (c) { + case 'b': + last.push(positions.wordBoundary()); + break; - return function(filepath) { - var contains = utils._contains(filepath, unixify(filepath), pattern); - if (contains === true || options.nocase !== true) { - return contains; - } - var lower = filepath.toLowerCase(); - return utils._contains(lower, unixify(lower), pattern); - }; -}; + case 'B': + last.push(positions.nonWordBoundary()); + break; -/** - * Returns a function that returns true if the given - * regex matches the `filename` of a file path. - * - * @param {RegExp} `re` Matching regex - * @return {Function} - */ + case 'w': + last.push(sets.words()); + break; -utils.matchBasename = function(re) { - return function(filepath) { - return re.test(filepath) || re.test(path.basename(filepath)); - }; -}; + case 'W': + last.push(sets.notWords()); + break; -/** - * Returns the given value unchanced. - * @return {any} - */ + case 'd': + last.push(sets.ints()); + break; -utils.identity = function(val) { - return val; -}; + case 'D': + last.push(sets.notInts()); + break; -/** - * Determines the filepath to return based on the provided options. - * @return {any} - */ + case 's': + last.push(sets.whitespace()); + break; -utils.value = function(str, unixify, options) { - if (options && options.unixify === false) { - return str; - } - if (options && typeof options.unixify === 'function') { - return options.unixify(str); - } - return unixify(str); -}; + case 'S': + last.push(sets.notWhitespace()); + break; -/** - * Returns a function that normalizes slashes in a string to forward - * slashes, strips `./` from beginning of paths, and optionally unescapes - * special characters. - * @return {Function} - */ + default: + // Check if c is integer. + // In which case it's a reference. + if (/\d/.test(c)) { + last.push({ type: types.REFERENCE, value: parseInt(c, 10) }); -utils.unixify = function(options) { - var opts = options || {}; - return function(filepath) { - if (opts.stripPrefix !== false) { - filepath = utils.stripPrefix(filepath); - } - if (opts.unescape === true) { - filepath = utils.unescape(filepath); - } - if (opts.unixify === true || utils.isWindows()) { - filepath = utils.toPosixPath(filepath); - } - return filepath; - }; -}; + // Escaped character. + } else { + last.push({ type: types.CHAR, value: c.charCodeAt(0) }); + } + } + break; -/***/ }), -/***/ 18918: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Positionals. + case '^': + last.push(positions.begin()); + break; -"use strict"; -/*! - * define-property - * - * Copyright (c) 2015-2018, Jon Schlinkert. - * Released under the MIT License. - */ + case '$': + last.push(positions.end()); + break; + // Handle custom sets. + case '[': + // Check if this class is 'anti' i.e. [^abc]. + var not; + if (str[i] === '^') { + not = true; + i++; + } else { + not = false; + } -var isobject = __webpack_require__(96667); -var isDescriptor = __webpack_require__(44133); -var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) - ? Reflect.defineProperty - : Object.defineProperty; + // Get all the characters in class. + var classTokens = util.tokenizeClass(str.slice(i), regexpStr); -module.exports = function defineProperty(obj, key, val) { - if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { - throw new TypeError('expected an object, function, or array'); - } + // Increase index by length of class. + i += classTokens[1]; + last.push({ + type: types.SET, + set: classTokens[0], + not: not, + }); - if (typeof key !== 'string') { - throw new TypeError('expected "key" to be a string'); - } + break; - if (isDescriptor(val)) { - define(obj, key, val); - return obj; - } - define(obj, key, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); + // Class of any character except \n. + case '.': + last.push(sets.anyChar()); + break; - return obj; -}; + // Push group onto stack. + case '(': + // Create group. + var group = { + type: types.GROUP, + stack: [], + remember: true, + }; -/***/ }), + c = str[i]; -/***/ 69148: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // If if this is a special kind of group. + if (c === '?') { + c = str[i + 1]; + i += 2; -"use strict"; + // Match if followed by. + if (c === '=') { + group.followedBy = true; + // Match if not followed by. + } else if (c === '!') { + group.notFollowedBy = true; -var isExtendable = __webpack_require__(61781); -var assignSymbols = __webpack_require__(64353); + } else if (c !== ':') { + util.error(regexpStr, + 'Invalid group, character \'' + c + + '\' after \'?\' at column ' + (i - 1)); + } -module.exports = Object.assign || function(obj/*, objects*/) { - if (obj === null || typeof obj === 'undefined') { - throw new TypeError('Cannot convert undefined or null to object'); - } - if (!isObject(obj)) { - obj = {}; - } - for (var i = 1; i < arguments.length; i++) { - var val = arguments[i]; - if (isString(val)) { - val = toObject(val); - } - if (isObject(val)) { - assign(obj, val); - assignSymbols(obj, val); - } - } - return obj; -}; + group.remember = false; + } -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } - } -} + // Insert subgroup into current group stack. + last.push(group); -function isString(val) { - return (val && typeof val === 'string'); -} + // Remember the current group for when the group closes. + groupStack.push(lastGroup); -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; - } - return obj; -} + // Make this new group the current group. + lastGroup = group; + last = group.stack; + break; -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); -} -/** - * Returns true if the given `key` is an own property of `obj`. - */ + // Pop group out of stack. + case ')': + if (groupStack.length === 0) { + util.error(regexpStr, 'Unmatched ) at column ' + (i - 1)); + } + lastGroup = groupStack.pop(); -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} + // Check if this group has a PIPE. + // To get back the correct last stack. + last = lastGroup.options ? + lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack; + break; -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); -} + // Use pipe character to give more choices. + case '|': + // Create array where options are if this is the first PIPE + // in this clause. + if (!lastGroup.options) { + lastGroup.options = [lastGroup.stack]; + delete lastGroup.stack; + } -/***/ }), + // Create a new stack and add to options for rest of clause. + var stack = []; + lastGroup.options.push(stack); + last = stack; + break; -/***/ 61781: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ + // Repetition. + // For every repetition, remove last element from last stack + // then insert back a RANGE object. + // This design is chosen because there could be more than + // one repetition symbols in a regex i.e. `a?+{2,3}`. + case '{': + var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max; + if (rs !== null) { + if (last.length === 0) { + repeatErr(i); + } + min = parseInt(rs[1], 10); + max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min; + i += rs[0].length; + last.push({ + type: types.REPETITION, + min: min, + max: max, + value: last.pop(), + }); + } else { + last.push({ + type: types.CHAR, + value: 123, + }); + } + break; + case '?': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 0, + max: 1, + value: last.pop(), + }); + break; -var isPlainObject = __webpack_require__(81064); + case '+': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 1, + max: Infinity, + value: last.pop(), + }); + break; -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); -}; + case '*': + if (last.length === 0) { + repeatErr(i); + } + last.push({ + type: types.REPETITION, + min: 0, + max: Infinity, + value: last.pop(), + }); + break; -/***/ }), + // Default is a character that is not `\[](){}?+*^$`. + default: + last.push({ + type: types.CHAR, + value: c.charCodeAt(0), + }); + } -/***/ 8025: -/***/ (function(module, exports) { + } -/*! - * is-windows - * - * Copyright © 2015-2018, Jon Schlinkert. - * Released under the MIT License. - */ - -(function(factory) { - if (exports && typeof exports === 'object' && "object" !== 'undefined') { - module.exports = factory(); - } else if (typeof define === 'function' && define.amd) { - define([], factory); - } else if (typeof window !== 'undefined') { - window.isWindows = factory(); - } else if (typeof global !== 'undefined') { - global.isWindows = factory(); - } else if (typeof self !== 'undefined') { - self.isWindows = factory(); - } else { - this.isWindows = factory(); + // Check if any groups have not been closed. + if (groupStack.length !== 0) { + util.error(regexpStr, 'Unterminated group'); } -})(function() { - 'use strict'; - return function isWindows() { - return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE)); - }; -}); + return start; +}; -/***/ }), +module.exports.types = types; -/***/ 42556: -/***/ (function(module) { -var toString = Object.prototype.toString; +/***/ }), -module.exports = function kindOf(val) { - if (val === void 0) return 'undefined'; - if (val === null) return 'null'; +/***/ 54771: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - var type = typeof val; - if (type === 'boolean') return 'boolean'; - if (type === 'string') return 'string'; - if (type === 'number') return 'number'; - if (type === 'symbol') return 'symbol'; - if (type === 'function') { - return isGeneratorFn(val) ? 'generatorfunction' : 'function'; - } +var types = __webpack_require__(40432); - if (isArray(val)) return 'array'; - if (isBuffer(val)) return 'buffer'; - if (isArguments(val)) return 'arguments'; - if (isDate(val)) return 'date'; - if (isError(val)) return 'error'; - if (isRegexp(val)) return 'regexp'; +exports.wordBoundary = function() { + return { type: types.POSITION, value: 'b' }; +}; - switch (ctorName(val)) { - case 'Symbol': return 'symbol'; - case 'Promise': return 'promise'; +exports.nonWordBoundary = function() { + return { type: types.POSITION, value: 'B' }; +}; - // Set, Map, WeakSet, WeakMap - case 'WeakMap': return 'weakmap'; - case 'WeakSet': return 'weakset'; - case 'Map': return 'map'; - case 'Set': return 'set'; +exports.begin = function() { + return { type: types.POSITION, value: '^' }; +}; - // 8-bit typed arrays - case 'Int8Array': return 'int8array'; - case 'Uint8Array': return 'uint8array'; - case 'Uint8ClampedArray': return 'uint8clampedarray'; +exports.end = function() { + return { type: types.POSITION, value: '$' }; +}; - // 16-bit typed arrays - case 'Int16Array': return 'int16array'; - case 'Uint16Array': return 'uint16array'; - // 32-bit typed arrays - case 'Int32Array': return 'int32array'; - case 'Uint32Array': return 'uint32array'; - case 'Float32Array': return 'float32array'; - case 'Float64Array': return 'float64array'; - } +/***/ }), - if (isGeneratorObj(val)) { - return 'generator'; - } +/***/ 28135: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - // Non-plain objects - type = toString.call(val); - switch (type) { - case '[object Object]': return 'object'; - // iterators - case '[object Map Iterator]': return 'mapiterator'; - case '[object Set Iterator]': return 'setiterator'; - case '[object String Iterator]': return 'stringiterator'; - case '[object Array Iterator]': return 'arrayiterator'; - } +var types = __webpack_require__(40432); - // other - return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +var INTS = function() { + return [{ type: types.RANGE , from: 48, to: 57 }]; }; -function ctorName(val) { - return typeof val.constructor === 'function' ? val.constructor.name : null; -} +var WORDS = function() { + return [ + { type: types.CHAR, value: 95 }, + { type: types.RANGE, from: 97, to: 122 }, + { type: types.RANGE, from: 65, to: 90 } + ].concat(INTS()); +}; -function isArray(val) { - if (Array.isArray) return Array.isArray(val); - return val instanceof Array; -} +var WHITESPACE = function() { + return [ + { type: types.CHAR, value: 9 }, + { type: types.CHAR, value: 10 }, + { type: types.CHAR, value: 11 }, + { type: types.CHAR, value: 12 }, + { type: types.CHAR, value: 13 }, + { type: types.CHAR, value: 32 }, + { type: types.CHAR, value: 160 }, + { type: types.CHAR, value: 5760 }, + { type: types.CHAR, value: 6158 }, + { type: types.CHAR, value: 8192 }, + { type: types.CHAR, value: 8193 }, + { type: types.CHAR, value: 8194 }, + { type: types.CHAR, value: 8195 }, + { type: types.CHAR, value: 8196 }, + { type: types.CHAR, value: 8197 }, + { type: types.CHAR, value: 8198 }, + { type: types.CHAR, value: 8199 }, + { type: types.CHAR, value: 8200 }, + { type: types.CHAR, value: 8201 }, + { type: types.CHAR, value: 8202 }, + { type: types.CHAR, value: 8232 }, + { type: types.CHAR, value: 8233 }, + { type: types.CHAR, value: 8239 }, + { type: types.CHAR, value: 8287 }, + { type: types.CHAR, value: 12288 }, + { type: types.CHAR, value: 65279 } + ]; +}; -function isError(val) { - return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); -} +var NOTANYCHAR = function() { + return [ + { type: types.CHAR, value: 10 }, + { type: types.CHAR, value: 13 }, + { type: types.CHAR, value: 8232 }, + { type: types.CHAR, value: 8233 }, + ]; +}; -function isDate(val) { - if (val instanceof Date) return true; - return typeof val.toDateString === 'function' - && typeof val.getDate === 'function' - && typeof val.setDate === 'function'; -} +// Predefined class objects. +exports.words = function() { + return { type: types.SET, set: WORDS(), not: false }; +}; -function isRegexp(val) { - if (val instanceof RegExp) return true; - return typeof val.flags === 'string' - && typeof val.ignoreCase === 'boolean' - && typeof val.multiline === 'boolean' - && typeof val.global === 'boolean'; -} +exports.notWords = function() { + return { type: types.SET, set: WORDS(), not: true }; +}; -function isGeneratorFn(name, val) { - return ctorName(name) === 'GeneratorFunction'; -} +exports.ints = function() { + return { type: types.SET, set: INTS(), not: false }; +}; -function isGeneratorObj(val) { - return typeof val.throw === 'function' - && typeof val.return === 'function' - && typeof val.next === 'function'; -} +exports.notInts = function() { + return { type: types.SET, set: INTS(), not: true }; +}; -function isArguments(val) { - try { - if (typeof val.length === 'number' && typeof val.callee === 'function') { - return true; - } - } catch (err) { - if (err.message.indexOf('callee') !== -1) { - return true; - } - } - return false; -} +exports.whitespace = function() { + return { type: types.SET, set: WHITESPACE(), not: false }; +}; -/** - * If you need to support Safari 5-7 (8-10 yr-old browser), - * take a look at https://github.com/feross/is-buffer - */ +exports.notWhitespace = function() { + return { type: types.SET, set: WHITESPACE(), not: true }; +}; -function isBuffer(val) { - if (val.constructor && typeof val.constructor.isBuffer === 'function') { - return val.constructor.isBuffer(val); - } - return false; -} +exports.anyChar = function() { + return { type: types.SET, set: NOTANYCHAR(), not: true }; +}; /***/ }), -/***/ 31368: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - +/***/ 40432: +/***/ (function(module) { -var typeOf = __webpack_require__(48865); -var copyDescriptor = __webpack_require__(3605); -var define = __webpack_require__(5477); +module.exports = { + ROOT : 0, + GROUP : 1, + POSITION : 2, + SET : 3, + RANGE : 4, + REPETITION : 5, + REFERENCE : 6, + CHAR : 7, +}; -/** - * Copy static properties, prototype properties, and descriptors from one object to another. - * - * ```js - * function App() {} - * var proto = App.prototype; - * App.prototype.set = function() {}; - * App.prototype.get = function() {}; - * - * var obj = {}; - * copy(obj, proto); - * ``` - * @param {Object} `receiver` - * @param {Object} `provider` - * @param {String|Array} `omit` One or more properties to omit - * @return {Object} - * @api public - */ -function copy(receiver, provider, omit) { - if (!isObject(receiver)) { - throw new TypeError('expected receiving object to be an object.'); - } - if (!isObject(provider)) { - throw new TypeError('expected providing object to be an object.'); - } +/***/ }), - var props = nativeKeys(provider); - var keys = Object.keys(provider); - var len = props.length; - omit = arrayify(omit); +/***/ 10265: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - while (len--) { - var key = props[len]; +var types = __webpack_require__(40432); +var sets = __webpack_require__(28135); - if (has(keys, key)) { - define(receiver, key, provider[key]); - } else if (!(key in receiver) && !has(omit, key)) { - copyDescriptor(receiver, provider, key); - } - } -}; -/** - * Return true if the given value is an object or function - */ +// All of these are private and only used by randexp. +// It's assumed that they will always be called with the correct input. -function isObject(val) { - return typeOf(val) === 'object' || typeof val === 'function'; -} +var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?'; +var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 }; /** - * Returns true if an array has any of the given elements, or an - * object has any of the give keys. - * - * ```js - * has(['a', 'b', 'c'], 'c'); - * //=> true - * - * has(['a', 'b', 'c'], ['c', 'z']); - * //=> true + * Finds character representations in str and convert all to + * their respective characters * - * has({a: 'b', c: 'd'}, ['c', 'z']); - * //=> true - * ``` - * @param {Object} `obj` - * @param {String|Array} `val` - * @return {Boolean} + * @param {String} str + * @return {String} */ - -function has(obj, val) { - val = arrayify(val); - var len = val.length; - - if (isObject(obj)) { - for (var key in obj) { - if (val.indexOf(key) > -1) { - return true; - } +exports.strToChars = function(str) { + /* jshint maxlen: false */ + var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g; + str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) { + if (lbs) { + return s; } - var keys = nativeKeys(obj); - return has(keys, val); - } - - if (Array.isArray(obj)) { - var arr = obj; - while (len--) { - if (arr.indexOf(val[len]) > -1) { - return true; - } - } - return false; - } + var code = b ? 8 : + a16 ? parseInt(a16, 16) : + b16 ? parseInt(b16, 16) : + c8 ? parseInt(c8, 8) : + dctrl ? CTRL.indexOf(dctrl) : + SLSH[eslsh]; - throw new TypeError('expected an array or object.'); -} + var c = String.fromCharCode(code); -/** - * Cast the given value to an array. - * - * ```js - * arrayify('foo'); - * //=> ['foo'] - * - * arrayify(['foo']); - * //=> ['foo'] - * ``` - * - * @param {String|Array} `val` - * @return {Array} - */ + // Escape special regex characters. + if (/[\[\]{}\^$.|?*+()]/.test(c)) { + c = '\\' + c; + } -function arrayify(val) { - return val ? (Array.isArray(val) ? val : [val]) : []; -} + return c; + }); -/** - * Returns true if a value has a `contructor` - * - * ```js - * hasConstructor({}); - * //=> true - * - * hasConstructor(Object.create(null)); - * //=> false - * ``` - * @param {Object} `value` - * @return {Boolean} - */ + return str; +}; -function hasConstructor(val) { - return isObject(val) && typeof val.constructor !== 'undefined'; -} /** - * Get the native `ownPropertyNames` from the constructor of the - * given `object`. An empty array is returned if the object does - * not have a constructor. - * - * ```js - * nativeKeys({a: 'b', b: 'c', c: 'd'}) - * //=> ['a', 'b', 'c'] - * - * nativeKeys(function(){}) - * //=> ['length', 'caller'] - * ``` + * turns class into tokens + * reads str until it encounters a ] not preceeded by a \ * - * @param {Object} `obj` Object that has a `constructor`. - * @return {Array} Array of keys. - */ - -function nativeKeys(val) { - if (!hasConstructor(val)) return []; - return Object.getOwnPropertyNames(val); -} - -/** - * Expose `copy` - */ - -module.exports = copy; - -/** - * Expose `copy.has` for tests + * @param {String} str + * @param {String} regexpStr + * @return {Array., Number>} */ +exports.tokenizeClass = function(str, regexpStr) { + /* jshint maxlen: false */ + var tokens = []; + var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g; + var rs, c; -module.exports.has = has; + while ((rs = regexp.exec(str)) != null) { + if (rs[1]) { + tokens.push(sets.words()); -/***/ }), + } else if (rs[2]) { + tokens.push(sets.ints()); -/***/ 59248: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + } else if (rs[3]) { + tokens.push(sets.whitespace()); -"use strict"; -/*! - * object-visit - * - * Copyright (c) 2015, 2017, Jon Schlinkert. - * Released under the MIT License. - */ + } else if (rs[4]) { + tokens.push(sets.notWords()); + } else if (rs[5]) { + tokens.push(sets.notInts()); + } else if (rs[6]) { + tokens.push(sets.notWhitespace()); -var isObject = __webpack_require__(96667); + } else if (rs[7]) { + tokens.push({ + type: types.RANGE, + from: (rs[8] || rs[9]).charCodeAt(0), + to: rs[10].charCodeAt(0), + }); -module.exports = function visit(thisArg, method, target, val) { - if (!isObject(thisArg) && typeof thisArg !== 'function') { - throw new Error('object-visit expects `thisArg` to be an object.'); - } + } else if (c = rs[12]) { + tokens.push({ + type: types.CHAR, + value: c.charCodeAt(0), + }); - if (typeof method !== 'string') { - throw new Error('object-visit expects `method` name to be a string'); + } else { + return [tokens, regexp.lastIndex]; + } } - if (typeof thisArg[method] !== 'function') { - return thisArg; - } + exports.error(regexpStr, 'Unterminated character class'); +}; - var args = [].slice.call(arguments, 3); - target = target || {}; - for (var key in target) { - var arr = [key, target[key]].concat(args); - thisArg[method].apply(thisArg, arr); - } - return thisArg; +/** + * Shortcut to throw errors. + * + * @param {String} regexp + * @param {String} msg + */ +exports.error = function(regexp, msg) { + throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg); }; /***/ }), -/***/ 38509: +/***/ 71217: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/*! - * object.pick - * - * Copyright (c) 2014-2015 Jon Schlinkert, contributors. - * Licensed under the MIT License - */ - - - -var isObject = __webpack_require__(96667); - -module.exports = function pick(obj, keys) { - if (!isObject(obj) && typeof obj !== 'function') { - return {}; - } - - var res = {}; - if (typeof keys === 'string') { - if (keys in obj) { - res[keys] = obj[keys]; - } - return res; - } - - var len = keys.length; - var idx = -1; +var parse = __webpack_require__(25622); +var types = parse.types; - while (++idx < len) { - var key = keys[idx]; - if (key in obj) { - res[key] = obj[key]; - } - } - return res; +module.exports = function (re, opts) { + if (!opts) opts = {}; + var replimit = opts.limit === undefined ? 25 : opts.limit; + + if (isRegExp(re)) re = re.source; + else if (typeof re !== 'string') re = String(re); + + try { re = parse(re) } + catch (err) { return false } + + var reps = 0; + return (function walk (node, starHeight) { + if (node.type === types.REPETITION) { + starHeight ++; + reps ++; + if (starHeight > 1) return false; + if (reps > replimit) return false; + } + + if (node.options) { + for (var i = 0, len = node.options.length; i < len; i++) { + var ok = walk({ stack: node.options[i] }, starHeight); + if (!ok) return false; + } + } + var stack = node.stack || (node.value && node.value.stack); + if (!stack) return true; + + for (var i = 0; i < stack.length; i++) { + var ok = walk(stack[i], starHeight); + if (!ok) return false; + } + + return true; + })(re, 0); }; - -/***/ }), - -/***/ 27255: -/***/ (function(module) { - -/*! - * pascalcase - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. - */ - -function pascalcase(str) { - if (typeof str !== 'string') { - throw new TypeError('expected a string.'); - } - str = str.replace(/([A-Z])/g, ' $1'); - if (str.length === 1) { return str.toUpperCase(); } - str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase(); - str = str.charAt(0).toUpperCase() + str.slice(1); - return str.replace(/[\W_]+(\w|$)/g, function (_, ch) { - return ch.toUpperCase(); - }); +function isRegExp (x) { + return {}.toString.call(x) === '[object RegExp]'; } -module.exports = pascalcase; - /***/ }), -/***/ 88412: -/***/ (function(module) { +/***/ 85841: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* +Copyright (c) 2014, Yahoo! Inc. All rights reserved. +Copyrights licensed under the New BSD License. +See the accompanying LICENSE file for terms. +*/ -/** - * POSIX character classes - */ - -module.exports = { - alnum: 'a-zA-Z0-9', - alpha: 'a-zA-Z', - ascii: '\\x00-\\x7F', - blank: ' \\t', - cntrl: '\\x00-\\x1F\\x7F', - digit: '0-9', - graph: '\\x21-\\x7E', - lower: 'a-z', - print: '\\x20-\\x7E ', - punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', - space: ' \\t\\r\\n\\v\\f', - upper: 'A-Z', - word: 'A-Za-z0-9_', - xdigit: 'A-Fa-f0-9' -}; +var randomBytes = __webpack_require__(79822); -/***/ }), +// Generate an internal UID to make the regexp pattern harder to guess. +var UID_LENGTH = 16; +var UID = generateUID(); +var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|U|I)-' + UID + '-(\\d+)__@"', 'g'); -/***/ 58404: -/***/ (function(module) { +var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g; +var IS_PURE_FUNCTION = /function.*?\(/; +var IS_ARROW_FUNCTION = /.*?=>.*?/; +var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g; -"use strict"; +var RESERVED_SYMBOLS = ['*', 'async']; +// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their +// Unicode char counterparts which are safe to use in JavaScript strings. +var ESCAPED_CHARS = { + '<' : '\\u003C', + '>' : '\\u003E', + '/' : '\\u002F', + '\u2028': '\\u2028', + '\u2029': '\\u2029' +}; -if (typeof process === 'undefined' || - !process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = { nextTick: nextTick }; -} else { - module.exports = process +function escapeUnsafeChars(unsafeChar) { + return ESCAPED_CHARS[unsafeChar]; } -function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; +function generateUID() { + var bytes = randomBytes(UID_LENGTH); + var result = ''; + for(var i=0; i - * https://github.com/rvagg/prr - * License: MIT - */ + var functions = []; + var regexps = []; + var dates = []; + var maps = []; + var sets = []; + var undefs = []; + var infinities= []; -(function (name, context, definition) { - if ( true && module.exports) - module.exports = definition() - else - context[name] = definition() -})('prr', this, function() { + // Returns placeholders for functions and regexps (identified by index) + // which are later replaced by their string representation. + function replacer(key, value) { - var setProperty = typeof Object.defineProperty == 'function' - ? function (obj, key, options) { - Object.defineProperty(obj, key, options) - return obj + // For nested function + if(options.ignoreFunction){ + deleteFunctions(value); } - : function (obj, key, options) { // < es5 - obj[key] = options.value - return obj + + if (!value && value !== undefined) { + return value; } - , makeOptions = function (value, options) { - var oo = typeof options == 'object' - , os = !oo && typeof options == 'string' - , op = function (p) { - return oo - ? !!options[p] - : os - ? options.indexOf(p[0]) > -1 - : false + // If the value is an object w/ a toJSON method, toJSON is called before + // the replacer runs, so we use this[key] to get the non-toJSONed value. + var origValue = this[key]; + var type = typeof origValue; + + if (type === 'object') { + if(origValue instanceof RegExp) { + return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@'; } - return { - enumerable : op('enumerable') - , configurable : op('configurable') - , writable : op('writable') - , value : value + if(origValue instanceof Date) { + return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@'; + } + + if(origValue instanceof Map) { + return '@__M-' + UID + '-' + (maps.push(origValue) - 1) + '__@'; + } + + if(origValue instanceof Set) { + return '@__S-' + UID + '-' + (sets.push(origValue) - 1) + '__@'; + } } - } - , prr = function (obj, key, value, options) { - var k + if (type === 'function') { + return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@'; + } - options = makeOptions(value, options) + if (type === 'undefined') { + return '@__U-' + UID + '-' + (undefs.push(origValue) - 1) + '__@'; + } - if (typeof key == 'object') { - for (k in key) { - if (Object.hasOwnProperty.call(key, k)) { - options.value = key[k] - setProperty(obj, k, options) - } - } - return obj + if (type === 'number' && !isNaN(origValue) && !isFinite(origValue)) { + return '@__I-' + UID + '-' + (infinities.push(origValue) - 1) + '__@'; } - return setProperty(obj, key, options) + return value; + } + + function serializeFunc(fn) { + var serializedFn = fn.toString(); + if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) { + throw new TypeError('Serializing native function: ' + fn.name); } - return prr -}) + // pure functions, example: {key: function() {}} + if(IS_PURE_FUNCTION.test(serializedFn)) { + return serializedFn; + } -/***/ }), + // arrow functions, example: arg1 => arg1+5 + if(IS_ARROW_FUNCTION.test(serializedFn)) { + return serializedFn; + } -/***/ 79822: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + var argsStartsAt = serializedFn.indexOf('('); + var def = serializedFn.substr(0, argsStartsAt) + .trim() + .split(' ') + .filter(function(val) { return val.length > 0 }); -module.exports = __webpack_require__(76417).randomBytes + var nonReservedSymbols = def.filter(function(val) { + return RESERVED_SYMBOLS.indexOf(val) === -1 + }); + // enhanced literal objects, example: {key() {}} + if(nonReservedSymbols.length > 0) { + return (def.indexOf('async') > -1 ? 'async ' : '') + 'function' + + (def.join('').indexOf('*') > -1 ? '*' : '') + + serializedFn.substr(argsStartsAt); + } -/***/ }), + // arrow functions + return serializedFn; + } -/***/ 42770: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Check if the parameter is function + if (options.ignoreFunction && typeof obj === "function") { + obj = undefined; + } + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (obj === undefined) { + return String(obj); + } -"use strict"; -// 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 str; -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. + // Creates a JSON string representation of the value. + // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args. + if (options.isJSON && !options.space) { + str = JSON.stringify(obj); + } else { + str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space); + } + + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (typeof str !== 'string') { + return String(str); + } + // Replace unsafe HTML and invalid JavaScript line terminator chars with + // their safe Unicode char counterpart. This _must_ happen before the + // regexps and functions are serialized and added back to the string. + if (options.unsafe !== true) { + str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars); + } + if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && undefs.length === 0 && infinities.length === 0) { + return str; + } -/**/ + // Replaces all occurrences of function, regexp, date, map and set placeholders in the + // JSON string with their string representations. If the original value can + // not be found, then `undefined` is used. + return str.replace(PLACE_HOLDER_REGEXP, function (match, backSlash, type, valueIndex) { + // The placeholder may not be preceded by a backslash. This is to prevent + // replacing things like `"a\"@__R--0__@"` and thus outputting + // invalid JS. + if (backSlash) { + return match; + } -var pna = __webpack_require__(58404); -/**/ + if (type === 'D') { + return "new Date(\"" + dates[valueIndex].toISOString() + "\")"; + } -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ + if (type === 'R') { + return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")"; + } -module.exports = Duplex; + if (type === 'M') { + return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")"; + } -/**/ -var util = Object.create(__webpack_require__(78334)); -util.inherits = __webpack_require__(2989); -/**/ + if (type === 'S') { + return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")"; + } -var Readable = __webpack_require__(79341); -var Writable = __webpack_require__(78063); + if (type === 'U') { + return 'undefined' + } -util.inherits(Duplex, Readable); + if (type === 'I') { + return infinities[valueIndex]; + } -{ - // avoid scope creep, the keys array can then be collected - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } + var fn = functions[valueIndex]; + + return serializeFunc(fn); + }); } -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); +/***/ }), - if (options && options.readable === false) this.readable = false; +/***/ 34857: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (options && options.writable === false) this.writable = false; +"use strict"; +/*! + * set-value + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - this.once('end', onend); -} -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); +var split = __webpack_require__(33218); +var extend = __webpack_require__(28727); +var isPlainObject = __webpack_require__(81064); +var isObject = __webpack_require__(18493); -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; +module.exports = function(obj, prop, val) { + if (!isObject(obj)) { + return obj; + } - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); -} + if (Array.isArray(prop)) { + prop = [].concat.apply([], prop).join('.'); + } -function onEndNT(self) { - self.end(); -} + if (typeof prop !== 'string') { + return obj; + } -Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; + var keys = split(prop, {sep: '.', brackets: true}).filter(isValidKey); + var len = keys.length; + var idx = -1; + var current = obj; + + while (++idx < len) { + var key = keys[idx]; + if (idx !== len - 1) { + if (!isObject(current[key])) { + current[key] = {}; + } + current = current[key]; + continue; } - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; + if (isPlainObject(current[key]) && isPlainObject(val)) { + current[key] = extend({}, current[key], val); + } else { + current[key] = val; + } } -}); - -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); - pna.nextTick(cb, err); + return obj; }; -/***/ }), - -/***/ 60143: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +function isValidKey(key) { + return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; +} -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. +/***/ }), +/***/ 12579: +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -module.exports = PassThrough; -var Transform = __webpack_require__(62826); +var isObject = __webpack_require__(96667); +var define = __webpack_require__(88599); +var utils = __webpack_require__(82071); +var ownNames; -/**/ -var util = Object.create(__webpack_require__(78334)); -util.inherits = __webpack_require__(2989); -/**/ +/** + * Create a new AST `Node` with the given `val` and `type`. + * + * ```js + * var node = new Node('*', 'Star'); + * var node = new Node({type: 'star', val: '*'}); + * ``` + * @name Node + * @param {String|Object} `val` Pass a matched substring, or an object to merge onto the node. + * @param {String} `type` The node type to use when `val` is a string. + * @return {Object} node instance + * @api public + */ -util.inherits(PassThrough, Transform); +function Node(val, type, parent) { + if (typeof type !== 'string') { + parent = type; + type = null; + } -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); + define(this, 'parent', parent); + define(this, 'isNode', true); + define(this, 'expect', null); - Transform.call(this, options); + if (typeof type !== 'string' && isObject(val)) { + lazyKeys(); + var keys = Object.keys(val); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (ownNames.indexOf(key) === -1) { + this[key] = val[key]; + } + } + } else { + this.type = type; + this.val = val; + } } -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; +/** + * Returns true if the given value is a node. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(Node.isNode(node)); //=> true + * console.log(Node.isNode({})); //=> false + * ``` + * @param {Object} `node` + * @returns {Boolean} + * @api public + */ -/***/ }), +Node.isNode = function(node) { + return utils.isNode(node); +}; -/***/ 79341: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * Define a non-enumberable property on the node instance. + * Useful for adding properties that shouldn't be extended + * or visible during debugging. + * + * ```js + * var node = new Node(); + * node.define('foo', 'something non-enumerable'); + * ``` + * @param {String} `name` + * @param {any} `val` + * @return {Object} returns the node instance + * @api public + */ -"use strict"; -// 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. +Node.prototype.define = function(name, val) { + define(this, name, val); + return this; +}; +/** + * Returns true if `node.val` is an empty string, or `node.nodes` does + * not contain any non-empty text nodes. + * + * ```js + * var node = new Node({type: 'text'}); + * node.isEmpty(); //=> true + * node.val = 'foo'; + * node.isEmpty(); //=> false + * ``` + * @param {Function} `fn` (optional) Filter function that is called on `node` and/or child nodes. `isEmpty` will return false immediately when the filter function returns false on any nodes. + * @return {Boolean} + * @api public + */ +Node.prototype.isEmpty = function(fn) { + return utils.isEmpty(this, fn); +}; -/**/ +/** + * Given node `foo` and node `bar`, push node `bar` onto `foo.nodes`, and + * set `foo` as `bar.parent`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.push(bar); + * ``` + * @param {Object} `node` + * @return {Number} Returns the length of `node.nodes` + * @api public + */ -var pna = __webpack_require__(58404); -/**/ +Node.prototype.push = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + define(node, 'parent', this); -module.exports = Readable; + this.nodes = this.nodes || []; + return this.nodes.push(node); +}; -/**/ -var isArray = __webpack_require__(21352); -/**/ +/** + * Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and + * set `foo` as `bar.parent`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.unshift(bar); + * ``` + * @param {Object} `node` + * @return {Number} Returns the length of `node.nodes` + * @api public + */ -/**/ -var Duplex; -/**/ +Node.prototype.unshift = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + define(node, 'parent', this); -Readable.ReadableState = ReadableState; + this.nodes = this.nodes || []; + return this.nodes.unshift(node); +}; -/**/ -var EE = __webpack_require__(28614).EventEmitter; +/** + * Pop a node from `node.nodes`. + * + * ```js + * var node = new Node({type: 'foo'}); + * node.push(new Node({type: 'a'})); + * node.push(new Node({type: 'b'})); + * node.push(new Node({type: 'c'})); + * node.push(new Node({type: 'd'})); + * console.log(node.nodes.length); + * //=> 4 + * node.pop(); + * console.log(node.nodes.length); + * //=> 3 + * ``` + * @return {Number} Returns the popped `node` + * @api public + */ -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; +Node.prototype.pop = function() { + return this.nodes && this.nodes.pop(); }; -/**/ - -/**/ -var Stream = __webpack_require__(1065); -/**/ -/**/ +/** + * Shift a node from `node.nodes`. + * + * ```js + * var node = new Node({type: 'foo'}); + * node.push(new Node({type: 'a'})); + * node.push(new Node({type: 'b'})); + * node.push(new Node({type: 'c'})); + * node.push(new Node({type: 'd'})); + * console.log(node.nodes.length); + * //=> 4 + * node.shift(); + * console.log(node.nodes.length); + * //=> 3 + * ``` + * @return {Object} Returns the shifted `node` + * @api public + */ -var Buffer = __webpack_require__(96788).Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} +Node.prototype.shift = function() { + return this.nodes && this.nodes.shift(); +}; -/**/ +/** + * Remove `node` from `node.nodes`. + * + * ```js + * node.remove(childNode); + * ``` + * @param {Object} `node` + * @return {Object} Returns the removed node. + * @api public + */ -/**/ -var util = Object.create(__webpack_require__(78334)); -util.inherits = __webpack_require__(2989); -/**/ +Node.prototype.remove = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + this.nodes = this.nodes || []; + var idx = node.index; + if (idx !== -1) { + node.index = -1; + return this.nodes.splice(idx, 1); + } + return null; +}; -/**/ -var debugUtil = __webpack_require__(31669); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ +/** + * Get the first child node from `node.nodes` that matches the given `type`. + * If `type` is a number, the child node at that index is returned. + * + * ```js + * var child = node.find(1); //<= index of the node to get + * var child = node.find('foo'); //<= node.type of a child node + * var child = node.find(/^(foo|bar)$/); //<= regex to match node.type + * var child = node.find(['foo', 'bar']); //<= array of node.type(s) + * ``` + * @param {String} `type` + * @return {Object} Returns a child node or undefined. + * @api public + */ -var BufferList = __webpack_require__(28878); -var destroyImpl = __webpack_require__(87915); -var StringDecoder; +Node.prototype.find = function(type) { + return utils.findNode(this.nodes, type); +}; -util.inherits(Readable, Stream); +/** + * Return true if the node is the given `type`. + * + * ```js + * var node = new Node({type: 'bar'}); + * cosole.log(node.isType('foo')); // false + * cosole.log(node.isType(/^(foo|bar)$/)); // true + * cosole.log(node.isType(['foo', 'bar'])); // true + * ``` + * @param {String} `type` + * @return {Boolean} + * @api public + */ -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +Node.prototype.isType = function(type) { + return utils.isType(this, type); +}; -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); +/** + * Return true if the `node.nodes` has the given `type`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.push(bar); + * + * cosole.log(foo.hasType('qux')); // false + * cosole.log(foo.hasType(/^(qux|bar)$/)); // true + * cosole.log(foo.hasType(['qux', 'bar'])); // true + * ``` + * @param {String} `type` + * @return {Boolean} + * @api public + */ - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} +Node.prototype.hasType = function(type) { + return utils.hasType(this, type); +}; -function ReadableState(options, stream) { - Duplex = Duplex || __webpack_require__(42770); +/** + * Get the siblings array, or `null` if it doesn't exist. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(bar.siblings.length) // 2 + * console.log(baz.siblings.length) // 2 + * ``` + * @return {Array} + * @api public + */ - options = options || {}; +Object.defineProperty(Node.prototype, 'siblings', { + set: function() { + throw new Error('node.siblings is a getter and cannot be defined'); + }, + get: function() { + return this.parent ? this.parent.nodes : null; + } +}); - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; +/** + * Get the node's current index from `node.parent.nodes`. + * This should always be correct, even when the parent adds nodes. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.unshift(qux); + * + * console.log(bar.index) // 1 + * console.log(baz.index) // 2 + * console.log(qux.index) // 0 + * ``` + * @return {Number} + * @api public + */ - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; +Object.defineProperty(Node.prototype, 'index', { + set: function(index) { + define(this, 'idx', index); + }, + get: function() { + if (!Array.isArray(this.siblings)) { + return -1; + } + var tok = this.idx !== -1 ? this.siblings[this.idx] : null; + if (tok !== this) { + this.idx = this.siblings.indexOf(this); + } + return this.idx; + } +}); - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; +/** + * Get the previous node from the siblings array or `null`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(baz.prev.type) // 'bar' + * ``` + * @return {Object} + * @api public + */ - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; +Object.defineProperty(Node.prototype, 'prev', { + set: function() { + throw new Error('node.prev is a getter and cannot be defined'); + }, + get: function() { + if (Array.isArray(this.siblings)) { + return this.siblings[this.index - 1] || this.parent.prev; + } + return null; + } +}); - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - - // has it been destroyed - this.destroyed = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; +/** + * Get the siblings array, or `null` if it doesn't exist. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(bar.siblings.length) // 2 + * console.log(baz.siblings.length) // 2 + * ``` + * @return {Object} + * @api public + */ - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = __webpack_require__(7395)/* .StringDecoder */ .s; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; +Object.defineProperty(Node.prototype, 'next', { + set: function() { + throw new Error('node.next is a getter and cannot be defined'); + }, + get: function() { + if (Array.isArray(this.siblings)) { + return this.siblings[this.index + 1] || this.parent.next; + } + return null; } -} - -function Readable(options) { - Duplex = Duplex || __webpack_require__(42770); - - if (!(this instanceof Readable)) return new Readable(options); +}); - this._readableState = new ReadableState(options, this); +/** + * Get the first node from `node.nodes`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); + * + * console.log(foo.first.type) // 'bar' + * ``` + * @return {Object} The first node, or undefiend + * @api public + */ - // legacy - this.readable = true; +Object.defineProperty(Node.prototype, 'first', { + get: function() { + return this.nodes ? this.nodes[0] : null; + } +}); - if (options) { - if (typeof options.read === 'function') this._read = options.read; +/** + * Get the last node from `node.nodes`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); + * + * console.log(foo.last.type) // 'qux' + * ``` + * @return {Object} The last node, or undefiend + * @api public + */ - if (typeof options.destroy === 'function') this._destroy = options.destroy; +Object.defineProperty(Node.prototype, 'last', { + get: function() { + return this.nodes ? utils.last(this.nodes) : null; } +}); - Stream.call(this); -} +/** + * Get the last node from `node.nodes`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); + * + * console.log(foo.last.type) // 'qux' + * ``` + * @return {Object} The last node, or undefiend + * @api public + */ -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; +Object.defineProperty(Node.prototype, 'scope', { + get: function() { + if (this.isScope !== true) { + return this.parent ? this.parent.scope : this; } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; + return this; } }); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); -}; - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; +/** + * Get own property names from Node prototype, but only the + * first time `Node` is instantiated + */ - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; +function lazyKeys() { + if (!ownNames) { + ownNames = Object.getOwnPropertyNames(Node.prototype); } +} - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; +/** + * Simplified assertion. Throws an error is `val` is falsey. + */ -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; +function assert(val, message) { + if (!val) throw new Error(message); +} -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } +/** + * Expose `Node` + */ - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - } - } +exports = module.exports = Node; - return needMoreData(state); -} -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); +/***/ }), - if (state.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state); -} +/***/ 88599: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __webpack_require__(7395)/* .StringDecoder */ .s; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; +var isDescriptor = __webpack_require__(44133); -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); } - return n; -} -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; + + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); } - return state.length; -} -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; - if (n !== 0) state.emittedReadable = false; - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } +/***/ }), - n = howMuchToRead(n, state); +/***/ 82071: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } +"use strict"; - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); +var typeOf = __webpack_require__(48865); +var utils = module.exports; - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } +/** + * Returns true if the given value is a node. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(utils.isNode(node)); //=> true + * console.log(utils.isNode({})); //=> false + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {Boolean} + * @api public + */ - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } +utils.isNode = function(node) { + return typeOf(node) === 'object' && node.isNode === true; +}; - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; +/** + * Emit an empty string for the given `node`. + * + * ```js + * // do nothing for beginning-of-string + * snapdragon.compiler.set('bos', utils.noop); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {undefined} + * @api public + */ - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } +utils.noop = function(node) { + append(this, '', node); +}; - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; +/** + * Appdend `node.val` to `compiler.output`, exactly as it was created + * by the parser. + * + * ```js + * snapdragon.compiler.set('text', utils.identity); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {undefined} + * @api public + */ - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } +utils.identity = function(node) { + append(this, node.val, node); +}; - if (ret !== null) this.emit('data', ret); +/** + * Previously named `.emit`, this method appends the given `val` + * to `compiler.output` for the given node. Useful when you know + * what value should be appended advance, regardless of the actual + * value of `node.val`. + * + * ```js + * snapdragon.compiler + * .set('i', function(node) { + * this.mapVisit(node); + * }) + * .set('i.open', utils.append('')) + * .set('i.close', utils.append('')) + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {Function} Returns a compiler middleware function. + * @api public + */ - return ret; +utils.append = function(val) { + return function(node) { + append(this, val, node); + }; }; -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); - } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} +/** + * Used in compiler middleware, this onverts an AST node into + * an empty `text` node and deletes `node.nodes` if it exists. + * The advantage of this method is that, as opposed to completely + * removing the node, indices will not need to be re-calculated + * in sibling nodes, and nothing is appended to the output. + * + * ```js + * utils.toNoop(node); + * // convert `node.nodes` to the given value instead of deleting it + * utils.toNoop(node, []); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array. + * @api public + */ -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - pna.nextTick(maybeReadMore_, stream, state); +utils.toNoop = function(node, nodes) { + if (nodes) { + node.nodes = nodes; + } else { + delete node.nodes; + node.type = 'text'; + node.val = ''; } -} +}; -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; -} +/** + * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon + * automatically calls registered compilers, this allows you to pass a visitor + * function. + * + * ```js + * snapdragon.compiler.set('i', function(node) { + * utils.visit(node, function(childNode) { + * // do stuff with "childNode" + * return childNode; + * }); + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `fn` + * @return {Object} returns the node after recursively visiting all child nodes. + * @api public + */ -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); +utils.visit = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(fn), 'expected a visitor function'); + fn(node); + return node.nodes ? utils.mapVisit(node, fn) : node; }; -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; +/** + * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by + * [visit](#visit), use this method if you do not want `fn` to be called on + * the first node. + * + * ```js + * snapdragon.compiler.set('i', function(node) { + * utils.mapVisit(node, function(childNode) { + * // do stuff with "childNode" + * return childNode; + * }); + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Object} `options` + * @param {Function} `fn` + * @return {Object} returns the node + * @api public + */ - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; +utils.mapVisit = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isArray(node.nodes), 'expected node.nodes to be an array'); + assert(isFunction(fn), 'expected a visitor function'); + + for (var i = 0; i < node.nodes.length; i++) { + utils.visit(node.nodes[i], fn); } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + return node; +}; - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; +/** + * Unshift an `*.open` node onto `node.nodes`. + * + * ```js + * var Node = require('snapdragon-node'); + * snapdragon.parser.set('brace', function(node) { + * var match = this.match(/^{/); + * if (match) { + * var parent = new Node({type: 'brace'}); + * utils.addOpen(parent, Node); + * console.log(parent.nodes[0]): + * // { type: 'brace.open', val: '' }; + * + * // push the parent "brace" node onto the stack + * this.push(parent); + * + * // return the parent node, so it's also added to the AST + * return brace; + * } + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the created opening node. + * @api public + */ - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); +utils.addOpen = function(node, Node, val, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } + if (typeof val === 'function') { + filter = val; + val = ''; } - function onend() { - debug('onend'); - dest.end(); + if (typeof filter === 'function' && !filter(node)) return; + var open = new Node({ type: node.type + '.open', val: val}); + var unshift = node.unshift || node.unshiftNode; + if (typeof unshift === 'function') { + unshift.call(node, open); + } else { + utils.unshiftNode(node, open); } + return open; +}; - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - - cleanedUp = true; +/** + * Push a `*.close` node onto `node.nodes`. + * + * ```js + * var Node = require('snapdragon-node'); + * snapdragon.parser.set('brace', function(node) { + * var match = this.match(/^}/); + * if (match) { + * var parent = this.parent(); + * if (parent.type !== 'brace') { + * throw new Error('missing opening: ' + '}'); + * } + * + * utils.addClose(parent, Node); + * console.log(parent.nodes[parent.nodes.length - 1]): + * // { type: 'brace.close', val: '' }; + * + * // no need to return a node, since the parent + * // was already added to the AST + * return; + * } + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the created closing node. + * @api public + */ - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } +utils.addClose = function(node, Node, val, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } + if (typeof val === 'function') { + filter = val; + val = ''; } - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + if (typeof filter === 'function' && !filter(node)) return; + var close = new Node({ type: node.type + '.close', val: val}); + var push = node.push || node.pushNode; + if (typeof push === 'function') { + push.call(node, close); + } else { + utils.pushNode(node, close); } + return close; +}; - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); +/** + * Wraps the given `node` with `*.open` and `*.close` nodes. + * + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the node + * @api public + */ - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); +utils.wrapNodes = function(node, Node, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } + utils.addOpen(node, Node, filter); + utils.addClose(node, Node, filter); + return node; +}; - // tell the dest that it's being piped to - dest.emit('pipe', src); +/** + * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent. + * + * ```js + * var parent = new Node({type: 'foo'}); + * var node = new Node({type: 'bar'}); + * utils.pushNode(parent, node); + * console.log(parent.nodes[0].type) // 'bar' + * console.log(node.parent.type) // 'foo' + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Object} Returns the child node + * @api public + */ - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } +utils.pushNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); - return dest; + node.define('parent', parent); + parent.nodes = parent.nodes || []; + parent.nodes.push(node); + return node; }; -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; +/** + * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent. + * + * ```js + * var parent = new Node({type: 'foo'}); + * var node = new Node({type: 'bar'}); + * utils.unshiftNode(parent, node); + * console.log(parent.nodes[0].type) // 'bar' + * console.log(node.parent.type) // 'foo' + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {undefined} + * @api public + */ - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; +utils.unshiftNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + node.define('parent', parent); + parent.nodes = parent.nodes || []; + parent.nodes.unshift(node); +}; - if (!dest) dest = state.pipes; +/** + * Pop the last `node` off of `parent.nodes`. The advantage of + * using this method is that it checks for `node.nodes` and works + * with any version of `snapdragon-node`. + * + * ```js + * var parent = new Node({type: 'foo'}); + * utils.pushNode(parent, new Node({type: 'foo'})); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.popNode(parent); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. + * @api public + */ - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; +utils.popNode = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (typeof node.pop === 'function') { + return node.pop(); } + return node.nodes && node.nodes.pop(); +}; - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; +/** + * Shift the first `node` off of `parent.nodes`. The advantage of + * using this method is that it checks for `node.nodes` and works + * with any version of `snapdragon-node`. + * + * ```js + * var parent = new Node({type: 'foo'}); + * utils.pushNode(parent, new Node({type: 'foo'})); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.shiftNode(parent); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. + * @api public + */ - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, unpipeInfo); - }return this; +utils.shiftNode = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (typeof node.shift === 'function') { + return node.shift(); } + return node.nodes && node.nodes.shift(); +}; - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; +/** + * Remove the specified `node` from `parent.nodes`. + * + * ```js + * var parent = new Node({type: 'abc'}); + * var foo = new Node({type: 'foo'}); + * utils.pushNode(parent, foo); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.removeNode(parent, foo); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`. + * @api public + */ - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; +utils.removeNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent.node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); - dest.emit('unpipe', this, unpipeInfo); + if (!parent.nodes) { + return null; + } - return this; + if (typeof parent.remove === 'function') { + return parent.remove(node); + } + + var idx = parent.nodes.indexOf(node); + if (idx !== -1) { + return parent.nodes.splice(idx, 1); + } }; -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); +/** + * Returns true if `node.type` matches the given `type`. Throws a + * `TypeError` if `node` is not an instance of `Node`. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(utils.isType(node, 'foo')); // false + * console.log(utils.isType(node, 'bar')); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` + * @return {Boolean} + * @api public + */ - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); +utils.isType = function(node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + switch (typeOf(type)) { + case 'array': + var types = type.slice(); + for (var i = 0; i < types.length; i++) { + if (utils.isType(node, types[i])) { + return true; + } } + return false; + case 'string': + return node.type === type; + case 'regexp': + return type.test(node.type); + default: { + throw new TypeError('expected "type" to be an array, string or regexp'); } } - - return res; }; -Readable.prototype.addListener = Readable.prototype.on; -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} +/** + * Returns true if the given `node` has the given `type` in `node.nodes`. + * Throws a `TypeError` if `node` is not an instance of `Node`. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'bar'}), + * new Node({type: 'baz'}) + * ] + * }); + * console.log(utils.hasType(node, 'xyz')); // false + * console.log(utils.hasType(node, 'baz')); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` + * @return {Boolean} + * @api public + */ -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); +utils.hasType = function(node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (!Array.isArray(node.nodes)) return false; + for (var i = 0; i < node.nodes.length; i++) { + if (utils.isType(node.nodes[i], type)) { + return true; + } } - return this; + return false; }; -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); - } -} +/** + * Returns the first node from `node.nodes` of the given `type` + * + * ```js + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'text', val: 'abc'}), + * new Node({type: 'text', val: 'xyz'}) + * ] + * }); + * + * var textNode = utils.firstOfType(node.nodes, 'text'); + * console.log(textNode.val); + * //=> 'abc' + * ``` + * @param {Array} `nodes` + * @param {String} `type` + * @return {Object|undefined} Returns the first matching node or undefined. + * @api public + */ -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); +utils.firstOfType = function(nodes, type) { + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + if (utils.isType(node, type)) { + return node; + } } +}; - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} +/** + * Returns the node at the specified index, or the first node of the + * given `type` from `node.nodes`. + * + * ```js + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'text', val: 'abc'}), + * new Node({type: 'text', val: 'xyz'}) + * ] + * }); + * + * var nodeOne = utils.findNode(node.nodes, 'text'); + * console.log(nodeOne.val); + * //=> 'abc' + * + * var nodeTwo = utils.findNode(node.nodes, 1); + * console.log(nodeTwo.val); + * //=> 'xyz' + * ``` + * + * @param {Array} `nodes` + * @param {String|Number} `type` Node type or index. + * @return {Object} Returns a node or undefined. + * @api public + */ -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); +utils.findNode = function(nodes, type) { + if (!Array.isArray(nodes)) { + return null; } - return this; + if (typeof type === 'number') { + return nodes[type]; + } + return utils.firstOfType(nodes, type); }; -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } +/** + * Returns true if the given node is an "*.open" node. + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * + * console.log(utils.isOpen(brace)); // false + * console.log(utils.isOpen(open)); // true + * console.log(utils.isOpen(close)); // false + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ - _this.push(null); - }); +utils.isOpen = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + return node.type.slice(-5) === '.open'; +}; - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); +/** + * Returns true if the given node is a "*.close" node. + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * + * console.log(utils.isClose(brace)); // false + * console.log(utils.isClose(open)); // false + * console.log(utils.isClose(close)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; +utils.isClose = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + return node.type.slice(-6) === '.close'; +}; - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); +/** + * Returns true if `node.nodes` **has** an `.open` node + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var open = new Node({type: 'brace.open'}); + * console.log(utils.hasOpen(brace)); // false + * + * brace.pushNode(open); + * console.log(utils.hasOpen(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } +utils.hasOpen = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + var first = node.first || node.nodes ? node.nodes[0] : null; + if (utils.isNode(first)) { + return first.type === node.type + '.open'; } + return false; +}; - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); +/** + * Returns true if `node.nodes` **has** a `.close` node + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var close = new Node({type: 'brace.close'}); + * console.log(utils.hasClose(brace)); // false + * + * brace.pushNode(close); + * console.log(utils.hasClose(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ + +utils.hasClose = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null; + if (utils.isNode(last)) { + return last.type === node.type + '.close'; } + return false; +}; - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; +/** + * Returns true if `node.nodes` has both `.open` and `.close` nodes + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * console.log(utils.hasOpen(brace)); // false + * console.log(utils.hasClose(brace)); // false + * + * brace.pushNode(open); + * brace.pushNode(close); + * console.log(utils.hasOpen(brace)); // true + * console.log(utils.hasClose(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ - return this; +utils.hasOpenAndClose = function(node) { + return utils.hasOpen(node) && utils.hasClose(node); }; -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._readableState.highWaterMark; - } -}); +/** + * Push the given `node` onto the `state.inside` array for the + * given type. This array is used as a specialized "stack" for + * only the given `node.type`. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * utils.addType(state, node); + * console.log(state.inside); + * //=> { brace: [{type: 'brace'}] } + * ``` + * @param {Object} `state` The `compiler.state` object or custom state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Array} Returns the `state.inside` stack for the given type. + * @api public + */ -// exposed for testing purposes only. -Readable._fromList = fromList; +utils.addType = function(state, node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; + var type = node.parent + ? node.parent.type + : node.type.replace(/\.open$/, ''); - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); + if (!state.hasOwnProperty('inside')) { + state.inside = {}; + } + if (!state.inside.hasOwnProperty(type)) { + state.inside[type] = []; } - return ret; -} + var arr = state.inside[type]; + arr.push(node); + return arr; +}; -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} +/** + * Remove the given `node` from the `state.inside` array for the + * given type. This array is used as a specialized "stack" for + * only the given `node.type`. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * utils.addType(state, node); + * console.log(state.inside); + * //=> { brace: [{type: 'brace'}] } + * utils.removeType(state, node); + * //=> { brace: [] } + * ``` + * @param {Object} `state` The `compiler.state` object or custom state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Array} Returns the `state.inside` stack for the given type. + * @api public + */ -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; +utils.removeType = function(state, node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); + + var type = node.parent + ? node.parent.type + : node.type.replace(/\.close$/, ''); + + if (state.inside.hasOwnProperty(type)) { + return state.inside[type].pop(); } - list.length -= c; - return ret; -} +}; -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); +/** + * Returns true if `node.val` is an empty string, or `node.nodes` does + * not contain any non-empty text nodes. + * + * ```js + * var node = new Node({type: 'text'}); + * utils.isEmpty(node); //=> true + * node.val = 'foo'; + * utils.isEmpty(node); //=> false + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `fn` + * @return {Boolean} + * @api public + */ - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } -} +utils.isEmpty = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); + if (!Array.isArray(node.nodes)) { + if (node.type !== 'text') { + return true; + } + if (typeof fn === 'function') { + return fn(node, node.parent); + } + return !utils.trim(node.val); } -} -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; + for (var i = 0; i < node.nodes.length; i++) { + var child = node.nodes[i]; + if (utils.isOpen(child) || utils.isClose(child)) { + continue; + } + if (!utils.isEmpty(child, fn)) { + return false; + } } - return -1; -} -/***/ }), + return true; +}; -/***/ 62826: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * Returns true if the `state.inside` stack for the given type exists + * and has one or more nodes on it. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * console.log(utils.isInsideType(state, 'brace')); //=> false + * utils.addType(state, node); + * console.log(utils.isInsideType(state, 'brace')); //=> true + * utils.removeType(state, node); + * console.log(utils.isInsideType(state, 'brace')); //=> false + * ``` + * @param {Object} `state` + * @param {String} `type` + * @return {Boolean} + * @api public + */ -"use strict"; -// 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. +utils.isInsideType = function(state, type) { + assert(isObject(state), 'expected state to be an object'); + assert(isString(type), 'expected type to be a string'); -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. + if (!state.hasOwnProperty('inside')) { + return false; + } + if (!state.inside.hasOwnProperty(type)) { + return false; + } + return state.inside[type].length > 0; +}; -module.exports = Transform; +/** + * Returns true if `node` is either a child or grand-child of the given `type`, + * or `state.inside[type]` is a non-empty array. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * console.log(utils.isInside(state, open, 'brace')); //=> false + * utils.pushNode(node, open); + * console.log(utils.isInside(state, open, 'brace')); //=> true + * ``` + * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` The `node.type` to check for. + * @return {Boolean} + * @api public + */ -var Duplex = __webpack_require__(42770); +utils.isInside = function(state, node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); -/**/ -var util = Object.create(__webpack_require__(78334)); -util.inherits = __webpack_require__(2989); -/**/ + if (Array.isArray(type)) { + for (var i = 0; i < type.length; i++) { + if (utils.isInside(state, node, type[i])) { + return true; + } + } + return false; + } -util.inherits(Transform, Duplex); + var parent = node.parent; + if (typeof type === 'string') { + return (parent && parent.type === type) || utils.isInsideType(state, type); + } -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; + if (typeOf(type) === 'regexp') { + if (parent && parent.type && type.test(parent.type)) { + return true; + } - var cb = ts.writecb; + var keys = Object.keys(state.inside); + var len = keys.length; + var idx = -1; + while (++idx < len) { + var key = keys[idx]; + var val = state.inside[key]; - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); + if (Array.isArray(val) && val.length !== 0 && type.test(key)) { + return true; + } + } } + return false; +}; - ts.writechunk = null; - ts.writecb = null; +/** + * Get the last `n` element from the given `array`. Used for getting + * a node from `node.nodes.` + * + * @param {Array} `array` + * @param {Number} `n` + * @return {undefined} + * @api public + */ - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; - cb(er); +/** + * Cast the given `val` to an array. + * + * ```js + * console.log(utils.arrayify('')); + * //=> [] + * console.log(utils.arrayify('foo')); + * //=> ['foo'] + * console.log(utils.arrayify(['foo'])); + * //=> ['foo'] + * ``` + * @param {any} `val` + * @return {Array} + * @api public + */ - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); +utils.arrayify = function(val) { + if (typeof val === 'string' && val !== '') { + return [val]; } -} + if (!Array.isArray(val)) { + return []; + } + return val; +}; -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); +/** + * Convert the given `val` to a string by joining with `,`. Useful + * for creating a cheerio/CSS/DOM-style selector from a list of strings. + * + * @param {any} `val` + * @return {Array} + * @api public + */ - Duplex.call(this, options); +utils.stringify = function(val) { + return utils.arrayify(val).join(','); +}; - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; +/** + * Ensure that the given value is a string and call `.trim()` on it, + * or return an empty string. + * + * @param {String} `str` + * @return {String} + * @api public + */ - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; +utils.trim = function(str) { + return typeof str === 'string' ? str.trim() : ''; +}; - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; +/** + * Return true if val is an object + */ - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; +function isObject(val) { + return typeOf(val) === 'object'; +} - if (typeof options.flush === 'function') this._flush = options.flush; - } +/** + * Return true if val is a string + */ - // When the writable side finishes, then flush out anything remaining. - this.on('prefinish', prefinish); +function isString(val) { + return typeof val === 'string'; } -function prefinish() { - var _this = this; +/** + * Return true if val is a function + */ - if (typeof this._flush === 'function') { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } +function isFunction(val) { + return typeof val === 'function'; } -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; +/** + * Return true if val is an array + */ -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; +function isArray(val) { + return Array.isArray(val); +} -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; +/** + * Shim to ensure the `.append` methods work with any version of snapdragon + */ - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; +function append(compiler, val, node) { + if (typeof compiler.append !== 'function') { + return compiler.emit(val, node); } -}; - -Transform.prototype._destroy = function (err, cb) { - var _this2 = this; - - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + return compiler.append(val, node); +} - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); +/** + * Simplified assertion. Throws an error is `val` is falsey. + */ - return stream.push(null); +function assert(val, message) { + if (!val) throw new Error(message); } + /***/ }), -/***/ 78063: +/***/ 79285: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. +var Base = __webpack_require__(87263); +var define = __webpack_require__(5477); +var Compiler = __webpack_require__(33003); +var Parser = __webpack_require__(35573); +var utils = __webpack_require__(622); +var regexCache = {}; +var cache = {}; +/** + * Create a new instance of `Snapdragon` with the given `options`. + * + * ```js + * var snapdragon = new Snapdragon(); + * ``` + * + * @param {Object} `options` + * @api public + */ -/**/ +function Snapdragon(options) { + Base.call(this, null, options); + this.options = utils.extend({source: 'string'}, this.options); + this.compiler = new Compiler(this.options); + this.parser = new Parser(this.options); -var pna = __webpack_require__(58404); -/**/ + Object.defineProperty(this, 'compilers', { + get: function() { + return this.compiler.compilers; + } + }); -module.exports = Writable; + Object.defineProperty(this, 'parsers', { + get: function() { + return this.parser.parsers; + } + }); -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; + Object.defineProperty(this, 'regex', { + get: function() { + return this.parser.regex; + } + }); } -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; +/** + * Inherit Base + */ - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ +Base.extend(Snapdragon); -/**/ -var Duplex; -/**/ +/** + * Add a parser to `snapdragon.parsers` for capturing the given `type` using + * the specified regex or parser function. A function is useful if you need + * to customize how the token is created and/or have access to the parser + * instance to check options, etc. + * + * ```js + * snapdragon + * .capture('slash', /^\//) + * .capture('dot', function() { + * var pos = this.position(); + * var m = this.match(/^\./); + * if (!m) return; + * return pos({ + * type: 'dot', + * val: m[0] + * }); + * }); + * ``` + * @param {String} `type` + * @param {RegExp|Function} `regex` + * @return {Object} Returns the parser instance for chaining + * @api public + */ -Writable.WritableState = WritableState; +Snapdragon.prototype.capture = function() { + return this.parser.capture.apply(this.parser, arguments); +}; -/**/ -var util = Object.create(__webpack_require__(78334)); -util.inherits = __webpack_require__(2989); -/**/ +/** + * Register a plugin `fn`. + * + * ```js + * var snapdragon = new Snapdgragon([options]); + * snapdragon.use(function() { + * console.log(this); //<= snapdragon instance + * console.log(this.parser); //<= parser instance + * console.log(this.compiler); //<= compiler instance + * }); + * ``` + * @param {Object} `fn` + * @api public + */ -/**/ -var internalUtil = { - deprecate: __webpack_require__(92262) +Snapdragon.prototype.use = function(fn) { + fn.call(this, this); + return this; }; -/**/ -/**/ -var Stream = __webpack_require__(1065); -/**/ +/** + * Parse the given `str`. + * + * ```js + * var snapdragon = new Snapdgragon([options]); + * // register parsers + * snapdragon.parser.use(function() {}); + * + * // parse + * var ast = snapdragon.parse('foo/bar'); + * console.log(ast); + * ``` + * @param {String} `str` + * @param {Object} `options` Set `options.sourcemap` to true to enable source maps. + * @return {Object} Returns an AST. + * @api public + */ -/**/ +Snapdragon.prototype.parse = function(str, options) { + this.options = utils.extend({}, this.options, options); + var parsed = this.parser.parse(str, this.options); -var Buffer = __webpack_require__(96788).Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} + // add non-enumerable parser reference + define(parsed, 'parser', this.parser); + return parsed; +}; -/**/ +/** + * Compile the given `AST`. + * + * ```js + * var snapdragon = new Snapdgragon([options]); + * // register plugins + * snapdragon.use(function() {}); + * // register parser plugins + * snapdragon.parser.use(function() {}); + * // register compiler plugins + * snapdragon.compiler.use(function() {}); + * + * // parse + * var ast = snapdragon.parse('foo/bar'); + * + * // compile + * var res = snapdragon.compile(ast); + * console.log(res.output); + * ``` + * @param {Object} `ast` + * @param {Object} `options` + * @return {Object} Returns an object with an `output` property with the rendered string. + * @api public + */ -var destroyImpl = __webpack_require__(87915); +Snapdragon.prototype.compile = function(ast, options) { + this.options = utils.extend({}, this.options, options); + var compiled = this.compiler.compile(ast, this.options); -util.inherits(Writable, Stream); + // add non-enumerable compiler reference + define(compiled, 'compiler', this.compiler); + return compiled; +}; -function nop() {} +/** + * Expose `Snapdragon` + */ -function WritableState(options, stream) { - Duplex = Duplex || __webpack_require__(42770); +module.exports = Snapdragon; - options = options || {}; +/** + * Expose `Parser` and `Compiler` + */ - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; +module.exports.Compiler = Compiler; +module.exports.Parser = Parser; - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; +/***/ }), - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; +/***/ 33003: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; +"use strict"; - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - // if _final has been called - this.finalCalled = false; +var use = __webpack_require__(77709); +var define = __webpack_require__(5477); +var debug = __webpack_require__(31185)('snapdragon:compiler'); +var utils = __webpack_require__(622); - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; +/** + * Create a new `Compiler` with the given `options`. + * @param {Object} `options` + */ - // has it been destroyed - this.destroyed = false; +function Compiler(options, state) { + debug('initializing', __filename); + this.options = utils.extend({source: 'string'}, options); + this.state = state || {}; + this.compilers = {}; + this.output = ''; + this.set('eos', function(node) { + return this.emit(node.val, node); + }); + this.set('noop', function(node) { + return this.emit(node.val, node); + }); + this.set('bos', function(node) { + return this.emit(node.val, node); + }); + use(this); +} - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; +/** + * Prototype methods + */ - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; +Compiler.prototype = { - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + /** + * Throw an error message with details including the cursor position. + * @param {String} `msg` Message to use in the Error. + */ - // a flag to see when we're in the middle of a write. - this.writing = false; + error: function(msg, node) { + var pos = node.position || {start: {column: 0}}; + var message = this.options.source + ' column:' + pos.start.column + ': ' + msg; - // when true all writes will be buffered until .uncork() call - this.corked = 0; + var err = new Error(message); + err.reason = msg; + err.column = pos.start.column; + err.source = this.pattern; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + if (this.options.silent) { + this.errors.push(err); + } else { + throw err; + } + }, - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + /** + * Define a non-enumberable property on the `Compiler` instance. + * + * ```js + * compiler.define('foo', 'bar'); + * ``` + * @name .define + * @param {String} `key` propery name + * @param {any} `val` property value + * @return {Object} Returns the Compiler instance for chaining. + * @api public + */ - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + define: function(key, val) { + define(this, key, val); + return this; + }, - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + /** + * Emit `node.val` + */ - // the amount that is being written when _write is called. - this.writelen = 0; + emit: function(str, node) { + this.output += str; + return str; + }, - this.bufferedRequest = null; - this.lastBufferedRequest = null; + /** + * Add a compiler `fn` with the given `name` + */ - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; + set: function(name, fn) { + this.compilers[name] = fn; + return this; + }, - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + /** + * Get compiler `name`. + */ - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + get: function(name) { + return this.compilers[name]; + }, - // count buffered requests - this.bufferedRequestCount = 0; + /** + * Get the previous AST node. + */ - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} + prev: function(n) { + return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' }; + }, -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; + /** + * Get the next AST node. + */ -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); + next: function(n) { + return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' }; + }, -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; + /** + * Visit `node`. + */ - return object && object._writableState instanceof WritableState; + visit: function(node, nodes, i) { + var fn = this.compilers[node.type]; + this.idx = i; + + if (typeof fn !== 'function') { + throw this.error('compiler "' + node.type + '" is not registered', node); } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} + return fn.call(this, node, nodes, i); + }, -function Writable(options) { - Duplex = Duplex || __webpack_require__(42770); + /** + * Map visit over array of `nodes`. + */ - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. + mapVisit: function(nodes) { + if (!Array.isArray(nodes)) { + throw new TypeError('expected an array'); + } + var len = nodes.length; + var idx = -1; + while (++idx < len) { + this.visit(nodes[idx], nodes, idx); + } + return this; + }, - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } + /** + * Compile `ast`. + */ - this._writableState = new WritableState(options, this); + compile: function(ast, options) { + var opts = utils.extend({}, this.options, options); + this.ast = ast; + this.parsingErrors = this.ast.errors; + this.output = ''; - // legacy. - this.writable = true; + // source map support + if (opts.sourcemap) { + var sourcemaps = __webpack_require__(59657); + sourcemaps(this); + this.mapVisit(this.ast.nodes); + this.applySourceMaps(); + this.map = opts.sourcemap === 'generator' ? this.map : this.map.toJSON(); + return this; + } - if (options) { - if (typeof options.write === 'function') this._write = options.write; + this.mapVisit(this.ast.nodes); + return this; + } +}; - if (typeof options.writev === 'function') this._writev = options.writev; +/** + * Expose `Compiler` + */ - if (typeof options.destroy === 'function') this._destroy = options.destroy; +module.exports = Compiler; - if (typeof options.final === 'function') this._final = options.final; - } - Stream.call(this); -} +/***/ }), -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; +/***/ 35573: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - pna.nextTick(cb, er); -} +"use strict"; -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - pna.nextTick(cb, er); - valid = false; - } - return valid; -} +var use = __webpack_require__(77709); +var util = __webpack_require__(31669); +var Cache = __webpack_require__(4337); +var define = __webpack_require__(5477); +var debug = __webpack_require__(31185)('snapdragon:parser'); +var Position = __webpack_require__(7974); +var utils = __webpack_require__(622); -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); +/** + * Create a new `Parser` with the given `input` and `options`. + * @param {String} `input` + * @param {Object} `options` + * @api public + */ - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } +function Parser(options) { + debug('initializing', __filename); + this.options = utils.extend({source: 'string'}, options); + this.init(this.options); + use(this); +} - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } +/** + * Prototype methods + */ - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; +Parser.prototype = { + constructor: Parser, - if (typeof cb !== 'function') cb = nop; + init: function(options) { + this.orig = ''; + this.input = ''; + this.parsed = ''; - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } + this.column = 1; + this.line = 1; - return ret; -}; - -Writable.prototype.cork = function () { - var state = this._writableState; + this.regex = new Cache(); + this.errors = this.errors || []; + this.parsers = this.parsers || {}; + this.types = this.types || []; + this.sets = this.sets || {}; + this.fns = this.fns || []; + this.currentType = 'root'; - state.corked++; -}; + var pos = this.position(); + this.bos = pos({type: 'bos', val: ''}); -Writable.prototype.uncork = function () { - var state = this._writableState; + this.ast = { + type: 'root', + errors: this.errors, + nodes: [this.bos] + }; - if (state.corked) { - state.corked--; + define(this.bos, 'parent', this.ast); + this.nodes = [this.ast]; - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; + this.count = 0; + this.setCount = 0; + this.stack = []; + }, -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; + /** + * Throw a formatted error with the cursor column and `msg`. + * @param {String} `msg` Message to use in the Error. + */ -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; -} + error: function(msg, node) { + var pos = node.position || {start: {column: 0, line: 0}}; + var line = pos.start.line; + var column = pos.start.column; + var source = this.options.source; -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); + var message = source + ' : ' + msg; + var err = new Error(message); + err.source = source; + err.reason = msg; + err.pos = pos; -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; + if (this.options.silent) { + this.errors.push(err); + } else { + throw err; } - } - var len = state.objectMode ? 1 : chunk.length; + }, - state.length += len; + /** + * Define a non-enumberable property on the `Parser` instance. + * + * ```js + * parser.define('foo', 'bar'); + * ``` + * @name .define + * @param {String} `key` propery name + * @param {any} `val` property value + * @return {Object} Returns the Parser instance for chaining. + * @api public + */ - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + define: function(key, val) { + define(this, key, val); + return this; + }, - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null + /** + * Mark position and patch `node.position`. + */ + + position: function() { + var start = { line: this.line, column: this.column }; + var self = this; + + return function(node) { + define(node, 'position', new Position(start, self)); + return node; }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; + }, + + /** + * Set parser `name` with the given `fn` + * @param {String} `name` + * @param {Function} `fn` + * @api public + */ + + set: function(type, fn) { + if (this.types.indexOf(type) === -1) { + this.types.push(type); } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } + this.parsers[type] = fn.bind(this); + return this; + }, - return ret; -} + /** + * Get parser `name` + * @param {String} `name` + * @api public + */ -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} + get: function(name) { + return this.parsers[name]; + }, -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; + /** + * Push a `token` onto the `type` stack. + * + * @param {String} `type` + * @return {Object} `token` + * @api public + */ - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - pna.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - pna.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } -} + push: function(type, token) { + this.sets[type] = this.sets[type] || []; + this.count++; + this.stack.push(token); + return this.sets[type].push(token); + }, -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} + /** + * Pop a token off of the `type` stack + * @param {String} `type` + * @returns {Object} Returns a token + * @api public + */ -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + pop: function(type) { + this.sets[type] = this.sets[type] || []; + this.count--; + this.stack.pop(); + return this.sets[type].pop(); + }, - onwriteStateUpdate(state); + /** + * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`. + * + * @param {String} `type` + * @return {Boolean} + * @api public + */ - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); + isInside: function(type) { + this.sets[type] = this.sets[type] || []; + return this.sets[type].length > 0; + }, - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + /** + * Return true if `node` is the given `type`. + * + * ```js + * parser.isType(node, 'brace'); + * ``` + * @param {Object} `node` + * @param {String} `type` + * @return {Boolean} + * @api public + */ - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } -} + isType: function(node, type) { + return node && node.type === type; + }, -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} + /** + * Get the previous AST node + * @return {Object} + */ -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} + prev: function(n) { + return this.stack.length > 0 + ? utils.last(this.stack, n) + : utils.last(this.nodes, n); + }, -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + /** + * Update line and column based on `str`. + */ - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + consume: function(len) { + this.input = this.input.substr(len); + }, - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; + /** + * Update column based on `str`. + */ - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + updatePosition: function(str, len) { + var lines = str.match(/\n/g); + if (lines) this.line += lines.length; + var i = str.lastIndexOf('\n'); + this.column = ~i ? len - i : this.column + len; + this.parsed += str; + this.consume(len); + }, - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); + /** + * Match `regex`, return captures, and update the cursor position by `match[0]` length. + * @param {RegExp} `regex` + * @return {Object} + */ + + match: function(regex) { + var m = regex.exec(this.input); + if (m) { + this.updatePosition(m[0], m[0].length); + return m; } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + }, - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } + /** + * Capture `type` with the given regex. + * @param {String} `type` + * @param {RegExp} `regex` + * @return {Function} + */ + + capture: function(type, regex) { + if (typeof regex === 'function') { + return this.set.apply(this, arguments); } - if (entry === null) state.lastBufferedRequest = null; - } + this.regex.set(type, regex); + this.set(type, function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(regex); + if (!m || !m[0]) return; - state.bufferedRequest = entry; - state.bufferProcessing = false; -} + var prev = this.prev(); + var node = pos({ + type: type, + val: m[0], + parsed: parsed, + rest: this.input + }); -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; + if (m[1]) { + node.inner = m[1]; + } -Writable.prototype._writev = null; + define(node, 'inside', this.stack.length > 0); + define(node, 'parent', prev); + prev.nodes.push(node); + }.bind(this)); + return this; + }, -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + /** + * Create a parser with open and close for parens, + * brackets or braces + */ - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + capturePair: function(type, openRegex, closeRegex, fn) { + this.sets[type] = this.sets[type] || []; - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + /** + * Open + */ - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + this.set(type + '.open', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(openRegex); + if (!m || !m[0]) return; - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); -}; + var val = m[0]; + this.setCount++; + this.specialChars = true; + var open = pos({ + type: type + '.open', + val: val, + rest: this.input + }); -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - stream.emit('error', err); - } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { - state.pendingcb++; - state.finalCalled = true; - pna.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} + if (typeof m[1] !== 'undefined') { + open.inner = m[1]; + } -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - } - } - return need; -} + var prev = this.prev(); + var node = pos({ + type: type, + nodes: [open] + }); -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} + define(node, 'rest', this.input); + define(node, 'parsed', parsed); + define(node, 'prefix', m[1]); + define(node, 'parent', prev); + define(open, 'parent', node); -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = corkReq; - } else { - state.corkedRequestsFree = corkReq; - } -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } + if (typeof fn === 'function') { + fn.call(this, open, node); + } - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; - } -}); + this.push(type, node); + prev.nodes.push(node); + }); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - this.end(); - cb(err); -}; + /** + * Close + */ -/***/ }), + this.set(type + '.close', function() { + var pos = this.position(); + var m = this.match(closeRegex); + if (!m || !m[0]) return; -/***/ 28878: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + var parent = this.pop(type); + var node = pos({ + type: type + '.close', + rest: this.input, + suffix: m[1], + val: m[0] + }); -"use strict"; + if (!this.isType(parent, type)) { + if (this.options.strict) { + throw new Error('missing opening "' + type + '"'); + } + this.setCount--; + node.escaped = true; + return node; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + if (node.suffix === '\\') { + parent.escaped = true; + node.escaped = true; + } -var Buffer = __webpack_require__(96788).Buffer; -var util = __webpack_require__(31669); + parent.nodes.push(node); + define(node, 'parent', parent); + }); -function copyBuffer(src, target, offset) { - src.copy(target, offset); -} + return this; + }, -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); + /** + * Capture end-of-string + */ - this.head = null; - this.tail = null; - this.length = 0; - } + eos: function() { + var pos = this.position(); + if (this.input) return; + var prev = this.prev(); - BufferList.prototype.push = function push(v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; + while (prev.type !== 'root' && !prev.visited) { + if (this.options.strict === true) { + throw new SyntaxError('invalid syntax:' + util.inspect(prev, null, 2)); + } - BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; + if (!hasDelims(prev)) { + prev.parent.escaped = true; + prev.escaped = true; + } - BufferList.prototype.shift = function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; + visit(prev, function(node) { + if (!hasDelims(node.parent)) { + node.parent.escaped = true; + node.escaped = true; + } + }); - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; + prev = prev.parent; + } - BufferList.prototype.join = function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; + var tok = pos({ + type: 'eos', + val: this.append || '' + }); - BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; + define(tok, 'parent', this.ast); + return tok; + }, - return BufferList; -}(); + /** + * Run parsers to advance the cursor position + */ -if (util && util.inspect && util.inspect.custom) { - module.exports.prototype[util.inspect.custom] = function () { - var obj = util.inspect({ length: this.length }); - return this.constructor.name + ' ' + obj; - }; -} + next: function() { + var parsed = this.parsed; + var len = this.types.length; + var idx = -1; + var tok; -/***/ }), + while (++idx < len) { + if ((tok = this.parsers[this.types[idx]].call(this))) { + define(tok, 'rest', this.input); + define(tok, 'parsed', parsed); + this.last = tok; + return tok; + } + } + }, -/***/ 87915: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * Parse the given string. + * @return {Array} + */ -"use strict"; + parse: function(input) { + if (typeof input !== 'string') { + throw new TypeError('expected a string'); + } + this.init(this.options); + this.orig = input; + this.input = input; + var self = this; -/**/ + function parse() { + // check input before calling `.next()` + input = self.input; -var pna = __webpack_require__(58404); -/**/ + // get the next AST ndoe + var node = self.next(); + if (node) { + var prev = self.prev(); + if (prev) { + define(node, 'parent', prev); + if (prev.nodes) { + prev.nodes.push(node); + } + } -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; + if (self.sets.hasOwnProperty(prev.type)) { + self.currentType = prev.type; + } + } - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; + // if we got here but input is not changed, throw an error + if (self.input && input === self.input) { + throw new Error('no parsers registered for: "' + self.input.slice(0, 5) + '"'); + } + } - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { - pna.nextTick(emitErrorNT, this, err); + while (this.input) parse(); + if (this.stack.length && this.options.strict) { + var node = this.stack.pop(); + throw this.error('missing opening ' + node.type + ': "' + this.orig + '"'); } - return this; - } - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks + var eos = this.eos(); + var tok = this.prev(); + if (tok.type !== 'eos') { + this.ast.nodes.push(eos); + } - if (this._readableState) { - this._readableState.destroyed = true; + return this.ast; } +}; - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; +/** + * Visit `node` with the given `fn` + */ + +function visit(node, fn) { + if (!node.visited) { + define(node, 'visited', true); + return node.nodes ? mapVisit(node.nodes, fn) : fn(node); } + return node; +} - this._destroy(err || null, function (err) { - if (!cb && err) { - pna.nextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; - } - } else if (cb) { - cb(err); - } - }); +/** + * Map visit over array of `nodes`. + */ - return this; +function mapVisit(nodes, fn) { + var len = nodes.length; + var idx = -1; + while (++idx < len) { + visit(nodes[idx], fn); + } } -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } +function hasOpen(node) { + return node.nodes && node.nodes[0].type === (node.type + '.open'); +} - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } +function hasClose(node) { + return node.nodes && utils.last(node.nodes).type === (node.type + '.close'); } -function emitErrorNT(self, err) { - self.emit('error', err); +function hasDelims(node) { + return hasOpen(node) && hasClose(node); } -module.exports = { - destroy: destroy, - undestroy: undestroy -}; +/** + * Expose `Parser` + */ + +module.exports = Parser; + /***/ }), -/***/ 1065: +/***/ 7974: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -module.exports = __webpack_require__(92413); +"use strict"; + + +var define = __webpack_require__(5477); + +/** + * Store position for a node + */ + +module.exports = function Position(start, parser) { + this.start = start; + this.end = { line: parser.line, column: parser.column }; + define(this, 'content', parser.orig); + define(this, 'source', parser.options.source); +}; /***/ }), -/***/ 96788: +/***/ 59657: /***/ (function(module, exports, __webpack_require__) { -/* eslint-disable node/no-deprecated-api */ -var buffer = __webpack_require__(64293) -var Buffer = buffer.Buffer +"use strict"; -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} +var fs = __webpack_require__(35747); +var path = __webpack_require__(85622); +var define = __webpack_require__(5477); +var utils = __webpack_require__(622); -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) +/** + * Expose `mixin()`. + * This code is based on `source-maps-support.js` in reworkcss/css + * https://github.com/reworkcss/css/blob/master/lib/stringify/source-map-support.js + * Copyright (c) 2012 TJ Holowaychuk + */ -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} +module.exports = mixin; -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 -} +/** + * Mixin source map support into `compiler`. + * + * @param {Object} `compiler` + * @api public + */ -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} +function mixin(compiler) { + define(compiler, '_comment', compiler.comment); + compiler.map = new utils.SourceMap.SourceMapGenerator(); + compiler.position = { line: 1, column: 1 }; + compiler.content = {}; + compiler.files = {}; -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') + for (var key in exports) { + define(compiler, key, exports[key]); } - return buffer.SlowBuffer(size) } +/** + * Update position. + * + * @param {String} str + */ -/***/ }), +exports.updatePosition = function(str) { + var lines = str.match(/\n/g); + if (lines) this.position.line += lines.length; + var i = str.lastIndexOf('\n'); + this.position.column = ~i ? str.length - i : this.position.column + str.length; +}; -/***/ 7395: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/** + * Emit `str` with `position`. + * + * @param {String} str + * @param {Object} [pos] + * @return {String} + */ -"use strict"; -// 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. +exports.emit = function(str, node) { + var position = node.position || {}; + var source = position.source; + if (source) { + if (position.filepath) { + source = utils.unixify(position.filepath); + } + this.map.addMapping({ + source: source, + generated: { + line: this.position.line, + column: Math.max(this.position.column - 1, 0) + }, + original: { + line: position.start.line, + column: position.start.column - 1 + } + }); + if (position.content) { + this.addContent(source, position); + } + if (position.filepath) { + this.addFile(source, position); + } -/**/ + this.updatePosition(str); + this.output += str; + } + return str; +}; -var Buffer = __webpack_require__(96788).Buffer; -/**/ +/** + * Adds a file to the source map output if it has not already been added + * @param {String} `file` + * @param {Object} `pos` + */ -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } +exports.addFile = function(file, position) { + if (typeof position.content !== 'string') return; + if (Object.prototype.hasOwnProperty.call(this.files, file)) return; + this.files[file] = position.content; }; -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.s = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; +/** + * Adds a content source to the source map output if it has not already been added + * @param {String} `source` + * @param {Object} `position` + */ -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; +exports.addContent = function(source, position) { + if (typeof position.content !== 'string') return; + if (Object.prototype.hasOwnProperty.call(this.content, source)) return; + this.map.setSourceContent(source, position.content); }; -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} +/** + * Applies any original source maps to the output and embeds the source file + * contents in the source map. + */ -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} +exports.applySourceMaps = function() { + Object.keys(this.files).forEach(function(file) { + var content = this.files[file]; + this.map.setSourceContent(file, content); -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); + if (this.options.inputSourcemaps === true) { + var originalMap = utils.sourceMapResolve.resolveSync(content, file, fs.readFileSync); + if (originalMap) { + var map = new utils.SourceMap.SourceMapConsumer(originalMap.map); + var relativeTo = originalMap.sourcesRelativeTo; + this.map.applySourceMap(map, file, utils.unixify(path.dirname(relativeTo))); } } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} + }, this); +}; -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} +/** + * Process comments, drops sourceMap comments. + * @param {Object} node + */ -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; +exports.comment = function(node) { + if (/^# sourceMappingURL=/.test(node.comment)) { + return this.emit('', node.position); } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} - -/***/ }), - -/***/ 68193: -/***/ (function(module, exports, __webpack_require__) { - -var Stream = __webpack_require__(92413); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream; - exports = module.exports = Stream.Readable; - exports.Readable = Stream.Readable; - exports.Writable = Stream.Writable; - exports.Duplex = Stream.Duplex; - exports.Transform = Stream.Transform; - exports.PassThrough = Stream.PassThrough; - exports.Stream = Stream; -} else { - exports = module.exports = __webpack_require__(79341); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __webpack_require__(78063); - exports.Duplex = __webpack_require__(42770); - exports.Transform = __webpack_require__(62826); - exports.PassThrough = __webpack_require__(60143); -} + return this._comment(node); +}; /***/ }), -/***/ 30931: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 622: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -var extend = __webpack_require__(39700); -var safe = __webpack_require__(71217); - /** - * The main export is a function that takes a `pattern` string and an `options` object. - * - * ```js - & var not = require('regex-not'); - & console.log(not('foo')); - & //=> /^(?:(?!^(?:foo)$).)*$/ - * ``` - * - * @param {String} `pattern` - * @param {Object} `options` - * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`. - * @api public + * Module dependencies */ -function toRegex(pattern, options) { - return new RegExp(toRegex.create(pattern, options)); -} +exports.extend = __webpack_require__(28727); +exports.SourceMap = __webpack_require__(96241); +exports.sourceMapResolve = __webpack_require__(10227); /** - * Create a regex-compatible string from the given `pattern` and `options`. - * - * ```js - & var not = require('regex-not'); - & console.log(not.create('foo')); - & //=> '^(?:(?!^(?:foo)$).)*$' - * ``` - * @param {String} `pattern` - * @param {Object} `options` - * @return {String} - * @api public + * Convert backslash in the given string to forward slashes */ -toRegex.create = function(pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); - } - - var opts = extend({}, options); - if (opts.contains === true) { - opts.strictNegate = false; - } +exports.unixify = function(fp) { + return fp.split(/\\+/).join('/'); +}; - var open = opts.strictOpen !== false ? '^' : ''; - var close = opts.strictClose !== false ? '$' : ''; - var endChar = opts.endChar ? opts.endChar : '+'; - var str = pattern; +/** + * Return true if `val` is a non-empty string + * + * @param {String} `str` + * @return {Boolean} + */ - if (opts.strictNegate === false) { - str = '(?:(?!(?:' + pattern + ')).)' + endChar; - } else { - str = '(?:(?!^(?:' + pattern + ')$).)' + endChar; - } +exports.isString = function(str) { + return str && typeof str === 'string'; +}; - var res = open + str + close; - if (opts.safe === true && safe(res) === false) { - throw new Error('potentially unsafe regular expression: ' + res); - } +/** + * Cast `val` to an array + * @return {Array} + */ - return res; +exports.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; }; /** - * Expose `toRegex` + * Get the last `n` element from the given `array` + * @param {Array} `array` + * @return {*} */ -module.exports = toRegex; +exports.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; /***/ }), -/***/ 39700: +/***/ 56609: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; - - -var isExtendable = __webpack_require__(93295); -var assignSymbols = __webpack_require__(64353); - -module.exports = Object.assign || function(obj/*, objects*/) { - if (obj === null || typeof obj === 'undefined') { - throw new TypeError('Cannot convert undefined or null to object'); - } - if (!isObject(obj)) { - obj = {}; - } - for (var i = 1; i < arguments.length; i++) { - var val = arguments[i]; - if (isString(val)) { - val = toObject(val); - } - if (isObject(val)) { - assign(obj, val); - assignSymbols(obj, val); - } - } - return obj; -}; +var decodeUriComponent = __webpack_require__(95748) -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } - } +function customDecodeUriComponent(string) { + // `decodeUriComponent` turns `+` into ` `, but that's not wanted. + return decodeUriComponent(string.replace(/\+/g, "%2B")) } -function isString(val) { - return (val && typeof val === 'string'); -} +module.exports = customDecodeUriComponent -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; - } - return obj; -} -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); -} +/***/ }), -/** - * Returns true if the given `key` is an own property of `obj`. - */ +/***/ 89825: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} +var url = __webpack_require__(78835) -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); +function resolveUrl(/* ...urls */) { + return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) { + return url.resolve(resolved, nextUrl) + }) } +module.exports = resolveUrl + /***/ }), -/***/ 93295: +/***/ 10227: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ - +var sourceMappingURL = __webpack_require__(21707) +var resolveUrl = __webpack_require__(89825) +var decodeUriComponent = __webpack_require__(56609) +var urix = __webpack_require__(67806) +var atob = __webpack_require__(83327) -var isPlainObject = __webpack_require__(81064); -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); -}; +function callbackAsync(callback, error, result) { + setImmediate(function() { callback(error, result) }) +} -/***/ }), +function parseMapToJSON(string, data) { + try { + return JSON.parse(string.replace(/^\)\]\}'/, "")) + } catch (error) { + error.sourceMapData = data + throw error + } +} -/***/ 69523: -/***/ (function(module) { +function readSync(read, url, data) { + var readUrl = decodeUriComponent(url) + try { + return String(read(readUrl)) + } catch (error) { + error.sourceMapData = data + throw error + } +} -"use strict"; -/*! - * repeat-element - * - * Copyright (c) 2015-present, Jon Schlinkert. - * Licensed under the MIT license. - */ - -module.exports = function repeat(ele, num) { - var arr = new Array(num); - - for (var i = 0; i < num; i++) { - arr[i] = ele; +function resolveSourceMap(code, codeUrl, read, callback) { + var mapData + try { + mapData = resolveSourceMapHelper(code, codeUrl) + } catch (error) { + return callbackAsync(callback, error) } + if (!mapData || mapData.map) { + return callbackAsync(callback, null, mapData) + } + var readUrl = decodeUriComponent(mapData.url) + read(readUrl, function(error, result) { + if (error) { + error.sourceMapData = mapData + return callback(error) + } + mapData.map = String(result) + try { + mapData.map = parseMapToJSON(mapData.map, mapData) + } catch (error) { + return callback(error) + } + callback(null, mapData) + }) +} - return arr; -}; - - -/***/ }), - -/***/ 6332: -/***/ (function(module) { - -"use strict"; -/*! - * repeat-string - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ - - - -/** - * Results cache - */ +function resolveSourceMapSync(code, codeUrl, read) { + var mapData = resolveSourceMapHelper(code, codeUrl) + if (!mapData || mapData.map) { + return mapData + } + mapData.map = readSync(read, mapData.url, mapData) + mapData.map = parseMapToJSON(mapData.map, mapData) + return mapData +} -var res = ''; -var cache; +var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/ /** - * Expose `repeat` + * The media type for JSON text is application/json. + * + * {@link https://tools.ietf.org/html/rfc8259#section-11 | IANA Considerations } + * + * `text/json` is non-standard media type */ - -module.exports = repeat; +var jsonMimeTypeRegex = /^(?:application|text)\/json$/ /** - * Repeat the given `string` the specified `number` - * of times. - * - * **Example:** - * - * ```js - * var repeat = require('repeat-string'); - * repeat('A', 5); - * //=> AAAAA - * ``` + * JSON text exchanged between systems that are not part of a closed ecosystem + * MUST be encoded using UTF-8. * - * @param {String} `string` The string to repeat - * @param {Number} `number` The number of times to repeat the string - * @return {String} Repeated string - * @api public + * {@link https://tools.ietf.org/html/rfc8259#section-8.1 | Character Encoding} */ +var jsonCharacterEncoding = "utf-8" -function repeat(str, num) { - if (typeof str !== 'string') { - throw new TypeError('expected a string'); +function base64ToBuf(b64) { + var binStr = atob(b64) + var len = binStr.length + var arr = new Uint8Array(len) + for (var i = 0; i < len; i++) { + arr[i] = binStr.charCodeAt(i) } + return arr +} - // cover common, quick use cases - if (num === 1) return str; - if (num === 2) return str + str; +function decodeBase64String(b64) { + if (typeof TextDecoder === "undefined" || typeof Uint8Array === "undefined") { + return atob(b64) + } + var buf = base64ToBuf(b64); + // Note: `decoder.decode` method will throw a `DOMException` with the + // `"EncodingError"` value when an coding error is found. + var decoder = new TextDecoder(jsonCharacterEncoding, {fatal: true}) + return decoder.decode(buf); +} - var max = str.length * num; - if (cache !== str || typeof cache === 'undefined') { - cache = str; - res = ''; - } else if (res.length >= max) { - return res.substr(0, max); +function resolveSourceMapHelper(code, codeUrl) { + codeUrl = urix(codeUrl) + + var url = sourceMappingURL.getFrom(code) + if (!url) { + return null } - while (max > res.length && num > 1) { - if (num & 1) { - res += str; + var dataUri = url.match(dataUriRegex) + if (dataUri) { + var mimeType = dataUri[1] || "text/plain" + var lastParameter = dataUri[2] || "" + var encoded = dataUri[3] || "" + var data = { + sourceMappingURL: url, + url: null, + sourcesRelativeTo: codeUrl, + map: encoded } - - num >>= 1; - str += str; + if (!jsonMimeTypeRegex.test(mimeType)) { + var error = new Error("Unuseful data uri mime type: " + mimeType) + error.sourceMapData = data + throw error + } + try { + data.map = parseMapToJSON( + lastParameter === ";base64" ? decodeBase64String(encoded) : decodeURIComponent(encoded), + data + ) + } catch (error) { + error.sourceMapData = data + throw error + } + return data } - res += str; - res = res.substr(0, max); - return res; + var mapUrl = resolveUrl(codeUrl, url) + return { + sourceMappingURL: url, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } } -/***/ }), -/***/ 25622: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +function resolveSources(map, mapUrl, read, options, callback) { + if (typeof options === "function") { + callback = options + options = {} + } + var pending = map.sources ? map.sources.length : 0 + var result = { + sourcesResolved: [], + sourcesContent: [] + } -var util = __webpack_require__(10265); -var types = __webpack_require__(40432); -var sets = __webpack_require__(28135); -var positions = __webpack_require__(54771); + if (pending === 0) { + callbackAsync(callback, null, result) + return + } + var done = function() { + pending-- + if (pending === 0) { + callback(null, result) + } + } -module.exports = function(regexpStr) { - var i = 0, l, c, - start = { type: types.ROOT, stack: []}, + resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { + result.sourcesResolved[index] = fullUrl + if (typeof sourceContent === "string") { + result.sourcesContent[index] = sourceContent + callbackAsync(done, null) + } else { + var readUrl = decodeUriComponent(fullUrl) + read(readUrl, function(error, source) { + result.sourcesContent[index] = error ? error : String(source) + done() + }) + } + }) +} - // Keep track of last clause/group and stack. - lastGroup = start, - last = start.stack, - groupStack = []; +function resolveSourcesSync(map, mapUrl, read, options) { + var result = { + sourcesResolved: [], + sourcesContent: [] + } + if (!map.sources || map.sources.length === 0) { + return result + } - var repeatErr = function(i) { - util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1)); - }; + resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { + result.sourcesResolved[index] = fullUrl + if (read !== null) { + if (typeof sourceContent === "string") { + result.sourcesContent[index] = sourceContent + } else { + var readUrl = decodeUriComponent(fullUrl) + try { + result.sourcesContent[index] = String(read(readUrl)) + } catch (error) { + result.sourcesContent[index] = error + } + } + } + }) - // Decode a few escaped characters. - var str = util.strToChars(regexpStr); - l = str.length; + return result +} - // Iterate through each character in string. - while (i < l) { - c = str[i++]; +var endingSlash = /\/?$/ - switch (c) { - // Handle escaped characters, inclues a few sets. - case '\\': - c = str[i++]; +function resolveSourcesHelper(map, mapUrl, options, fn) { + options = options || {} + mapUrl = urix(mapUrl) + var fullUrl + var sourceContent + var sourceRoot + for (var index = 0, len = map.sources.length; index < len; index++) { + sourceRoot = null + if (typeof options.sourceRoot === "string") { + sourceRoot = options.sourceRoot + } else if (typeof map.sourceRoot === "string" && options.sourceRoot !== false) { + sourceRoot = map.sourceRoot + } + // If the sourceRoot is the empty string, it is equivalent to not setting + // the property at all. + if (sourceRoot === null || sourceRoot === '') { + fullUrl = resolveUrl(mapUrl, map.sources[index]) + } else { + // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes + // `/scripts/subdir/`, not `/scripts/`. Pointing to a file as source root + // does not make sense. + fullUrl = resolveUrl(mapUrl, sourceRoot.replace(endingSlash, "/"), map.sources[index]) + } + sourceContent = (map.sourcesContent || [])[index] + fn(fullUrl, sourceContent, index) + } +} - switch (c) { - case 'b': - last.push(positions.wordBoundary()); - break; - case 'B': - last.push(positions.nonWordBoundary()); - break; - case 'w': - last.push(sets.words()); - break; +function resolve(code, codeUrl, read, options, callback) { + if (typeof options === "function") { + callback = options + options = {} + } + if (code === null) { + var mapUrl = codeUrl + var data = { + sourceMappingURL: null, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } + var readUrl = decodeUriComponent(mapUrl) + read(readUrl, function(error, result) { + if (error) { + error.sourceMapData = data + return callback(error) + } + data.map = String(result) + try { + data.map = parseMapToJSON(data.map, data) + } catch (error) { + return callback(error) + } + _resolveSources(data) + }) + } else { + resolveSourceMap(code, codeUrl, read, function(error, mapData) { + if (error) { + return callback(error) + } + if (!mapData) { + return callback(null, null) + } + _resolveSources(mapData) + }) + } - case 'W': - last.push(sets.notWords()); - break; + function _resolveSources(mapData) { + resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) { + if (error) { + return callback(error) + } + mapData.sourcesResolved = result.sourcesResolved + mapData.sourcesContent = result.sourcesContent + callback(null, mapData) + }) + } +} - case 'd': - last.push(sets.ints()); - break; +function resolveSync(code, codeUrl, read, options) { + var mapData + if (code === null) { + var mapUrl = codeUrl + mapData = { + sourceMappingURL: null, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } + mapData.map = readSync(read, mapUrl, mapData) + mapData.map = parseMapToJSON(mapData.map, mapData) + } else { + mapData = resolveSourceMapSync(code, codeUrl, read) + if (!mapData) { + return null + } + } + var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options) + mapData.sourcesResolved = result.sourcesResolved + mapData.sourcesContent = result.sourcesContent + return mapData +} - case 'D': - last.push(sets.notInts()); - break; - case 's': - last.push(sets.whitespace()); - break; - case 'S': - last.push(sets.notWhitespace()); - break; +module.exports = { + resolveSourceMap: resolveSourceMap, + resolveSourceMapSync: resolveSourceMapSync, + resolveSources: resolveSources, + resolveSourcesSync: resolveSourcesSync, + resolve: resolve, + resolveSync: resolveSync, + parseMapToJSON: parseMapToJSON +} - default: - // Check if c is integer. - // In which case it's a reference. - if (/\d/.test(c)) { - last.push({ type: types.REFERENCE, value: parseInt(c, 10) }); - // Escaped character. - } else { - last.push({ type: types.CHAR, value: c.charCodeAt(0) }); - } - } +/***/ }), - break; +/***/ 21707: +/***/ (function(module) { +// Copyright 2014 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) - // Positionals. - case '^': - last.push(positions.begin()); - break; +void (function(root, factory) { + if (typeof define === "function" && define.amd) { + define(factory) + } else if (true) { + module.exports = factory() + } else {} +}(this, function() { - case '$': - last.push(positions.end()); - break; + var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/ + var regex = RegExp( + "(?:" + + "/\\*" + + "(?:\\s*\r?\n(?://)?)?" + + "(?:" + innerRegex.source + ")" + + "\\s*" + + "\\*/" + + "|" + + "//(?:" + innerRegex.source + ")" + + ")" + + "\\s*" + ) - // Handle custom sets. - case '[': - // Check if this class is 'anti' i.e. [^abc]. - var not; - if (str[i] === '^') { - not = true; - i++; - } else { - not = false; - } + return { - // Get all the characters in class. - var classTokens = util.tokenizeClass(str.slice(i), regexpStr); + regex: regex, + _innerRegex: innerRegex, - // Increase index by length of class. - i += classTokens[1]; - last.push({ - type: types.SET, - set: classTokens[0], - not: not, - }); + getFrom: function(code) { + var match = code.match(regex) + return (match ? match[1] || match[2] || "" : null) + }, - break; + existsIn: function(code) { + return regex.test(code) + }, + removeFrom: function(code) { + return code.replace(regex, "") + }, - // Class of any character except \n. - case '.': - last.push(sets.anyChar()); - break; + insertBefore: function(code, string) { + var match = code.match(regex) + if (match) { + return code.slice(0, match.index) + string + code.slice(match.index) + } else { + return code + string + } + } + } +})); - // Push group onto stack. - case '(': - // Create group. - var group = { - type: types.GROUP, - stack: [], - remember: true, - }; - c = str[i]; +/***/ }), - // If if this is a special kind of group. - if (c === '?') { - c = str[i + 1]; - i += 2; +/***/ 33218: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Match if followed by. - if (c === '=') { - group.followedBy = true; +"use strict"; +/*! + * split-string + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ - // Match if not followed by. - } else if (c === '!') { - group.notFollowedBy = true; - } else if (c !== ':') { - util.error(regexpStr, - 'Invalid group, character \'' + c + - '\' after \'?\' at column ' + (i - 1)); - } - group.remember = false; - } +var extend = __webpack_require__(66889); - // Insert subgroup into current group stack. - last.push(group); +module.exports = function(str, options, fn) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } - // Remember the current group for when the group closes. - groupStack.push(lastGroup); + if (typeof options === 'function') { + fn = options; + options = null; + } - // Make this new group the current group. - lastGroup = group; - last = group.stack; - break; + // allow separator to be defined as a string + if (typeof options === 'string') { + options = { sep: options }; + } + var opts = extend({sep: '.'}, options); + var quotes = opts.quotes || ['"', "'", '`']; + var brackets; - // Pop group out of stack. - case ')': - if (groupStack.length === 0) { - util.error(regexpStr, 'Unmatched ) at column ' + (i - 1)); - } - lastGroup = groupStack.pop(); + if (opts.brackets === true) { + brackets = { + '<': '>', + '(': ')', + '[': ']', + '{': '}' + }; + } else if (opts.brackets) { + brackets = opts.brackets; + } - // Check if this group has a PIPE. - // To get back the correct last stack. - last = lastGroup.options ? - lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack; - break; + var tokens = []; + var stack = []; + var arr = ['']; + var sep = opts.sep; + var len = str.length; + var idx = -1; + var closeIdx; + function expected() { + if (brackets && stack.length) { + return brackets[stack[stack.length - 1]]; + } + } - // Use pipe character to give more choices. - case '|': - // Create array where options are if this is the first PIPE - // in this clause. - if (!lastGroup.options) { - lastGroup.options = [lastGroup.stack]; - delete lastGroup.stack; - } + while (++idx < len) { + var ch = str[idx]; + var next = str[idx + 1]; + var tok = { val: ch, idx: idx, arr: arr, str: str }; + tokens.push(tok); - // Create a new stack and add to options for rest of clause. - var stack = []; - lastGroup.options.push(stack); - last = stack; - break; + if (ch === '\\') { + tok.val = keepEscaping(opts, str, idx) === true ? (ch + next) : next; + tok.escaped = true; + if (typeof fn === 'function') { + fn(tok); + } + arr[arr.length - 1] += tok.val; + idx++; + continue; + } + if (brackets && brackets[ch]) { + stack.push(ch); + var e = expected(); + var i = idx + 1; - // Repetition. - // For every repetition, remove last element from last stack - // then insert back a RANGE object. - // This design is chosen because there could be more than - // one repetition symbols in a regex i.e. `a?+{2,3}`. - case '{': - var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max; - if (rs !== null) { - if (last.length === 0) { - repeatErr(i); + if (str.indexOf(e, i + 1) !== -1) { + while (stack.length && i < len) { + var s = str[++i]; + if (s === '\\') { + s++; + continue; } - min = parseInt(rs[1], 10); - max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min; - i += rs[0].length; - last.push({ - type: types.REPETITION, - min: min, - max: max, - value: last.pop(), - }); - } else { - last.push({ - type: types.CHAR, - value: 123, - }); - } - break; + if (quotes.indexOf(s) !== -1) { + i = getClosingQuote(str, s, i + 1); + continue; + } - case '?': - if (last.length === 0) { - repeatErr(i); - } - last.push({ - type: types.REPETITION, - min: 0, - max: 1, - value: last.pop(), - }); - break; + e = expected(); + if (stack.length && str.indexOf(e, i + 1) === -1) { + break; + } - case '+': - if (last.length === 0) { - repeatErr(i); - } - last.push({ - type: types.REPETITION, - min: 1, - max: Infinity, - value: last.pop(), - }); - break; + if (brackets[s]) { + stack.push(s); + continue; + } - case '*': - if (last.length === 0) { - repeatErr(i); + if (e === s) { + stack.pop(); + } } - last.push({ - type: types.REPETITION, - min: 0, - max: Infinity, - value: last.pop(), - }); - break; + } + closeIdx = i; + if (closeIdx === -1) { + arr[arr.length - 1] += ch; + continue; + } - // Default is a character that is not `\[](){}?+*^$`. - default: - last.push({ - type: types.CHAR, - value: c.charCodeAt(0), - }); + ch = str.slice(idx, closeIdx + 1); + tok.val = ch; + tok.idx = idx = closeIdx; } - } - - // Check if any groups have not been closed. - if (groupStack.length !== 0) { - util.error(regexpStr, 'Unterminated group'); - } - - return start; -}; + if (quotes.indexOf(ch) !== -1) { + closeIdx = getClosingQuote(str, ch, idx + 1); + if (closeIdx === -1) { + arr[arr.length - 1] += ch; + continue; + } -module.exports.types = types; + if (keepQuotes(ch, opts) === true) { + ch = str.slice(idx, closeIdx + 1); + } else { + ch = str.slice(idx + 1, closeIdx); + } + tok.val = ch; + tok.idx = idx = closeIdx; + } -/***/ }), + if (typeof fn === 'function') { + fn(tok, tokens); + ch = tok.val; + idx = tok.idx; + } -/***/ 54771: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + if (tok.val === sep && tok.split !== false) { + arr.push(''); + continue; + } -var types = __webpack_require__(40432); + arr[arr.length - 1] += tok.val; + } -exports.wordBoundary = function() { - return { type: types.POSITION, value: 'b' }; + return arr; }; -exports.nonWordBoundary = function() { - return { type: types.POSITION, value: 'B' }; -}; +function getClosingQuote(str, ch, i, brackets) { + var idx = str.indexOf(ch, i); + if (str.charAt(idx - 1) === '\\') { + return getClosingQuote(str, ch, idx + 1); + } + return idx; +} -exports.begin = function() { - return { type: types.POSITION, value: '^' }; -}; +function keepQuotes(ch, opts) { + if (opts.keepDoubleQuotes === true && ch === '"') return true; + if (opts.keepSingleQuotes === true && ch === "'") return true; + return opts.keepQuotes; +} -exports.end = function() { - return { type: types.POSITION, value: '$' }; -}; +function keepEscaping(opts, str, idx) { + if (typeof opts.keepEscaping === 'function') { + return opts.keepEscaping(str, idx); + } + return opts.keepEscaping === true || str[idx + 1] === '\\'; +} /***/ }), -/***/ 28135: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -var types = __webpack_require__(40432); +/***/ 66889: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -var INTS = function() { - return [{ type: types.RANGE , from: 48, to: 57 }]; -}; +"use strict"; -var WORDS = function() { - return [ - { type: types.CHAR, value: 95 }, - { type: types.RANGE, from: 97, to: 122 }, - { type: types.RANGE, from: 65, to: 90 } - ].concat(INTS()); -}; -var WHITESPACE = function() { - return [ - { type: types.CHAR, value: 9 }, - { type: types.CHAR, value: 10 }, - { type: types.CHAR, value: 11 }, - { type: types.CHAR, value: 12 }, - { type: types.CHAR, value: 13 }, - { type: types.CHAR, value: 32 }, - { type: types.CHAR, value: 160 }, - { type: types.CHAR, value: 5760 }, - { type: types.CHAR, value: 6158 }, - { type: types.CHAR, value: 8192 }, - { type: types.CHAR, value: 8193 }, - { type: types.CHAR, value: 8194 }, - { type: types.CHAR, value: 8195 }, - { type: types.CHAR, value: 8196 }, - { type: types.CHAR, value: 8197 }, - { type: types.CHAR, value: 8198 }, - { type: types.CHAR, value: 8199 }, - { type: types.CHAR, value: 8200 }, - { type: types.CHAR, value: 8201 }, - { type: types.CHAR, value: 8202 }, - { type: types.CHAR, value: 8232 }, - { type: types.CHAR, value: 8233 }, - { type: types.CHAR, value: 8239 }, - { type: types.CHAR, value: 8287 }, - { type: types.CHAR, value: 12288 }, - { type: types.CHAR, value: 65279 } - ]; -}; +var isExtendable = __webpack_require__(28730); +var assignSymbols = __webpack_require__(64353); -var NOTANYCHAR = function() { - return [ - { type: types.CHAR, value: 10 }, - { type: types.CHAR, value: 13 }, - { type: types.CHAR, value: 8232 }, - { type: types.CHAR, value: 8233 }, - ]; +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; }; -// Predefined class objects. -exports.words = function() { - return { type: types.SET, set: WORDS(), not: false }; -}; +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} -exports.notWords = function() { - return { type: types.SET, set: WORDS(), not: true }; -}; +function isString(val) { + return (val && typeof val === 'string'); +} -exports.ints = function() { - return { type: types.SET, set: INTS(), not: false }; -}; +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} -exports.notInts = function() { - return { type: types.SET, set: INTS(), not: true }; -}; +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} -exports.whitespace = function() { - return { type: types.SET, set: WHITESPACE(), not: false }; -}; +/** + * Returns true if the given `key` is an own property of `obj`. + */ -exports.notWhitespace = function() { - return { type: types.SET, set: WHITESPACE(), not: true }; -}; +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} -exports.anyChar = function() { - return { type: types.SET, set: NOTANYCHAR(), not: true }; -}; +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} /***/ }), -/***/ 40432: -/***/ (function(module) { +/***/ 28730: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -module.exports = { - ROOT : 0, - GROUP : 1, - POSITION : 2, - SET : 3, - RANGE : 4, - REPETITION : 5, - REFERENCE : 6, - CHAR : 7, +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isPlainObject = __webpack_require__(81064); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); }; /***/ }), -/***/ 10265: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 69457: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -var types = __webpack_require__(40432); -var sets = __webpack_require__(28135); +"use strict"; +/*! + * static-extend + * + * Copyright (c) 2016, Jon Schlinkert. + * Licensed under the MIT License. + */ -// All of these are private and only used by randexp. -// It's assumed that they will always be called with the correct input. -var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?'; -var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 }; +var copy = __webpack_require__(31368); +var define = __webpack_require__(5477); +var util = __webpack_require__(31669); /** - * Finds character representations in str and convert all to - * their respective characters + * Returns a function for extending the static properties, + * prototype properties, and descriptors from the `Parent` + * constructor onto `Child` constructors. * - * @param {String} str - * @return {String} + * ```js + * var extend = require('static-extend'); + * Parent.extend = extend(Parent); + * + * // optionally pass a custom merge function as the second arg + * Parent.extend = extend(Parent, function(Child) { + * Child.prototype.mixin = function(key, val) { + * Child.prototype[key] = val; + * }; + * }); + * + * // extend "child" constructors + * Parent.extend(Child); + * + * // optionally define prototype methods as the second arg + * Parent.extend(Child, { + * foo: function() {}, + * bar: function() {} + * }); + * ``` + * @param {Function} `Parent` Parent ctor + * @param {Function} `extendFn` Optional extend function for handling any necessary custom merging. Useful when updating methods that require a specific prototype. + * @param {Function} `Child` Child ctor + * @param {Object} `proto` Optionally pass additional prototype properties to inherit. + * @return {Object} + * @api public */ -exports.strToChars = function(str) { - /* jshint maxlen: false */ - var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g; - str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) { - if (lbs) { - return s; + +function extend(Parent, extendFn) { + if (typeof Parent !== 'function') { + throw new TypeError('expected Parent to be a function.'); + } + + return function(Ctor, proto) { + if (typeof Ctor !== 'function') { + throw new TypeError('expected Ctor to be a function.'); } - var code = b ? 8 : - a16 ? parseInt(a16, 16) : - b16 ? parseInt(b16, 16) : - c8 ? parseInt(c8, 8) : - dctrl ? CTRL.indexOf(dctrl) : - SLSH[eslsh]; + util.inherits(Ctor, Parent); + copy(Ctor, Parent); - var c = String.fromCharCode(code); + // proto can be null or a plain object + if (typeof proto === 'object') { + var obj = Object.create(proto); - // Escape special regex characters. - if (/[\[\]{}\^$.|?*+()]/.test(c)) { - c = '\\' + c; + for (var k in obj) { + Ctor.prototype[k] = obj[k]; + } } - return c; - }); + // keep a reference to the parent prototype + define(Ctor.prototype, '_parent_', { + configurable: true, + set: function() {}, + get: function() { + return Parent.prototype; + } + }); - return str; -}; + if (typeof extendFn === 'function') { + extendFn(Ctor, Parent); + } + Ctor.extend = extend(Ctor, extendFn); + }; +}; /** - * turns class into tokens - * reads str until it encounters a ] not preceeded by a \ - * - * @param {String} str - * @param {String} regexpStr - * @return {Array., Number>} + * Expose `extend` */ -exports.tokenizeClass = function(str, regexpStr) { - /* jshint maxlen: false */ - var tokens = []; - var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g; - var rs, c; +module.exports = extend; - while ((rs = regexp.exec(str)) != null) { - if (rs[1]) { - tokens.push(sets.words()); - } else if (rs[2]) { - tokens.push(sets.ints()); +/***/ }), - } else if (rs[3]) { - tokens.push(sets.whitespace()); +/***/ 16326: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - } else if (rs[4]) { - tokens.push(sets.notWords()); +"use strict"; - } else if (rs[5]) { - tokens.push(sets.notInts()); - } else if (rs[6]) { - tokens.push(sets.notWhitespace()); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; - } else if (rs[7]) { - tokens.push({ - type: types.RANGE, - from: (rs[8] || rs[9]).charCodeAt(0), - to: rs[10].charCodeAt(0), - }); +var _os = _interopRequireDefault(__webpack_require__(12087)); - } else if (c = rs[12]) { - tokens.push({ - type: types.CHAR, - value: c.charCodeAt(0), - }); +var _cacache = _interopRequireDefault(__webpack_require__(36801)); - } else { - return [tokens, regexp.lastIndex]; - } - } +var _findCacheDir = _interopRequireDefault(__webpack_require__(61844)); - exports.error(regexpStr, 'Unterminated character class'); -}; +var _workerFarm = _interopRequireDefault(__webpack_require__(18921)); +var _serializeJavascript = _interopRequireDefault(__webpack_require__(85841)); -/** - * Shortcut to throw errors. - * - * @param {String} regexp - * @param {String} msg - */ -exports.error = function(regexp, msg) { - throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg); -}; +var _isWsl = _interopRequireDefault(__webpack_require__(47543)); +var _minify = _interopRequireDefault(__webpack_require__(30787)); -/***/ }), +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ 71217: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const worker = __webpack_require__.ab + "worker.js"; -var parse = __webpack_require__(25622); -var types = parse.types; +class TaskRunner { + constructor(options = {}) { + const { + cache, + parallel + } = options; + this.cacheDir = cache === true ? (0, _findCacheDir.default)({ + name: 'terser-webpack-plugin' + }) || _os.default.tmpdir() : cache; // In some cases cpus() returns undefined + // https://github.com/nodejs/node/issues/19022 -module.exports = function (re, opts) { - if (!opts) opts = {}; - var replimit = opts.limit === undefined ? 25 : opts.limit; - - if (isRegExp(re)) re = re.source; - else if (typeof re !== 'string') re = String(re); - - try { re = parse(re) } - catch (err) { return false } - - var reps = 0; - return (function walk (node, starHeight) { - if (node.type === types.REPETITION) { - starHeight ++; - reps ++; - if (starHeight > 1) return false; - if (reps > replimit) return false; - } - - if (node.options) { - for (var i = 0, len = node.options.length; i < len; i++) { - var ok = walk({ stack: node.options[i] }, starHeight); - if (!ok) return false; - } + const cpus = _os.default.cpus() || { + length: 1 + }; // WSL sometimes freezes, error seems to be on the WSL side + // https://github.com/webpack-contrib/terser-webpack-plugin/issues/21 + + this.maxConcurrentWorkers = _isWsl.default ? 1 : parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1); + } + + run(tasks, callback) { + /* istanbul ignore if */ + if (!tasks.length) { + callback(null, []); + return; + } + + if (this.maxConcurrentWorkers > 1) { + const workerOptions = process.platform === 'win32' ? { + maxConcurrentWorkers: this.maxConcurrentWorkers, + maxConcurrentCallsPerWorker: 1 + } : { + maxConcurrentWorkers: this.maxConcurrentWorkers + }; + this.workers = (0, _workerFarm.default)(workerOptions, __webpack_require__.ab + "worker.js"); + + this.boundWorkers = (options, cb) => { + try { + this.workers((0, _serializeJavascript.default)(options), cb); + } catch (error) { + // worker-farm can fail with ENOMEM or something else + cb(error); } - var stack = node.stack || (node.value && node.value.stack); - if (!stack) return true; - - for (var i = 0; i < stack.length; i++) { - var ok = walk(stack[i], starHeight); - if (!ok) return false; + }; + } else { + this.boundWorkers = (options, cb) => { + try { + cb(null, (0, _minify.default)(options)); + } catch (error) { + cb(error); } - - return true; - })(re, 0); -}; + }; + } + + let toRun = tasks.length; + const results = []; + + const step = (index, data) => { + toRun -= 1; + results[index] = data; + + if (!toRun) { + callback(null, results); + } + }; + + tasks.forEach((task, index) => { + const enqueue = () => { + this.boundWorkers(task, (error, data) => { + const result = error ? { + error + } : data; + + const done = () => step(index, result); + + if (this.cacheDir && !result.error) { + _cacache.default.put(this.cacheDir, (0, _serializeJavascript.default)(task.cacheKeys), JSON.stringify(data)).then(done, done); + } else { + done(); + } + }); + }; + + if (this.cacheDir) { + _cacache.default.get(this.cacheDir, (0, _serializeJavascript.default)(task.cacheKeys)).then(({ + data + }) => step(index, JSON.parse(data)), enqueue); + } else { + enqueue(); + } + }); + } + + exit() { + if (this.workers) { + _workerFarm.default.end(this.workers); + } + } -function isRegExp (x) { - return {}.toString.call(x) === '[object RegExp]'; } +exports.default = TaskRunner; /***/ }), -/***/ 85841: +/***/ 89301: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/* -Copyright (c) 2014, Yahoo! Inc. All rights reserved. -Copyrights licensed under the New BSD License. -See the accompanying LICENSE file for terms. -*/ +const plugin = __webpack_require__(43884); -var randomBytes = __webpack_require__(79822); - -// Generate an internal UID to make the regexp pattern harder to guess. -var UID_LENGTH = 16; -var UID = generateUID(); -var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|U|I)-' + UID + '-(\\d+)__@"', 'g'); +module.exports = plugin.default; -var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g; -var IS_PURE_FUNCTION = /function.*?\(/; -var IS_ARROW_FUNCTION = /.*?=>.*?/; -var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g; +/***/ }), -var RESERVED_SYMBOLS = ['*', 'async']; +/***/ 43884: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their -// Unicode char counterparts which are safe to use in JavaScript strings. -var ESCAPED_CHARS = { - '<' : '\\u003C', - '>' : '\\u003E', - '/' : '\\u002F', - '\u2028': '\\u2028', - '\u2029': '\\u2029' -}; +"use strict"; -function escapeUnsafeChars(unsafeChar) { - return ESCAPED_CHARS[unsafeChar]; -} -function generateUID() { - var bytes = randomBytes(UID_LENGTH); - var result = ''; - for(var i=0; i true, + warningsFilter = () => true, + extractComments = false, + sourceMap = false, + cache = false, + cacheKeys = defaultCacheKeys => defaultCacheKeys, + parallel = false, + include, + exclude + } = options; + this.options = { + test, + chunkFilter, + warningsFilter, + extractComments, + sourceMap, + cache, + cacheKeys, + parallel, + include, + exclude, + minify, + terserOptions: _objectSpread({ + output: { + comments: extractComments ? false : /^\**!|@preserve|@license|@cc_on/i + } + }, terserOptions) + }; + } - // pure functions, example: {key: function() {}} - if(IS_PURE_FUNCTION.test(serializedFn)) { - return serializedFn; - } + static isSourceMap(input) { + // All required options for `new SourceMapConsumer(...options)` + // https://github.com/mozilla/source-map#new-sourcemapconsumerrawsourcemap + return Boolean(input && input.version && input.sources && Array.isArray(input.sources) && typeof input.mappings === 'string'); + } - // arrow functions, example: arg1 => arg1+5 - if(IS_ARROW_FUNCTION.test(serializedFn)) { - return serializedFn; - } + static buildSourceMap(inputSourceMap) { + if (!inputSourceMap || !TerserPlugin.isSourceMap(inputSourceMap)) { + return null; + } - var argsStartsAt = serializedFn.indexOf('('); - var def = serializedFn.substr(0, argsStartsAt) - .trim() - .split(' ') - .filter(function(val) { return val.length > 0 }); + return new _sourceMap.SourceMapConsumer(inputSourceMap); + } - var nonReservedSymbols = def.filter(function(val) { - return RESERVED_SYMBOLS.indexOf(val) === -1 + static buildError(err, file, sourceMap, requestShortener) { + // Handling error which should have line, col, filename and message + if (err.line) { + const original = sourceMap && sourceMap.originalPositionFor({ + line: err.line, + column: err.col }); - // enhanced literal objects, example: {key() {}} - if(nonReservedSymbols.length > 0) { - return (def.indexOf('async') > -1 ? 'async ' : '') + 'function' - + (def.join('').indexOf('*') > -1 ? '*' : '') - + serializedFn.substr(argsStartsAt); + if (original && original.source && requestShortener) { + return new Error(`${file} from Terser\n${err.message} [${requestShortener.shorten(original.source)}:${original.line},${original.column}][${file}:${err.line},${err.col}]`); } - // arrow functions - return serializedFn; + return new Error(`${file} from Terser\n${err.message} [${file}:${err.line},${err.col}]`); + } else if (err.stack) { + return new Error(`${file} from Terser\n${err.stack}`); } - // Check if the parameter is function - if (options.ignoreFunction && typeof obj === "function") { - obj = undefined; - } - // Protects against `JSON.stringify()` returning `undefined`, by serializing - // to the literal string: "undefined". - if (obj === undefined) { - return String(obj); - } + return new Error(`${file} from Terser\n${err.message}`); + } - var str; + static buildWarning(warning, file, sourceMap, requestShortener, warningsFilter) { + let warningMessage = warning; + let locationMessage = ''; + let source = null; - // Creates a JSON string representation of the value. - // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args. - if (options.isJSON && !options.space) { - str = JSON.stringify(obj); - } else { - str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space); - } + if (sourceMap) { + const match = warningRegex.exec(warning); - // Protects against `JSON.stringify()` returning `undefined`, by serializing - // to the literal string: "undefined". - if (typeof str !== 'string') { - return String(str); - } + if (match) { + const line = +match[1]; + const column = +match[2]; + const original = sourceMap.originalPositionFor({ + line, + column + }); - // Replace unsafe HTML and invalid JavaScript line terminator chars with - // their safe Unicode char counterpart. This _must_ happen before the - // regexps and functions are serialized and added back to the string. - if (options.unsafe !== true) { - str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars); + if (original && original.source && original.source !== file && requestShortener) { + ({ + source + } = original); + warningMessage = `${warningMessage.replace(warningRegex, '')}`; + locationMessage = `[${requestShortener.shorten(original.source)}:${original.line},${original.column}]`; + } + } } - if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && undefs.length === 0 && infinities.length === 0) { - return str; + if (warningsFilter && !warningsFilter(warning, source)) { + return null; } - // Replaces all occurrences of function, regexp, date, map and set placeholders in the - // JSON string with their string representations. If the original value can - // not be found, then `undefined` is used. - return str.replace(PLACE_HOLDER_REGEXP, function (match, backSlash, type, valueIndex) { - // The placeholder may not be preceded by a backslash. This is to prevent - // replacing things like `"a\"@__R--0__@"` and thus outputting - // invalid JS. - if (backSlash) { - return match; - } + return `Terser Plugin: ${warningMessage}${locationMessage}`; + } - if (type === 'D') { - return "new Date(\"" + dates[valueIndex].toISOString() + "\")"; - } + apply(compiler) { + const buildModuleFn = moduleArg => { + // to get detailed location info about errors + moduleArg.useSourceMap = true; + }; - if (type === 'R') { - return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")"; - } + const optimizeFn = (compilation, chunks, callback) => { + const taskRunner = new _TaskRunner.default({ + cache: this.options.cache, + parallel: this.options.parallel + }); + const processedAssets = new WeakSet(); + const tasks = []; + const { + chunkFilter + } = this.options; + Array.from(chunks).filter(chunk => chunkFilter && chunkFilter(chunk)).reduce((acc, chunk) => acc.concat(chunk.files || []), []).concat(compilation.additionalChunkAssets || []).filter(_ModuleFilenameHelpers.default.matchObject.bind(null, this.options)).forEach(file => { + let inputSourceMap; + const asset = compilation.assets[file]; - if (type === 'M') { - return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")"; + if (processedAssets.has(asset)) { + return; } - if (type === 'S') { - return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")"; - } + try { + let input; - if (type === 'U') { - return 'undefined' - } + if (this.options.sourceMap && asset.sourceAndMap) { + const { + source, + map + } = asset.sourceAndMap(); + input = source; - if (type === 'I') { - return infinities[valueIndex]; - } + if (TerserPlugin.isSourceMap(map)) { + inputSourceMap = map; + } else { + inputSourceMap = map; + compilation.warnings.push(new Error(`${file} contains invalid source map`)); + } + } else { + input = asset.source(); + inputSourceMap = null; + } // Handling comment extraction - var fn = functions[valueIndex]; - return serializeFunc(fn); - }); -} + let commentsFile = false; + if (this.options.extractComments) { + commentsFile = this.options.extractComments.filename || `${file}.LICENSE`; -/***/ }), + if (typeof commentsFile === 'function') { + commentsFile = commentsFile(file); + } + } -/***/ 34857: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const task = { + file, + input, + inputSourceMap, + commentsFile, + extractComments: this.options.extractComments, + terserOptions: this.options.terserOptions, + minify: this.options.minify + }; -"use strict"; -/*! - * set-value - * - * Copyright (c) 2014-2015, 2017, Jon Schlinkert. - * Released under the MIT License. - */ + if (this.options.cache) { + const defaultCacheKeys = { + terser: _package.default.version, + node_version: process.version, + // eslint-disable-next-line global-require + 'terser-webpack-plugin': __webpack_require__(9122)/* .version */ .i8, + 'terser-webpack-plugin-options': this.options, + hash: _crypto.default.createHash('md4').update(input).digest('hex') + }; + task.cacheKeys = this.options.cacheKeys(defaultCacheKeys, file); + } + tasks.push(task); + } catch (error) { + compilation.errors.push(TerserPlugin.buildError(error, file, TerserPlugin.buildSourceMap(inputSourceMap), new _RequestShortener.default(compiler.context))); + } + }); + taskRunner.run(tasks, (tasksError, results) => { + if (tasksError) { + compilation.errors.push(tasksError); + return; + } + results.forEach((data, index) => { + const { + file, + input, + inputSourceMap, + commentsFile + } = tasks[index]; + const { + error, + map, + code, + warnings + } = data; + let { + extractedComments + } = data; + let sourceMap = null; -var split = __webpack_require__(33218); -var extend = __webpack_require__(28727); -var isPlainObject = __webpack_require__(81064); -var isObject = __webpack_require__(18493); + if (error || warnings && warnings.length > 0) { + sourceMap = TerserPlugin.buildSourceMap(inputSourceMap); + } // Handling results + // Error case: add errors, and go to next file -module.exports = function(obj, prop, val) { - if (!isObject(obj)) { - return obj; - } - if (Array.isArray(prop)) { - prop = [].concat.apply([], prop).join('.'); - } + if (error) { + compilation.errors.push(TerserPlugin.buildError(error, file, sourceMap, new _RequestShortener.default(compiler.context))); + return; + } - if (typeof prop !== 'string') { - return obj; - } + let outputSource; - var keys = split(prop, {sep: '.', brackets: true}).filter(isValidKey); - var len = keys.length; - var idx = -1; - var current = obj; + if (map) { + outputSource = new _webpackSources.SourceMapSource(code, file, JSON.parse(map), input, inputSourceMap, true); + } else { + outputSource = new _webpackSources.RawSource(code); + } // Write extracted comments to commentsFile - while (++idx < len) { - var key = keys[idx]; - if (idx !== len - 1) { - if (!isObject(current[key])) { - current[key] = {}; - } - current = current[key]; - continue; - } - if (isPlainObject(current[key]) && isPlainObject(val)) { - current[key] = extend({}, current[key], val); - } else { - current[key] = val; - } - } + if (commentsFile && extractedComments && extractedComments.length > 0) { + if (commentsFile in compilation.assets) { + const commentsFileSource = compilation.assets[commentsFile].source(); + extractedComments = extractedComments.filter(comment => !commentsFileSource.includes(comment)); + } - return obj; -}; + if (extractedComments.length > 0) { + // Add a banner to the original file + if (this.options.extractComments.banner !== false) { + let banner = this.options.extractComments.banner || `For license information please see ${_path.default.posix.basename(commentsFile)}`; -function isValidKey(key) { - return key !== '__proto__' && key !== 'constructor' && key !== 'prototype'; -} + if (typeof banner === 'function') { + banner = banner(commentsFile); + } + if (banner) { + outputSource = new _webpackSources.ConcatSource(`/*! ${banner} */\n`, outputSource); + } + } -/***/ }), + const commentsSource = new _webpackSources.RawSource(`${extractedComments.join('\n\n')}\n`); -/***/ 12579: -/***/ (function(module, exports, __webpack_require__) { + if (commentsFile in compilation.assets) { + // commentsFile already exists, append new comments... + if (compilation.assets[commentsFile] instanceof _webpackSources.ConcatSource) { + compilation.assets[commentsFile].add('\n'); + compilation.assets[commentsFile].add(commentsSource); + } else { + compilation.assets[commentsFile] = new _webpackSources.ConcatSource(compilation.assets[commentsFile], '\n', commentsSource); + } + } else { + compilation.assets[commentsFile] = commentsSource; + } + } + } // Updating assets -"use strict"; + processedAssets.add(compilation.assets[file] = outputSource); // Handling warnings -var isObject = __webpack_require__(96667); -var define = __webpack_require__(88599); -var utils = __webpack_require__(82071); -var ownNames; + if (warnings && warnings.length > 0) { + warnings.forEach(warning => { + const builtWarning = TerserPlugin.buildWarning(warning, file, sourceMap, new _RequestShortener.default(compiler.context), this.options.warningsFilter); -/** - * Create a new AST `Node` with the given `val` and `type`. - * - * ```js - * var node = new Node('*', 'Star'); - * var node = new Node({type: 'star', val: '*'}); - * ``` - * @name Node - * @param {String|Object} `val` Pass a matched substring, or an object to merge onto the node. - * @param {String} `type` The node type to use when `val` is a string. - * @return {Object} node instance - * @api public - */ + if (builtWarning) { + compilation.warnings.push(builtWarning); + } + }); + } + }); + taskRunner.exit(); + callback(); + }); + }; -function Node(val, type, parent) { - if (typeof type !== 'string') { - parent = type; - type = null; - } + const plugin = { + name: this.constructor.name + }; + compiler.hooks.compilation.tap(plugin, compilation => { + if (this.options.sourceMap) { + compilation.hooks.buildModule.tap(plugin, buildModuleFn); + } - define(this, 'parent', parent); - define(this, 'isNode', true); - define(this, 'expect', null); + const { + mainTemplate, + chunkTemplate + } = compilation; // Regenerate `contenthash` for minified assets - if (typeof type !== 'string' && isObject(val)) { - lazyKeys(); - var keys = Object.keys(val); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (ownNames.indexOf(key) === -1) { - this[key] = val[key]; + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.hashForChunk.tap(plugin, hash => { + const data = (0, _serializeJavascript.default)({ + terser: _package.default.version, + terserOptions: this.options.terserOptions + }); + hash.update('TerserPlugin'); + hash.update(data); + }); } - } - } else { - this.type = type; - this.val = val; + + compilation.hooks.optimizeChunkAssets.tapAsync(plugin, optimizeFn.bind(this, compilation)); + }); } + } -/** - * Returns true if the given value is a node. - * - * ```js - * var Node = require('snapdragon-node'); - * var node = new Node({type: 'foo'}); - * console.log(Node.isNode(node)); //=> true - * console.log(Node.isNode({})); //=> false - * ``` - * @param {Object} `node` - * @returns {Boolean} - * @api public - */ +var _default = TerserPlugin; +exports.default = _default; -Node.isNode = function(node) { - return utils.isNode(node); -}; +/***/ }), -/** - * Define a non-enumberable property on the node instance. - * Useful for adding properties that shouldn't be extended - * or visible during debugging. - * - * ```js - * var node = new Node(); - * node.define('foo', 'something non-enumerable'); - * ``` - * @param {String} `name` - * @param {any} `val` - * @return {Object} returns the node instance - * @api public - */ +/***/ 30787: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -Node.prototype.define = function(name, val) { - define(this, name, val); - return this; -}; +"use strict"; -/** - * Returns true if `node.val` is an empty string, or `node.nodes` does - * not contain any non-empty text nodes. - * - * ```js - * var node = new Node({type: 'text'}); - * node.isEmpty(); //=> true - * node.val = 'foo'; - * node.isEmpty(); //=> false - * ``` - * @param {Function} `fn` (optional) Filter function that is called on `node` and/or child nodes. `isEmpty` will return false immediately when the filter function returns false on any nodes. - * @return {Boolean} - * @api public - */ -Node.prototype.isEmpty = function(fn) { - return utils.isEmpty(this, fn); -}; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.default = void 0; -/** - * Given node `foo` and node `bar`, push node `bar` onto `foo.nodes`, and - * set `foo` as `bar.parent`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * foo.push(bar); - * ``` - * @param {Object} `node` - * @return {Number} Returns the length of `node.nodes` - * @api public - */ +var _terser = __webpack_require__(54775); -Node.prototype.push = function(node) { - assert(Node.isNode(node), 'expected node to be an instance of Node'); - define(node, 'parent', this); +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - this.nodes = this.nodes || []; - return this.nodes.push(node); -}; +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } -/** - * Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and - * set `foo` as `bar.parent`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * foo.unshift(bar); - * ``` - * @param {Object} `node` - * @return {Number} Returns the length of `node.nodes` - * @api public - */ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -Node.prototype.unshift = function(node) { - assert(Node.isNode(node), 'expected node to be an instance of Node'); - define(node, 'parent', this); +const buildTerserOptions = ({ + ecma, + warnings, + parse = {}, + compress = {}, + mangle, + module, + output, + toplevel, + nameCache, + ie8, - this.nodes = this.nodes || []; - return this.nodes.unshift(node); -}; + /* eslint-disable camelcase */ + keep_classnames, + keep_fnames, -/** - * Pop a node from `node.nodes`. - * - * ```js - * var node = new Node({type: 'foo'}); - * node.push(new Node({type: 'a'})); - * node.push(new Node({type: 'b'})); - * node.push(new Node({type: 'c'})); - * node.push(new Node({type: 'd'})); - * console.log(node.nodes.length); - * //=> 4 - * node.pop(); - * console.log(node.nodes.length); - * //=> 3 - * ``` - * @return {Number} Returns the popped `node` - * @api public - */ + /* eslint-enable camelcase */ + safari10 +} = {}) => ({ + ecma, + warnings, + parse: _objectSpread({}, parse), + compress: typeof compress === 'boolean' ? compress : _objectSpread({}, compress), + // eslint-disable-next-line no-nested-ternary + mangle: mangle == null ? true : typeof mangle === 'boolean' ? mangle : _objectSpread({}, mangle), + output: _objectSpread({ + shebang: true, + comments: false, + beautify: false, + semicolons: true + }, output), + module, + // Ignoring sourceMap from options + sourceMap: null, + toplevel, + nameCache, + ie8, + keep_classnames, + keep_fnames, + safari10 +}); -Node.prototype.pop = function() { - return this.nodes && this.nodes.pop(); -}; +const buildComments = (options, terserOptions, extractedComments) => { + const condition = {}; + const commentsOpts = terserOptions.output.comments; // Use /^\**!|@preserve|@license|@cc_on/i RegExp -/** - * Shift a node from `node.nodes`. - * - * ```js - * var node = new Node({type: 'foo'}); - * node.push(new Node({type: 'a'})); - * node.push(new Node({type: 'b'})); - * node.push(new Node({type: 'c'})); - * node.push(new Node({type: 'd'})); - * console.log(node.nodes.length); - * //=> 4 - * node.shift(); - * console.log(node.nodes.length); - * //=> 3 - * ``` - * @return {Object} Returns the shifted `node` - * @api public - */ + if (typeof options.extractComments === 'boolean') { + condition.preserve = commentsOpts; + condition.extract = /^\**!|@preserve|@license|@cc_on/i; + } else if (typeof options.extractComments === 'string' || options.extractComments instanceof RegExp) { + // extractComments specifies the extract condition and commentsOpts specifies the preserve condition + condition.preserve = commentsOpts; + condition.extract = options.extractComments; + } else if (typeof options.extractComments === 'function') { + condition.preserve = commentsOpts; + condition.extract = options.extractComments; + } else if (Object.prototype.hasOwnProperty.call(options.extractComments, 'condition')) { + // Extract condition is given in extractComments.condition + condition.preserve = commentsOpts; + condition.extract = options.extractComments.condition; + } else { + // No extract condition is given. Extract comments that match commentsOpts instead of preserving them + condition.preserve = false; + condition.extract = commentsOpts; + } // Ensure that both conditions are functions -Node.prototype.shift = function() { - return this.nodes && this.nodes.shift(); -}; -/** - * Remove `node` from `node.nodes`. - * - * ```js - * node.remove(childNode); - * ``` - * @param {Object} `node` - * @return {Object} Returns the removed node. - * @api public - */ + ['preserve', 'extract'].forEach(key => { + let regexStr; + let regex; -Node.prototype.remove = function(node) { - assert(Node.isNode(node), 'expected node to be an instance of Node'); - this.nodes = this.nodes || []; - var idx = node.index; - if (idx !== -1) { - node.index = -1; - return this.nodes.splice(idx, 1); - } - return null; -}; + switch (typeof condition[key]) { + case 'boolean': + condition[key] = condition[key] ? () => true : () => false; + break; -/** - * Get the first child node from `node.nodes` that matches the given `type`. - * If `type` is a number, the child node at that index is returned. - * - * ```js - * var child = node.find(1); //<= index of the node to get - * var child = node.find('foo'); //<= node.type of a child node - * var child = node.find(/^(foo|bar)$/); //<= regex to match node.type - * var child = node.find(['foo', 'bar']); //<= array of node.type(s) - * ``` - * @param {String} `type` - * @return {Object} Returns a child node or undefined. - * @api public - */ + case 'function': + break; -Node.prototype.find = function(type) { - return utils.findNode(this.nodes, type); -}; + case 'string': + if (condition[key] === 'all') { + condition[key] = () => true; -/** - * Return true if the node is the given `type`. - * - * ```js - * var node = new Node({type: 'bar'}); - * cosole.log(node.isType('foo')); // false - * cosole.log(node.isType(/^(foo|bar)$/)); // true - * cosole.log(node.isType(['foo', 'bar'])); // true - * ``` - * @param {String} `type` - * @return {Boolean} - * @api public - */ + break; + } -Node.prototype.isType = function(type) { - return utils.isType(this, type); + if (condition[key] === 'some') { + condition[key] = (astNode, comment) => { + return comment.type === 'comment2' && /^\**!|@preserve|@license|@cc_on/i.test(comment.value); + }; + + break; + } + + regexStr = condition[key]; + + condition[key] = (astNode, comment) => { + return new RegExp(regexStr).test(comment.value); + }; + + break; + + default: + regex = condition[key]; + + condition[key] = (astNode, comment) => regex.test(comment.value); + + } + }); // Redefine the comments function to extract and preserve + // comments according to the two conditions + + return (astNode, comment) => { + if (condition.extract(astNode, comment)) { + const commentText = comment.type === 'comment2' ? `/*${comment.value}*/` : `//${comment.value}`; // Don't include duplicate comments + + if (!extractedComments.includes(commentText)) { + extractedComments.push(commentText); + } + } + + return condition.preserve(astNode, comment); + }; }; -/** - * Return true if the `node.nodes` has the given `type`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * foo.push(bar); - * - * cosole.log(foo.hasType('qux')); // false - * cosole.log(foo.hasType(/^(qux|bar)$/)); // true - * cosole.log(foo.hasType(['qux', 'bar'])); // true - * ``` - * @param {String} `type` - * @return {Boolean} - * @api public - */ +const minify = options => { + const { + file, + input, + inputSourceMap, + extractComments, + minify: minifyFn + } = options; -Node.prototype.hasType = function(type) { - return utils.hasType(this, type); + if (minifyFn) { + return minifyFn({ + [file]: input + }, inputSourceMap); + } // Copy terser options + + + const terserOptions = buildTerserOptions(options.terserOptions); // Let terser generate a SourceMap + + if (inputSourceMap) { + terserOptions.sourceMap = true; + } + + const extractedComments = []; + + if (extractComments) { + terserOptions.output.comments = buildComments(options, terserOptions, extractedComments); + } + + const { + error, + map, + code, + warnings + } = (0, _terser.minify)({ + [file]: input + }, terserOptions); + return { + error, + map, + code, + warnings, + extractedComments + }; }; -/** - * Get the siblings array, or `null` if it doesn't exist. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * foo.push(bar); - * foo.push(baz); +var _default = minify; +exports.default = _default; + +/***/ }), + +/***/ 71708: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * to-object-path * - * console.log(bar.siblings.length) // 2 - * console.log(baz.siblings.length) // 2 - * ``` - * @return {Array} - * @api public + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. */ -Object.defineProperty(Node.prototype, 'siblings', { - set: function() { - throw new Error('node.siblings is a getter and cannot be defined'); - }, - get: function() { - return this.parent ? this.parent.nodes : null; + + +var typeOf = __webpack_require__(48865); + +module.exports = function toPath(args) { + if (typeOf(args) !== 'arguments') { + args = arguments; } -}); + return filter(args).join('.'); +}; -/** - * Get the node's current index from `node.parent.nodes`. - * This should always be correct, even when the parent adds nodes. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * var qux = new Node({type: 'qux'}); - * foo.push(bar); - * foo.push(baz); - * foo.unshift(qux); - * - * console.log(bar.index) // 1 - * console.log(baz.index) // 2 - * console.log(qux.index) // 0 - * ``` - * @return {Number} - * @api public - */ +function filter(arr) { + var len = arr.length; + var idx = -1; + var res = []; -Object.defineProperty(Node.prototype, 'index', { - set: function(index) { - define(this, 'idx', index); - }, - get: function() { - if (!Array.isArray(this.siblings)) { - return -1; - } - var tok = this.idx !== -1 ? this.siblings[this.idx] : null; - if (tok !== this) { - this.idx = this.siblings.indexOf(this); + while (++idx < len) { + var ele = arr[idx]; + if (typeOf(ele) === 'arguments' || Array.isArray(ele)) { + res.push.apply(res, filter(ele)); + } else if (typeof ele === 'string') { + res.push(ele); } - return this.idx; } -}); + return res; +} + + +/***/ }), + +/***/ 51279: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; + + +var safe = __webpack_require__(71217); +var define = __webpack_require__(74998); +var extend = __webpack_require__(99793); +var not = __webpack_require__(30931); +var MAX_LENGTH = 1024 * 64; /** - * Get the previous node from the siblings array or `null`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * foo.push(bar); - * foo.push(baz); - * - * console.log(baz.prev.type) // 'bar' - * ``` - * @return {Object} - * @api public + * Session cache */ -Object.defineProperty(Node.prototype, 'prev', { - set: function() { - throw new Error('node.prev is a getter and cannot be defined'); - }, - get: function() { - if (Array.isArray(this.siblings)) { - return this.siblings[this.index - 1] || this.parent.prev; - } - return null; - } -}); +var cache = {}; /** - * Get the siblings array, or `null` if it doesn't exist. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * foo.push(bar); - * foo.push(baz); + * Create a regular expression from the given `pattern` string. * - * console.log(bar.siblings.length) // 2 - * console.log(baz.siblings.length) // 2 - * ``` - * @return {Object} + * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. + * @param {Object} `options` + * @return {RegExp} * @api public */ -Object.defineProperty(Node.prototype, 'next', { - set: function() { - throw new Error('node.next is a getter and cannot be defined'); - }, - get: function() { - if (Array.isArray(this.siblings)) { - return this.siblings[this.index + 1] || this.parent.next; - } - return null; +module.exports = function(patterns, options) { + if (!Array.isArray(patterns)) { + return makeRe(patterns, options); } -}); + return makeRe(patterns.join('|'), options); +}; /** - * Get the first node from `node.nodes`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * var qux = new Node({type: 'qux'}); - * foo.push(bar); - * foo.push(baz); - * foo.push(qux); + * Create a regular expression from the given `pattern` string. * - * console.log(foo.first.type) // 'bar' - * ``` - * @return {Object} The first node, or undefiend + * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. + * @param {Object} `options` + * @return {RegExp} * @api public */ -Object.defineProperty(Node.prototype, 'first', { - get: function() { - return this.nodes ? this.nodes[0] : null; +function makeRe(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; } -}); -/** - * Get the last node from `node.nodes`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * var qux = new Node({type: 'qux'}); - * foo.push(bar); - * foo.push(baz); - * foo.push(qux); - * - * console.log(foo.last.type) // 'qux' - * ``` - * @return {Object} The last node, or undefiend - * @api public - */ + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } -Object.defineProperty(Node.prototype, 'last', { - get: function() { - return this.nodes ? utils.last(this.nodes) : null; + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); } -}); -/** - * Get the last node from `node.nodes`. - * - * ```js - * var foo = new Node({type: 'foo'}); - * var bar = new Node({type: 'bar'}); - * var baz = new Node({type: 'baz'}); - * var qux = new Node({type: 'qux'}); - * foo.push(bar); - * foo.push(baz); - * foo.push(qux); - * - * console.log(foo.last.type) // 'qux' - * ``` - * @return {Object} The last node, or undefiend - * @api public - */ + var key = pattern; + // do this before shallow cloning options, it's a lot faster + if (!options || (options && options.cache !== false)) { + key = createKey(pattern, options); -Object.defineProperty(Node.prototype, 'scope', { - get: function() { - if (this.isScope !== true) { - return this.parent ? this.parent.scope : this; + if (cache.hasOwnProperty(key)) { + return cache[key]; } - return this; } -}); + + var opts = extend({}, options); + if (opts.contains === true) { + if (opts.negate === true) { + opts.strictNegate = false; + } else { + opts.strict = false; + } + } + + if (opts.strict === false) { + opts.strictOpen = false; + opts.strictClose = false; + } + + var open = opts.strictOpen !== false ? '^' : ''; + var close = opts.strictClose !== false ? '$' : ''; + var flags = opts.flags || ''; + var regex; + + if (opts.nocase === true && !/i/.test(flags)) { + flags += 'i'; + } + + try { + if (opts.negate || typeof opts.strictNegate === 'boolean') { + pattern = not.create(pattern, opts); + } + + var str = open + '(?:' + pattern + ')' + close; + regex = new RegExp(str, flags); + + if (opts.safe === true && safe(regex) === false) { + throw new Error('potentially unsafe regular expression: ' + regex.source); + } + + } catch (err) { + if (opts.strictErrors === true || opts.safe === true) { + err.key = key; + err.pattern = pattern; + err.originalOptions = options; + err.createdOptions = opts; + throw err; + } + + try { + regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$'); + } catch (err) { + regex = /.^/; //<= match nothing + } + } + + if (opts.cache !== false) { + memoize(regex, key, pattern, opts); + } + return regex; +} /** - * Get own property names from Node prototype, but only the - * first time `Node` is instantiated + * Memoize generated regex. This can result in dramatic speed improvements + * and simplify debugging by adding options and pattern to the regex. It can be + * disabled by passing setting `options.cache` to false. */ -function lazyKeys() { - if (!ownNames) { - ownNames = Object.getOwnPropertyNames(Node.prototype); - } +function memoize(regex, key, pattern, options) { + define(regex, 'cached', true); + define(regex, 'pattern', pattern); + define(regex, 'options', options); + define(regex, 'key', key); + cache[key] = regex; } /** - * Simplified assertion. Throws an error is `val` is falsey. + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. */ -function assert(val, message) { - if (!val) throw new Error(message); +function createKey(pattern, options) { + if (!options) return pattern; + var key = pattern; + for (var prop in options) { + if (options.hasOwnProperty(prop)) { + key += ';' + prop + '=' + String(options[prop]); + } + } + return key; } /** - * Expose `Node` + * Expose `makeRe` */ -exports = module.exports = Node; +module.exports.makeRe = makeRe; /***/ }), -/***/ 88599: +/***/ 74998: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /*! * define-property * - * Copyright (c) 2015, 2017, Jon Schlinkert. + * Copyright (c) 2015-2018, Jon Schlinkert. * Released under the MIT License. */ +var isobject = __webpack_require__(96667); var isDescriptor = __webpack_require__(44133); +var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) + ? Reflect.defineProperty + : Object.defineProperty; -module.exports = function defineProperty(obj, prop, val) { - if (typeof obj !== 'object' && typeof obj !== 'function') { - throw new TypeError('expected an object or function.'); +module.exports = function defineProperty(obj, key, val) { + if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { + throw new TypeError('expected an object, function, or array'); } - if (typeof prop !== 'string') { - throw new TypeError('expected `prop` to be a string.'); + if (typeof key !== 'string') { + throw new TypeError('expected "key" to be a string'); } - if (isDescriptor(val) && ('set' in val || 'get' in val)) { - return Object.defineProperty(obj, prop, val); + if (isDescriptor(val)) { + define(obj, key, val); + return obj; } - return Object.defineProperty(obj, prop, { + define(obj, key, { configurable: true, enumerable: false, writable: true, value: val }); + + return obj; }; /***/ }), -/***/ 82071: +/***/ 99793: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -var typeOf = __webpack_require__(48865); -var utils = module.exports; - -/** - * Returns true if the given value is a node. - * - * ```js - * var Node = require('snapdragon-node'); - * var node = new Node({type: 'foo'}); - * console.log(utils.isNode(node)); //=> true - * console.log(utils.isNode({})); //=> false - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @returns {Boolean} - * @api public - */ +var isExtendable = __webpack_require__(78947); +var assignSymbols = __webpack_require__(64353); -utils.isNode = function(node) { - return typeOf(node) === 'object' && node.isNode === true; +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; }; -/** - * Emit an empty string for the given `node`. - * - * ```js - * // do nothing for beginning-of-string - * snapdragon.compiler.set('bos', utils.noop); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @returns {undefined} - * @api public - */ - -utils.noop = function(node) { - append(this, '', node); -}; - -/** - * Appdend `node.val` to `compiler.output`, exactly as it was created - * by the parser. - * - * ```js - * snapdragon.compiler.set('text', utils.identity); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @returns {undefined} - * @api public - */ - -utils.identity = function(node) { - append(this, node.val, node); -}; - -/** - * Previously named `.emit`, this method appends the given `val` - * to `compiler.output` for the given node. Useful when you know - * what value should be appended advance, regardless of the actual - * value of `node.val`. - * - * ```js - * snapdragon.compiler - * .set('i', function(node) { - * this.mapVisit(node); - * }) - * .set('i.open', utils.append('')) - * .set('i.close', utils.append('')) - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @returns {Function} Returns a compiler middleware function. - * @api public - */ - -utils.append = function(val) { - return function(node) { - append(this, val, node); - }; -}; - -/** - * Used in compiler middleware, this onverts an AST node into - * an empty `text` node and deletes `node.nodes` if it exists. - * The advantage of this method is that, as opposed to completely - * removing the node, indices will not need to be re-calculated - * in sibling nodes, and nothing is appended to the output. - * - * ```js - * utils.toNoop(node); - * // convert `node.nodes` to the given value instead of deleting it - * utils.toNoop(node, []); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array. - * @api public - */ - -utils.toNoop = function(node, nodes) { - if (nodes) { - node.nodes = nodes; - } else { - delete node.nodes; - node.type = 'text'; - node.val = ''; - } -}; - -/** - * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon - * automatically calls registered compilers, this allows you to pass a visitor - * function. - * - * ```js - * snapdragon.compiler.set('i', function(node) { - * utils.visit(node, function(childNode) { - * // do stuff with "childNode" - * return childNode; - * }); - * }); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Function} `fn` - * @return {Object} returns the node after recursively visiting all child nodes. - * @api public - */ - -utils.visit = function(node, fn) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isFunction(fn), 'expected a visitor function'); - fn(node); - return node.nodes ? utils.mapVisit(node, fn) : node; -}; - -/** - * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by - * [visit](#visit), use this method if you do not want `fn` to be called on - * the first node. - * - * ```js - * snapdragon.compiler.set('i', function(node) { - * utils.mapVisit(node, function(childNode) { - * // do stuff with "childNode" - * return childNode; - * }); - * }); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Object} `options` - * @param {Function} `fn` - * @return {Object} returns the node - * @api public - */ - -utils.mapVisit = function(node, fn) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isArray(node.nodes), 'expected node.nodes to be an array'); - assert(isFunction(fn), 'expected a visitor function'); - - for (var i = 0; i < node.nodes.length; i++) { - utils.visit(node.nodes[i], fn); - } - return node; -}; - -/** - * Unshift an `*.open` node onto `node.nodes`. - * - * ```js - * var Node = require('snapdragon-node'); - * snapdragon.parser.set('brace', function(node) { - * var match = this.match(/^{/); - * if (match) { - * var parent = new Node({type: 'brace'}); - * utils.addOpen(parent, Node); - * console.log(parent.nodes[0]): - * // { type: 'brace.open', val: '' }; - * - * // push the parent "brace" node onto the stack - * this.push(parent); - * - * // return the parent node, so it's also added to the AST - * return brace; - * } - * }); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. - * @param {Function} `filter` Optionaly specify a filter function to exclude the node. - * @return {Object} Returns the created opening node. - * @api public - */ - -utils.addOpen = function(node, Node, val, filter) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isFunction(Node), 'expected Node to be a constructor function'); - - if (typeof val === 'function') { - filter = val; - val = ''; - } - - if (typeof filter === 'function' && !filter(node)) return; - var open = new Node({ type: node.type + '.open', val: val}); - var unshift = node.unshift || node.unshiftNode; - if (typeof unshift === 'function') { - unshift.call(node, open); - } else { - utils.unshiftNode(node, open); +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } } - return open; -}; - -/** - * Push a `*.close` node onto `node.nodes`. - * - * ```js - * var Node = require('snapdragon-node'); - * snapdragon.parser.set('brace', function(node) { - * var match = this.match(/^}/); - * if (match) { - * var parent = this.parent(); - * if (parent.type !== 'brace') { - * throw new Error('missing opening: ' + '}'); - * } - * - * utils.addClose(parent, Node); - * console.log(parent.nodes[parent.nodes.length - 1]): - * // { type: 'brace.close', val: '' }; - * - * // no need to return a node, since the parent - * // was already added to the AST - * return; - * } - * }); - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. - * @param {Function} `filter` Optionaly specify a filter function to exclude the node. - * @return {Object} Returns the created closing node. - * @api public - */ - -utils.addClose = function(node, Node, val, filter) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isFunction(Node), 'expected Node to be a constructor function'); +} - if (typeof val === 'function') { - filter = val; - val = ''; - } +function isString(val) { + return (val && typeof val === 'string'); +} - if (typeof filter === 'function' && !filter(node)) return; - var close = new Node({ type: node.type + '.close', val: val}); - var push = node.push || node.pushNode; - if (typeof push === 'function') { - push.call(node, close); - } else { - utils.pushNode(node, close); +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; } - return close; -}; - -/** - * Wraps the given `node` with `*.open` and `*.close` nodes. - * - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. - * @param {Function} `filter` Optionaly specify a filter function to exclude the node. - * @return {Object} Returns the node - * @api public - */ - -utils.wrapNodes = function(node, Node, filter) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isFunction(Node), 'expected Node to be a constructor function'); - - utils.addOpen(node, Node, filter); - utils.addClose(node, Node, filter); - return node; -}; - -/** - * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent. - * - * ```js - * var parent = new Node({type: 'foo'}); - * var node = new Node({type: 'bar'}); - * utils.pushNode(parent, node); - * console.log(parent.nodes[0].type) // 'bar' - * console.log(node.parent.type) // 'foo' - * ``` - * @param {Object} `parent` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Object} Returns the child node - * @api public - */ - -utils.pushNode = function(parent, node) { - assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); - assert(utils.isNode(node), 'expected node to be an instance of Node'); + return obj; +} - node.define('parent', parent); - parent.nodes = parent.nodes || []; - parent.nodes.push(node); - return node; -}; +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} /** - * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent. - * - * ```js - * var parent = new Node({type: 'foo'}); - * var node = new Node({type: 'bar'}); - * utils.unshiftNode(parent, node); - * console.log(parent.nodes[0].type) // 'bar' - * console.log(node.parent.type) // 'foo' - * ``` - * @param {Object} `parent` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {undefined} - * @api public + * Returns true if the given `key` is an own property of `obj`. */ -utils.unshiftNode = function(parent, node) { - assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); - assert(utils.isNode(node), 'expected node to be an instance of Node'); - - node.define('parent', parent); - parent.nodes = parent.nodes || []; - parent.nodes.unshift(node); -}; +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} -/** - * Pop the last `node` off of `parent.nodes`. The advantage of - * using this method is that it checks for `node.nodes` and works - * with any version of `snapdragon-node`. - * - * ```js - * var parent = new Node({type: 'foo'}); - * utils.pushNode(parent, new Node({type: 'foo'})); - * utils.pushNode(parent, new Node({type: 'bar'})); - * utils.pushNode(parent, new Node({type: 'baz'})); - * console.log(parent.nodes.length); //=> 3 - * utils.popNode(parent); - * console.log(parent.nodes.length); //=> 2 - * ``` - * @param {Object} `parent` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. - * @api public - */ +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} -utils.popNode = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - if (typeof node.pop === 'function') { - return node.pop(); - } - return node.nodes && node.nodes.pop(); -}; -/** - * Shift the first `node` off of `parent.nodes`. The advantage of - * using this method is that it checks for `node.nodes` and works - * with any version of `snapdragon-node`. - * - * ```js - * var parent = new Node({type: 'foo'}); - * utils.pushNode(parent, new Node({type: 'foo'})); - * utils.pushNode(parent, new Node({type: 'bar'})); - * utils.pushNode(parent, new Node({type: 'baz'})); - * console.log(parent.nodes.length); //=> 3 - * utils.shiftNode(parent); - * console.log(parent.nodes.length); //=> 2 - * ``` - * @param {Object} `parent` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. - * @api public - */ +/***/ }), -utils.shiftNode = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - if (typeof node.shift === 'function') { - return node.shift(); - } - return node.nodes && node.nodes.shift(); -}; +/***/ 78947: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * Remove the specified `node` from `parent.nodes`. +"use strict"; +/*! + * is-extendable * - * ```js - * var parent = new Node({type: 'abc'}); - * var foo = new Node({type: 'foo'}); - * utils.pushNode(parent, foo); - * utils.pushNode(parent, new Node({type: 'bar'})); - * utils.pushNode(parent, new Node({type: 'baz'})); - * console.log(parent.nodes.length); //=> 3 - * utils.removeNode(parent, foo); - * console.log(parent.nodes.length); //=> 2 - * ``` - * @param {Object} `parent` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`. - * @api public + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -utils.removeNode = function(parent, node) { - assert(utils.isNode(parent), 'expected parent.node to be an instance of Node'); - assert(utils.isNode(node), 'expected node to be an instance of Node'); - - if (!parent.nodes) { - return null; - } - - if (typeof parent.remove === 'function') { - return parent.remove(node); - } - var idx = parent.nodes.indexOf(node); - if (idx !== -1) { - return parent.nodes.splice(idx, 1); - } -}; -/** - * Returns true if `node.type` matches the given `type`. Throws a - * `TypeError` if `node` is not an instance of `Node`. - * - * ```js - * var Node = require('snapdragon-node'); - * var node = new Node({type: 'foo'}); - * console.log(utils.isType(node, 'foo')); // false - * console.log(utils.isType(node, 'bar')); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {String} `type` - * @return {Boolean} - * @api public - */ +var isPlainObject = __webpack_require__(81064); -utils.isType = function(node, type) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - switch (typeOf(type)) { - case 'array': - var types = type.slice(); - for (var i = 0; i < types.length; i++) { - if (utils.isType(node, types[i])) { - return true; - } - } - return false; - case 'string': - return node.type === type; - case 'regexp': - return type.test(node.type); - default: { - throw new TypeError('expected "type" to be an array, string or regexp'); - } - } +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); }; -/** - * Returns true if the given `node` has the given `type` in `node.nodes`. - * Throws a `TypeError` if `node` is not an instance of `Node`. - * - * ```js - * var Node = require('snapdragon-node'); - * var node = new Node({ - * type: 'foo', - * nodes: [ - * new Node({type: 'bar'}), - * new Node({type: 'baz'}) - * ] - * }); - * console.log(utils.hasType(node, 'xyz')); // false - * console.log(utils.hasType(node, 'baz')); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {String} `type` - * @return {Boolean} - * @api public - */ - -utils.hasType = function(node, type) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - if (!Array.isArray(node.nodes)) return false; - for (var i = 0; i < node.nodes.length; i++) { - if (utils.isType(node.nodes[i], type)) { - return true; - } - } - return false; -}; -/** - * Returns the first node from `node.nodes` of the given `type` - * - * ```js - * var node = new Node({ - * type: 'foo', - * nodes: [ - * new Node({type: 'text', val: 'abc'}), - * new Node({type: 'text', val: 'xyz'}) - * ] - * }); - * - * var textNode = utils.firstOfType(node.nodes, 'text'); - * console.log(textNode.val); - * //=> 'abc' - * ``` - * @param {Array} `nodes` - * @param {String} `type` - * @return {Object|undefined} Returns the first matching node or undefined. - * @api public - */ +/***/ }), -utils.firstOfType = function(nodes, type) { - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - if (utils.isType(node, type)) { - return node; - } - } -}; +/***/ 29859: +/***/ (function(module) { -/** - * Returns the node at the specified index, or the first node of the - * given `type` from `node.nodes`. - * - * ```js - * var node = new Node({ - * type: 'foo', - * nodes: [ - * new Node({type: 'text', val: 'abc'}), - * new Node({type: 'text', val: 'xyz'}) - * ] - * }); - * - * var nodeOne = utils.findNode(node.nodes, 'text'); - * console.log(nodeOne.val); - * //=> 'abc' - * - * var nodeTwo = utils.findNode(node.nodes, 1); - * console.log(nodeTwo.val); - * //=> 'xyz' - * ``` - * - * @param {Array} `nodes` - * @param {String|Number} `type` Node type or index. - * @return {Object} Returns a node or undefined. - * @api public - */ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + + __extends = function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function (m, exports) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + }; + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + } + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); -utils.findNode = function(nodes, type) { - if (!Array.isArray(nodes)) { - return null; + +/***/ }), + +/***/ 7716: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; + + +var isObject = __webpack_require__(18493); +var union = __webpack_require__(69123); +var get = __webpack_require__(89304); +var set = __webpack_require__(34857); + +module.exports = function unionValue(obj, prop, value) { + if (!isObject(obj)) { + throw new TypeError('union-value expects the first argument to be an object.'); } - if (typeof type === 'number') { - return nodes[type]; + + if (typeof prop !== 'string') { + throw new TypeError('union-value expects `prop` to be a string.'); } - return utils.firstOfType(nodes, type); + + var arr = arrayify(get(obj, prop)); + set(obj, prop, union(arr, arrayify(value))); + return obj; }; -/** - * Returns true if the given node is an "*.open" node. - * - * ```js - * var Node = require('snapdragon-node'); - * var brace = new Node({type: 'brace'}); - * var open = new Node({type: 'brace.open'}); - * var close = new Node({type: 'brace.close'}); - * - * console.log(utils.isOpen(brace)); // false - * console.log(utils.isOpen(open)); // true - * console.log(utils.isOpen(close)); // false - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Boolean} - * @api public - */ +function arrayify(val) { + if (val === null || typeof val === 'undefined') { + return []; + } + if (Array.isArray(val)) { + return val; + } + return [val]; +} -utils.isOpen = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - return node.type.slice(-5) === '.open'; -}; -/** - * Returns true if the given node is a "*.close" node. - * - * ```js - * var Node = require('snapdragon-node'); - * var brace = new Node({type: 'brace'}); - * var open = new Node({type: 'brace.open'}); - * var close = new Node({type: 'brace.close'}); +/***/ }), + +/***/ 5834: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * unset-value * - * console.log(utils.isClose(brace)); // false - * console.log(utils.isClose(open)); // false - * console.log(utils.isClose(close)); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Boolean} - * @api public + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. */ -utils.isClose = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - return node.type.slice(-6) === '.close'; + + +var isObject = __webpack_require__(96667); +var has = __webpack_require__(77735); + +module.exports = function unset(obj, prop) { + if (!isObject(obj)) { + throw new TypeError('expected an object.'); + } + if (obj.hasOwnProperty(prop)) { + delete obj[prop]; + return true; + } + + if (has(obj, prop)) { + var segs = prop.split('.'); + var last = segs.pop(); + while (segs.length && segs[segs.length - 1].slice(-1) === '\\') { + last = segs.pop().slice(0, -1) + '.' + last; + } + while (segs.length) obj = obj[prop = segs.shift()]; + return (delete obj[last]); + } + return true; }; -/** - * Returns true if `node.nodes` **has** an `.open` node - * - * ```js - * var Node = require('snapdragon-node'); - * var brace = new Node({ - * type: 'brace', - * nodes: [] - * }); - * - * var open = new Node({type: 'brace.open'}); - * console.log(utils.hasOpen(brace)); // false + +/***/ }), + +/***/ 77735: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * has-value * - * brace.pushNode(open); - * console.log(utils.hasOpen(brace)); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Boolean} - * @api public + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. */ -utils.hasOpen = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - var first = node.first || node.nodes ? node.nodes[0] : null; - if (utils.isNode(first)) { - return first.type === node.type + '.open'; + + +var isObject = __webpack_require__(78037); +var hasValues = __webpack_require__(38719); +var get = __webpack_require__(89304); + +module.exports = function(obj, prop, noZero) { + if (isObject(obj)) { + return hasValues(get(obj, prop), noZero); } - return false; + return hasValues(obj, prop); }; -/** - * Returns true if `node.nodes` **has** a `.close` node - * - * ```js - * var Node = require('snapdragon-node'); - * var brace = new Node({ - * type: 'brace', - * nodes: [] - * }); - * - * var close = new Node({type: 'brace.close'}); - * console.log(utils.hasClose(brace)); // false + +/***/ }), + +/***/ 78037: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/*! + * isobject * - * brace.pushNode(close); - * console.log(utils.hasClose(brace)); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Boolean} - * @api public + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. */ -utils.hasClose = function(node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null; - if (utils.isNode(last)) { - return last.type === node.type + '.close'; - } - return false; + + +var isArray = __webpack_require__(21352); + +module.exports = function isObject(val) { + return val != null && typeof val === 'object' && isArray(val) === false; }; -/** - * Returns true if `node.nodes` has both `.open` and `.close` nodes + +/***/ }), + +/***/ 38719: +/***/ (function(module) { + +"use strict"; +/*! + * has-values * - * ```js - * var Node = require('snapdragon-node'); - * var brace = new Node({ - * type: 'brace', - * nodes: [] - * }); - * - * var open = new Node({type: 'brace.open'}); - * var close = new Node({type: 'brace.close'}); - * console.log(utils.hasOpen(brace)); // false - * console.log(utils.hasClose(brace)); // false - * - * brace.pushNode(open); - * brace.pushNode(close); - * console.log(utils.hasOpen(brace)); // true - * console.log(utils.hasClose(brace)); // true - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Boolean} - * @api public + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. */ -utils.hasOpenAndClose = function(node) { - return utils.hasOpen(node) && utils.hasClose(node); -}; -/** - * Push the given `node` onto the `state.inside` array for the - * given type. This array is used as a specialized "stack" for - * only the given `node.type`. - * - * ```js - * var state = { inside: {}}; - * var node = new Node({type: 'brace'}); - * utils.addType(state, node); - * console.log(state.inside); - * //=> { brace: [{type: 'brace'}] } - * ``` - * @param {Object} `state` The `compiler.state` object or custom state object. - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Array} Returns the `state.inside` stack for the given type. - * @api public - */ -utils.addType = function(state, node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isObject(state), 'expected state to be an object'); +module.exports = function hasValue(o, noZero) { + if (o === null || o === undefined) { + return false; + } - var type = node.parent - ? node.parent.type - : node.type.replace(/\.open$/, ''); + if (typeof o === 'boolean') { + return true; + } - if (!state.hasOwnProperty('inside')) { - state.inside = {}; + if (typeof o === 'number') { + if (o === 0 && noZero === true) { + return false; + } + return true; } - if (!state.inside.hasOwnProperty(type)) { - state.inside[type] = []; + + if (o.length !== undefined) { + return o.length !== 0; } - var arr = state.inside[type]; - arr.push(node); - return arr; + for (var key in o) { + if (o.hasOwnProperty(key)) { + return true; + } + } + return false; }; -/** - * Remove the given `node` from the `state.inside` array for the - * given type. This array is used as a specialized "stack" for - * only the given `node.type`. - * - * ```js - * var state = { inside: {}}; - * var node = new Node({type: 'brace'}); - * utils.addType(state, node); - * console.log(state.inside); - * //=> { brace: [{type: 'brace'}] } - * utils.removeType(state, node); - * //=> { brace: [] } - * ``` - * @param {Object} `state` The `compiler.state` object or custom state object. - * @param {Object} `node` Instance of [snapdragon-node][] - * @return {Array} Returns the `state.inside` stack for the given type. - * @api public - */ - -utils.removeType = function(state, node) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isObject(state), 'expected state to be an object'); - - var type = node.parent - ? node.parent.type - : node.type.replace(/\.close$/, ''); - if (state.inside.hasOwnProperty(type)) { - return state.inside[type].pop(); - } -}; +/***/ }), -/** - * Returns true if `node.val` is an empty string, or `node.nodes` does - * not contain any non-empty text nodes. - * - * ```js - * var node = new Node({type: 'text'}); - * utils.isEmpty(node); //=> true - * node.val = 'foo'; - * utils.isEmpty(node); //=> false - * ``` - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {Function} `fn` - * @return {Boolean} - * @api public - */ +/***/ 94007: +/***/ (function(__unused_webpack_module, exports) { -utils.isEmpty = function(node, fn) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); +/** @license URI.js v4.2.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, (function (exports) { 'use strict'; - if (!Array.isArray(node.nodes)) { - if (node.type !== 'text') { - return true; - } - if (typeof fn === 'function') { - return fn(node, node.parent); +function merge() { + for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { + sets[_key] = arguments[_key]; } - return !utils.trim(node.val); - } - for (var i = 0; i < node.nodes.length; i++) { - var child = node.nodes[i]; - if (utils.isOpen(child) || utils.isClose(child)) { - continue; + if (sets.length > 1) { + sets[0] = sets[0].slice(0, -1); + var xl = sets.length - 1; + for (var x = 1; x < xl; ++x) { + sets[x] = sets[x].slice(1, -1); + } + sets[xl] = sets[xl].slice(1); + return sets.join(''); + } else { + return sets[0]; } - if (!utils.isEmpty(child, fn)) { - return false; +} +function subexp(str) { + return "(?:" + str + ")"; +} +function typeOf(o) { + return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); +} +function toUpperCase(str) { + return str.toUpperCase(); +} +function toArray(obj) { + return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; +} +function assign(target, source) { + var obj = target; + if (source) { + for (var key in source) { + obj[key] = source[key]; + } } - } + return obj; +} - return true; -}; +function buildExps(isIRI) { + var ALPHA$$ = "[A-Za-z]", + CR$ = "[\\x0D]", + DIGIT$$ = "[0-9]", + DQUOTE$$ = "[\\x22]", + HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), + //case-insensitive + LF$$ = "[\\x0A]", + SP$$ = "[\\x20]", + PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), + //expanded + GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", + SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", + RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), + UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", + //subset, excludes bidi control characters + IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", + //subset + UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), + SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), + USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), + DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), + DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), + //relaxed parsing rules + IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), + H16$ = subexp(HEXDIG$$ + "{1,4}"), + LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), + IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), + // 6( h16 ":" ) ls32 + IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), + // "::" 5( h16 ":" ) ls32 + IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), + //[ h16 ] "::" 4( h16 ":" ) ls32 + IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), + //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), + //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), + //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), + //[ *4( h16 ":" ) h16 ] "::" ls32 + IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), + //[ *5( h16 ":" ) h16 ] "::" h16 + IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), + //[ *6( h16 ":" ) h16 ] "::" + IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), + ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), + //RFC 6874 + IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), + //RFC 6874 + IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), + //RFC 6874, with relaxed parsing rules + IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), + IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), + //RFC 6874 + REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), + HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), + PORT$ = subexp(DIGIT$$ + "*"), + AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), + PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), + SEGMENT$ = subexp(PCHAR$ + "*"), + SEGMENT_NZ$ = subexp(PCHAR$ + "+"), + SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), + PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), + PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), + //simplified + PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), + //simplified + PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), + //simplified + PATH_EMPTY$ = "(?!" + PCHAR$ + ")", + PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), + FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), + HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), + URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), + RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), + URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), + ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), + GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", + SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", + AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; + return { + NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), + NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), + NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), + ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), + UNRESERVED: new RegExp(UNRESERVED$$, "g"), + OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), + PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), + IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), + IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules + }; +} +var URI_PROTOCOL = buildExps(false); -/** - * Returns true if the `state.inside` stack for the given type exists - * and has one or more nodes on it. - * - * ```js - * var state = { inside: {}}; - * var node = new Node({type: 'brace'}); - * console.log(utils.isInsideType(state, 'brace')); //=> false - * utils.addType(state, node); - * console.log(utils.isInsideType(state, 'brace')); //=> true - * utils.removeType(state, node); - * console.log(utils.isInsideType(state, 'brace')); //=> false - * ``` - * @param {Object} `state` - * @param {String} `type` - * @return {Boolean} - * @api public - */ +var IRI_PROTOCOL = buildExps(true); -utils.isInsideType = function(state, type) { - assert(isObject(state), 'expected state to be an object'); - assert(isString(type), 'expected type to be a string'); +var slicedToArray = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; - if (!state.hasOwnProperty('inside')) { - return false; - } + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); - if (!state.inside.hasOwnProperty(type)) { - return false; + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; } - return state.inside[type].length > 0; -}; + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if (Symbol.iterator in Object(arr)) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); -/** - * Returns true if `node` is either a child or grand-child of the given `type`, - * or `state.inside[type]` is a non-empty array. - * - * ```js - * var state = { inside: {}}; - * var node = new Node({type: 'brace'}); - * var open = new Node({type: 'brace.open'}); - * console.log(utils.isInside(state, open, 'brace')); //=> false - * utils.pushNode(node, open); - * console.log(utils.isInside(state, open, 'brace')); //=> true - * ``` - * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object. - * @param {Object} `node` Instance of [snapdragon-node][] - * @param {String} `type` The `node.type` to check for. - * @return {Boolean} - * @api public - */ -utils.isInside = function(state, node, type) { - assert(utils.isNode(node), 'expected node to be an instance of Node'); - assert(isObject(state), 'expected state to be an object'); - if (Array.isArray(type)) { - for (var i = 0; i < type.length; i++) { - if (utils.isInside(state, node, type[i])) { - return true; - } - } - return false; - } - var parent = node.parent; - if (typeof type === 'string') { - return (parent && parent.type === type) || utils.isInsideType(state, type); - } - if (typeOf(type) === 'regexp') { - if (parent && parent.type && type.test(parent.type)) { - return true; - } - var keys = Object.keys(state.inside); - var len = keys.length; - var idx = -1; - while (++idx < len) { - var key = keys[idx]; - var val = state.inside[key]; - if (Array.isArray(val) && val.length !== 0 && type.test(key)) { - return true; - } - } - } - return false; -}; -/** - * Get the last `n` element from the given `array`. Used for getting - * a node from `node.nodes.` - * - * @param {Array} `array` - * @param {Number} `n` - * @return {undefined} - * @api public - */ -utils.last = function(arr, n) { - return arr[arr.length - (n || 1)]; -}; -/** - * Cast the given `val` to an array. - * - * ```js - * console.log(utils.arrayify('')); - * //=> [] - * console.log(utils.arrayify('foo')); - * //=> ['foo'] - * console.log(utils.arrayify(['foo'])); - * //=> ['foo'] - * ``` - * @param {any} `val` - * @return {Array} - * @api public - */ -utils.arrayify = function(val) { - if (typeof val === 'string' && val !== '') { - return [val]; - } - if (!Array.isArray(val)) { - return []; + + +var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); } - return val; }; -/** - * Convert the given `val` to a string by joining with `,`. Useful - * for creating a cheerio/CSS/DOM-style selector from a list of strings. - * - * @param {any} `val` - * @return {Array} - * @api public - */ +/** Highest positive signed 32-bit float value */ -utils.stringify = function(val) { - return utils.arrayify(val).join(','); -}; +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 -/** - * Ensure that the given value is a string and call `.trim()` on it, - * or return an empty string. - * - * @param {String} `str` - * @return {String} - * @api public - */ +/** Bootstring parameters */ +var base = 36; +var tMin = 1; +var tMax = 26; +var skew = 38; +var damp = 700; +var initialBias = 72; +var initialN = 128; // 0x80 +var delimiter = '-'; // '\x2D' -utils.trim = function(str) { - return typeof str === 'string' ? str.trim() : ''; +/** Regular expressions */ +var regexPunycode = /^xn--/; +var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' }; -/** - * Return true if val is an object - */ +/** Convenience shortcuts */ +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; -function isObject(val) { - return typeOf(val) === 'object'; -} +/*--------------------------------------------------------------------------*/ /** - * Return true if val is a string + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. */ - -function isString(val) { - return typeof val === 'string'; +function error$1(type) { + throw new RangeError(errors[type]); } /** - * Return true if val is a function + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. */ - -function isFunction(val) { - return typeof val === 'function'; -} - -/** - * Return true if val is an array - */ - -function isArray(val) { - return Array.isArray(val); +function map(array, fn) { + var result = []; + var length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; } /** - * Shim to ensure the `.append` methods work with any version of snapdragon + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. */ - -function append(compiler, val, node) { - if (typeof compiler.append !== 'function') { - return compiler.emit(val, node); - } - return compiler.append(val, node); +function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; } /** - * Simplified assertion. Throws an error is `val` is falsey. + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. */ - -function assert(val, message) { - if (!val) throw new Error(message); +function ucs2decode(string) { + var output = []; + var counter = 0; + var length = string.length; + while (counter < length) { + var value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // Low surrogate. + output.push(((value & 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. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; } - -/***/ }), - -/***/ 79285: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -var Base = __webpack_require__(87263); -var define = __webpack_require__(5477); -var Compiler = __webpack_require__(33003); -var Parser = __webpack_require__(35573); -var utils = __webpack_require__(622); -var regexCache = {}; -var cache = {}; - /** - * Create a new instance of `Snapdragon` with the given `options`. - * - * ```js - * var snapdragon = new Snapdragon(); - * ``` - * - * @param {Object} `options` - * @api public + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). */ - -function Snapdragon(options) { - Base.call(this, null, options); - this.options = utils.extend({source: 'string'}, this.options); - this.compiler = new Compiler(this.options); - this.parser = new Parser(this.options); - - Object.defineProperty(this, 'compilers', { - get: function() { - return this.compiler.compilers; - } - }); - - Object.defineProperty(this, 'parsers', { - get: function() { - return this.parser.parsers; - } - }); - - Object.defineProperty(this, 'regex', { - get: function() { - return this.parser.regex; - } - }); -} +var ucs2encode = function ucs2encode(array) { + return String.fromCodePoint.apply(String, toConsumableArray(array)); +}; /** - * Inherit Base + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. */ - -Base.extend(Snapdragon); +var basicToDigit = function basicToDigit(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; /** - * Add a parser to `snapdragon.parsers` for capturing the given `type` using - * the specified regex or parser function. A function is useful if you need - * to customize how the token is created and/or have access to the parser - * instance to check options, etc. - * - * ```js - * snapdragon - * .capture('slash', /^\//) - * .capture('dot', function() { - * var pos = this.position(); - * var m = this.match(/^\./); - * if (!m) return; - * return pos({ - * type: 'dot', - * val: m[0] - * }); - * }); - * ``` - * @param {String} `type` - * @param {RegExp|Function} `regex` - * @return {Object} Returns the parser instance for chaining - * @api public + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. */ - -Snapdragon.prototype.capture = function() { - return this.parser.capture.apply(this.parser, arguments); +var digitToBasic = function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); }; /** - * Register a plugin `fn`. - * - * ```js - * var snapdragon = new Snapdgragon([options]); - * snapdragon.use(function() { - * console.log(this); //<= snapdragon instance - * console.log(this.parser); //<= parser instance - * console.log(this.compiler); //<= compiler instance - * }); - * ``` - * @param {Object} `fn` - * @api public + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private */ - -Snapdragon.prototype.use = function(fn) { - fn.call(this, this); - return this; +var adapt = function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); }; /** - * Parse the given `str`. - * - * ```js - * var snapdragon = new Snapdgragon([options]); - * // register parsers - * snapdragon.parser.use(function() {}); - * - * // parse - * var ast = snapdragon.parse('foo/bar'); - * console.log(ast); - * ``` - * @param {String} `str` - * @param {Object} `options` Set `options.sourcemap` to true to enable source maps. - * @return {Object} Returns an AST. - * @api public + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. */ +var decode = function decode(input) { + // Don't use UCS-2. + var output = []; + var inputLength = input.length; + var i = 0; + var n = initialN; + var bias = initialBias; -Snapdragon.prototype.parse = function(str, options) { - this.options = utils.extend({}, this.options, options); - var parsed = this.parser.parse(str, this.options); + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. - // add non-enumerable parser reference - define(parsed, 'parser', this.parser); - return parsed; -}; + var basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } -/** - * Compile the given `AST`. - * - * ```js - * var snapdragon = new Snapdgragon([options]); - * // register plugins - * snapdragon.use(function() {}); - * // register parser plugins - * snapdragon.parser.use(function() {}); - * // register compiler plugins - * snapdragon.compiler.use(function() {}); - * - * // parse - * var ast = snapdragon.parse('foo/bar'); - * - * // compile - * var res = snapdragon.compile(ast); - * console.log(res.output); - * ``` - * @param {Object} `ast` - * @param {Object} `options` - * @return {Object} Returns an object with an `output` property with the rendered string. - * @api public - */ + for (var j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error$1('not-basic'); + } + output.push(input.charCodeAt(j)); + } -Snapdragon.prototype.compile = function(ast, options) { - this.options = utils.extend({}, this.options, options); - var compiled = this.compiler.compile(ast, this.options); + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. - // add non-enumerable compiler reference - define(compiled, 'compiler', this.compiler); - return compiled; -}; + for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ -/** - * Expose `Snapdragon` - */ + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + var oldi = i; + for (var w = 1, k = base;; /* no condition */k += base) { -module.exports = Snapdragon; + if (index >= inputLength) { + error$1('invalid-input'); + } -/** - * Expose `Parser` and `Compiler` - */ + var digit = basicToDigit(input.charCodeAt(index++)); -module.exports.Compiler = Compiler; -module.exports.Parser = Parser; + if (digit >= base || digit > floor((maxInt - i) / w)) { + error$1('overflow'); + } + i += digit * w; + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; -/***/ }), + if (digit < t) { + break; + } -/***/ 33003: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + var baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error$1('overflow'); + } -"use strict"; + w *= baseMinusT; + } + var out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); -var use = __webpack_require__(77709); -var define = __webpack_require__(5477); -var debug = __webpack_require__(31185)('snapdragon:compiler'); -var utils = __webpack_require__(622); + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error$1('overflow'); + } -/** - * Create a new `Compiler` with the given `options`. - * @param {Object} `options` - */ + n += floor(i / out); + i %= out; -function Compiler(options, state) { - debug('initializing', __filename); - this.options = utils.extend({source: 'string'}, options); - this.state = state || {}; - this.compilers = {}; - this.output = ''; - this.set('eos', function(node) { - return this.emit(node.val, node); - }); - this.set('noop', function(node) { - return this.emit(node.val, node); - }); - this.set('bos', function(node) { - return this.emit(node.val, node); - }); - use(this); -} + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + + return String.fromCodePoint.apply(String, output); +}; /** - * Prototype methods + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. */ +var encode = function encode(input) { + var output = []; -Compiler.prototype = { - - /** - * Throw an error message with details including the cursor position. - * @param {String} `msg` Message to use in the Error. - */ + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); - error: function(msg, node) { - var pos = node.position || {start: {column: 0}}; - var message = this.options.source + ' column:' + pos.start.column + ': ' + msg; + // Cache the length. + var inputLength = input.length; - var err = new Error(message); - err.reason = msg; - err.column = pos.start.column; - err.source = this.pattern; + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; - if (this.options.silent) { - this.errors.push(err); - } else { - throw err; - } - }, + // Handle the basic code points. + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; - /** - * Define a non-enumberable property on the `Compiler` instance. - * - * ```js - * compiler.define('foo', 'bar'); - * ``` - * @name .define - * @param {String} `key` propery name - * @param {any} `val` property value - * @return {Object} Returns the Compiler instance for chaining. - * @api public - */ + try { + for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _currentValue2 = _step.value; - define: function(key, val) { - define(this, key, val); - return this; - }, + if (_currentValue2 < 0x80) { + output.push(stringFromCharCode(_currentValue2)); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } - /** - * Emit `node.val` - */ + var basicLength = output.length; + var handledCPCount = basicLength; - emit: function(str, node) { - this.output += str; - return str; - }, + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. - /** - * Add a compiler `fn` with the given `name` - */ + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } - set: function(name, fn) { - this.compilers[name] = fn; - return this; - }, + // Main encoding loop: + while (handledCPCount < inputLength) { - /** - * Get compiler `name`. - */ + // All non-basic code points < n have been handled already. Find the next + // larger one: + var m = maxInt; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; - get: function(name) { - return this.compilers[name]; - }, + try { + for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var currentValue = _step2.value; - /** - * Get the previous AST node. - */ + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } - prev: function(n) { - return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' }; - }, - - /** - * Get the next AST node. - */ - - next: function(n) { - return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' }; - }, - - /** - * Visit `node`. - */ - - visit: function(node, nodes, i) { - var fn = this.compilers[node.type]; - this.idx = i; + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } - if (typeof fn !== 'function') { - throw this.error('compiler "' + node.type + '" is not registered', node); - } - return fn.call(this, node, nodes, i); - }, + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error$1('overflow'); + } - /** - * Map visit over array of `nodes`. - */ + delta += (m - n) * handledCPCountPlusOne; + n = m; - mapVisit: function(nodes) { - if (!Array.isArray(nodes)) { - throw new TypeError('expected an array'); - } - var len = nodes.length; - var idx = -1; - while (++idx < len) { - this.visit(nodes[idx], nodes, idx); - } - return this; - }, + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; - /** - * Compile `ast`. - */ + try { + for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _currentValue = _step3.value; - compile: function(ast, options) { - var opts = utils.extend({}, this.options, options); - this.ast = ast; - this.parsingErrors = this.ast.errors; - this.output = ''; + if (_currentValue < n && ++delta > maxInt) { + error$1('overflow'); + } + if (_currentValue == n) { + // Represent delta as a generalized variable-length integer. + var q = delta; + for (var k = base;; /* no condition */k += base) { + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + var qMinusT = q - t; + var baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); + } - // source map support - if (opts.sourcemap) { - var sourcemaps = __webpack_require__(59657); - sourcemaps(this); - this.mapVisit(this.ast.nodes); - this.applySourceMaps(); - this.map = opts.sourcemap === 'generator' ? this.map : this.map.toJSON(); - return this; - } + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } - this.mapVisit(this.ast.nodes); - return this; - } + ++delta; + ++n; + } + return output.join(''); }; /** - * Expose `Compiler` + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. */ +var toUnicode = function toUnicode(input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); +}; -module.exports = Compiler; - - -/***/ }), - -/***/ 35573: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +var toASCII = function toASCII(input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); +}; +/*--------------------------------------------------------------------------*/ -var use = __webpack_require__(77709); -var util = __webpack_require__(31669); -var Cache = __webpack_require__(4337); -var define = __webpack_require__(5477); -var debug = __webpack_require__(31185)('snapdragon:parser'); -var Position = __webpack_require__(7974); -var utils = __webpack_require__(622); +/** Define the public API */ +var punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; /** - * Create a new `Parser` with the given `input` and `options`. - * @param {String} `input` - * @param {Object} `options` - * @api public + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author Gary Court + * @see http://github.com/garycourt/uri-js */ - -function Parser(options) { - debug('initializing', __filename); - this.options = utils.extend({source: 'string'}, options); - this.init(this.options); - use(this); -} - /** - * Prototype methods + * Copyright 2011 Gary Court. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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 GARY COURT ``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 GARY COURT 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. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. */ +var SCHEMES = {}; +function pctEncChar(chr) { + var c = chr.charCodeAt(0); + var e = void 0; + if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); + return e; +} +function pctDecChars(str) { + var newStr = ""; + var i = 0; + var il = str.length; + while (i < il) { + var c = parseInt(str.substr(i + 1, 2), 16); + if (c < 128) { + newStr += String.fromCharCode(c); + i += 3; + } else if (c >= 194 && c < 224) { + if (il - i >= 6) { + var c2 = parseInt(str.substr(i + 4, 2), 16); + newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); + } else { + newStr += str.substr(i, 6); + } + i += 6; + } else if (c >= 224) { + if (il - i >= 9) { + var _c = parseInt(str.substr(i + 4, 2), 16); + var c3 = parseInt(str.substr(i + 7, 2), 16); + newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); + } else { + newStr += str.substr(i, 9); + } + i += 9; + } else { + newStr += str.substr(i, 3); + i += 3; + } + } + return newStr; +} +function _normalizeComponentEncoding(components, protocol) { + function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(protocol.UNRESERVED) ? str : decStr; + } + if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); + if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + return components; +} -Parser.prototype = { - constructor: Parser, - - init: function(options) { - this.orig = ''; - this.input = ''; - this.parsed = ''; - - this.column = 1; - this.line = 1; - - this.regex = new Cache(); - this.errors = this.errors || []; - this.parsers = this.parsers || {}; - this.types = this.types || []; - this.sets = this.sets || {}; - this.fns = this.fns || []; - this.currentType = 'root'; - - var pos = this.position(); - this.bos = pos({type: 'bos', val: ''}); - - this.ast = { - type: 'root', - errors: this.errors, - nodes: [this.bos] - }; - - define(this.bos, 'parent', this.ast); - this.nodes = [this.ast]; - - this.count = 0; - this.setCount = 0; - this.stack = []; - }, - - /** - * Throw a formatted error with the cursor column and `msg`. - * @param {String} `msg` Message to use in the Error. - */ - - error: function(msg, node) { - var pos = node.position || {start: {column: 0, line: 0}}; - var line = pos.start.line; - var column = pos.start.column; - var source = this.options.source; +function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; +} +function _normalizeIPv4(host, protocol) { + var matches = host.match(protocol.IPV4ADDRESS) || []; - var message = source + ' : ' + msg; - var err = new Error(message); - err.source = source; - err.reason = msg; - err.pos = pos; + var _matches = slicedToArray(matches, 2), + address = _matches[1]; - if (this.options.silent) { - this.errors.push(err); + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); } else { - throw err; + return host; } - }, - - /** - * Define a non-enumberable property on the `Parser` instance. - * - * ```js - * parser.define('foo', 'bar'); - * ``` - * @name .define - * @param {String} `key` propery name - * @param {any} `val` property value - * @return {Object} Returns the Parser instance for chaining. - * @api public - */ - - define: function(key, val) { - define(this, key, val); - return this; - }, - - /** - * Mark position and patch `node.position`. - */ - - position: function() { - var start = { line: this.line, column: this.column }; - var self = this; +} +function _normalizeIPv6(host, protocol) { + var matches = host.match(protocol.IPV6ADDRESS) || []; - return function(node) { - define(node, 'position', new Position(start, self)); - return node; - }; - }, + var _matches2 = slicedToArray(matches, 3), + address = _matches2[1], + zone = _matches2[2]; - /** - * Set parser `name` with the given `fn` - * @param {String} `name` - * @param {Function} `fn` - * @api public - */ + if (address) { + var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), + _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), + last = _address$toLowerCase$2[0], + first = _address$toLowerCase$2[1]; - set: function(type, fn) { - if (this.types.indexOf(type) === -1) { - this.types.push(type); + var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; + var lastFields = last.split(":").map(_stripLeadingZeros); + var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); + var fieldCount = isLastFieldIPv4Address ? 7 : 8; + var lastFieldsStart = lastFields.length - fieldCount; + var fields = Array(fieldCount); + for (var x = 0; x < fieldCount; ++x) { + fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; + } + if (isLastFieldIPv4Address) { + fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); + } + var allZeroFields = fields.reduce(function (acc, field, index) { + if (!field || field === "0") { + var lastLongest = acc[acc.length - 1]; + if (lastLongest && lastLongest.index + lastLongest.length === index) { + lastLongest.length++; + } else { + acc.push({ index: index, length: 1 }); + } + } + return acc; + }, []); + var longestZeroFields = allZeroFields.sort(function (a, b) { + return b.length - a.length; + })[0]; + var newHost = void 0; + if (longestZeroFields && longestZeroFields.length > 1) { + var newFirst = fields.slice(0, longestZeroFields.index); + var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); + newHost = newFirst.join(":") + "::" + newLast.join(":"); + } else { + newHost = fields.join(":"); + } + if (zone) { + newHost += "%" + zone; + } + return newHost; + } else { + return host; } - this.parsers[type] = fn.bind(this); - return this; - }, - - /** - * Get parser `name` - * @param {String} `name` - * @api public - */ - - get: function(name) { - return this.parsers[name]; - }, - - /** - * Push a `token` onto the `type` stack. - * - * @param {String} `type` - * @return {Object} `token` - * @api public - */ - - push: function(type, token) { - this.sets[type] = this.sets[type] || []; - this.count++; - this.stack.push(token); - return this.sets[type].push(token); - }, - - /** - * Pop a token off of the `type` stack - * @param {String} `type` - * @returns {Object} Returns a token - * @api public - */ - - pop: function(type) { - this.sets[type] = this.sets[type] || []; - this.count--; - this.stack.pop(); - return this.sets[type].pop(); - }, - - /** - * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`. - * - * @param {String} `type` - * @return {Boolean} - * @api public - */ - - isInside: function(type) { - this.sets[type] = this.sets[type] || []; - return this.sets[type].length > 0; - }, +} +var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; +var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; +function parse(uriString) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - /** - * Return true if `node` is the given `type`. - * - * ```js - * parser.isType(node, 'brace'); - * ``` - * @param {Object} `node` - * @param {String} `type` - * @return {Boolean} - * @api public - */ - - isType: function(node, type) { - return node && node.type === type; - }, - - /** - * Get the previous AST node - * @return {Object} - */ - - prev: function(n) { - return this.stack.length > 0 - ? utils.last(this.stack, n) - : utils.last(this.nodes, n); - }, - - /** - * Update line and column based on `str`. - */ - - consume: function(len) { - this.input = this.input.substr(len); - }, - - /** - * Update column based on `str`. - */ - - updatePosition: function(str, len) { - var lines = str.match(/\n/g); - if (lines) this.line += lines.length; - var i = str.lastIndexOf('\n'); - this.column = ~i ? len - i : this.column + len; - this.parsed += str; - this.consume(len); - }, - - /** - * Match `regex`, return captures, and update the cursor position by `match[0]` length. - * @param {RegExp} `regex` - * @return {Object} - */ - - match: function(regex) { - var m = regex.exec(this.input); - if (m) { - this.updatePosition(m[0], m[0].length); - return m; + var components = {}; + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; + var matches = uriString.match(URI_PARSE); + if (matches) { + if (NO_MATCH_IS_UNDEFINED) { + //store each component + components.scheme = matches[1]; + components.userinfo = matches[3]; + components.host = matches[4]; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = matches[7]; + components.fragment = matches[8]; + //fix port number + if (isNaN(components.port)) { + components.port = matches[5]; + } + } else { + //IE FIX for improper RegExp matching + //store each component + components.scheme = matches[1] || undefined; + components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; + components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; + components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; + //fix port number + if (isNaN(components.port)) { + components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; + } + } + if (components.host) { + //normalize IP hosts + components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); + } + //determine reference type + if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { + components.reference = "same-document"; + } else if (components.scheme === undefined) { + components.reference = "relative"; + } else if (components.fragment === undefined) { + components.reference = "absolute"; + } else { + components.reference = "uri"; + } + //check for reference errors + if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { + components.error = components.error || "URI is not a " + options.reference + " reference."; + } + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + //if host component is a domain name + if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { + //convert Unicode IDN -> ASCII IDN + try { + components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; + } + } + //convert IRI -> URI + _normalizeComponentEncoding(components, URI_PROTOCOL); + } else { + //normalize encodings + _normalizeComponentEncoding(components, protocol); + } + //perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(components, options); + } + } else { + components.error = components.error || "URI can not be parsed."; } - }, - - /** - * Capture `type` with the given regex. - * @param {String} `type` - * @param {RegExp} `regex` - * @return {Function} - */ + return components; +} - capture: function(type, regex) { - if (typeof regex === 'function') { - return this.set.apply(this, arguments); +function _recomposeAuthority(components, options) { + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo); + uriTokens.push("@"); } + if (components.host !== undefined) { + //normalize IP hosts, add brackets and escape zone separator for IPv6 + uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { + return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; + })); + } + if (typeof components.port === "number") { + uriTokens.push(":"); + uriTokens.push(components.port.toString(10)); + } + return uriTokens.length ? uriTokens.join("") : undefined; +} - this.regex.set(type, regex); - this.set(type, function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(regex); - if (!m || !m[0]) return; - - var prev = this.prev(); - var node = pos({ - type: type, - val: m[0], - parsed: parsed, - rest: this.input - }); - - if (m[1]) { - node.inner = m[1]; - } - - define(node, 'inside', this.stack.length > 0); - define(node, 'parent', prev); - prev.nodes.push(node); - }.bind(this)); - return this; - }, - - /** - * Create a parser with open and close for parens, - * brackets or braces - */ - - capturePair: function(type, openRegex, closeRegex, fn) { - this.sets[type] = this.sets[type] || []; - - /** - * Open - */ - - this.set(type + '.open', function() { - var parsed = this.parsed; - var pos = this.position(); - var m = this.match(openRegex); - if (!m || !m[0]) return; - - var val = m[0]; - this.setCount++; - this.specialChars = true; - var open = pos({ - type: type + '.open', - val: val, - rest: this.input - }); - - if (typeof m[1] !== 'undefined') { - open.inner = m[1]; - } - - var prev = this.prev(); - var node = pos({ - type: type, - nodes: [open] - }); - - define(node, 'rest', this.input); - define(node, 'parsed', parsed); - define(node, 'prefix', m[1]); - define(node, 'parent', prev); - define(open, 'parent', node); - - if (typeof fn === 'function') { - fn.call(this, open, node); - } - - this.push(type, node); - prev.nodes.push(node); - }); - - /** - * Close - */ - - this.set(type + '.close', function() { - var pos = this.position(); - var m = this.match(closeRegex); - if (!m || !m[0]) return; - - var parent = this.pop(type); - var node = pos({ - type: type + '.close', - rest: this.input, - suffix: m[1], - val: m[0] - }); - - if (!this.isType(parent, type)) { - if (this.options.strict) { - throw new Error('missing opening "' + type + '"'); +var RDS1 = /^\.\.?\//; +var RDS2 = /^\/\.(\/|$)/; +var RDS3 = /^\/\.\.(\/|$)/; +var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; +function removeDotSegments(input) { + var output = []; + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, ""); + } else if (input.match(RDS2)) { + input = input.replace(RDS2, "/"); + } else if (input.match(RDS3)) { + input = input.replace(RDS3, "/"); + output.pop(); + } else if (input === "." || input === "..") { + input = ""; + } else { + var im = input.match(RDS5); + if (im) { + var s = im[0]; + input = input.slice(s.length); + output.push(s); + } else { + throw new Error("Unexpected dot segment condition"); + } } + } + return output.join(""); +} - this.setCount--; - node.escaped = true; - return node; - } - - if (node.suffix === '\\') { - parent.escaped = true; - node.escaped = true; - } - - parent.nodes.push(node); - define(node, 'parent', parent); - }); - - return this; - }, - - /** - * Capture end-of-string - */ - - eos: function() { - var pos = this.position(); - if (this.input) return; - var prev = this.prev(); - - while (prev.type !== 'root' && !prev.visited) { - if (this.options.strict === true) { - throw new SyntaxError('invalid syntax:' + util.inspect(prev, null, 2)); - } +function serialize(components) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - if (!hasDelims(prev)) { - prev.parent.escaped = true; - prev.escaped = true; - } + var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); + if (components.host) { + //if host component is an IPv6 address + if (protocol.IPV6ADDRESS.test(components.host)) {} + //TODO: normalize IPv6 address as per RFC 5952 - visit(prev, function(node) { - if (!hasDelims(node.parent)) { - node.parent.escaped = true; - node.escaped = true; + //if host component is a domain name + else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { + //convert IDN via punycode + try { + components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + } + } + //normalize encoding + _normalizeComponentEncoding(components, protocol); + if (options.reference !== "suffix" && components.scheme) { + uriTokens.push(components.scheme); + uriTokens.push(":"); + } + var authority = _recomposeAuthority(components, options); + if (authority !== undefined) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (components.path && components.path.charAt(0) !== "/") { + uriTokens.push("/"); } - }); - - prev = prev.parent; } + if (components.path !== undefined) { + var s = components.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === undefined) { + s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" + } + uriTokens.push(s); + } + if (components.query !== undefined) { + uriTokens.push("?"); + uriTokens.push(components.query); + } + if (components.fragment !== undefined) { + uriTokens.push("#"); + uriTokens.push(components.fragment); + } + return uriTokens.join(""); //merge tokens into a string +} - var tok = pos({ - type: 'eos', - val: this.append || '' - }); - - define(tok, 'parent', this.ast); - return tok; - }, +function resolveComponents(base, relative) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var skipNormalization = arguments[3]; - /** - * Run parsers to advance the cursor position - */ + var target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); //normalize base components + relative = parse(serialize(relative, options), options); //normalize relative components + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== undefined) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path.charAt(0) === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + //target.authority = base.authority; + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; +} - next: function() { - var parsed = this.parsed; - var len = this.types.length; - var idx = -1; - var tok; +function resolve(baseURI, relativeURI, options) { + var schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); +} - while (++idx < len) { - if ((tok = this.parsers[this.types[idx]].call(this))) { - define(tok, 'rest', this.input); - define(tok, 'parsed', parsed); - this.last = tok; - return tok; - } +function normalize(uri, options) { + if (typeof uri === "string") { + uri = serialize(parse(uri, options), options); + } else if (typeOf(uri) === "object") { + uri = parse(serialize(uri, options), options); } - }, - - /** - * Parse the given string. - * @return {Array} - */ + return uri; +} - parse: function(input) { - if (typeof input !== 'string') { - throw new TypeError('expected a string'); +function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = serialize(parse(uriA, options), options); + } else if (typeOf(uriA) === "object") { + uriA = serialize(uriA, options); + } + if (typeof uriB === "string") { + uriB = serialize(parse(uriB, options), options); + } else if (typeOf(uriB) === "object") { + uriB = serialize(uriB, options); } + return uriA === uriB; +} - this.init(this.options); - this.orig = input; - this.input = input; - var self = this; +function escapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); +} - function parse() { - // check input before calling `.next()` - input = self.input; +function unescapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); +} - // get the next AST ndoe - var node = self.next(); - if (node) { - var prev = self.prev(); - if (prev) { - define(node, 'parent', prev); - if (prev.nodes) { - prev.nodes.push(node); - } +var handler = { + scheme: "http", + domainHost: true, + parse: function parse(components, options) { + //report missing host + if (!components.host) { + components.error = components.error || "HTTP URIs must have a host."; } - - if (self.sets.hasOwnProperty(prev.type)) { - self.currentType = prev.type; + return components; + }, + serialize: function serialize(components, options) { + //normalize the default port + if (components.port === (String(components.scheme).toLowerCase() !== "https" ? 80 : 443) || components.port === "") { + components.port = undefined; } - } - - // if we got here but input is not changed, throw an error - if (self.input && input === self.input) { - throw new Error('no parsers registered for: "' + self.input.slice(0, 5) + '"'); - } + //normalize the empty path + if (!components.path) { + components.path = "/"; + } + //NOTE: We do not parse query strings for HTTP URIs + //as WWW Form Url Encoded query strings are part of the HTML4+ spec, + //and not the HTTP spec. + return components; } +}; - while (this.input) parse(); - if (this.stack.length && this.options.strict) { - var node = this.stack.pop(); - throw this.error('missing opening ' + node.type + ': "' + this.orig + '"'); - } +var handler$1 = { + scheme: "https", + domainHost: handler.domainHost, + parse: handler.parse, + serialize: handler.serialize +}; - var eos = this.eos(); - var tok = this.prev(); - if (tok.type !== 'eos') { - this.ast.nodes.push(eos); +var O = {}; +var isIRI = true; +//RFC 3986 +var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; +var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive +var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded +//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = +//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) +//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext +//const VCHAR$$ = "[\\x21-\\x7E]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext +//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); +//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); +//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); +var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; +var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; +var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); +var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; +var UNRESERVED = new RegExp(UNRESERVED$$, "g"); +var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); +var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); +var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); +var NOT_HFVALUE = NOT_HFNAME; +function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(UNRESERVED) ? str : decStr; +} +var handler$2 = { + scheme: "mailto", + parse: function parse$$1(components, options) { + var mailtoComponents = components; + var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; + mailtoComponents.path = undefined; + if (mailtoComponents.query) { + var unknownHeaders = false; + var headers = {}; + var hfields = mailtoComponents.query.split("&"); + for (var x = 0, xl = hfields.length; x < xl; ++x) { + var hfield = hfields[x].split("="); + switch (hfield[0]) { + case "to": + var toAddrs = hfield[1].split(","); + for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { + to.push(toAddrs[_x]); + } + break; + case "subject": + mailtoComponents.subject = unescapeComponent(hfield[1], options); + break; + case "body": + mailtoComponents.body = unescapeComponent(hfield[1], options); + break; + default: + unknownHeaders = true; + headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); + break; + } + } + if (unknownHeaders) mailtoComponents.headers = headers; + } + mailtoComponents.query = undefined; + for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { + var addr = to[_x2].split("@"); + addr[0] = unescapeComponent(addr[0]); + if (!options.unicodeSupport) { + //convert Unicode IDN -> ASCII IDN + try { + addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); + } catch (e) { + mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; + } + } else { + addr[1] = unescapeComponent(addr[1], options).toLowerCase(); + } + to[_x2] = addr.join("@"); + } + return mailtoComponents; + }, + serialize: function serialize$$1(mailtoComponents, options) { + var components = mailtoComponents; + var to = toArray(mailtoComponents.to); + if (to) { + for (var x = 0, xl = to.length; x < xl; ++x) { + var toAddr = String(to[x]); + var atIdx = toAddr.lastIndexOf("@"); + var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); + var domain = toAddr.slice(atIdx + 1); + //convert IDN via punycode + try { + domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); + } catch (e) { + components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + to[x] = localPart + "@" + domain; + } + components.path = to.join(","); + } + var headers = mailtoComponents.headers = mailtoComponents.headers || {}; + if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; + if (mailtoComponents.body) headers["body"] = mailtoComponents.body; + var fields = []; + for (var name in headers) { + if (headers[name] !== O[name]) { + fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); + } + } + if (fields.length) { + components.query = fields.join("&"); + } + return components; } +}; - return this.ast; - } +var URN_PARSE = /^([^\:]+)\:(.*)/; +//RFC 2141 +var handler$3 = { + scheme: "urn", + parse: function parse$$1(components, options) { + var matches = components.path && components.path.match(URN_PARSE); + var urnComponents = components; + if (matches) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = matches[1].toLowerCase(); + var nss = matches[2]; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + urnComponents.nid = nid; + urnComponents.nss = nss; + urnComponents.path = undefined; + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options); + } + } else { + urnComponents.error = urnComponents.error || "URN can not be parsed."; + } + return urnComponents; + }, + serialize: function serialize$$1(urnComponents, options) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = urnComponents.nid; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options); + } + var uriComponents = urnComponents; + var nss = urnComponents.nss; + uriComponents.path = (nid || options.nid) + ":" + nss; + return uriComponents; + } }; -/** - * Visit `node` with the given `fn` - */ +var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; +//RFC 4122 +var handler$4 = { + scheme: "urn:uuid", + parse: function parse(urnComponents, options) { + var uuidComponents = urnComponents; + uuidComponents.uuid = uuidComponents.nss; + uuidComponents.nss = undefined; + if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { + uuidComponents.error = uuidComponents.error || "UUID is not valid."; + } + return uuidComponents; + }, + serialize: function serialize(uuidComponents, options) { + var urnComponents = uuidComponents; + //normalize UUID + urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); + return urnComponents; + } +}; -function visit(node, fn) { - if (!node.visited) { - define(node, 'visited', true); - return node.nodes ? mapVisit(node.nodes, fn) : fn(node); - } - return node; -} +SCHEMES[handler.scheme] = handler; +SCHEMES[handler$1.scheme] = handler$1; +SCHEMES[handler$2.scheme] = handler$2; +SCHEMES[handler$3.scheme] = handler$3; +SCHEMES[handler$4.scheme] = handler$4; -/** - * Map visit over array of `nodes`. - */ +exports.SCHEMES = SCHEMES; +exports.pctEncChar = pctEncChar; +exports.pctDecChars = pctDecChars; +exports.parse = parse; +exports.removeDotSegments = removeDotSegments; +exports.serialize = serialize; +exports.resolveComponents = resolveComponents; +exports.resolve = resolve; +exports.normalize = normalize; +exports.equal = equal; +exports.escapeComponent = escapeComponent; +exports.unescapeComponent = unescapeComponent; -function mapVisit(nodes, fn) { - var len = nodes.length; - var idx = -1; - while (++idx < len) { - visit(nodes[idx], fn); - } -} +Object.defineProperty(exports, '__esModule', { value: true }); -function hasOpen(node) { - return node.nodes && node.nodes[0].type === (node.type + '.open'); -} +}))); +//# sourceMappingURL=uri.all.js.map -function hasClose(node) { - return node.nodes && utils.last(node.nodes).type === (node.type + '.close'); -} -function hasDelims(node) { - return hasOpen(node) && hasClose(node); -} +/***/ }), -/** - * Expose `Parser` - */ +/***/ 67806: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -module.exports = Parser; +// Copyright 2014 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) + +var path = __webpack_require__(85622) + +"use strict" + +function urix(aPath) { + if (path.sep === "\\") { + return aPath + .replace(/\\/g, "/") + .replace(/^[a-z]:\/?/i, "/") + } + return aPath +} + +module.exports = urix /***/ }), -/***/ 7974: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 77709: +/***/ (function(module) { "use strict"; - - -var define = __webpack_require__(5477); - -/** - * Store position for a node +/*! + * use + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. */ -module.exports = function Position(start, parser) { - this.start = start; - this.end = { line: parser.line, column: parser.column }; - define(this, 'content', parser.orig); - define(this, 'source', parser.options.source); -}; -/***/ }), +module.exports = function base(app, options) { + if (!isObject(app) && typeof app !== 'function') { + throw new TypeError('expected an object or function'); + } -/***/ 59657: -/***/ (function(module, exports, __webpack_require__) { + var opts = isObject(options) ? options : {}; + var prop = typeof opts.prop === 'string' ? opts.prop : 'fns'; + if (!Array.isArray(app[prop])) { + define(app, prop, []); + } -"use strict"; + /** + * Define a plugin function to be passed to use. The only + * parameter exposed to the plugin is `app`, the object or function. + * passed to `use(app)`. `app` is also exposed as `this` in plugins. + * + * Additionally, **if a plugin returns a function, the function will + * be pushed onto the `fns` array**, allowing the plugin to be + * called at a later point by the `run` method. + * + * ```js + * var use = require('use'); + * + * // define a plugin + * function foo(app) { + * // do stuff + * } + * + * var app = function(){}; + * use(app); + * + * // register plugins + * app.use(foo); + * app.use(bar); + * app.use(baz); + * ``` + * @name .use + * @param {Function} `fn` plugin function to call + * @api public + */ + define(app, 'use', use); -var fs = __webpack_require__(35747); -var path = __webpack_require__(85622); -var define = __webpack_require__(5477); -var utils = __webpack_require__(622); + /** + * Run all plugins on `fns`. Any plugin that returns a function + * when called by `use` is pushed onto the `fns` array. + * + * ```js + * var config = {}; + * app.run(config); + * ``` + * @name .run + * @param {Object} `value` Object to be modified by plugins. + * @return {Object} Returns the object passed to `run` + * @api public + */ -/** - * Expose `mixin()`. - * This code is based on `source-maps-support.js` in reworkcss/css - * https://github.com/reworkcss/css/blob/master/lib/stringify/source-map-support.js - * Copyright (c) 2012 TJ Holowaychuk - */ + define(app, 'run', function(val) { + if (!isObject(val)) return; -module.exports = mixin; + if (!val.use || !val.run) { + define(val, prop, val[prop] || []); + define(val, 'use', use); + } -/** - * Mixin source map support into `compiler`. - * - * @param {Object} `compiler` - * @api public - */ + if (!val[prop] || val[prop].indexOf(base) === -1) { + val.use(base); + } -function mixin(compiler) { - define(compiler, '_comment', compiler.comment); - compiler.map = new utils.SourceMap.SourceMapGenerator(); - compiler.position = { line: 1, column: 1 }; - compiler.content = {}; - compiler.files = {}; + var self = this || app; + var fns = self[prop]; + var len = fns.length; + var idx = -1; - for (var key in exports) { - define(compiler, key, exports[key]); - } -} + while (++idx < len) { + val.use(fns[idx]); + } + return val; + }); -/** - * Update position. - * - * @param {String} str - */ + /** + * Call plugin `fn`. If a function is returned push it into the + * `fns` array to be called by the `run` method. + */ -exports.updatePosition = function(str) { - var lines = str.match(/\n/g); - if (lines) this.position.line += lines.length; - var i = str.lastIndexOf('\n'); - this.position.column = ~i ? str.length - i : this.position.column + str.length; -}; + function use(type, fn, options) { + var offset = 1; -/** - * Emit `str` with `position`. - * - * @param {String} str - * @param {Object} [pos] - * @return {String} - */ + if (typeof type === 'string' || Array.isArray(type)) { + fn = wrap(type, fn); + offset++; + } else { + options = fn; + fn = type; + } -exports.emit = function(str, node) { - var position = node.position || {}; - var source = position.source; - if (source) { - if (position.filepath) { - source = utils.unixify(position.filepath); + if (typeof fn !== 'function') { + throw new TypeError('expected a function'); } - this.map.addMapping({ - source: source, - generated: { - line: this.position.line, - column: Math.max(this.position.column - 1, 0) - }, - original: { - line: position.start.line, - column: position.start.column - 1 - } - }); + var self = this || app; + var fns = self[prop]; - if (position.content) { - this.addContent(source, position); + var args = [].slice.call(arguments, offset); + args.unshift(self); + + if (typeof opts.hook === 'function') { + opts.hook.apply(self, args); } - if (position.filepath) { - this.addFile(source, position); + + var val = fn.apply(self, args); + if (typeof val === 'function' && fns.indexOf(val) === -1) { + fns.push(val); } + return self; + } - this.updatePosition(str); - this.output += str; + /** + * Wrap a named plugin function so that it's only called on objects of the + * given `type` + * + * @param {String} `type` + * @param {Function} `fn` Plugin function + * @return {Function} + */ + + function wrap(type, fn) { + return function plugin() { + return this.type === type ? fn.apply(this, arguments) : plugin; + }; } - return str; -}; -/** - * Adds a file to the source map output if it has not already been added - * @param {String} `file` - * @param {Object} `pos` - */ + return app; +}; -exports.addFile = function(file, position) { - if (typeof position.content !== 'string') return; - if (Object.prototype.hasOwnProperty.call(this.files, file)) return; - this.files[file] = position.content; -}; +function isObject(val) { + return val && typeof val === 'object' && !Array.isArray(val); +} -/** - * Adds a content source to the source map output if it has not already been added - * @param {String} `source` - * @param {Object} `position` - */ +function define(obj, key, val) { + Object.defineProperty(obj, key, { + configurable: true, + writable: true, + value: val + }); +} -exports.addContent = function(source, position) { - if (typeof position.content !== 'string') return; - if (Object.prototype.hasOwnProperty.call(this.content, source)) return; - this.map.setSourceContent(source, position.content); -}; -/** - * Applies any original source maps to the output and embeds the source file - * contents in the source map. - */ +/***/ }), -exports.applySourceMaps = function() { - Object.keys(this.files).forEach(function(file) { - var content = this.files[file]; - this.map.setSourceContent(file, content); +/***/ 92262: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (this.options.inputSourcemaps === true) { - var originalMap = utils.sourceMapResolve.resolveSync(content, file, fs.readFileSync); - if (originalMap) { - var map = new utils.SourceMap.SourceMapConsumer(originalMap.map); - var relativeTo = originalMap.sourcesRelativeTo; - this.map.applySourceMap(map, file, utils.unixify(path.dirname(relativeTo))); - } - } - }, this); -}; /** - * Process comments, drops sourceMap comments. - * @param {Object} node + * For Node.js, simply re-export the core `util.deprecate` function. */ -exports.comment = function(node) { - if (/^# sourceMappingURL=/.test(node.comment)) { - return this.emit('', node.position); - } - return this._comment(node); -}; +module.exports = __webpack_require__(31669).deprecate; /***/ }), -/***/ 622: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 24059: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; +module.exports = __webpack_require__(47257); -/** - * Module dependencies - */ +/***/ }), -exports.extend = __webpack_require__(28727); -exports.SourceMap = __webpack_require__(96241); -exports.sourceMapResolve = __webpack_require__(10227); +/***/ 71118: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * Convert backslash in the given string to forward slashes - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -exports.unixify = function(fp) { - return fp.split(/\\+/).join('/'); -}; -/** - * Return true if `val` is a non-empty string - * - * @param {String} `str` - * @return {Boolean} - */ +const ConstDependency = __webpack_require__(71101); +const ParserHelpers = __webpack_require__(23999); -exports.isString = function(str) { - return str && typeof str === 'string'; +const NullFactory = __webpack_require__(40438); + +/* eslint-disable camelcase */ +const REPLACEMENTS = { + __webpack_require__: "__webpack_require__", + __webpack_public_path__: "__webpack_require__.p", + __webpack_modules__: "__webpack_require__.m", + __webpack_chunk_load__: "__webpack_require__.e", + __non_webpack_require__: "require", + __webpack_nonce__: "__webpack_require__.nc", + "require.onError": "__webpack_require__.oe" +}; +const NO_WEBPACK_REQUIRE = { + __non_webpack_require__: true +}; +const REPLACEMENT_TYPES = { + __webpack_public_path__: "string", + __webpack_require__: "function", + __webpack_modules__: "object", + __webpack_chunk_load__: "function", + __webpack_nonce__: "string" }; +/* eslint-enable camelcase */ -/** - * Cast `val` to an array - * @return {Array} - */ +class APIPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "APIPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); -exports.arrayify = function(val) { - if (typeof val === 'string') return [val]; - return val ? (Array.isArray(val) ? val : [val]) : []; -}; + const handler = parser => { + Object.keys(REPLACEMENTS).forEach(key => { + parser.hooks.expression + .for(key) + .tap( + "APIPlugin", + NO_WEBPACK_REQUIRE[key] + ? ParserHelpers.toConstantDependency( + parser, + REPLACEMENTS[key] + ) + : ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + REPLACEMENTS[key] + ) + ); + const type = REPLACEMENT_TYPES[key]; + if (type) { + parser.hooks.evaluateTypeof + .for(key) + .tap("APIPlugin", ParserHelpers.evaluateToString(type)); + } + }); + }; -/** - * Get the last `n` element from the given `array` - * @param {Array} `array` - * @return {*} - */ + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("APIPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("APIPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("APIPlugin", handler); + } + ); + } +} -exports.last = function(arr, n) { - return arr[arr.length - (n || 1)]; -}; +module.exports = APIPlugin; /***/ }), -/***/ 56609: +/***/ 36104: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -var decodeUriComponent = __webpack_require__(95748) - -function customDecodeUriComponent(string) { - // `decodeUriComponent` turns `+` into ` `, but that's not wanted. - return decodeUriComponent(string.replace(/\+/g, "%2B")) -} +"use strict"; -module.exports = customDecodeUriComponent +const WebpackError = __webpack_require__(97391); +const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/; -/***/ }), +/** + * @param {string=} method method name + * @returns {string} message + */ +function createMessage(method) { + return `Abstract method${method ? " " + method : ""}. Must be overridden.`; +} -/***/ 89825: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @constructor + */ +function Message() { + this.stack = undefined; + Error.captureStackTrace(this); + /** @type {RegExpMatchArray} */ + const match = this.stack.split("\n")[3].match(CURRENT_METHOD_REGEXP); -var url = __webpack_require__(78835) + this.message = match && match[1] ? createMessage(match[1]) : createMessage(); +} -function resolveUrl(/* ...urls */) { - return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) { - return url.resolve(resolved, nextUrl) - }) +/** + * Error for abstract method + * @example + * class FooClass { + * abstractMethod() { + * throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overriden. + * } + * } + * + */ +class AbstractMethodError extends WebpackError { + constructor() { + super(new Message().message); + this.name = "AbstractMethodError"; + } } -module.exports = resolveUrl +module.exports = AbstractMethodError; /***/ }), -/***/ 10227: +/***/ 9701: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -var sourceMappingURL = __webpack_require__(21707) - -var resolveUrl = __webpack_require__(89825) -var decodeUriComponent = __webpack_require__(56609) -var urix = __webpack_require__(67806) -var atob = __webpack_require__(83327) +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ -function callbackAsync(callback, error, result) { - setImmediate(function() { callback(error, result) }) -} +const { ConcatSource } = __webpack_require__(53665); +const Template = __webpack_require__(96066); -function parseMapToJSON(string, data) { - try { - return JSON.parse(string.replace(/^\)\]\}'/, "")) - } catch (error) { - error.sourceMapData = data - throw error - } -} +/** @typedef {import("./Compilation")} Compilation */ -function readSync(read, url, data) { - var readUrl = decodeUriComponent(url) - try { - return String(read(readUrl)) - } catch (error) { - error.sourceMapData = data - throw error - } -} +/** + * @typedef {Object} AmdMainTemplatePluginOptions + * @param {string=} name the library name + * @property {boolean=} requireAsWrapper + */ +class AmdMainTemplatePlugin { + /** + * @param {AmdMainTemplatePluginOptions} options the plugin options + */ + constructor(options) { + if (!options || typeof options === "string") { + this.name = options; + this.requireAsWrapper = false; + } else { + this.name = options.name; + this.requireAsWrapper = options.requireAsWrapper; + } + } + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; -function resolveSourceMap(code, codeUrl, read, callback) { - var mapData - try { - mapData = resolveSourceMapHelper(code, codeUrl) - } catch (error) { - return callbackAsync(callback, error) - } - if (!mapData || mapData.map) { - return callbackAsync(callback, null, mapData) - } - var readUrl = decodeUriComponent(mapData.url) - read(readUrl, function(error, result) { - if (error) { - error.sourceMapData = mapData - return callback(error) - } - mapData.map = String(result) - try { - mapData.map = parseMapToJSON(mapData.map, mapData) - } catch (error) { - return callback(error) - } - callback(null, mapData) - }) -} + const onRenderWithEntry = (source, chunk, hash) => { + const externals = chunk.getModules().filter(m => m.external); + const externalsDepsArray = JSON.stringify( + externals.map(m => + typeof m.request === "object" ? m.request.amd : m.request + ) + ); + const externalsArguments = externals + .map( + m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` + ) + .join(", "); -function resolveSourceMapSync(code, codeUrl, read) { - var mapData = resolveSourceMapHelper(code, codeUrl) - if (!mapData || mapData.map) { - return mapData - } - mapData.map = readSync(read, mapData.url, mapData) - mapData.map = parseMapToJSON(mapData.map, mapData) - return mapData -} + if (this.requireAsWrapper) { + return new ConcatSource( + `require(${externalsDepsArray}, function(${externalsArguments}) { return `, + source, + "});" + ); + } else if (this.name) { + const name = mainTemplate.getAssetPath(this.name, { + hash, + chunk + }); -var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/ + return new ConcatSource( + `define(${JSON.stringify( + name + )}, ${externalsDepsArray}, function(${externalsArguments}) { return `, + source, + "});" + ); + } else if (externalsArguments) { + return new ConcatSource( + `define(${externalsDepsArray}, function(${externalsArguments}) { return `, + source, + "});" + ); + } else { + return new ConcatSource("define(function() { return ", source, "});"); + } + }; -/** - * The media type for JSON text is application/json. - * - * {@link https://tools.ietf.org/html/rfc8259#section-11 | IANA Considerations } - * - * `text/json` is non-standard media type - */ -var jsonMimeTypeRegex = /^(?:application|text)\/json$/ + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "AmdMainTemplatePlugin", + onRenderWithEntry + ); + } -/** - * JSON text exchanged between systems that are not part of a closed ecosystem - * MUST be encoded using UTF-8. - * - * {@link https://tools.ietf.org/html/rfc8259#section-8.1 | Character Encoding} - */ -var jsonCharacterEncoding = "utf-8" + mainTemplate.hooks.globalHashPaths.tap("AmdMainTemplatePlugin", paths => { + if (this.name) { + paths.push(this.name); + } + return paths; + }); -function base64ToBuf(b64) { - var binStr = atob(b64) - var len = binStr.length - var arr = new Uint8Array(len) - for (var i = 0; i < len; i++) { - arr[i] = binStr.charCodeAt(i) - } - return arr + mainTemplate.hooks.hash.tap("AmdMainTemplatePlugin", hash => { + hash.update("exports amd"); + if (this.name) { + hash.update(this.name); + } + }); + } } -function decodeBase64String(b64) { - if (typeof TextDecoder === "undefined" || typeof Uint8Array === "undefined") { - return atob(b64) - } - var buf = base64ToBuf(b64); - // Note: `decoder.decode` method will throw a `DOMException` with the - // `"EncodingError"` value when an coding error is found. - var decoder = new TextDecoder(jsonCharacterEncoding, {fatal: true}) - return decoder.decode(buf); -} +module.exports = AmdMainTemplatePlugin; -function resolveSourceMapHelper(code, codeUrl) { - codeUrl = urix(codeUrl) - var url = sourceMappingURL.getFrom(code) - if (!url) { - return null - } +/***/ }), - var dataUri = url.match(dataUriRegex) - if (dataUri) { - var mimeType = dataUri[1] || "text/plain" - var lastParameter = dataUri[2] || "" - var encoded = dataUri[3] || "" - var data = { - sourceMappingURL: url, - url: null, - sourcesRelativeTo: codeUrl, - map: encoded - } - if (!jsonMimeTypeRegex.test(mimeType)) { - var error = new Error("Unuseful data uri mime type: " + mimeType) - error.sourceMapData = data - throw error - } - try { - data.map = parseMapToJSON( - lastParameter === ";base64" ? decodeBase64String(encoded) : decodeURIComponent(encoded), - data - ) - } catch (error) { - error.sourceMapData = data - throw error - } - return data - } +/***/ 22814: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - var mapUrl = resolveUrl(codeUrl, url) - return { - sourceMappingURL: url, - url: mapUrl, - sourcesRelativeTo: mapUrl, - map: null - } -} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +const DependenciesBlock = __webpack_require__(16071); -function resolveSources(map, mapUrl, read, options, callback) { - if (typeof options === "function") { - callback = options - options = {} - } - var pending = map.sources ? map.sources.length : 0 - var result = { - sourcesResolved: [], - sourcesContent: [] - } +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./util/createHash").Hash} Hash */ +/** @typedef {TODO} GroupOptions */ - if (pending === 0) { - callbackAsync(callback, null, result) - return - } +module.exports = class AsyncDependenciesBlock extends DependenciesBlock { + /** + * @param {GroupOptions} groupOptions options for the group + * @param {Module} module the Module object + * @param {DependencyLocation=} loc the line of code + * @param {TODO=} request the request + */ + constructor(groupOptions, module, loc, request) { + super(); + if (typeof groupOptions === "string") { + groupOptions = { name: groupOptions }; + } else if (!groupOptions) { + groupOptions = { name: undefined }; + } + this.groupOptions = groupOptions; + /** @type {ChunkGroup=} */ + this.chunkGroup = undefined; + this.module = module; + this.loc = loc; + this.request = request; + /** @type {DependenciesBlock} */ + this.parent = undefined; + } - var done = function() { - pending-- - if (pending === 0) { - callback(null, result) - } - } - - resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { - result.sourcesResolved[index] = fullUrl - if (typeof sourceContent === "string") { - result.sourcesContent[index] = sourceContent - callbackAsync(done, null) - } else { - var readUrl = decodeUriComponent(fullUrl) - read(readUrl, function(error, source) { - result.sourcesContent[index] = error ? error : String(source) - done() - }) - } - }) -} - -function resolveSourcesSync(map, mapUrl, read, options) { - var result = { - sourcesResolved: [], - sourcesContent: [] - } - - if (!map.sources || map.sources.length === 0) { - return result - } + /** + * @returns {string} The name of the chunk + */ + get chunkName() { + return this.groupOptions.name; + } - resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { - result.sourcesResolved[index] = fullUrl - if (read !== null) { - if (typeof sourceContent === "string") { - result.sourcesContent[index] = sourceContent - } else { - var readUrl = decodeUriComponent(fullUrl) - try { - result.sourcesContent[index] = String(read(readUrl)) - } catch (error) { - result.sourcesContent[index] = error - } - } - } - }) + /** + * @param {string} value The new chunk name + * @returns {void} + */ + set chunkName(value) { + this.groupOptions.name = value; + } - return result -} + /** + * @returns {never} this throws and should never be called + */ + get chunks() { + throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); + } -var endingSlash = /\/?$/ + /** + * @param {never} value setter value + * @returns {never} this is going to throw therefore we should throw type + * assertions by returning never + */ + set chunks(value) { + throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); + } -function resolveSourcesHelper(map, mapUrl, options, fn) { - options = options || {} - mapUrl = urix(mapUrl) - var fullUrl - var sourceContent - var sourceRoot - for (var index = 0, len = map.sources.length; index < len; index++) { - sourceRoot = null - if (typeof options.sourceRoot === "string") { - sourceRoot = options.sourceRoot - } else if (typeof map.sourceRoot === "string" && options.sourceRoot !== false) { - sourceRoot = map.sourceRoot - } - // If the sourceRoot is the empty string, it is equivalent to not setting - // the property at all. - if (sourceRoot === null || sourceRoot === '') { - fullUrl = resolveUrl(mapUrl, map.sources[index]) - } else { - // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes - // `/scripts/subdir/`, not `/scripts/`. Pointing to a file as source root - // does not make sense. - fullUrl = resolveUrl(mapUrl, sourceRoot.replace(endingSlash, "/"), map.sources[index]) - } - sourceContent = (map.sourcesContent || [])[index] - fn(fullUrl, sourceContent, index) - } -} + /** + * @param {Hash} hash the hash used to track block changes, from "crypto" module + * @returns {void} + */ + updateHash(hash) { + hash.update(JSON.stringify(this.groupOptions)); + hash.update( + (this.chunkGroup && + this.chunkGroup.chunks + .map(chunk => { + return chunk.id !== null ? chunk.id : ""; + }) + .join(",")) || + "" + ); + super.updateHash(hash); + } + /** + * @returns {void} + */ + disconnect() { + this.chunkGroup = undefined; + super.disconnect(); + } + /** + * @returns {void} + */ + unseal() { + this.chunkGroup = undefined; + super.unseal(); + } -function resolve(code, codeUrl, read, options, callback) { - if (typeof options === "function") { - callback = options - options = {} - } - if (code === null) { - var mapUrl = codeUrl - var data = { - sourceMappingURL: null, - url: mapUrl, - sourcesRelativeTo: mapUrl, - map: null - } - var readUrl = decodeUriComponent(mapUrl) - read(readUrl, function(error, result) { - if (error) { - error.sourceMapData = data - return callback(error) - } - data.map = String(result) - try { - data.map = parseMapToJSON(data.map, data) - } catch (error) { - return callback(error) - } - _resolveSources(data) - }) - } else { - resolveSourceMap(code, codeUrl, read, function(error, mapData) { - if (error) { - return callback(error) - } - if (!mapData) { - return callback(null, null) - } - _resolveSources(mapData) - }) - } + /** + * @returns {void} + */ + sortItems() { + super.sortItems(); + } +}; - function _resolveSources(mapData) { - resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) { - if (error) { - return callback(error) - } - mapData.sourcesResolved = result.sourcesResolved - mapData.sourcesContent = result.sourcesContent - callback(null, mapData) - }) - } -} -function resolveSync(code, codeUrl, read, options) { - var mapData - if (code === null) { - var mapUrl = codeUrl - mapData = { - sourceMappingURL: null, - url: mapUrl, - sourcesRelativeTo: mapUrl, - map: null - } - mapData.map = readSync(read, mapUrl, mapData) - mapData.map = parseMapToJSON(mapData.map, mapData) - } else { - mapData = resolveSourceMapSync(code, codeUrl, read) - if (!mapData) { - return null - } - } - var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options) - mapData.sourcesResolved = result.sourcesResolved - mapData.sourcesContent = result.sourcesContent - return mapData -} +/***/ }), +/***/ 67089: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ -module.exports = { - resolveSourceMap: resolveSourceMap, - resolveSourceMapSync: resolveSourceMapSync, - resolveSources: resolveSources, - resolveSourcesSync: resolveSourcesSync, - resolve: resolve, - resolveSync: resolveSync, - parseMapToJSON: parseMapToJSON -} +const WebpackError = __webpack_require__(97391); -/***/ }), +/** @typedef {import("./Module")} Module */ -/***/ 21707: -/***/ (function(module) { +class AsyncDependencyToInitialChunkError extends WebpackError { + /** + * Creates an instance of AsyncDependencyToInitialChunkError. + * @param {string} chunkName Name of Chunk + * @param {Module} module module tied to dependency + * @param {TODO} loc location of dependency + */ + constructor(chunkName, module, loc) { + super( + `It's not allowed to load an initial chunk on demand. The chunk name "${chunkName}" is already used by an entrypoint.` + ); -// Copyright 2014 Simon Lydell -// X11 (“MIT”) Licensed. (See LICENSE.) + this.name = "AsyncDependencyToInitialChunkError"; + this.module = module; + this.loc = loc; -void (function(root, factory) { - if (typeof define === "function" && define.amd) { - define(factory) - } else if (true) { - module.exports = factory() - } else {} -}(this, function() { + Error.captureStackTrace(this, this.constructor); + } +} - var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/ +module.exports = AsyncDependencyToInitialChunkError; - var regex = RegExp( - "(?:" + - "/\\*" + - "(?:\\s*\r?\n(?://)?)?" + - "(?:" + innerRegex.source + ")" + - "\\s*" + - "\\*/" + - "|" + - "//(?:" + innerRegex.source + ")" + - ")" + - "\\s*" - ) - return { +/***/ }), - regex: regex, - _innerRegex: innerRegex, +/***/ 51596: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - getFrom: function(code) { - var match = code.match(regex) - return (match ? match[1] || match[2] || "" : null) - }, +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - existsIn: function(code) { - return regex.test(code) - }, - removeFrom: function(code) { - return code.replace(regex, "") - }, +const asyncLib = __webpack_require__(36386); +const PrefetchDependency = __webpack_require__(14237); +const NormalModule = __webpack_require__(25963); - insertBefore: function(code, string) { - var match = code.match(regex) - if (match) { - return code.slice(0, match.index) + string + code.slice(match.index) - } else { - return code + string - } - } - } +/** @typedef {import("./Compiler")} Compiler */ -})); +class AutomaticPrefetchPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "AutomaticPrefetchPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + PrefetchDependency, + normalModuleFactory + ); + } + ); + let lastModules = null; + compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => { + lastModules = compilation.modules + .filter(m => m instanceof NormalModule) + .map((/** @type {NormalModule} */ m) => ({ + context: m.context, + request: m.request + })); + }); + compiler.hooks.make.tapAsync( + "AutomaticPrefetchPlugin", + (compilation, callback) => { + if (!lastModules) return callback(); + asyncLib.forEach( + lastModules, + (m, callback) => { + compilation.prefetch( + m.context || compiler.context, + new PrefetchDependency(m.request), + callback + ); + }, + callback + ); + } + ); + } +} +module.exports = AutomaticPrefetchPlugin; /***/ }), -/***/ 33218: +/***/ 4009: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/*! - * split-string - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ -var extend = __webpack_require__(66889); +const { ConcatSource } = __webpack_require__(53665); +const ModuleFilenameHelpers = __webpack_require__(71474); +const Template = __webpack_require__(96066); -module.exports = function(str, options, fn) { - if (typeof str !== 'string') { - throw new TypeError('expected a string'); - } +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(10171); - if (typeof options === 'function') { - fn = options; - options = null; - } +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */ +/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */ - // allow separator to be defined as a string - if (typeof options === 'string') { - options = { sep: options }; - } +const wrapComment = str => { + if (!str.includes("\n")) { + return Template.toComment(str); + } + return `/*!\n * ${str + .replace(/\*\//g, "* /") + .split("\n") + .join("\n * ")}\n */`; +}; - var opts = extend({sep: '.'}, options); - var quotes = opts.quotes || ['"', "'", '`']; - var brackets; +class BannerPlugin { + /** + * @param {BannerPluginArgument} options options object + */ + constructor(options) { + if (arguments.length > 1) { + throw new Error( + "BannerPlugin only takes one argument (pass an options object)" + ); + } - if (opts.brackets === true) { - brackets = { - '<': '>', - '(': ')', - '[': ']', - '{': '}' - }; - } else if (opts.brackets) { - brackets = opts.brackets; - } + validateOptions(schema, options, "Banner Plugin"); - var tokens = []; - var stack = []; - var arr = ['']; - var sep = opts.sep; - var len = str.length; - var idx = -1; - var closeIdx; + if (typeof options === "string" || typeof options === "function") { + options = { + banner: options + }; + } - function expected() { - if (brackets && stack.length) { - return brackets[stack[stack.length - 1]]; - } - } + /** @type {BannerPluginOptions} */ + this.options = options; - while (++idx < len) { - var ch = str[idx]; - var next = str[idx + 1]; - var tok = { val: ch, idx: idx, arr: arr, str: str }; - tokens.push(tok); + const bannerOption = options.banner; + if (typeof bannerOption === "function") { + const getBanner = bannerOption; + this.banner = this.options.raw + ? getBanner + : data => wrapComment(getBanner(data)); + } else { + const banner = this.options.raw + ? bannerOption + : wrapComment(bannerOption); + this.banner = () => banner; + } + } - if (ch === '\\') { - tok.val = keepEscaping(opts, str, idx) === true ? (ch + next) : next; - tok.escaped = true; - if (typeof fn === 'function') { - fn(tok); - } - arr[arr.length - 1] += tok.val; - idx++; - continue; - } + apply(compiler) { + const options = this.options; + const banner = this.banner; + const matchObject = ModuleFilenameHelpers.matchObject.bind( + undefined, + options + ); - if (brackets && brackets[ch]) { - stack.push(ch); - var e = expected(); - var i = idx + 1; + compiler.hooks.compilation.tap("BannerPlugin", compilation => { + compilation.hooks.optimizeChunkAssets.tap("BannerPlugin", chunks => { + for (const chunk of chunks) { + if (options.entryOnly && !chunk.canBeInitial()) { + continue; + } - if (str.indexOf(e, i + 1) !== -1) { - while (stack.length && i < len) { - var s = str[++i]; - if (s === '\\') { - s++; - continue; - } + for (const file of chunk.files) { + if (!matchObject(file)) { + continue; + } - if (quotes.indexOf(s) !== -1) { - i = getClosingQuote(str, s, i + 1); - continue; - } + let query = ""; + let filename = file; + const hash = compilation.hash; + const querySplit = filename.indexOf("?"); - e = expected(); - if (stack.length && str.indexOf(e, i + 1) === -1) { - break; - } + if (querySplit >= 0) { + query = filename.substr(querySplit); + filename = filename.substr(0, querySplit); + } - if (brackets[s]) { - stack.push(s); - continue; - } - - if (e === s) { - stack.pop(); - } - } - } - - closeIdx = i; - if (closeIdx === -1) { - arr[arr.length - 1] += ch; - continue; - } - - ch = str.slice(idx, closeIdx + 1); - tok.val = ch; - tok.idx = idx = closeIdx; - } - - if (quotes.indexOf(ch) !== -1) { - closeIdx = getClosingQuote(str, ch, idx + 1); - if (closeIdx === -1) { - arr[arr.length - 1] += ch; - continue; - } - - if (keepQuotes(ch, opts) === true) { - ch = str.slice(idx, closeIdx + 1); - } else { - ch = str.slice(idx + 1, closeIdx); - } - - tok.val = ch; - tok.idx = idx = closeIdx; - } - - if (typeof fn === 'function') { - fn(tok, tokens); - ch = tok.val; - idx = tok.idx; - } - - if (tok.val === sep && tok.split !== false) { - arr.push(''); - continue; - } + const lastSlashIndex = filename.lastIndexOf("/"); - arr[arr.length - 1] += tok.val; - } + const basename = + lastSlashIndex === -1 + ? filename + : filename.substr(lastSlashIndex + 1); - return arr; -}; + const data = { + hash, + chunk, + filename, + basename, + query + }; -function getClosingQuote(str, ch, i, brackets) { - var idx = str.indexOf(ch, i); - if (str.charAt(idx - 1) === '\\') { - return getClosingQuote(str, ch, idx + 1); - } - return idx; -} + const comment = compilation.getPath(banner(data), data); -function keepQuotes(ch, opts) { - if (opts.keepDoubleQuotes === true && ch === '"') return true; - if (opts.keepSingleQuotes === true && ch === "'") return true; - return opts.keepQuotes; + compilation.updateAsset( + file, + old => new ConcatSource(comment, "\n", old) + ); + } + } + }); + }); + } } -function keepEscaping(opts, str, idx) { - if (typeof opts.keepEscaping === 'function') { - return opts.keepEscaping(str, idx); - } - return opts.keepEscaping === true || str[idx + 1] === '\\'; -} +module.exports = BannerPlugin; /***/ }), -/***/ 66889: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 96770: +/***/ (function(module) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -var isExtendable = __webpack_require__(28730); -var assignSymbols = __webpack_require__(64353); -module.exports = Object.assign || function(obj/*, objects*/) { - if (obj === null || typeof obj === 'undefined') { - throw new TypeError('Cannot convert undefined or null to object'); - } - if (!isObject(obj)) { - obj = {}; - } - for (var i = 1; i < arguments.length; i++) { - var val = arguments[i]; - if (isString(val)) { - val = toObject(val); - } - if (isObject(val)) { - assign(obj, val); - assignSymbols(obj, val); - } - } - return obj; -}; +const TypeUnknown = 0; +const TypeNull = 1; +const TypeString = 2; +const TypeNumber = 3; +const TypeBoolean = 4; +const TypeRegExp = 5; +const TypeConditional = 6; +const TypeArray = 7; +const TypeConstArray = 8; +const TypeIdentifier = 9; +const TypeWrapped = 10; +const TypeTemplateString = 11; -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } - } -} +class BasicEvaluatedExpression { + constructor() { + this.type = TypeUnknown; + this.range = null; + this.falsy = false; + this.truthy = false; + this.bool = null; + this.number = null; + this.regExp = null; + this.string = null; + this.quasis = null; + this.parts = null; + this.array = null; + this.items = null; + this.options = null; + this.prefix = null; + this.postfix = null; + this.wrappedInnerExpressions = null; + this.expression = null; + } -function isString(val) { - return (val && typeof val === 'string'); -} + isNull() { + return this.type === TypeNull; + } -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; - } - return obj; -} + isString() { + return this.type === TypeString; + } -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); -} + isNumber() { + return this.type === TypeNumber; + } -/** - * Returns true if the given `key` is an own property of `obj`. - */ + isBoolean() { + return this.type === TypeBoolean; + } -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} + isRegExp() { + return this.type === TypeRegExp; + } -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); -} + isConditional() { + return this.type === TypeConditional; + } + isArray() { + return this.type === TypeArray; + } -/***/ }), + isConstArray() { + return this.type === TypeConstArray; + } -/***/ 28730: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + isIdentifier() { + return this.type === TypeIdentifier; + } -"use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ + isWrapped() { + return this.type === TypeWrapped; + } + isTemplateString() { + return this.type === TypeTemplateString; + } + isTruthy() { + return this.truthy; + } -var isPlainObject = __webpack_require__(81064); + isFalsy() { + return this.falsy; + } -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); -}; + asBool() { + if (this.truthy) return true; + if (this.falsy) return false; + if (this.isBoolean()) return this.bool; + if (this.isNull()) return false; + if (this.isString()) return this.string !== ""; + if (this.isNumber()) return this.number !== 0; + if (this.isRegExp()) return true; + if (this.isArray()) return true; + if (this.isConstArray()) return true; + if (this.isWrapped()) { + return (this.prefix && this.prefix.asBool()) || + (this.postfix && this.postfix.asBool()) + ? true + : undefined; + } + if (this.isTemplateString()) { + const str = this.asString(); + if (typeof str === "string") return str !== ""; + } + return undefined; + } + asString() { + if (this.isBoolean()) return `${this.bool}`; + if (this.isNull()) return "null"; + if (this.isString()) return this.string; + if (this.isNumber()) return `${this.number}`; + if (this.isRegExp()) return `${this.regExp}`; + if (this.isArray()) { + let array = []; + for (const item of this.items) { + const itemStr = item.asString(); + if (itemStr === undefined) return undefined; + array.push(itemStr); + } + return `${array}`; + } + if (this.isConstArray()) return `${this.array}`; + if (this.isTemplateString()) { + let str = ""; + for (const part of this.parts) { + const partStr = part.asString(); + if (partStr === undefined) return undefined; + str += partStr; + } + return str; + } + return undefined; + } -/***/ }), + setString(string) { + this.type = TypeString; + this.string = string; + return this; + } -/***/ 69457: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + setNull() { + this.type = TypeNull; + return this; + } -"use strict"; -/*! - * static-extend - * - * Copyright (c) 2016, Jon Schlinkert. - * Licensed under the MIT License. - */ + setNumber(number) { + this.type = TypeNumber; + this.number = number; + return this; + } + setBoolean(bool) { + this.type = TypeBoolean; + this.bool = bool; + return this; + } + setRegExp(regExp) { + this.type = TypeRegExp; + this.regExp = regExp; + return this; + } -var copy = __webpack_require__(31368); -var define = __webpack_require__(5477); -var util = __webpack_require__(31669); + setIdentifier(identifier) { + this.type = TypeIdentifier; + this.identifier = identifier; + return this; + } -/** - * Returns a function for extending the static properties, - * prototype properties, and descriptors from the `Parent` - * constructor onto `Child` constructors. - * - * ```js - * var extend = require('static-extend'); - * Parent.extend = extend(Parent); - * - * // optionally pass a custom merge function as the second arg - * Parent.extend = extend(Parent, function(Child) { - * Child.prototype.mixin = function(key, val) { - * Child.prototype[key] = val; - * }; - * }); - * - * // extend "child" constructors - * Parent.extend(Child); - * - * // optionally define prototype methods as the second arg - * Parent.extend(Child, { - * foo: function() {}, - * bar: function() {} - * }); - * ``` - * @param {Function} `Parent` Parent ctor - * @param {Function} `extendFn` Optional extend function for handling any necessary custom merging. Useful when updating methods that require a specific prototype. - * @param {Function} `Child` Child ctor - * @param {Object} `proto` Optionally pass additional prototype properties to inherit. - * @return {Object} - * @api public - */ + setWrapped(prefix, postfix, innerExpressions) { + this.type = TypeWrapped; + this.prefix = prefix; + this.postfix = postfix; + this.wrappedInnerExpressions = innerExpressions; + return this; + } -function extend(Parent, extendFn) { - if (typeof Parent !== 'function') { - throw new TypeError('expected Parent to be a function.'); - } + setOptions(options) { + this.type = TypeConditional; + this.options = options; + return this; + } - return function(Ctor, proto) { - if (typeof Ctor !== 'function') { - throw new TypeError('expected Ctor to be a function.'); - } + addOptions(options) { + if (!this.options) { + this.type = TypeConditional; + this.options = []; + } + for (const item of options) { + this.options.push(item); + } + return this; + } - util.inherits(Ctor, Parent); - copy(Ctor, Parent); + setItems(items) { + this.type = TypeArray; + this.items = items; + return this; + } - // proto can be null or a plain object - if (typeof proto === 'object') { - var obj = Object.create(proto); + setArray(array) { + this.type = TypeConstArray; + this.array = array; + return this; + } - for (var k in obj) { - Ctor.prototype[k] = obj[k]; - } - } + setTemplateString(quasis, parts, kind) { + this.type = TypeTemplateString; + this.quasis = quasis; + this.parts = parts; + this.templateStringKind = kind; + return this; + } - // keep a reference to the parent prototype - define(Ctor.prototype, '_parent_', { - configurable: true, - set: function() {}, - get: function() { - return Parent.prototype; - } - }); + setTruthy() { + this.falsy = false; + this.truthy = true; + return this; + } - if (typeof extendFn === 'function') { - extendFn(Ctor, Parent); - } + setFalsy() { + this.falsy = true; + this.truthy = false; + return this; + } - Ctor.extend = extend(Ctor, extendFn); - }; -}; + setRange(range) { + this.range = range; + return this; + } -/** - * Expose `extend` - */ + setExpression(expression) { + this.expression = expression; + return this; + } +} -module.exports = extend; +module.exports = BasicEvaluatedExpression; /***/ }), -/***/ 16326: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/***/ 6465: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.default = void 0; - -var _os = _interopRequireDefault(__webpack_require__(12087)); - -var _cacache = _interopRequireDefault(__webpack_require__(36801)); - -var _findCacheDir = _interopRequireDefault(__webpack_require__(61844)); - -var _workerFarm = _interopRequireDefault(__webpack_require__(18921)); - -var _serializeJavascript = _interopRequireDefault(__webpack_require__(85841)); - -var _isWsl = _interopRequireDefault(__webpack_require__(47543)); - -var _minify = _interopRequireDefault(__webpack_require__(30787)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const worker = __webpack_require__.ab + "worker.js"; - -class TaskRunner { - constructor(options = {}) { - const { - cache, - parallel - } = options; - this.cacheDir = cache === true ? (0, _findCacheDir.default)({ - name: 'terser-webpack-plugin' - }) || _os.default.tmpdir() : cache; // In some cases cpus() returns undefined - // https://github.com/nodejs/node/issues/19022 - - const cpus = _os.default.cpus() || { - length: 1 - }; // WSL sometimes freezes, error seems to be on the WSL side - // https://github.com/webpack-contrib/terser-webpack-plugin/issues/21 - - this.maxConcurrentWorkers = _isWsl.default ? 1 : parallel === true ? cpus.length - 1 : Math.min(Number(parallel) || 0, cpus.length - 1); - } +const asyncLib = __webpack_require__(36386); - run(tasks, callback) { - /* istanbul ignore if */ - if (!tasks.length) { - callback(null, []); - return; - } +class CachePlugin { + constructor(cache) { + this.cache = cache || {}; + this.FS_ACCURACY = 2000; + } - if (this.maxConcurrentWorkers > 1) { - const workerOptions = process.platform === 'win32' ? { - maxConcurrentWorkers: this.maxConcurrentWorkers, - maxConcurrentCallsPerWorker: 1 - } : { - maxConcurrentWorkers: this.maxConcurrentWorkers - }; - this.workers = (0, _workerFarm.default)(workerOptions, __webpack_require__.ab + "worker.js"); - - this.boundWorkers = (options, cb) => { - try { - this.workers((0, _serializeJavascript.default)(options), cb); - } catch (error) { - // worker-farm can fail with ENOMEM or something else - cb(error); - } - }; - } else { - this.boundWorkers = (options, cb) => { - try { - cb(null, (0, _minify.default)(options)); - } catch (error) { - cb(error); - } - }; - } - - let toRun = tasks.length; - const results = []; - - const step = (index, data) => { - toRun -= 1; - results[index] = data; - - if (!toRun) { - callback(null, results); - } - }; + apply(compiler) { + if (Array.isArray(compiler.compilers)) { + compiler.compilers.forEach((c, idx) => { + new CachePlugin((this.cache[idx] = this.cache[idx] || {})).apply(c); + }); + } else { + const registerCacheToCompiler = (compiler, cache) => { + compiler.hooks.thisCompilation.tap("CachePlugin", compilation => { + compilation.cache = cache; + compilation.hooks.childCompiler.tap( + "CachePlugin", + (childCompiler, compilerName, compilerIndex) => { + let childCache; + if (!cache.children) { + cache.children = {}; + } + if (!cache.children[compilerName]) { + cache.children[compilerName] = []; + } + if (cache.children[compilerName][compilerIndex]) { + childCache = cache.children[compilerName][compilerIndex]; + } else { + cache.children[compilerName].push((childCache = {})); + } + registerCacheToCompiler(childCompiler, childCache); + } + ); + }); + }; + registerCacheToCompiler(compiler, this.cache); + compiler.hooks.watchRun.tap("CachePlugin", () => { + this.watching = true; + }); + compiler.hooks.run.tapAsync("CachePlugin", (compiler, callback) => { + if (!compiler._lastCompilationFileDependencies) { + return callback(); + } + const fs = compiler.inputFileSystem; + const fileTs = (compiler.fileTimestamps = new Map()); + asyncLib.forEach( + compiler._lastCompilationFileDependencies, + (file, callback) => { + fs.stat(file, (err, stat) => { + if (err) { + if (err.code === "ENOENT") return callback(); + return callback(err); + } - tasks.forEach((task, index) => { - const enqueue = () => { - this.boundWorkers(task, (error, data) => { - const result = error ? { - error - } : data; + if (stat.mtime) this.applyMtime(+stat.mtime); - const done = () => step(index, result); + fileTs.set(file, +stat.mtime || Infinity); - if (this.cacheDir && !result.error) { - _cacache.default.put(this.cacheDir, (0, _serializeJavascript.default)(task.cacheKeys), JSON.stringify(data)).then(done, done); - } else { - done(); - } - }); - }; + callback(); + }); + }, + err => { + if (err) return callback(err); - if (this.cacheDir) { - _cacache.default.get(this.cacheDir, (0, _serializeJavascript.default)(task.cacheKeys)).then(({ - data - }) => step(index, JSON.parse(data)), enqueue); - } else { - enqueue(); - } - }); - } + for (const [file, ts] of fileTs) { + fileTs.set(file, ts + this.FS_ACCURACY); + } - exit() { - if (this.workers) { - _workerFarm.default.end(this.workers); - } - } + callback(); + } + ); + }); + compiler.hooks.afterCompile.tap("CachePlugin", compilation => { + compilation.compiler._lastCompilationFileDependencies = + compilation.fileDependencies; + compilation.compiler._lastCompilationContextDependencies = + compilation.contextDependencies; + }); + } + } + /* istanbul ignore next */ + applyMtime(mtime) { + if (this.FS_ACCURACY > 1 && mtime % 2 !== 0) this.FS_ACCURACY = 1; + else if (this.FS_ACCURACY > 10 && mtime % 20 !== 0) this.FS_ACCURACY = 10; + else if (this.FS_ACCURACY > 100 && mtime % 200 !== 0) + this.FS_ACCURACY = 100; + else if (this.FS_ACCURACY > 1000 && mtime % 2000 !== 0) + this.FS_ACCURACY = 1000; + } } +module.exports = CachePlugin; -exports.default = TaskRunner; /***/ }), -/***/ 89301: +/***/ 8335: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -const plugin = __webpack_require__(43884); +const WebpackError = __webpack_require__(97391); -module.exports = plugin.default; +/** @typedef {import("./Module")} Module */ -/***/ }), +/** + * @param {Module[]} modules the modules to be sorted + * @returns {Module[]} sorted version of original modules + */ +const sortModules = modules => { + return modules.slice().sort((a, b) => { + const aIdent = a.identifier(); + const bIdent = b.identifier(); + /* istanbul ignore next */ + if (aIdent < bIdent) return -1; + /* istanbul ignore next */ + if (aIdent > bIdent) return 1; + /* istanbul ignore next */ + return 0; + }); +}; -/***/ 43884: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +/** + * @param {Module[]} modules each module from throw + * @returns {string} each message from provided moduels + */ +const createModulesListMessage = modules => { + return modules + .map(m => { + let message = `* ${m.identifier()}`; + const validReasons = m.reasons.filter(reason => reason.module); -"use strict"; + if (validReasons.length > 0) { + message += `\n Used by ${validReasons.length} module(s), i. e.`; + message += `\n ${validReasons[0].module.identifier()}`; + } + return message; + }) + .join("\n"); +}; +class CaseSensitiveModulesWarning extends WebpackError { + /** + * Creates an instance of CaseSensitiveModulesWarning. + * @param {Module[]} modules modules that were detected + */ + constructor(modules) { + const sortedModules = sortModules(modules); + const modulesList = createModulesListMessage(sortedModules); + super(`There are multiple modules with names that only differ in casing. +This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. +Use equal casing. Compare these module identifiers: +${modulesList}`); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.default = void 0; + this.name = "CaseSensitiveModulesWarning"; + this.origin = this.module = sortedModules[0]; -var _crypto = _interopRequireDefault(__webpack_require__(76417)); + Error.captureStackTrace(this, this.constructor); + } +} -var _path = _interopRequireDefault(__webpack_require__(85622)); +module.exports = CaseSensitiveModulesWarning; -var _sourceMap = __webpack_require__(96241); -var _webpackSources = __webpack_require__(53665); +/***/ }), -var _RequestShortener = _interopRequireDefault(__webpack_require__(54254)); +/***/ 2919: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -var _ModuleFilenameHelpers = _interopRequireDefault(__webpack_require__(71474)); +"use strict"; +/* +MIT License http://www.opensource.org/licenses/mit-license.php +Author Tobias Koppers @sokra +*/ -var _schemaUtils = _interopRequireDefault(__webpack_require__(33225)); -var _serializeJavascript = _interopRequireDefault(__webpack_require__(85841)); +const util = __webpack_require__(31669); +const SortableSet = __webpack_require__(50071); +const intersect = __webpack_require__(54262).intersect; +const GraphHelpers = __webpack_require__(32973); +const Entrypoint = __webpack_require__(71931); +let debugId = 1000; +const ERR_CHUNK_ENTRY = "Chunk.entry was removed. Use hasRuntime()"; +const ERR_CHUNK_INITIAL = + "Chunk.initial was removed. Use canBeInitial/isOnlyInitial()"; -var _package = _interopRequireDefault(__webpack_require__(92203)); +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./ModuleReason")} ModuleReason */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./util/createHash").Hash} Hash */ -var _options = _interopRequireDefault(__webpack_require__(11840)); +/** + * @typedef {Object} WithId an object who has an id property * + * @property {string | number} id the id of the object + */ -var _TaskRunner = _interopRequireDefault(__webpack_require__(16326)); +/** + * Compare two Modules based on their ids for sorting + * @param {Module} a module + * @param {Module} b module + * @returns {-1|0|1} sort value + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// TODO use @callback +/** @typedef {(a: Module, b: Module) => -1|0|1} ModuleSortPredicate */ +/** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ +/** @typedef {(c: Chunk) => boolean} ChunkFilterPredicate */ -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } +const sortModuleById = (a, b) => { + if (a.id < b.id) return -1; + if (b.id < a.id) return 1; + return 0; +}; -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } +/** + * Compare two ChunkGroups based on their ids for sorting + * @param {ChunkGroup} a chunk group + * @param {ChunkGroup} b chunk group + * @returns {-1|0|1} sort value + */ +const sortChunkGroupById = (a, b) => { + if (a.id < b.id) return -1; + if (b.id < a.id) return 1; + return 0; +}; -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +/** + * Compare two Identifiables , based on their ids for sorting + * @param {Module} a first object with ident fn + * @param {Module} b second object with ident fn + * @returns {-1|0|1} The order number of the sort + */ +const sortByIdentifier = (a, b) => { + if (a.identifier() > b.identifier()) return 1; + if (a.identifier() < b.identifier()) return -1; + return 0; +}; -const warningRegex = /\[.+:([0-9]+),([0-9]+)\]/; +/** + * @returns {string} a concatenation of module identifiers sorted + * @param {SortableSet} set to pull module identifiers from + */ +const getModulesIdent = set => { + set.sort(); + let str = ""; + for (const m of set) { + str += m.identifier() + "#"; + } + return str; +}; -class TerserPlugin { - constructor(options = {}) { - (0, _schemaUtils.default)(_options.default, options, 'Terser Plugin'); - const { - minify, - terserOptions = {}, - test = /\.m?js(\?.*)?$/i, - chunkFilter = () => true, - warningsFilter = () => true, - extractComments = false, - sourceMap = false, - cache = false, - cacheKeys = defaultCacheKeys => defaultCacheKeys, - parallel = false, - include, - exclude - } = options; - this.options = { - test, - chunkFilter, - warningsFilter, - extractComments, - sourceMap, - cache, - cacheKeys, - parallel, - include, - exclude, - minify, - terserOptions: _objectSpread({ - output: { - comments: extractComments ? false : /^\**!|@preserve|@license|@cc_on/i - } - }, terserOptions) - }; - } +/** + * @template T + * @param {SortableSet} set the sortable set to convert to array + * @returns {Array} the array returned from Array.from(set) + */ +const getArray = set => Array.from(set); - static isSourceMap(input) { - // All required options for `new SourceMapConsumer(...options)` - // https://github.com/mozilla/source-map#new-sourcemapconsumerrawsourcemap - return Boolean(input && input.version && input.sources && Array.isArray(input.sources) && typeof input.mappings === 'string'); - } +/** + * @param {SortableSet} set the sortable Set to get the count/size of + * @returns {number} the size of the modules + */ +const getModulesSize = set => { + let size = 0; + for (const module of set) { + size += module.size(); + } + return size; +}; - static buildSourceMap(inputSourceMap) { - if (!inputSourceMap || !TerserPlugin.isSourceMap(inputSourceMap)) { - return null; - } +/** + * A Chunk is a unit of encapsulation for Modules. + * Chunks are "rendered" into bundles that get emitted when the build completes. + */ +class Chunk { + /** + * @param {string=} name of chunk being created, is optional (for subclasses) + */ + constructor(name) { + /** @type {number | null} */ + this.id = null; + /** @type {number[] | null} */ + this.ids = null; + /** @type {number} */ + this.debugId = debugId++; + /** @type {string} */ + this.name = name; + /** @type {boolean} */ + this.preventIntegration = false; + /** @type {Module=} */ + this.entryModule = undefined; + /** @private @type {SortableSet} */ + this._modules = new SortableSet(undefined, sortByIdentifier); + /** @type {string?} */ + this.filenameTemplate = undefined; + /** @private @type {SortableSet} */ + this._groups = new SortableSet(undefined, sortChunkGroupById); + /** @type {string[]} */ + this.files = []; + /** @type {boolean} */ + this.rendered = false; + /** @type {string=} */ + this.hash = undefined; + /** @type {Object} */ + this.contentHash = Object.create(null); + /** @type {string=} */ + this.renderedHash = undefined; + /** @type {string=} */ + this.chunkReason = undefined; + /** @type {boolean} */ + this.extraAsync = false; + this.removedModules = undefined; + } - return new _sourceMap.SourceMapConsumer(inputSourceMap); - } + /** + * @deprecated Chunk.entry has been deprecated. Please use .hasRuntime() instead + * @returns {never} Throws an error trying to access this property + */ + get entry() { + throw new Error(ERR_CHUNK_ENTRY); + } - static buildError(err, file, sourceMap, requestShortener) { - // Handling error which should have line, col, filename and message - if (err.line) { - const original = sourceMap && sourceMap.originalPositionFor({ - line: err.line, - column: err.col - }); + /** + * @deprecated .entry has been deprecated. Please use .hasRuntime() instead + * @param {never} data The data that was attempting to be set + * @returns {never} Throws an error trying to access this property + */ + set entry(data) { + throw new Error(ERR_CHUNK_ENTRY); + } - if (original && original.source && requestShortener) { - return new Error(`${file} from Terser\n${err.message} [${requestShortener.shorten(original.source)}:${original.line},${original.column}][${file}:${err.line},${err.col}]`); - } + /** + * @deprecated Chunk.initial was removed. Use canBeInitial/isOnlyInitial() + * @returns {never} Throws an error trying to access this property + */ + get initial() { + throw new Error(ERR_CHUNK_INITIAL); + } - return new Error(`${file} from Terser\n${err.message} [${file}:${err.line},${err.col}]`); - } else if (err.stack) { - return new Error(`${file} from Terser\n${err.stack}`); - } + /** + * @deprecated Chunk.initial was removed. Use canBeInitial/isOnlyInitial() + * @param {never} data The data attempting to be set + * @returns {never} Throws an error trying to access this property + */ + set initial(data) { + throw new Error(ERR_CHUNK_INITIAL); + } - return new Error(`${file} from Terser\n${err.message}`); - } + /** + * @returns {boolean} whether or not the Chunk will have a runtime + */ + hasRuntime() { + for (const chunkGroup of this._groups) { + if ( + chunkGroup.isInitial() && + chunkGroup instanceof Entrypoint && + chunkGroup.getRuntimeChunk() === this + ) { + return true; + } + } + return false; + } - static buildWarning(warning, file, sourceMap, requestShortener, warningsFilter) { - let warningMessage = warning; - let locationMessage = ''; - let source = null; + /** + * @returns {boolean} whether or not this chunk can be an initial chunk + */ + canBeInitial() { + for (const chunkGroup of this._groups) { + if (chunkGroup.isInitial()) return true; + } + return false; + } - if (sourceMap) { - const match = warningRegex.exec(warning); + /** + * @returns {boolean} whether this chunk can only be an initial chunk + */ + isOnlyInitial() { + if (this._groups.size <= 0) return false; + for (const chunkGroup of this._groups) { + if (!chunkGroup.isInitial()) return false; + } + return true; + } - if (match) { - const line = +match[1]; - const column = +match[2]; - const original = sourceMap.originalPositionFor({ - line, - column - }); + /** + * @returns {boolean} if this chunk contains the entry module + */ + hasEntryModule() { + return !!this.entryModule; + } - if (original && original.source && original.source !== file && requestShortener) { - ({ - source - } = original); - warningMessage = `${warningMessage.replace(warningRegex, '')}`; - locationMessage = `[${requestShortener.shorten(original.source)}:${original.line},${original.column}]`; - } - } - } + /** + * @param {Module} module the module that will be added to this chunk. + * @returns {boolean} returns true if the chunk doesn't have the module and it was added + */ + addModule(module) { + if (!this._modules.has(module)) { + this._modules.add(module); + return true; + } + return false; + } - if (warningsFilter && !warningsFilter(warning, source)) { - return null; - } + /** + * @param {Module} module the module that will be removed from this chunk + * @returns {boolean} returns true if chunk exists and is successfully deleted + */ + removeModule(module) { + if (this._modules.delete(module)) { + module.removeChunk(this); + return true; + } + return false; + } - return `Terser Plugin: ${warningMessage}${locationMessage}`; - } + /** + * @param {Module[]} modules the new modules to be set + * @returns {void} set new modules to this chunk and return nothing + */ + setModules(modules) { + this._modules = new SortableSet(modules, sortByIdentifier); + } - apply(compiler) { - const buildModuleFn = moduleArg => { - // to get detailed location info about errors - moduleArg.useSourceMap = true; - }; + /** + * @returns {number} the amount of modules in chunk + */ + getNumberOfModules() { + return this._modules.size; + } - const optimizeFn = (compilation, chunks, callback) => { - const taskRunner = new _TaskRunner.default({ - cache: this.options.cache, - parallel: this.options.parallel - }); - const processedAssets = new WeakSet(); - const tasks = []; - const { - chunkFilter - } = this.options; - Array.from(chunks).filter(chunk => chunkFilter && chunkFilter(chunk)).reduce((acc, chunk) => acc.concat(chunk.files || []), []).concat(compilation.additionalChunkAssets || []).filter(_ModuleFilenameHelpers.default.matchObject.bind(null, this.options)).forEach(file => { - let inputSourceMap; - const asset = compilation.assets[file]; + /** + * @returns {SortableSet} return the modules SortableSet for this chunk + */ + get modulesIterable() { + return this._modules; + } - if (processedAssets.has(asset)) { - return; - } + /** + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being added + * @returns {boolean} returns true if chunk is not apart of chunkGroup and is added successfully + */ + addGroup(chunkGroup) { + if (this._groups.has(chunkGroup)) return false; + this._groups.add(chunkGroup); + return true; + } - try { - let input; + /** + * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from + * @returns {boolean} returns true if chunk does exist in chunkGroup and is removed + */ + removeGroup(chunkGroup) { + if (!this._groups.has(chunkGroup)) return false; + this._groups.delete(chunkGroup); + return true; + } - if (this.options.sourceMap && asset.sourceAndMap) { - const { - source, - map - } = asset.sourceAndMap(); - input = source; + /** + * @param {ChunkGroup} chunkGroup the chunkGroup to check + * @returns {boolean} returns true if chunk has chunkGroup reference and exists in chunkGroup + */ + isInGroup(chunkGroup) { + return this._groups.has(chunkGroup); + } - if (TerserPlugin.isSourceMap(map)) { - inputSourceMap = map; - } else { - inputSourceMap = map; - compilation.warnings.push(new Error(`${file} contains invalid source map`)); - } - } else { - input = asset.source(); - inputSourceMap = null; - } // Handling comment extraction + /** + * @returns {number} the amount of groups said chunk is in + */ + getNumberOfGroups() { + return this._groups.size; + } + /** + * @returns {SortableSet} the chunkGroups that said chunk is referenced in + */ + get groupsIterable() { + return this._groups; + } - let commentsFile = false; + /** + * @param {Chunk} otherChunk the chunk to compare itself with + * @returns {-1|0|1} this is a comparitor function like sort and returns -1, 0, or 1 based on sort order + */ + compareTo(otherChunk) { + if (this.name && !otherChunk.name) return -1; + if (!this.name && otherChunk.name) return 1; + if (this.name < otherChunk.name) return -1; + if (this.name > otherChunk.name) return 1; + if (this._modules.size > otherChunk._modules.size) return -1; + if (this._modules.size < otherChunk._modules.size) return 1; + this._modules.sort(); + otherChunk._modules.sort(); + const a = this._modules[Symbol.iterator](); + const b = otherChunk._modules[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = a.next(); + if (aItem.done) return 0; + const bItem = b.next(); + const aModuleIdentifier = aItem.value.identifier(); + const bModuleIdentifier = bItem.value.identifier(); + if (aModuleIdentifier < bModuleIdentifier) return -1; + if (aModuleIdentifier > bModuleIdentifier) return 1; + } + } - if (this.options.extractComments) { - commentsFile = this.options.extractComments.filename || `${file}.LICENSE`; + /** + * @param {Module} module Module to check + * @returns {boolean} returns true if module does exist in this chunk + */ + containsModule(module) { + return this._modules.has(module); + } - if (typeof commentsFile === 'function') { - commentsFile = commentsFile(file); - } - } + /** + * @returns {Module[]} an array of modules (do not modify) + */ + getModules() { + return this._modules.getFromCache(getArray); + } - const task = { - file, - input, - inputSourceMap, - commentsFile, - extractComments: this.options.extractComments, - terserOptions: this.options.terserOptions, - minify: this.options.minify - }; + getModulesIdent() { + return this._modules.getFromUnorderedCache(getModulesIdent); + } - if (this.options.cache) { - const defaultCacheKeys = { - terser: _package.default.version, - node_version: process.version, - // eslint-disable-next-line global-require - 'terser-webpack-plugin': __webpack_require__(9122)/* .version */ .i8, - 'terser-webpack-plugin-options': this.options, - hash: _crypto.default.createHash('md4').update(input).digest('hex') - }; - task.cacheKeys = this.options.cacheKeys(defaultCacheKeys, file); - } + /** + * @param {string=} reason reason why chunk is removed + * @returns {void} + */ + remove(reason) { + // cleanup modules + // Array.from is used here to create a clone, because removeChunk modifies this._modules + for (const module of Array.from(this._modules)) { + module.removeChunk(this); + } + for (const chunkGroup of this._groups) { + chunkGroup.removeChunk(this); + } + } - tasks.push(task); - } catch (error) { - compilation.errors.push(TerserPlugin.buildError(error, file, TerserPlugin.buildSourceMap(inputSourceMap), new _RequestShortener.default(compiler.context))); - } - }); - taskRunner.run(tasks, (tasksError, results) => { - if (tasksError) { - compilation.errors.push(tasksError); - return; - } + /** + * + * @param {Module} module module to move + * @param {Chunk} otherChunk other chunk to move it to + * @returns {void} + */ + moveModule(module, otherChunk) { + GraphHelpers.disconnectChunkAndModule(this, module); + GraphHelpers.connectChunkAndModule(otherChunk, module); + module.rewriteChunkInReasons(this, [otherChunk]); + } - results.forEach((data, index) => { - const { - file, - input, - inputSourceMap, - commentsFile - } = tasks[index]; - const { - error, - map, - code, - warnings - } = data; - let { - extractedComments - } = data; - let sourceMap = null; + /** + * + * @param {Chunk} otherChunk the chunk to integrate with + * @param {string} reason reason why the module is being integrated + * @returns {boolean} returns true or false if integration succeeds or fails + */ + integrate(otherChunk, reason) { + if (!this.canBeIntegrated(otherChunk)) { + return false; + } - if (error || warnings && warnings.length > 0) { - sourceMap = TerserPlugin.buildSourceMap(inputSourceMap); - } // Handling results - // Error case: add errors, and go to next file + // Pick a new name for the integrated chunk + if (this.name && otherChunk.name) { + if (this.hasEntryModule() === otherChunk.hasEntryModule()) { + // When both chunks have entry modules or none have one, use + // shortest name + if (this.name.length !== otherChunk.name.length) { + this.name = + this.name.length < otherChunk.name.length + ? this.name + : otherChunk.name; + } else { + this.name = this.name < otherChunk.name ? this.name : otherChunk.name; + } + } else if (otherChunk.hasEntryModule()) { + // Pick the name of the chunk with the entry module + this.name = otherChunk.name; + } + } else if (otherChunk.name) { + this.name = otherChunk.name; + } + // Array.from is used here to create a clone, because moveModule modifies otherChunk._modules + for (const module of Array.from(otherChunk._modules)) { + otherChunk.moveModule(module, this); + } + otherChunk._modules.clear(); - if (error) { - compilation.errors.push(TerserPlugin.buildError(error, file, sourceMap, new _RequestShortener.default(compiler.context))); - return; - } + if (otherChunk.entryModule) { + this.entryModule = otherChunk.entryModule; + } - let outputSource; + for (const chunkGroup of otherChunk._groups) { + chunkGroup.replaceChunk(otherChunk, this); + this.addGroup(chunkGroup); + } + otherChunk._groups.clear(); - if (map) { - outputSource = new _webpackSources.SourceMapSource(code, file, JSON.parse(map), input, inputSourceMap, true); - } else { - outputSource = new _webpackSources.RawSource(code); - } // Write extracted comments to commentsFile + return true; + } + /** + * @param {Chunk} newChunk the new chunk that will be split out of the current chunk + * @returns {void} + */ + split(newChunk) { + for (const chunkGroup of this._groups) { + chunkGroup.insertChunk(newChunk, this); + newChunk.addGroup(chunkGroup); + } + } - if (commentsFile && extractedComments && extractedComments.length > 0) { - if (commentsFile in compilation.assets) { - const commentsFileSource = compilation.assets[commentsFile].source(); - extractedComments = extractedComments.filter(comment => !commentsFileSource.includes(comment)); - } + isEmpty() { + return this._modules.size === 0; + } - if (extractedComments.length > 0) { - // Add a banner to the original file - if (this.options.extractComments.banner !== false) { - let banner = this.options.extractComments.banner || `For license information please see ${_path.default.posix.basename(commentsFile)}`; + updateHash(hash) { + hash.update(`${this.id} `); + hash.update(this.ids ? this.ids.join(",") : ""); + hash.update(`${this.name || ""} `); + for (const m of this._modules) { + hash.update(m.hash); + } + } - if (typeof banner === 'function') { - banner = banner(commentsFile); - } + canBeIntegrated(otherChunk) { + if (this.preventIntegration || otherChunk.preventIntegration) { + return false; + } - if (banner) { - outputSource = new _webpackSources.ConcatSource(`/*! ${banner} */\n`, outputSource); - } - } + /** + * @param {Chunk} a chunk + * @param {Chunk} b chunk + * @returns {boolean} true, if a is always available when b is reached + */ + const isAvailable = (a, b) => { + const queue = new Set(b.groupsIterable); + for (const chunkGroup of queue) { + if (a.isInGroup(chunkGroup)) continue; + if (chunkGroup.isInitial()) return false; + for (const parent of chunkGroup.parentsIterable) { + queue.add(parent); + } + } + return true; + }; - const commentsSource = new _webpackSources.RawSource(`${extractedComments.join('\n\n')}\n`); + const selfHasRuntime = this.hasRuntime(); + const otherChunkHasRuntime = otherChunk.hasRuntime(); - if (commentsFile in compilation.assets) { - // commentsFile already exists, append new comments... - if (compilation.assets[commentsFile] instanceof _webpackSources.ConcatSource) { - compilation.assets[commentsFile].add('\n'); - compilation.assets[commentsFile].add(commentsSource); - } else { - compilation.assets[commentsFile] = new _webpackSources.ConcatSource(compilation.assets[commentsFile], '\n', commentsSource); - } - } else { - compilation.assets[commentsFile] = commentsSource; - } - } - } // Updating assets + if (selfHasRuntime !== otherChunkHasRuntime) { + if (selfHasRuntime) { + return isAvailable(this, otherChunk); + } else if (otherChunkHasRuntime) { + return isAvailable(otherChunk, this); + } else { + return false; + } + } + if (this.hasEntryModule() || otherChunk.hasEntryModule()) { + return false; + } - processedAssets.add(compilation.assets[file] = outputSource); // Handling warnings + return true; + } - if (warnings && warnings.length > 0) { - warnings.forEach(warning => { - const builtWarning = TerserPlugin.buildWarning(warning, file, sourceMap, new _RequestShortener.default(compiler.context), this.options.warningsFilter); + /** + * + * @param {number} size the size + * @param {Object} options the options passed in + * @returns {number} the multiplier returned + */ + addMultiplierAndOverhead(size, options) { + const overhead = + typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; + const multiplicator = this.canBeInitial() + ? options.entryChunkMultiplicator || 10 + : 1; - if (builtWarning) { - compilation.warnings.push(builtWarning); - } - }); - } - }); - taskRunner.exit(); - callback(); - }); - }; + return size * multiplicator + overhead; + } - const plugin = { - name: this.constructor.name - }; - compiler.hooks.compilation.tap(plugin, compilation => { - if (this.options.sourceMap) { - compilation.hooks.buildModule.tap(plugin, buildModuleFn); - } + /** + * @returns {number} the size of all modules + */ + modulesSize() { + return this._modules.getFromUnorderedCache(getModulesSize); + } - const { - mainTemplate, - chunkTemplate - } = compilation; // Regenerate `contenthash` for minified assets + /** + * @param {Object} options the size display options + * @returns {number} the chunk size + */ + size(options = {}) { + return this.addMultiplierAndOverhead(this.modulesSize(), options); + } - for (const template of [mainTemplate, chunkTemplate]) { - template.hooks.hashForChunk.tap(plugin, hash => { - const data = (0, _serializeJavascript.default)({ - terser: _package.default.version, - terserOptions: this.options.terserOptions - }); - hash.update('TerserPlugin'); - hash.update(data); - }); - } + /** + * @param {Chunk} otherChunk the other chunk + * @param {TODO} options the options for this function + * @returns {number | false} the size, or false if it can't be integrated + */ + integratedSize(otherChunk, options) { + // Chunk if it's possible to integrate this chunk + if (!this.canBeIntegrated(otherChunk)) { + return false; + } - compilation.hooks.optimizeChunkAssets.tapAsync(plugin, optimizeFn.bind(this, compilation)); - }); - } + let integratedModulesSize = this.modulesSize(); + // only count modules that do not exist in this chunk! + for (const otherModule of otherChunk._modules) { + if (!this._modules.has(otherModule)) { + integratedModulesSize += otherModule.size(); + } + } -} + return this.addMultiplierAndOverhead(integratedModulesSize, options); + } -var _default = TerserPlugin; -exports.default = _default; + /** + * @param {function(Module, Module): -1|0|1=} sortByFn a predicate function used to sort modules + * @returns {void} + */ + sortModules(sortByFn) { + this._modules.sortWith(sortByFn || sortModuleById); + } -/***/ }), + sortItems() { + this.sortModules(); + } -/***/ 30787: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + /** + * @returns {Set} a set of all the async chunks + */ + getAllAsyncChunks() { + const queue = new Set(); + const chunks = new Set(); -"use strict"; + const initialChunks = intersect( + Array.from(this.groupsIterable, g => new Set(g.chunks)) + ); + for (const chunkGroup of this.groupsIterable) { + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.default = void 0; - -var _terser = __webpack_require__(54775); - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -const buildTerserOptions = ({ - ecma, - warnings, - parse = {}, - compress = {}, - mangle, - module, - output, - toplevel, - nameCache, - ie8, - - /* eslint-disable camelcase */ - keep_classnames, - keep_fnames, - - /* eslint-enable camelcase */ - safari10 -} = {}) => ({ - ecma, - warnings, - parse: _objectSpread({}, parse), - compress: typeof compress === 'boolean' ? compress : _objectSpread({}, compress), - // eslint-disable-next-line no-nested-ternary - mangle: mangle == null ? true : typeof mangle === 'boolean' ? mangle : _objectSpread({}, mangle), - output: _objectSpread({ - shebang: true, - comments: false, - beautify: false, - semicolons: true - }, output), - module, - // Ignoring sourceMap from options - sourceMap: null, - toplevel, - nameCache, - ie8, - keep_classnames, - keep_fnames, - safari10 -}); - -const buildComments = (options, terserOptions, extractedComments) => { - const condition = {}; - const commentsOpts = terserOptions.output.comments; // Use /^\**!|@preserve|@license|@cc_on/i RegExp - - if (typeof options.extractComments === 'boolean') { - condition.preserve = commentsOpts; - condition.extract = /^\**!|@preserve|@license|@cc_on/i; - } else if (typeof options.extractComments === 'string' || options.extractComments instanceof RegExp) { - // extractComments specifies the extract condition and commentsOpts specifies the preserve condition - condition.preserve = commentsOpts; - condition.extract = options.extractComments; - } else if (typeof options.extractComments === 'function') { - condition.preserve = commentsOpts; - condition.extract = options.extractComments; - } else if (Object.prototype.hasOwnProperty.call(options.extractComments, 'condition')) { - // Extract condition is given in extractComments.condition - condition.preserve = commentsOpts; - condition.extract = options.extractComments.condition; - } else { - // No extract condition is given. Extract comments that match commentsOpts instead of preserving them - condition.preserve = false; - condition.extract = commentsOpts; - } // Ensure that both conditions are functions + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + if (!initialChunks.has(chunk)) { + chunks.add(chunk); + } + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + return chunks; + } - ['preserve', 'extract'].forEach(key => { - let regexStr; - let regex; + /** + * @typedef {Object} ChunkMaps + * @property {Record} hash + * @property {Record>} contentHash + * @property {Record} name + */ - switch (typeof condition[key]) { - case 'boolean': - condition[key] = condition[key] ? () => true : () => false; - break; + /** + * @param {boolean} realHash should the full hash or the rendered hash be used + * @returns {ChunkMaps} the chunk map information + */ + getChunkMaps(realHash) { + /** @type {Record} */ + const chunkHashMap = Object.create(null); + /** @type {Record>} */ + const chunkContentHashMap = Object.create(null); + /** @type {Record} */ + const chunkNameMap = Object.create(null); - case 'function': - break; + for (const chunk of this.getAllAsyncChunks()) { + chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash; + for (const key of Object.keys(chunk.contentHash)) { + if (!chunkContentHashMap[key]) { + chunkContentHashMap[key] = Object.create(null); + } + chunkContentHashMap[key][chunk.id] = chunk.contentHash[key]; + } + if (chunk.name) { + chunkNameMap[chunk.id] = chunk.name; + } + } - case 'string': - if (condition[key] === 'all') { - condition[key] = () => true; + return { + hash: chunkHashMap, + contentHash: chunkContentHashMap, + name: chunkNameMap + }; + } - break; - } + /** + * @returns {Record[]>} a record object of names to lists of child ids(?) + */ + getChildIdsByOrders() { + const lists = new Map(); + for (const group of this.groupsIterable) { + if (group.chunks[group.chunks.length - 1] === this) { + for (const childGroup of group.childrenIterable) { + // TODO webpack 5 remove this check for options + if (typeof childGroup.options === "object") { + for (const key of Object.keys(childGroup.options)) { + if (key.endsWith("Order")) { + const name = key.substr(0, key.length - "Order".length); + let list = lists.get(name); + if (list === undefined) lists.set(name, (list = [])); + list.push({ + order: childGroup.options[key], + group: childGroup + }); + } + } + } + } + } + } + const result = Object.create(null); + for (const [name, list] of lists) { + list.sort((a, b) => { + const cmp = b.order - a.order; + if (cmp !== 0) return cmp; + // TODO webpack 5 remove this check of compareTo + if (a.group.compareTo) { + return a.group.compareTo(b.group); + } + return 0; + }); + result[name] = Array.from( + list.reduce((set, item) => { + for (const chunk of item.group.chunks) { + set.add(chunk.id); + } + return set; + }, new Set()) + ); + } + return result; + } - if (condition[key] === 'some') { - condition[key] = (astNode, comment) => { - return comment.type === 'comment2' && /^\**!|@preserve|@license|@cc_on/i.test(comment.value); - }; + getChildIdsByOrdersMap(includeDirectChildren) { + const chunkMaps = Object.create(null); - break; - } + const addChildIdsByOrdersToMap = chunk => { + const data = chunk.getChildIdsByOrders(); + for (const key of Object.keys(data)) { + let chunkMap = chunkMaps[key]; + if (chunkMap === undefined) { + chunkMaps[key] = chunkMap = Object.create(null); + } + chunkMap[chunk.id] = data[key]; + } + }; - regexStr = condition[key]; + if (includeDirectChildren) { + const chunks = new Set(); + for (const chunkGroup of this.groupsIterable) { + for (const chunk of chunkGroup.chunks) { + chunks.add(chunk); + } + } + for (const chunk of chunks) { + addChildIdsByOrdersToMap(chunk); + } + } - condition[key] = (astNode, comment) => { - return new RegExp(regexStr).test(comment.value); - }; + for (const chunk of this.getAllAsyncChunks()) { + addChildIdsByOrdersToMap(chunk); + } - break; + return chunkMaps; + } - default: - regex = condition[key]; + /** + * @typedef {Object} ChunkModuleMaps + * @property {Record} id + * @property {Record} hash + */ - condition[key] = (astNode, comment) => regex.test(comment.value); + /** + * @param {ModuleFilterPredicate} filterFn function used to filter modules + * @returns {ChunkModuleMaps} module map information + */ + getChunkModuleMaps(filterFn) { + /** @type {Record} */ + const chunkModuleIdMap = Object.create(null); + /** @type {Record} */ + const chunkModuleHashMap = Object.create(null); - } - }); // Redefine the comments function to extract and preserve - // comments according to the two conditions + for (const chunk of this.getAllAsyncChunks()) { + /** @type {(string|number)[]} */ + let array; + for (const module of chunk.modulesIterable) { + if (filterFn(module)) { + if (array === undefined) { + array = []; + chunkModuleIdMap[chunk.id] = array; + } + array.push(module.id); + chunkModuleHashMap[module.id] = module.renderedHash; + } + } + if (array !== undefined) { + array.sort(); + } + } - return (astNode, comment) => { - if (condition.extract(astNode, comment)) { - const commentText = comment.type === 'comment2' ? `/*${comment.value}*/` : `//${comment.value}`; // Don't include duplicate comments + return { + id: chunkModuleIdMap, + hash: chunkModuleHashMap + }; + } - if (!extractedComments.includes(commentText)) { - extractedComments.push(commentText); - } - } + /** + * + * @param {function(Module): boolean} filterFn predicate function used to filter modules + * @param {function(Chunk): boolean} filterChunkFn predicate function used to filter chunks + * @returns {boolean} return true if module exists in graph + */ + hasModuleInGraph(filterFn, filterChunkFn) { + const queue = new Set(this.groupsIterable); + const chunksProcessed = new Set(); - return condition.preserve(astNode, comment); - }; -}; + for (const chunkGroup of queue) { + for (const chunk of chunkGroup.chunks) { + if (!chunksProcessed.has(chunk)) { + chunksProcessed.add(chunk); + if (!filterChunkFn || filterChunkFn(chunk)) { + for (const module of chunk.modulesIterable) { + if (filterFn(module)) { + return true; + } + } + } + } + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } + } + return false; + } -const minify = options => { - const { - file, - input, - inputSourceMap, - extractComments, - minify: minifyFn - } = options; + toString() { + return `Chunk[${Array.from(this._modules).join()}]`; + } +} - if (minifyFn) { - return minifyFn({ - [file]: input - }, inputSourceMap); - } // Copy terser options +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "forEachModule", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @this {Chunk} + * @typedef {function(any, any, Set): void} ForEachModuleCallback + * @param {ForEachModuleCallback} fn Callback function + * @returns {void} + */ + function(fn) { + this._modules.forEach(fn); + }, + "Chunk.forEachModule: Use for(const module of chunk.modulesIterable) instead" + ) +}); +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "mapModules", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @this {Chunk} + * @typedef {function(any, number): any} MapModulesCallback + * @param {MapModulesCallback} fn Callback function + * @returns {TODO[]} result of mapped modules + */ + function(fn) { + return Array.from(this._modules, fn); + }, + "Chunk.mapModules: Use Array.from(chunk.modulesIterable, fn) instead" + ) +}); - const terserOptions = buildTerserOptions(options.terserOptions); // Let terser generate a SourceMap +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "chunks", { + configurable: false, + get() { + throw new Error("Chunk.chunks: Use ChunkGroup.getChildren() instead"); + }, + set() { + throw new Error("Chunk.chunks: Use ChunkGroup.add/removeChild() instead"); + } +}); - if (inputSourceMap) { - terserOptions.sourceMap = true; - } +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "parents", { + configurable: false, + get() { + throw new Error("Chunk.parents: Use ChunkGroup.getParents() instead"); + }, + set() { + throw new Error("Chunk.parents: Use ChunkGroup.add/removeParent() instead"); + } +}); - const extractedComments = []; +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "blocks", { + configurable: false, + get() { + throw new Error("Chunk.blocks: Use ChunkGroup.getBlocks() instead"); + }, + set() { + throw new Error("Chunk.blocks: Use ChunkGroup.add/removeBlock() instead"); + } +}); - if (extractComments) { - terserOptions.output.comments = buildComments(options, terserOptions, extractedComments); - } +// TODO remove in webpack 5 +Object.defineProperty(Chunk.prototype, "entrypoints", { + configurable: false, + get() { + throw new Error( + "Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead" + ); + }, + set() { + throw new Error("Chunk.entrypoints: Use Chunks.addGroup instead"); + } +}); - const { - error, - map, - code, - warnings - } = (0, _terser.minify)({ - [file]: input - }, terserOptions); - return { - error, - map, - code, - warnings, - extractedComments - }; -}; +module.exports = Chunk; -var _default = minify; -exports.default = _default; /***/ }), -/***/ 71708: +/***/ 52911: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/*! - * to-object-path - * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. - */ - - - -var typeOf = __webpack_require__(48865); - -module.exports = function toPath(args) { - if (typeOf(args) !== 'arguments') { - args = arguments; - } - return filter(args).join('.'); -}; - -function filter(arr) { - var len = arr.length; - var idx = -1; - var res = []; - - while (++idx < len) { - var ele = arr[idx]; - if (typeOf(ele) === 'arguments' || Array.isArray(ele)) { - res.push.apply(res, filter(ele)); - } else if (typeof ele === 'string') { - res.push(ele); - } - } - return res; -} - +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/***/ }), -/***/ 51279: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const SortableSet = __webpack_require__(50071); +const compareLocations = __webpack_require__(22562); -"use strict"; +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./ModuleReason")} ModuleReason */ +/** @typedef {{module: Module, loc: TODO, request: string}} OriginRecord */ +/** @typedef {string|{name: string}} ChunkGroupOptions */ -var safe = __webpack_require__(71217); -var define = __webpack_require__(74998); -var extend = __webpack_require__(99793); -var not = __webpack_require__(30931); -var MAX_LENGTH = 1024 * 64; +let debugId = 5000; /** - * Session cache + * @template T + * @param {SortableSet} set set to convert to array. + * @returns {T[]} the array format of existing set */ - -var cache = {}; +const getArray = set => Array.from(set); /** - * Create a regular expression from the given `pattern` string. - * - * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. - * @param {Object} `options` - * @return {RegExp} - * @api public + * A convenience method used to sort chunks based on their id's + * @param {ChunkGroup} a first sorting comparator + * @param {ChunkGroup} b second sorting comparator + * @returns {1|0|-1} a sorting index to determine order */ - -module.exports = function(patterns, options) { - if (!Array.isArray(patterns)) { - return makeRe(patterns, options); - } - return makeRe(patterns.join('|'), options); +const sortById = (a, b) => { + if (a.id < b.id) return -1; + if (b.id < a.id) return 1; + return 0; }; /** - * Create a regular expression from the given `pattern` string. - * - * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. - * @param {Object} `options` - * @return {RegExp} - * @api public + * @param {OriginRecord} a the first comparator in sort + * @param {OriginRecord} b the second comparator in sort + * @returns {1|-1|0} returns sorting order as index */ +const sortOrigin = (a, b) => { + const aIdent = a.module ? a.module.identifier() : ""; + const bIdent = b.module ? b.module.identifier() : ""; + if (aIdent < bIdent) return -1; + if (aIdent > bIdent) return 1; + return compareLocations(a.loc, b.loc); +}; -function makeRe(pattern, options) { - if (pattern instanceof RegExp) { - return pattern; - } +class ChunkGroup { + /** + * Creates an instance of ChunkGroup. + * @param {ChunkGroupOptions=} options chunk group options passed to chunkGroup + */ + constructor(options) { + if (typeof options === "string") { + options = { name: options }; + } else if (!options) { + options = { name: undefined }; + } + /** @type {number} */ + this.groupDebugId = debugId++; + this.options = options; + /** @type {SortableSet} */ + this._children = new SortableSet(undefined, sortById); + this._parents = new SortableSet(undefined, sortById); + this._blocks = new SortableSet(); + /** @type {Chunk[]} */ + this.chunks = []; + /** @type {OriginRecord[]} */ + this.origins = []; + /** Indices in top-down order */ + /** @private @type {Map} */ + this._moduleIndices = new Map(); + /** Indices in bottom-up order */ + /** @private @type {Map} */ + this._moduleIndices2 = new Map(); + } - if (typeof pattern !== 'string') { - throw new TypeError('expected a string'); - } + /** + * when a new chunk is added to a chunkGroup, addingOptions will occur. + * @param {ChunkGroupOptions} options the chunkGroup options passed to addOptions + * @returns {void} + */ + addOptions(options) { + for (const key of Object.keys(options)) { + if (this.options[key] === undefined) { + this.options[key] = options[key]; + } else if (this.options[key] !== options[key]) { + if (key.endsWith("Order")) { + this.options[key] = Math.max(this.options[key], options[key]); + } else { + throw new Error( + `ChunkGroup.addOptions: No option merge strategy for ${key}` + ); + } + } + } + } - if (pattern.length > MAX_LENGTH) { - throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); - } + /** + * returns the name of current ChunkGroup + * @returns {string|undefined} returns the ChunkGroup name + */ + get name() { + return this.options.name; + } - var key = pattern; - // do this before shallow cloning options, it's a lot faster - if (!options || (options && options.cache !== false)) { - key = createKey(pattern, options); + /** + * sets a new name for current ChunkGroup + * @param {string} value the new name for ChunkGroup + * @returns {void} + */ + set name(value) { + this.options.name = value; + } - if (cache.hasOwnProperty(key)) { - return cache[key]; - } - } + /** + * get a uniqueId for ChunkGroup, made up of its member Chunk debugId's + * @returns {string} a unique concatenation of chunk debugId's + */ + get debugId() { + return Array.from(this.chunks, x => x.debugId).join("+"); + } - var opts = extend({}, options); - if (opts.contains === true) { - if (opts.negate === true) { - opts.strictNegate = false; - } else { - opts.strict = false; - } - } + /** + * get a unique id for ChunkGroup, made up of its member Chunk id's + * @returns {string} a unique concatenation of chunk ids + */ + get id() { + return Array.from(this.chunks, x => x.id).join("+"); + } - if (opts.strict === false) { - opts.strictOpen = false; - opts.strictClose = false; - } + /** + * Performs an unshift of a specific chunk + * @param {Chunk} chunk chunk being unshifted + * @returns {boolean} returns true if attempted chunk shift is accepted + */ + unshiftChunk(chunk) { + const oldIdx = this.chunks.indexOf(chunk); + if (oldIdx > 0) { + this.chunks.splice(oldIdx, 1); + this.chunks.unshift(chunk); + } else if (oldIdx < 0) { + this.chunks.unshift(chunk); + return true; + } + return false; + } - var open = opts.strictOpen !== false ? '^' : ''; - var close = opts.strictClose !== false ? '$' : ''; - var flags = opts.flags || ''; - var regex; + /** + * inserts a chunk before another existing chunk in group + * @param {Chunk} chunk Chunk being inserted + * @param {Chunk} before Placeholder/target chunk marking new chunk insertion point + * @returns {boolean} return true if insertion was successful + */ + insertChunk(chunk, before) { + const oldIdx = this.chunks.indexOf(chunk); + const idx = this.chunks.indexOf(before); + if (idx < 0) { + throw new Error("before chunk not found"); + } + if (oldIdx >= 0 && oldIdx > idx) { + this.chunks.splice(oldIdx, 1); + this.chunks.splice(idx, 0, chunk); + } else if (oldIdx < 0) { + this.chunks.splice(idx, 0, chunk); + return true; + } + return false; + } - if (opts.nocase === true && !/i/.test(flags)) { - flags += 'i'; - } + /** + * add a chunk into ChunkGroup. Is pushed on or prepended + * @param {Chunk} chunk chunk being pushed into ChunkGroupS + * @returns {boolean} returns true if chunk addition was successful. + */ + pushChunk(chunk) { + const oldIdx = this.chunks.indexOf(chunk); + if (oldIdx >= 0) { + return false; + } + this.chunks.push(chunk); + return true; + } - try { - if (opts.negate || typeof opts.strictNegate === 'boolean') { - pattern = not.create(pattern, opts); - } + /** + * @param {Chunk} oldChunk chunk to be replaced + * @param {Chunk} newChunk New chunk that will be replaced with + * @returns {boolean} returns true if the replacement was successful + */ + replaceChunk(oldChunk, newChunk) { + const oldIdx = this.chunks.indexOf(oldChunk); + if (oldIdx < 0) return false; + const newIdx = this.chunks.indexOf(newChunk); + if (newIdx < 0) { + this.chunks[oldIdx] = newChunk; + return true; + } + if (newIdx < oldIdx) { + this.chunks.splice(oldIdx, 1); + return true; + } else if (newIdx !== oldIdx) { + this.chunks[oldIdx] = newChunk; + this.chunks.splice(newIdx, 1); + return true; + } + } - var str = open + '(?:' + pattern + ')' + close; - regex = new RegExp(str, flags); + removeChunk(chunk) { + const idx = this.chunks.indexOf(chunk); + if (idx >= 0) { + this.chunks.splice(idx, 1); + return true; + } + return false; + } - if (opts.safe === true && safe(regex) === false) { - throw new Error('potentially unsafe regular expression: ' + regex.source); - } + isInitial() { + return false; + } - } catch (err) { - if (opts.strictErrors === true || opts.safe === true) { - err.key = key; - err.pattern = pattern; - err.originalOptions = options; - err.createdOptions = opts; - throw err; - } + addChild(chunk) { + if (this._children.has(chunk)) { + return false; + } + this._children.add(chunk); + return true; + } - try { - regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$'); - } catch (err) { - regex = /.^/; //<= match nothing - } - } + getChildren() { + return this._children.getFromCache(getArray); + } - if (opts.cache !== false) { - memoize(regex, key, pattern, opts); - } - return regex; -} + getNumberOfChildren() { + return this._children.size; + } -/** - * Memoize generated regex. This can result in dramatic speed improvements - * and simplify debugging by adding options and pattern to the regex. It can be - * disabled by passing setting `options.cache` to false. - */ + get childrenIterable() { + return this._children; + } -function memoize(regex, key, pattern, options) { - define(regex, 'cached', true); - define(regex, 'pattern', pattern); - define(regex, 'options', options); - define(regex, 'key', key); - cache[key] = regex; -} + removeChild(chunk) { + if (!this._children.has(chunk)) { + return false; + } -/** - * Create the key to use for memoization. The key is generated - * by iterating over the options and concatenating key-value pairs - * to the pattern string. - */ + this._children.delete(chunk); + chunk.removeParent(this); + return true; + } -function createKey(pattern, options) { - if (!options) return pattern; - var key = pattern; - for (var prop in options) { - if (options.hasOwnProperty(prop)) { - key += ';' + prop + '=' + String(options[prop]); - } - } - return key; -} + addParent(parentChunk) { + if (!this._parents.has(parentChunk)) { + this._parents.add(parentChunk); + return true; + } + return false; + } -/** - * Expose `makeRe` - */ + getParents() { + return this._parents.getFromCache(getArray); + } -module.exports.makeRe = makeRe; + setParents(newParents) { + this._parents.clear(); + for (const p of newParents) { + this._parents.add(p); + } + } + getNumberOfParents() { + return this._parents.size; + } -/***/ }), + hasParent(parent) { + return this._parents.has(parent); + } -/***/ 74998: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + get parentsIterable() { + return this._parents; + } -"use strict"; -/*! - * define-property - * - * Copyright (c) 2015-2018, Jon Schlinkert. - * Released under the MIT License. - */ + removeParent(chunk) { + if (this._parents.delete(chunk)) { + chunk.removeChunk(this); + return true; + } + return false; + } + /** + * @returns {Array} - an array containing the blocks + */ + getBlocks() { + return this._blocks.getFromCache(getArray); + } + getNumberOfBlocks() { + return this._blocks.size; + } -var isobject = __webpack_require__(96667); -var isDescriptor = __webpack_require__(44133); -var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty) - ? Reflect.defineProperty - : Object.defineProperty; + hasBlock(block) { + return this._blocks.has(block); + } -module.exports = function defineProperty(obj, key, val) { - if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) { - throw new TypeError('expected an object, function, or array'); - } + get blocksIterable() { + return this._blocks; + } - if (typeof key !== 'string') { - throw new TypeError('expected "key" to be a string'); - } + addBlock(block) { + if (!this._blocks.has(block)) { + this._blocks.add(block); + return true; + } + return false; + } - if (isDescriptor(val)) { - define(obj, key, val); - return obj; - } + addOrigin(module, loc, request) { + this.origins.push({ + module, + loc, + request + }); + } - define(obj, key, { - configurable: true, - enumerable: false, - writable: true, - value: val - }); + containsModule(module) { + for (const chunk of this.chunks) { + if (chunk.containsModule(module)) return true; + } + return false; + } - return obj; -}; + getFiles() { + const files = new Set(); + for (const chunk of this.chunks) { + for (const file of chunk.files) { + files.add(file); + } + } -/***/ }), + return Array.from(files); + } -/***/ 99793: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {string=} reason reason for removing ChunkGroup + * @returns {void} + */ + remove(reason) { + // cleanup parents + for (const parentChunkGroup of this._parents) { + // remove this chunk from its parents + parentChunkGroup._children.delete(this); -"use strict"; + // cleanup "sub chunks" + for (const chunkGroup of this._children) { + /** + * remove this chunk as "intermediary" and connect + * it "sub chunks" and parents directly + */ + // add parent to each "sub chunk" + chunkGroup.addParent(parentChunkGroup); + // add "sub chunk" to parent + parentChunkGroup.addChild(chunkGroup); + } + } + /** + * we need to iterate again over the children + * to remove this from the child's parents. + * This can not be done in the above loop + * as it is not guaranteed that `this._parents` contains anything. + */ + for (const chunkGroup of this._children) { + // remove this as parent of every "sub chunk" + chunkGroup._parents.delete(this); + } -var isExtendable = __webpack_require__(78947); -var assignSymbols = __webpack_require__(64353); + // cleanup blocks + for (const block of this._blocks) { + block.chunkGroup = null; + } -module.exports = Object.assign || function(obj/*, objects*/) { - if (obj === null || typeof obj === 'undefined') { - throw new TypeError('Cannot convert undefined or null to object'); - } - if (!isObject(obj)) { - obj = {}; - } - for (var i = 1; i < arguments.length; i++) { - var val = arguments[i]; - if (isString(val)) { - val = toObject(val); - } - if (isObject(val)) { - assign(obj, val); - assignSymbols(obj, val); - } - } - return obj; -}; + // remove chunks + for (const chunk of this.chunks) { + chunk.removeGroup(this); + } + } -function assign(a, b) { - for (var key in b) { - if (hasOwn(b, key)) { - a[key] = b[key]; - } - } -} + sortItems() { + this.origins.sort(sortOrigin); + this._parents.sort(); + this._children.sort(); + } -function isString(val) { - return (val && typeof val === 'string'); -} + /** + * Sorting predicate which allows current ChunkGroup to be compared against another. + * Sorting values are based off of number of chunks in ChunkGroup. + * + * @param {ChunkGroup} otherGroup the chunkGroup to compare this against + * @returns {-1|0|1} sort position for comparison + */ + compareTo(otherGroup) { + if (this.chunks.length > otherGroup.chunks.length) return -1; + if (this.chunks.length < otherGroup.chunks.length) return 1; + const a = this.chunks[Symbol.iterator](); + const b = otherGroup.chunks[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = a.next(); + const bItem = b.next(); + if (aItem.done) return 0; + const cmp = aItem.value.compareTo(bItem.value); + if (cmp !== 0) return cmp; + } + } -function toObject(str) { - var obj = {}; - for (var i in str) { - obj[i] = str[i]; - } - return obj; -} + getChildrenByOrders() { + const lists = new Map(); + for (const childGroup of this._children) { + // TODO webpack 5 remove this check for options + if (typeof childGroup.options === "object") { + for (const key of Object.keys(childGroup.options)) { + if (key.endsWith("Order")) { + const name = key.substr(0, key.length - "Order".length); + let list = lists.get(name); + if (list === undefined) { + lists.set(name, (list = [])); + } + list.push({ + order: childGroup.options[key], + group: childGroup + }); + } + } + } + } + const result = Object.create(null); + for (const [name, list] of lists) { + list.sort((a, b) => { + const cmp = b.order - a.order; + if (cmp !== 0) return cmp; + // TODO webpack 5 remove this check of compareTo + if (a.group.compareTo) { + return a.group.compareTo(b.group); + } + return 0; + }); + result[name] = list.map(i => i.group); + } + return result; + } -function isObject(val) { - return (val && typeof val === 'object') || isExtendable(val); -} + /** + * Sets the top-down index of a module in this ChunkGroup + * @param {Module} module module for which the index should be set + * @param {number} index the index of the module + * @returns {void} + */ + setModuleIndex(module, index) { + this._moduleIndices.set(module, index); + } -/** - * Returns true if the given `key` is an own property of `obj`. - */ + /** + * Gets the top-down index of a module in this ChunkGroup + * @param {Module} module the module + * @returns {number} index + */ + getModuleIndex(module) { + return this._moduleIndices.get(module); + } -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} + /** + * Sets the bottom-up index of a module in this ChunkGroup + * @param {Module} module module for which the index should be set + * @param {number} index the index of the module + * @returns {void} + */ + setModuleIndex2(module, index) { + this._moduleIndices2.set(module, index); + } -function isEnum(obj, key) { - return Object.prototype.propertyIsEnumerable.call(obj, key); + /** + * Gets the bottom-up index of a module in this ChunkGroup + * @param {Module} module the module + * @returns {number} index + */ + getModuleIndex2(module) { + return this._moduleIndices2.get(module); + } + + checkConstraints() { + const chunk = this; + for (const child of chunk._children) { + if (!child._parents.has(chunk)) { + throw new Error( + `checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}` + ); + } + } + for (const parentChunk of chunk._parents) { + if (!parentChunk._children.has(chunk)) { + throw new Error( + `checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}` + ); + } + } + } } +module.exports = ChunkGroup; + /***/ }), -/***/ 78947: +/***/ 69865: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/*! - * is-extendable - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ - +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -var isPlainObject = __webpack_require__(81064); +const WebpackError = __webpack_require__(97391); -module.exports = function isExtendable(val) { - return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); -}; +/** @typedef {import("./Chunk")} Chunk */ +class ChunkRenderError extends WebpackError { + /** + * Create a new ChunkRenderError + * @param {Chunk} chunk A chunk + * @param {string} file Related file + * @param {Error} error Original error + */ + constructor(chunk, file, error) { + super(); -/***/ }), + this.name = "ChunkRenderError"; + this.error = error; + this.message = error.message; + this.details = error.stack; + this.file = file; + this.chunk = chunk; -/***/ 29859: -/***/ (function(module) { + Error.captureStackTrace(this, this.constructor); + } +} -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - - __extends = function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function (m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - }; - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - } - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); +module.exports = ChunkRenderError; /***/ }), -/***/ 7716: +/***/ 6170: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -var isObject = __webpack_require__(18493); -var union = __webpack_require__(69123); -var get = __webpack_require__(89304); -var set = __webpack_require__(34857); +const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(56758); -module.exports = function unionValue(obj, prop, value) { - if (!isObject(obj)) { - throw new TypeError('union-value expects the first argument to be an object.'); - } +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Module")} Module} */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate} */ +/** @typedef {import("./util/createHash").Hash} Hash} */ - if (typeof prop !== 'string') { - throw new TypeError('union-value expects `prop` to be a string.'); - } +/** + * @typedef {Object} RenderManifestOptions + * @property {Chunk} chunk the chunk used to render + * @property {string} hash + * @property {string} fullHash + * @property {TODO} outputOptions + * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates + * @property {Map} dependencyTemplates + */ - var arr = arrayify(get(obj, prop)); - set(obj, prop, union(arr, arrayify(value))); - return obj; -}; +module.exports = class ChunkTemplate extends Tapable { + constructor(outputOptions) { + super(); + this.outputOptions = outputOptions || {}; + this.hooks = { + /** @type {SyncWaterfallHook} */ + renderManifest: new SyncWaterfallHook(["result", "options"]), + modules: new SyncWaterfallHook([ + "source", + "chunk", + "moduleTemplate", + "dependencyTemplates" + ]), + render: new SyncWaterfallHook([ + "source", + "chunk", + "moduleTemplate", + "dependencyTemplates" + ]), + renderWithEntry: new SyncWaterfallHook(["source", "chunk"]), + hash: new SyncHook(["hash"]), + hashForChunk: new SyncHook(["hash", "chunk"]) + }; + } -function arrayify(val) { - if (val === null || typeof val === 'undefined') { - return []; - } - if (Array.isArray(val)) { - return val; - } - return [val]; -} + /** + * + * @param {RenderManifestOptions} options render manifest options + * @returns {TODO[]} returns render manifest + */ + getRenderManifest(options) { + const result = []; + this.hooks.renderManifest.call(result, options); -/***/ }), + return result; + } -/***/ 5834: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * Updates hash with information from this template + * @param {Hash} hash the hash to update + * @returns {void} + */ + updateHash(hash) { + hash.update("ChunkTemplate"); + hash.update("2"); + this.hooks.hash.call(hash); + } -"use strict"; -/*! - * unset-value - * - * Copyright (c) 2015, 2017, Jon Schlinkert. - * Released under the MIT License. - */ + /** + * TODO webpack 5: remove moduleTemplate and dependencyTemplates + * Updates hash with chunk-specific information from this template + * @param {Hash} hash the hash to update + * @param {Chunk} chunk the chunk + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map} dependencyTemplates dependency templates + * @returns {void} + */ + updateHashForChunk(hash, chunk, moduleTemplate, dependencyTemplates) { + this.updateHash(hash); + this.hooks.hashForChunk.call(hash, chunk); + } +}; +/***/ }), -var isObject = __webpack_require__(96667); -var has = __webpack_require__(77735); +/***/ 51760: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -module.exports = function unset(obj, prop) { - if (!isObject(obj)) { - throw new TypeError('expected an object.'); - } - if (obj.hasOwnProperty(prop)) { - delete obj[prop]; - return true; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (has(obj, prop)) { - var segs = prop.split('.'); - var last = segs.pop(); - while (segs.length && segs[segs.length - 1].slice(-1) === '\\') { - last = segs.pop().slice(0, -1) + '.' + last; - } - while (segs.length) obj = obj[prop = segs.shift()]; - return (delete obj[last]); - } - return true; -}; +const WebpackError = __webpack_require__(97391); -/***/ }), +/** @typedef {import("./Module")} Module */ -/***/ 77735: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -"use strict"; -/*! - * has-value - * - * Copyright (c) 2014-2016, Jon Schlinkert. - * Licensed under the MIT License. - */ +class CommentCompilationWarning extends WebpackError { + /** + * + * @param {string} message warning message + * @param {Module} module affected module + * @param {DependencyLocation} loc affected lines of code + */ + constructor(message, module, loc) { + super(message); + this.name = "CommentCompilationWarning"; + this.module = module; + this.loc = loc; -var isObject = __webpack_require__(78037); -var hasValues = __webpack_require__(38719); -var get = __webpack_require__(89304); + Error.captureStackTrace(this, this.constructor); + } +} -module.exports = function(obj, prop, noZero) { - if (isObject(obj)) { - return hasValues(get(obj, prop), noZero); - } - return hasValues(obj, prop); -}; +module.exports = CommentCompilationWarning; /***/ }), -/***/ 78037: +/***/ 85736: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/*! - * isobject - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +const path = __webpack_require__(85622); +const ParserHelpers = __webpack_require__(23999); -var isArray = __webpack_require__(21352); +class CommonJsStuffPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "CommonJsStuffPlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + parser.hooks.expression + .for("require.main.require") + .tap( + "CommonJsStuffPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + "require.main.require is not supported by webpack." + ) + ); + parser.hooks.expression + .for("module.parent.require") + .tap( + "CommonJsStuffPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + "module.parent.require is not supported by webpack." + ) + ); + parser.hooks.expression + .for("require.main") + .tap( + "CommonJsStuffPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.c[__webpack_require__.s]" + ) + ); + parser.hooks.expression + .for("module.loaded") + .tap("CommonJsStuffPlugin", expr => { + parser.state.module.buildMeta.moduleConcatenationBailout = + "module.loaded"; + return ParserHelpers.toConstantDependency( + parser, + "module.l" + )(expr); + }); + parser.hooks.expression + .for("module.id") + .tap("CommonJsStuffPlugin", expr => { + parser.state.module.buildMeta.moduleConcatenationBailout = + "module.id"; + return ParserHelpers.toConstantDependency( + parser, + "module.i" + )(expr); + }); + parser.hooks.expression + .for("module.exports") + .tap("CommonJsStuffPlugin", () => { + const module = parser.state.module; + const isHarmony = + module.buildMeta && module.buildMeta.exportsType; + if (!isHarmony) return true; + }); + parser.hooks.evaluateIdentifier + .for("module.hot") + .tap( + "CommonJsStuffPlugin", + ParserHelpers.evaluateToIdentifier("module.hot", false) + ); + parser.hooks.expression + .for("module") + .tap("CommonJsStuffPlugin", () => { + const module = parser.state.module; + const isHarmony = + module.buildMeta && module.buildMeta.exportsType; + let moduleJsPath = isHarmony ? __webpack_require__.ab + "harmony-module.js" : __webpack_require__.ab + "module.js"; + if (module.context) { + moduleJsPath = path.relative( + parser.state.module.context, + moduleJsPath + ); + if (!/^[A-Z]:/i.test(moduleJsPath)) { + moduleJsPath = `./${moduleJsPath.replace(/\\/g, "/")}`; + } + } + return ParserHelpers.addParsedVariableToModule( + parser, + "module", + `require(${JSON.stringify(moduleJsPath)})(module)` + ); + }); + }; -module.exports = function isObject(val) { - return val != null && typeof val === 'object' && isArray(val) === false; -}; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CommonJsStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("CommonJsStuffPlugin", handler); + } + ); + } +} +module.exports = CommonJsStuffPlugin; /***/ }), -/***/ 38719: -/***/ (function(module) { +/***/ 85918: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/*! - * has-values - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +const ConstDependency = __webpack_require__(71101); -module.exports = function hasValue(o, noZero) { - if (o === null || o === undefined) { - return false; - } +const NullFactory = __webpack_require__(40438); - if (typeof o === 'boolean') { - return true; - } +/** @typedef {import("./Compiler")} Compiler */ - if (typeof o === 'number') { - if (o === 0 && noZero === true) { - return false; - } - return true; - } +class CompatibilityPlugin { + /** + * Apply the plugin + * @param {Compiler} compiler Webpack Compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "CompatibilityPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); - if (o.length !== undefined) { - return o.length !== 0; - } + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CompatibilityPlugin", (parser, parserOptions) => { + if ( + parserOptions.browserify !== undefined && + !parserOptions.browserify + ) + return; - for (var key in o) { - if (o.hasOwnProperty(key)) { - return true; - } - } - return false; -}; + parser.hooks.call + .for("require") + .tap("CompatibilityPlugin", expr => { + // support for browserify style require delegator: "require(o, !0)" + if (expr.arguments.length !== 2) return; + const second = parser.evaluateExpression(expr.arguments[1]); + if (!second.isBoolean()) return; + if (second.asBool() !== true) return; + const dep = new ConstDependency("require", expr.callee.range); + dep.loc = expr.loc; + if (parser.state.current.dependencies.length > 1) { + const last = + parser.state.current.dependencies[ + parser.state.current.dependencies.length - 1 + ]; + if ( + last.critical && + last.options && + last.options.request === "." && + last.userRequest === "." && + last.options.recursive + ) + parser.state.current.dependencies.pop(); + } + parser.state.current.addDependency(dep); + return true; + }); + }); + } + ); + } +} +module.exports = CompatibilityPlugin; /***/ }), -/***/ 94007: -/***/ (function(__unused_webpack_module, exports) { +/***/ 34968: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** @license URI.js v4.2.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, (function (exports) { 'use strict'; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ -function merge() { - for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { - sets[_key] = arguments[_key]; - } - if (sets.length > 1) { - sets[0] = sets[0].slice(0, -1); - var xl = sets.length - 1; - for (var x = 1; x < xl; ++x) { - sets[x] = sets[x].slice(1, -1); - } - sets[xl] = sets[xl].slice(1); - return sets.join(''); - } else { - return sets[0]; - } -} -function subexp(str) { - return "(?:" + str + ")"; -} -function typeOf(o) { - return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); -} -function toUpperCase(str) { - return str.toUpperCase(); -} -function toArray(obj) { - return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; -} -function assign(target, source) { - var obj = target; - if (source) { - for (var key in source) { - obj[key] = source[key]; - } - } - return obj; -} +const asyncLib = __webpack_require__(36386); +const util = __webpack_require__(31669); +const { CachedSource } = __webpack_require__(53665); +const { + Tapable, + SyncHook, + SyncBailHook, + SyncWaterfallHook, + AsyncSeriesHook +} = __webpack_require__(56758); +const EntryModuleNotFoundError = __webpack_require__(99531); +const ModuleNotFoundError = __webpack_require__(71638); +const ModuleDependencyWarning = __webpack_require__(59136); +const ModuleDependencyError = __webpack_require__(14953); +const ChunkGroup = __webpack_require__(52911); +const Chunk = __webpack_require__(2919); +const Entrypoint = __webpack_require__(71931); +const MainTemplate = __webpack_require__(43626); +const ChunkTemplate = __webpack_require__(6170); +const HotUpdateChunkTemplate = __webpack_require__(66062); +const ModuleTemplate = __webpack_require__(75100); +const RuntimeTemplate = __webpack_require__(44006); +const ChunkRenderError = __webpack_require__(69865); +const Stats = __webpack_require__(99977); +const Semaphore = __webpack_require__(33349); +const createHash = __webpack_require__(15660); +const SortableSet = __webpack_require__(50071); +const GraphHelpers = __webpack_require__(32973); +const ModuleDependency = __webpack_require__(90865); +const compareLocations = __webpack_require__(22562); +const { Logger, LogType } = __webpack_require__(47194); +const ErrorHelpers = __webpack_require__(80140); +const buildChunkGraph = __webpack_require__(52337); +const WebpackError = __webpack_require__(97391); -function buildExps(isIRI) { - var ALPHA$$ = "[A-Za-z]", - CR$ = "[\\x0D]", - DIGIT$$ = "[0-9]", - DQUOTE$$ = "[\\x22]", - HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), - //case-insensitive - LF$$ = "[\\x0A]", - SP$$ = "[\\x20]", - PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), - //expanded - GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", - SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", - RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), - UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", - //subset, excludes bidi control characters - IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", - //subset - UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), - SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), - USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), - DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), - DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), - //relaxed parsing rules - IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), - H16$ = subexp(HEXDIG$$ + "{1,4}"), - LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), - IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), - // 6( h16 ":" ) ls32 - IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), - // "::" 5( h16 ":" ) ls32 - IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), - //[ h16 ] "::" 4( h16 ":" ) ls32 - IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), - //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 - IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), - //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 - IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), - //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 - IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), - //[ *4( h16 ":" ) h16 ] "::" ls32 - IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), - //[ *5( h16 ":" ) h16 ] "::" h16 - IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), - //[ *6( h16 ":" ) h16 ] "::" - IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), - ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), - //RFC 6874 - IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), - //RFC 6874 - IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$), - //RFC 6874, with relaxed parsing rules - IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), - IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), - //RFC 6874 - REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), - HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$), - PORT$ = subexp(DIGIT$$ + "*"), - AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), - PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), - SEGMENT$ = subexp(PCHAR$ + "*"), - SEGMENT_NZ$ = subexp(PCHAR$ + "+"), - SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), - PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), - PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), - //simplified - PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), - //simplified - PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), - //simplified - PATH_EMPTY$ = "(?!" + PCHAR$ + ")", - PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), - QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"), - FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), - HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), - URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), - RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), - RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), - URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), - ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), - GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", - RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", - ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", - SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", - AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$"; - return { - NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), - NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), - NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), - ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), - UNRESERVED: new RegExp(UNRESERVED$$, "g"), - OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), - PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), - IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), - IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules - }; -} -var URI_PROTOCOL = buildExps(false); +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./DependenciesBlockVariable")} DependenciesBlockVariable */ +/** @typedef {import("./dependencies/SingleEntryDependency")} SingleEntryDependency */ +/** @typedef {import("./dependencies/MultiEntryDependency")} MultiEntryDependency */ +/** @typedef {import("./dependencies/DllEntryDependency")} DllEntryDependency */ +/** @typedef {import("./dependencies/DependencyReference")} DependencyReference */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ +/** @typedef {import("./util/createHash").Hash} Hash */ -var IRI_PROTOCOL = buildExps(true); +// TODO use @callback +/** @typedef {{[assetName: string]: Source}} CompilationAssets */ +/** @typedef {(err: Error|null, result?: Module) => void } ModuleCallback */ +/** @typedef {(err?: Error|null, result?: Module) => void } ModuleChainCallback */ +/** @typedef {(module: Module) => void} OnModuleCallback */ +/** @typedef {(err?: Error|null) => void} Callback */ +/** @typedef {(d: Dependency) => any} DepBlockVarDependenciesCallback */ +/** @typedef {new (...args: any[]) => Dependency} DepConstructor */ +/** @typedef {{apply: () => void}} Plugin */ -var slicedToArray = function () { - function sliceIterator(arr, i) { - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"]) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - return function (arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if (Symbol.iterator in Object(arr)) { - return sliceIterator(arr, i); - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } - }; -}(); - - - - - - - - - - - - - -var toConsumableArray = function (arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; - - return arr2; - } else { - return Array.from(arr); - } -}; - -/** Highest positive signed 32-bit float value */ +/** + * @typedef {Object} ModuleFactoryCreateDataContextInfo + * @property {string} issuer + * @property {string} compiler + */ -var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 +/** + * @typedef {Object} ModuleFactoryCreateData + * @property {ModuleFactoryCreateDataContextInfo} contextInfo + * @property {any=} resolveOptions + * @property {string} context + * @property {Dependency[]} dependencies + */ -/** Bootstring parameters */ -var base = 36; -var tMin = 1; -var tMax = 26; -var skew = 38; -var damp = 700; -var initialBias = 72; -var initialN = 128; // 0x80 -var delimiter = '-'; // '\x2D' +/** + * @typedef {Object} ModuleFactory + * @property {(data: ModuleFactoryCreateData, callback: ModuleCallback) => any} create + */ -/** Regular expressions */ -var regexPunycode = /^xn--/; -var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars -var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators +/** + * @typedef {Object} SortedDependency + * @property {ModuleFactory} factory + * @property {Dependency[]} dependencies + */ -/** Error messages */ -var errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' -}; +/** + * @typedef {Object} DependenciesBlockLike + * @property {Dependency[]} dependencies + * @property {AsyncDependenciesBlock[]} blocks + * @property {DependenciesBlockVariable[]} variables + */ -/** Convenience shortcuts */ -var baseMinusTMin = base - tMin; -var floor = Math.floor; -var stringFromCharCode = String.fromCharCode; +/** + * @typedef {Object} LogEntry + * @property {string} type + * @property {any[]} args + * @property {number} time + * @property {string[]=} trace + */ -/*--------------------------------------------------------------------------*/ +/** + * @typedef {Object} AssetInfo + * @property {boolean=} immutable true, if the asset can be long term cached forever (contains a hash) + * @property {number=} size size in bytes, only set after asset has been emitted + * @property {boolean=} development true, when asset is only used for development and doesn't count towards user-facing assets + * @property {boolean=} hotModuleReplacement true, when asset ships data for updating an existing application (HMR) + */ /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. + * @typedef {Object} Asset + * @property {string} name the filename of the asset + * @property {Source} source source of the asset + * @property {AssetInfo} info info about the asset */ -function error$1(type) { - throw new RangeError(errors[type]); -} /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. + * @param {Chunk} a first chunk to sort by id + * @param {Chunk} b second chunk to sort by id + * @returns {-1|0|1} sort value */ -function map(array, fn) { - var result = []; - var length = array.length; - while (length--) { - result[length] = fn(array[length]); +const byId = (a, b) => { + if (typeof a.id !== typeof b.id) { + return typeof a.id < typeof b.id ? -1 : 1; } - return result; -} + if (a.id < b.id) return -1; + if (a.id > b.id) return 1; + return 0; +}; /** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. + * @param {Module} a first module to sort by + * @param {Module} b second module to sort by + * @returns {-1|0|1} sort value */ -function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; +const byIdOrIdentifier = (a, b) => { + if (typeof a.id !== typeof b.id) { + return typeof a.id < typeof b.id ? -1 : 1; } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; -} + if (a.id < b.id) return -1; + if (a.id > b.id) return 1; + const identA = a.identifier(); + const identB = b.identifier(); + if (identA < identB) return -1; + if (identA > identB) return 1; + return 0; +}; /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. + * @param {Module} a first module to sort by + * @param {Module} b second module to sort by + * @returns {-1|0|1} sort value */ -function ucs2decode(string) { - var output = []; - var counter = 0; - var length = string.length; - while (counter < length) { - var value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // It's a high surrogate, and there is a next character. - var extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { - // Low surrogate. - output.push(((value & 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. - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; -} +const byIndexOrIdentifier = (a, b) => { + if (a.index < b.index) return -1; + if (a.index > b.index) return 1; + const identA = a.identifier(); + const identB = b.identifier(); + if (identA < identB) return -1; + if (identA > identB) return 1; + return 0; +}; /** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). + * @param {Compilation} a first compilation to sort by + * @param {Compilation} b second compilation to sort by + * @returns {-1|0|1} sort value */ -var ucs2encode = function ucs2encode(array) { - return String.fromCodePoint.apply(String, toConsumableArray(array)); +const byNameOrHash = (a, b) => { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + if (a.fullHash < b.fullHash) return -1; + if (a.fullHash > b.fullHash) return 1; + return 0; }; /** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. + * @param {DependenciesBlockVariable[]} variables DepBlock Variables to iterate over + * @param {DepBlockVarDependenciesCallback} fn callback to apply on iterated elements + * @returns {void} */ -var basicToDigit = function basicToDigit(codePoint) { - if (codePoint - 0x30 < 0x0A) { - return codePoint - 0x16; - } - if (codePoint - 0x41 < 0x1A) { - return codePoint - 0x41; - } - if (codePoint - 0x61 < 0x1A) { - return codePoint - 0x61; +const iterationBlockVariable = (variables, fn) => { + for ( + let indexVariable = 0; + indexVariable < variables.length; + indexVariable++ + ) { + const varDep = variables[indexVariable].dependencies; + for (let indexVDep = 0; indexVDep < varDep.length; indexVDep++) { + fn(varDep[indexVDep]); + } } - return base; }; /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. + * @template T + * @param {T[]} arr array of elements to iterate over + * @param {function(T): void} fn callback applied to each element + * @returns {void} */ -var digitToBasic = function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +const iterationOfArrayCallback = (arr, fn) => { + for (let index = 0; index < arr.length; index++) { + fn(arr[index]); + } }; /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private + * @template T + * @param {Set} set set to add items to + * @param {Set} otherSet set to add items from + * @returns {void} */ -var adapt = function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); +const addAllToSet = (set, otherSet) => { + for (const item of otherSet) { + set.add(item); } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); }; /** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. + * @param {Source} a a source + * @param {Source} b another source + * @returns {boolean} true, when both sources are equal */ -var decode = function decode(input) { - // Don't use UCS-2. - var output = []; - var inputLength = input.length; - var i = 0; - var n = initialN; - var bias = initialBias; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. +const isSourceEqual = (a, b) => { + if (a === b) return true; + // TODO webpack 5: check .buffer() instead, it's called anyway during emit + /** @type {Buffer|string} */ + let aSource = a.source(); + /** @type {Buffer|string} */ + let bSource = b.source(); + if (aSource === bSource) return true; + if (typeof aSource === "string" && typeof bSource === "string") return false; + if (!Buffer.isBuffer(aSource)) aSource = Buffer.from(aSource, "utf-8"); + if (!Buffer.isBuffer(bSource)) bSource = Buffer.from(bSource, "utf-8"); + return aSource.equals(bSource); +}; - var basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } +class Compilation extends Tapable { + /** + * Creates an instance of Compilation. + * @param {Compiler} compiler the compiler which created the compilation + */ + constructor(compiler) { + super(); + this.hooks = { + /** @type {SyncHook} */ + buildModule: new SyncHook(["module"]), + /** @type {SyncHook} */ + rebuildModule: new SyncHook(["module"]), + /** @type {SyncHook} */ + failedModule: new SyncHook(["module", "error"]), + /** @type {SyncHook} */ + succeedModule: new SyncHook(["module"]), - for (var j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error$1('not-basic'); - } - output.push(input.charCodeAt(j)); - } + /** @type {SyncHook} */ + addEntry: new SyncHook(["entry", "name"]), + /** @type {SyncHook} */ + failedEntry: new SyncHook(["entry", "name", "error"]), + /** @type {SyncHook} */ + succeedEntry: new SyncHook(["entry", "name", "module"]), - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. + /** @type {SyncWaterfallHook} */ + dependencyReference: new SyncWaterfallHook([ + "dependencyReference", + "dependency", + "module" + ]), - for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ + /** @type {AsyncSeriesHook} */ + finishModules: new AsyncSeriesHook(["modules"]), + /** @type {SyncHook} */ + finishRebuildingModule: new SyncHook(["module"]), + /** @type {SyncHook} */ + unseal: new SyncHook([]), + /** @type {SyncHook} */ + seal: new SyncHook([]), - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - var oldi = i; - for (var w = 1, k = base;; /* no condition */k += base) { + /** @type {SyncHook} */ + beforeChunks: new SyncHook([]), + /** @type {SyncHook} */ + afterChunks: new SyncHook(["chunks"]), - if (index >= inputLength) { - error$1('invalid-input'); - } + /** @type {SyncBailHook} */ + optimizeDependenciesBasic: new SyncBailHook(["modules"]), + /** @type {SyncBailHook} */ + optimizeDependencies: new SyncBailHook(["modules"]), + /** @type {SyncBailHook} */ + optimizeDependenciesAdvanced: new SyncBailHook(["modules"]), + /** @type {SyncBailHook} */ + afterOptimizeDependencies: new SyncHook(["modules"]), - var digit = basicToDigit(input.charCodeAt(index++)); + /** @type {SyncHook} */ + optimize: new SyncHook([]), + /** @type {SyncBailHook} */ + optimizeModulesBasic: new SyncBailHook(["modules"]), + /** @type {SyncBailHook} */ + optimizeModules: new SyncBailHook(["modules"]), + /** @type {SyncBailHook} */ + optimizeModulesAdvanced: new SyncBailHook(["modules"]), + /** @type {SyncHook} */ + afterOptimizeModules: new SyncHook(["modules"]), - if (digit >= base || digit > floor((maxInt - i) / w)) { - error$1('overflow'); - } + /** @type {SyncBailHook} */ + optimizeChunksBasic: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncBailHook} */ + optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncBailHook} */ + optimizeChunksAdvanced: new SyncBailHook(["chunks", "chunkGroups"]), + /** @type {SyncHook} */ + afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]), - i += digit * w; - var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + /** @type {AsyncSeriesHook} */ + optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), + /** @type {SyncHook} */ + afterOptimizeTree: new SyncHook(["chunks", "modules"]), - if (digit < t) { - break; - } + /** @type {SyncBailHook} */ + optimizeChunkModulesBasic: new SyncBailHook(["chunks", "modules"]), + /** @type {SyncBailHook} */ + optimizeChunkModules: new SyncBailHook(["chunks", "modules"]), + /** @type {SyncBailHook} */ + optimizeChunkModulesAdvanced: new SyncBailHook(["chunks", "modules"]), + /** @type {SyncHook} */ + afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]), + /** @type {SyncBailHook} */ + shouldRecord: new SyncBailHook([]), - var baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error$1('overflow'); - } + /** @type {SyncHook} */ + reviveModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook} */ + optimizeModuleOrder: new SyncHook(["modules"]), + /** @type {SyncHook} */ + advancedOptimizeModuleOrder: new SyncHook(["modules"]), + /** @type {SyncHook} */ + beforeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook} */ + moduleIds: new SyncHook(["modules"]), + /** @type {SyncHook} */ + optimizeModuleIds: new SyncHook(["modules"]), + /** @type {SyncHook} */ + afterOptimizeModuleIds: new SyncHook(["modules"]), - w *= baseMinusT; - } + /** @type {SyncHook} */ + reviveChunks: new SyncHook(["chunks", "records"]), + /** @type {SyncHook} */ + optimizeChunkOrder: new SyncHook(["chunks"]), + /** @type {SyncHook} */ + beforeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook} */ + optimizeChunkIds: new SyncHook(["chunks"]), + /** @type {SyncHook} */ + afterOptimizeChunkIds: new SyncHook(["chunks"]), - var out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); + /** @type {SyncHook} */ + recordModules: new SyncHook(["modules", "records"]), + /** @type {SyncHook} */ + recordChunks: new SyncHook(["chunks", "records"]), - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error$1('overflow'); - } + /** @type {SyncHook} */ + beforeHash: new SyncHook([]), + /** @type {SyncHook} */ + contentHash: new SyncHook(["chunk"]), + /** @type {SyncHook} */ + afterHash: new SyncHook([]), + /** @type {SyncHook} */ + recordHash: new SyncHook(["records"]), + /** @type {SyncHook} */ + record: new SyncHook(["compilation", "records"]), - n += floor(i / out); - i %= out; + /** @type {SyncHook} */ + beforeModuleAssets: new SyncHook([]), + /** @type {SyncBailHook} */ + shouldGenerateChunkAssets: new SyncBailHook([]), + /** @type {SyncHook} */ + beforeChunkAssets: new SyncHook([]), + /** @type {SyncHook} */ + additionalChunkAssets: new SyncHook(["chunks"]), - // Insert `n` at position `i` of the output. - output.splice(i++, 0, n); - } + /** @type {AsyncSeriesHook} */ + additionalAssets: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook} */ + optimizeChunkAssets: new AsyncSeriesHook(["chunks"]), + /** @type {SyncHook} */ + afterOptimizeChunkAssets: new SyncHook(["chunks"]), + /** @type {AsyncSeriesHook} */ + optimizeAssets: new AsyncSeriesHook(["assets"]), + /** @type {SyncHook} */ + afterOptimizeAssets: new SyncHook(["assets"]), - return String.fromCodePoint.apply(String, output); -}; + /** @type {SyncBailHook} */ + needAdditionalSeal: new SyncBailHook([]), + /** @type {AsyncSeriesHook} */ + afterSeal: new AsyncSeriesHook([]), -/** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ -var encode = function encode(input) { - var output = []; + /** @type {SyncHook} */ + chunkHash: new SyncHook(["chunk", "chunkHash"]), + /** @type {SyncHook} */ + moduleAsset: new SyncHook(["module", "filename"]), + /** @type {SyncHook} */ + chunkAsset: new SyncHook(["chunk", "filename"]), - // Convert the input in UCS-2 to an array of Unicode code points. - input = ucs2decode(input); + /** @type {SyncWaterfallHook} */ + assetPath: new SyncWaterfallHook(["filename", "data"]), // TODO MainTemplate - // Cache the length. - var inputLength = input.length; + /** @type {SyncBailHook} */ + needAdditionalPass: new SyncBailHook([]), - // Initialize the state. - var n = initialN; - var delta = 0; - var bias = initialBias; + /** @type {SyncHook} */ + childCompiler: new SyncHook([ + "childCompiler", + "compilerName", + "compilerIndex" + ]), - // Handle the basic code points. - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; + /** @type {SyncBailHook} */ + log: new SyncBailHook(["origin", "logEntry"]), - try { - for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var _currentValue2 = _step.value; + // TODO the following hooks are weirdly located here + // TODO move them for webpack 5 + /** @type {SyncHook} */ + normalModuleLoader: new SyncHook(["loaderContext", "module"]), - if (_currentValue2 < 0x80) { - output.push(stringFromCharCode(_currentValue2)); - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; + /** @type {SyncBailHook} */ + optimizeExtractedChunksBasic: new SyncBailHook(["chunks"]), + /** @type {SyncBailHook} */ + optimizeExtractedChunks: new SyncBailHook(["chunks"]), + /** @type {SyncBailHook} */ + optimizeExtractedChunksAdvanced: new SyncBailHook(["chunks"]), + /** @type {SyncHook} */ + afterOptimizeExtractedChunks: new SyncHook(["chunks"]) + }; + this._pluginCompat.tap("Compilation", options => { + switch (options.name) { + case "optimize-tree": + case "additional-assets": + case "optimize-chunk-assets": + case "optimize-assets": + case "after-seal": + options.async = true; + break; } - } - } - - var basicLength = output.length; - var handledCPCount = basicLength; + }); + /** @type {string=} */ + this.name = undefined; + /** @type {Compiler} */ + this.compiler = compiler; + this.resolverFactory = compiler.resolverFactory; + this.inputFileSystem = compiler.inputFileSystem; + this.requestShortener = compiler.requestShortener; - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. + const options = compiler.options; + this.options = options; + this.outputOptions = options && options.output; + /** @type {boolean=} */ + this.bail = options && options.bail; + this.profile = options && options.profile; + this.performance = options && options.performance; - // Finish the basic string with a delimiter unless it's empty. - if (basicLength) { - output.push(delimiter); - } + this.mainTemplate = new MainTemplate(this.outputOptions); + this.chunkTemplate = new ChunkTemplate(this.outputOptions); + this.hotUpdateChunkTemplate = new HotUpdateChunkTemplate( + this.outputOptions + ); + this.runtimeTemplate = new RuntimeTemplate( + this.outputOptions, + this.requestShortener + ); + this.moduleTemplates = { + javascript: new ModuleTemplate(this.runtimeTemplate, "javascript"), + webassembly: new ModuleTemplate(this.runtimeTemplate, "webassembly") + }; - // Main encoding loop: - while (handledCPCount < inputLength) { + this.semaphore = new Semaphore(options.parallelism || 100); - // All non-basic code points < n have been handled already. Find the next - // larger one: - var m = maxInt; - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; + this.entries = []; + /** @private @type {{name: string, request: string, module: Module}[]} */ + this._preparedEntrypoints = []; + /** @type {Map} */ + this.entrypoints = new Map(); + /** @type {Chunk[]} */ + this.chunks = []; + /** @type {ChunkGroup[]} */ + this.chunkGroups = []; + /** @type {Map} */ + this.namedChunkGroups = new Map(); + /** @type {Map} */ + this.namedChunks = new Map(); + /** @type {Module[]} */ + this.modules = []; + /** @private @type {Map} */ + this._modules = new Map(); + this.cache = null; + this.records = null; + /** @type {string[]} */ + this.additionalChunkAssets = []; + /** @type {CompilationAssets} */ + this.assets = {}; + /** @type {Map} */ + this.assetsInfo = new Map(); + /** @type {WebpackError[]} */ + this.errors = []; + /** @type {WebpackError[]} */ + this.warnings = []; + /** @type {Compilation[]} */ + this.children = []; + /** @type {Map} */ + this.logging = new Map(); + /** @type {Map} */ + this.dependencyFactories = new Map(); + /** @type {Map} */ + this.dependencyTemplates = new Map(); + // TODO refactor this in webpack 5 to a custom DependencyTemplates class with a hash property + // @ts-ignore + this.dependencyTemplates.set("hash", ""); + this.childrenCounters = {}; + /** @type {Set} */ + this.usedChunkIds = null; + /** @type {Set} */ + this.usedModuleIds = null; + /** @type {Map=} */ + this.fileTimestamps = undefined; + /** @type {Map=} */ + this.contextTimestamps = undefined; + /** @type {Set=} */ + this.compilationDependencies = undefined; + /** @private @type {Map} */ + this._buildingModules = new Map(); + /** @private @type {Map} */ + this._rebuildingModules = new Map(); + /** @type {Set} */ + this.emittedAssets = new Set(); + } - try { - for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var currentValue = _step2.value; + getStats() { + return new Stats(this); + } - if (currentValue >= n && currentValue < m) { - m = currentValue; + /** + * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name + * @returns {Logger} a logger with that name + */ + getLogger(name) { + if (!name) { + throw new TypeError("Compilation.getLogger(name) called without a name"); + } + /** @type {LogEntry[] | undefined} */ + let logEntries; + return new Logger((type, args) => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compilation.getLogger(name) called with a function not returning a name" + ); } } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow. - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return) { - _iterator2.return(); + let trace; + switch (type) { + case LogType.warn: + case LogType.error: + case LogType.trace: + trace = ErrorHelpers.cutOffLoaderExecution(new Error("Trace").stack) + .split("\n") + .slice(3); + break; + } + /** @type {LogEntry} */ + const logEntry = { + time: Date.now(), + type, + args, + trace + }; + if (this.hooks.log.call(name, logEntry) === undefined) { + if (logEntry.type === LogType.profileEnd) { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profileEnd === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profileEnd(`[${name}] ${logEntry.args[0]}`); + } } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; + if (logEntries === undefined) { + logEntries = this.logging.get(name); + if (logEntries === undefined) { + logEntries = []; + this.logging.set(name, logEntries); + } + } + logEntries.push(logEntry); + if (logEntry.type === LogType.profile) { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profile === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profile(`[${name}] ${logEntry.args[0]}`); + } } } - } - - var handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error$1('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; + }); + } - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; + /** + * @typedef {Object} AddModuleResult + * @property {Module} module the added or existing module + * @property {boolean} issuer was this the first request for this module + * @property {boolean} build should the module be build + * @property {boolean} dependencies should dependencies be walked + */ - try { - for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var _currentValue = _step3.value; + /** + * @param {Module} module module to be added that was created + * @param {any=} cacheGroup cacheGroup it is apart of + * @returns {AddModuleResult} returns meta about whether or not the module had built + * had an issuer, or any dependnecies + */ + addModule(module, cacheGroup) { + const identifier = module.identifier(); + const alreadyAddedModule = this._modules.get(identifier); + if (alreadyAddedModule) { + return { + module: alreadyAddedModule, + issuer: false, + build: false, + dependencies: false + }; + } + const cacheName = (cacheGroup || "m") + identifier; + if (this.cache && this.cache[cacheName]) { + const cacheModule = this.cache[cacheName]; - if (_currentValue < n && ++delta > maxInt) { - error$1('overflow'); - } - if (_currentValue == n) { - // Represent delta as a generalized variable-length integer. - var q = delta; - for (var k = base;; /* no condition */k += base) { - var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - if (q < t) { - break; - } - var qMinusT = q - t; - var baseMinusT = base - t; - output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); - q = floor(qMinusT / baseMinusT); - } + if (typeof cacheModule.updateCacheModule === "function") { + cacheModule.updateCacheModule(module); + } - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } + let rebuild = true; + if (this.fileTimestamps && this.contextTimestamps) { + rebuild = cacheModule.needRebuild( + this.fileTimestamps, + this.contextTimestamps + ); } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3.return) { - _iterator3.return(); + + if (!rebuild) { + cacheModule.disconnect(); + this._modules.set(identifier, cacheModule); + this.modules.push(cacheModule); + for (const err of cacheModule.errors) { + this.errors.push(err); } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; + for (const err of cacheModule.warnings) { + this.warnings.push(err); } + return { + module: cacheModule, + issuer: true, + build: false, + dependencies: true + }; } + cacheModule.unbuild(); + module = cacheModule; } - - ++delta; - ++n; + this._modules.set(identifier, module); + if (this.cache) { + this.cache[cacheName] = module; + } + this.modules.push(module); + return { + module: module, + issuer: true, + build: true, + dependencies: true + }; } - return output.join(''); -}; - -/** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ -var toUnicode = function toUnicode(input) { - return mapDomain(input, function (string) { - return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; - }); -}; - -/** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ -var toASCII = function toASCII(input) { - return mapDomain(input, function (string) { - return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; - }); -}; -/*--------------------------------------------------------------------------*/ + /** + * Fetches a module from a compilation by its identifier + * @param {Module} module the module provided + * @returns {Module} the module requested + */ + getModule(module) { + const identifier = module.identifier(); + return this._modules.get(identifier); + } -/** Define the public API */ -var punycode = { /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '2.1.0', + * Attempts to search for a module by its identifier + * @param {string} identifier identifier (usually path) for module + * @returns {Module|undefined} attempt to search for module and return it, else undefined + */ + findModule(identifier) { + return this._modules.get(identifier); + } + /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode -}; + * @param {Module} module module with its callback list + * @param {Callback} callback the callback function + * @returns {void} + */ + waitForBuildingFinished(module, callback) { + let callbackList = this._buildingModules.get(module); + if (callbackList) { + callbackList.push(() => callback()); + } else { + process.nextTick(callback); + } + } -/** - * URI.js - * - * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. - * @author Gary Court - * @see http://github.com/garycourt/uri-js - */ -/** - * Copyright 2011 Gary Court. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. 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 GARY COURT ``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 GARY COURT 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. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of Gary Court. - */ -var SCHEMES = {}; -function pctEncChar(chr) { - var c = chr.charCodeAt(0); - var e = void 0; - if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); - return e; -} -function pctDecChars(str) { - var newStr = ""; - var i = 0; - var il = str.length; - while (i < il) { - var c = parseInt(str.substr(i + 1, 2), 16); - if (c < 128) { - newStr += String.fromCharCode(c); - i += 3; - } else if (c >= 194 && c < 224) { - if (il - i >= 6) { - var c2 = parseInt(str.substr(i + 4, 2), 16); - newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); - } else { - newStr += str.substr(i, 6); - } - i += 6; - } else if (c >= 224) { - if (il - i >= 9) { - var _c = parseInt(str.substr(i + 4, 2), 16); - var c3 = parseInt(str.substr(i + 7, 2), 16); - newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); - } else { - newStr += str.substr(i, 9); - } - i += 9; - } else { - newStr += str.substr(i, 3); - i += 3; - } - } - return newStr; -} -function _normalizeComponentEncoding(components, protocol) { - function decodeUnreserved(str) { - var decStr = pctDecChars(str); - return !decStr.match(protocol.UNRESERVED) ? str : decStr; - } - if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); - if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - return components; -} + /** + * Builds the module object + * + * @param {Module} module module to be built + * @param {boolean} optional optional flag + * @param {Module=} origin origin module this module build was requested from + * @param {Dependency[]=} dependencies optional dependencies from the module to be built + * @param {TODO} thisCallback the callback + * @returns {TODO} returns the callback function with results + */ + buildModule(module, optional, origin, dependencies, thisCallback) { + let callbackList = this._buildingModules.get(module); + if (callbackList) { + callbackList.push(thisCallback); + return; + } + this._buildingModules.set(module, (callbackList = [thisCallback])); -function _stripLeadingZeros(str) { - return str.replace(/^0*(.*)/, "$1") || "0"; -} -function _normalizeIPv4(host, protocol) { - var matches = host.match(protocol.IPV4ADDRESS) || []; + const callback = err => { + this._buildingModules.delete(module); + for (const cb of callbackList) { + cb(err); + } + }; - var _matches = slicedToArray(matches, 2), - address = _matches[1]; + this.hooks.buildModule.call(module); + module.build( + this.options, + this, + this.resolverFactory.get("normal", module.resolveOptions), + this.inputFileSystem, + error => { + const errors = module.errors; + for (let indexError = 0; indexError < errors.length; indexError++) { + const err = errors[indexError]; + err.origin = origin; + err.dependencies = dependencies; + if (optional) { + this.warnings.push(err); + } else { + this.errors.push(err); + } + } - if (address) { - return address.split(".").map(_stripLeadingZeros).join("."); - } else { - return host; - } -} -function _normalizeIPv6(host, protocol) { - var matches = host.match(protocol.IPV6ADDRESS) || []; + const warnings = module.warnings; + for ( + let indexWarning = 0; + indexWarning < warnings.length; + indexWarning++ + ) { + const war = warnings[indexWarning]; + war.origin = origin; + war.dependencies = dependencies; + this.warnings.push(war); + } + const originalMap = module.dependencies.reduce((map, v, i) => { + map.set(v, i); + return map; + }, new Map()); + module.dependencies.sort((a, b) => { + const cmp = compareLocations(a.loc, b.loc); + if (cmp) return cmp; + return originalMap.get(a) - originalMap.get(b); + }); + if (error) { + this.hooks.failedModule.call(module, error); + return callback(error); + } + this.hooks.succeedModule.call(module); + return callback(); + } + ); + } - var _matches2 = slicedToArray(matches, 3), - address = _matches2[1], - zone = _matches2[2]; + /** + * @param {Module} module to be processed for deps + * @param {ModuleCallback} callback callback to be triggered + * @returns {void} + */ + processModuleDependencies(module, callback) { + const dependencies = new Map(); - if (address) { - var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), - _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), - last = _address$toLowerCase$2[0], - first = _address$toLowerCase$2[1]; + const addDependency = dep => { + const resourceIdent = dep.getResourceIdentifier(); + if (resourceIdent) { + const factory = this.dependencyFactories.get(dep.constructor); + if (factory === undefined) { + throw new Error( + `No module factory available for dependency type: ${dep.constructor.name}` + ); + } + let innerMap = dependencies.get(factory); + if (innerMap === undefined) { + dependencies.set(factory, (innerMap = new Map())); + } + let list = innerMap.get(resourceIdent); + if (list === undefined) innerMap.set(resourceIdent, (list = [])); + list.push(dep); + } + }; - var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; - var lastFields = last.split(":").map(_stripLeadingZeros); - var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); - var fieldCount = isLastFieldIPv4Address ? 7 : 8; - var lastFieldsStart = lastFields.length - fieldCount; - var fields = Array(fieldCount); - for (var x = 0; x < fieldCount; ++x) { - fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; - } - if (isLastFieldIPv4Address) { - fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); - } - var allZeroFields = fields.reduce(function (acc, field, index) { - if (!field || field === "0") { - var lastLongest = acc[acc.length - 1]; - if (lastLongest && lastLongest.index + lastLongest.length === index) { - lastLongest.length++; - } else { - acc.push({ index: index, length: 1 }); - } - } - return acc; - }, []); - var longestZeroFields = allZeroFields.sort(function (a, b) { - return b.length - a.length; - })[0]; - var newHost = void 0; - if (longestZeroFields && longestZeroFields.length > 1) { - var newFirst = fields.slice(0, longestZeroFields.index); - var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); - newHost = newFirst.join(":") + "::" + newLast.join(":"); - } else { - newHost = fields.join(":"); - } - if (zone) { - newHost += "%" + zone; - } - return newHost; - } else { - return host; - } -} -var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; -var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; -function parse(uriString) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + const addDependenciesBlock = block => { + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, addDependency); + } + if (block.blocks) { + iterationOfArrayCallback(block.blocks, addDependenciesBlock); + } + if (block.variables) { + iterationBlockVariable(block.variables, addDependency); + } + }; - var components = {}; - var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; - if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; - var matches = uriString.match(URI_PARSE); - if (matches) { - if (NO_MATCH_IS_UNDEFINED) { - //store each component - components.scheme = matches[1]; - components.userinfo = matches[3]; - components.host = matches[4]; - components.port = parseInt(matches[5], 10); - components.path = matches[6] || ""; - components.query = matches[7]; - components.fragment = matches[8]; - //fix port number - if (isNaN(components.port)) { - components.port = matches[5]; - } - } else { - //IE FIX for improper RegExp matching - //store each component - components.scheme = matches[1] || undefined; - components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; - components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; - components.port = parseInt(matches[5], 10); - components.path = matches[6] || ""; - components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; - components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; - //fix port number - if (isNaN(components.port)) { - components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; - } - } - if (components.host) { - //normalize IP hosts - components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); - } - //determine reference type - if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { - components.reference = "same-document"; - } else if (components.scheme === undefined) { - components.reference = "relative"; - } else if (components.fragment === undefined) { - components.reference = "absolute"; - } else { - components.reference = "uri"; - } - //check for reference errors - if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { - components.error = components.error || "URI is not a " + options.reference + " reference."; - } - //find scheme handler - var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; - //check if scheme can't handle IRIs - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - //if host component is a domain name - if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { - //convert Unicode IDN -> ASCII IDN - try { - components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); - } catch (e) { - components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; - } - } - //convert IRI -> URI - _normalizeComponentEncoding(components, URI_PROTOCOL); - } else { - //normalize encodings - _normalizeComponentEncoding(components, protocol); - } - //perform scheme specific parsing - if (schemeHandler && schemeHandler.parse) { - schemeHandler.parse(components, options); - } - } else { - components.error = components.error || "URI can not be parsed."; - } - return components; -} + try { + addDependenciesBlock(module); + } catch (e) { + callback(e); + } -function _recomposeAuthority(components, options) { - var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; - var uriTokens = []; - if (components.userinfo !== undefined) { - uriTokens.push(components.userinfo); - uriTokens.push("@"); - } - if (components.host !== undefined) { - //normalize IP hosts, add brackets and escape zone separator for IPv6 - uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { - return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; - })); - } - if (typeof components.port === "number") { - uriTokens.push(":"); - uriTokens.push(components.port.toString(10)); - } - return uriTokens.length ? uriTokens.join("") : undefined; -} + const sortedDependencies = []; -var RDS1 = /^\.\.?\//; -var RDS2 = /^\/\.(\/|$)/; -var RDS3 = /^\/\.\.(\/|$)/; -var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; -function removeDotSegments(input) { - var output = []; - while (input.length) { - if (input.match(RDS1)) { - input = input.replace(RDS1, ""); - } else if (input.match(RDS2)) { - input = input.replace(RDS2, "/"); - } else if (input.match(RDS3)) { - input = input.replace(RDS3, "/"); - output.pop(); - } else if (input === "." || input === "..") { - input = ""; - } else { - var im = input.match(RDS5); - if (im) { - var s = im[0]; - input = input.slice(s.length); - output.push(s); - } else { - throw new Error("Unexpected dot segment condition"); - } - } - } - return output.join(""); -} + for (const pair1 of dependencies) { + for (const pair2 of pair1[1]) { + sortedDependencies.push({ + factory: pair1[0], + dependencies: pair2[1] + }); + } + } -function serialize(components) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this.addModuleDependencies( + module, + sortedDependencies, + this.bail, + null, + true, + callback + ); + } - var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; - var uriTokens = []; - //find scheme handler - var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; - //perform scheme specific serialization - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); - if (components.host) { - //if host component is an IPv6 address - if (protocol.IPV6ADDRESS.test(components.host)) {} - //TODO: normalize IPv6 address as per RFC 5952 + /** + * @param {Module} module module to add deps to + * @param {SortedDependency[]} dependencies set of sorted dependencies to iterate through + * @param {(boolean|null)=} bail whether to bail or not + * @param {TODO} cacheGroup optional cacheGroup + * @param {boolean} recursive whether it is recursive traversal + * @param {function} callback callback for when dependencies are finished being added + * @returns {void} + */ + addModuleDependencies( + module, + dependencies, + bail, + cacheGroup, + recursive, + callback + ) { + const start = this.profile && Date.now(); + const currentProfile = this.profile && {}; - //if host component is a domain name - else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { - //convert IDN via punycode - try { - components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); - } catch (e) { - components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; - } - } - } - //normalize encoding - _normalizeComponentEncoding(components, protocol); - if (options.reference !== "suffix" && components.scheme) { - uriTokens.push(components.scheme); - uriTokens.push(":"); - } - var authority = _recomposeAuthority(components, options); - if (authority !== undefined) { - if (options.reference !== "suffix") { - uriTokens.push("//"); - } - uriTokens.push(authority); - if (components.path && components.path.charAt(0) !== "/") { - uriTokens.push("/"); - } - } - if (components.path !== undefined) { - var s = components.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { - s = removeDotSegments(s); - } - if (authority === undefined) { - s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" - } - uriTokens.push(s); - } - if (components.query !== undefined) { - uriTokens.push("?"); - uriTokens.push(components.query); - } - if (components.fragment !== undefined) { - uriTokens.push("#"); - uriTokens.push(components.fragment); - } - return uriTokens.join(""); //merge tokens into a string -} + asyncLib.forEach( + dependencies, + (item, callback) => { + const dependencies = item.dependencies; -function resolveComponents(base, relative) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var skipNormalization = arguments[3]; + const errorAndCallback = err => { + err.origin = module; + err.dependencies = dependencies; + this.errors.push(err); + if (bail) { + callback(err); + } else { + callback(); + } + }; + const warningAndCallback = err => { + err.origin = module; + this.warnings.push(err); + callback(); + }; - var target = {}; - if (!skipNormalization) { - base = parse(serialize(base, options), options); //normalize base components - relative = parse(serialize(relative, options), options); //normalize relative components - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - //target.authority = relative.authority; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { - //target.authority = relative.authority; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== undefined) { - target.query = relative.query; - } else { - target.query = base.query; - } - } else { - if (relative.path.charAt(0) === "/") { - target.path = removeDotSegments(relative.path); - } else { - if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { - target.path = "/" + relative.path; - } else if (!base.path) { - target.path = relative.path; - } else { - target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; - } - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - //target.authority = base.authority; - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target; -} - -function resolve(baseURI, relativeURI, options) { - var schemelessOptions = assign({ scheme: 'null' }, options); - return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); -} - -function normalize(uri, options) { - if (typeof uri === "string") { - uri = serialize(parse(uri, options), options); - } else if (typeOf(uri) === "object") { - uri = parse(serialize(uri, options), options); - } - return uri; -} + const semaphore = this.semaphore; + semaphore.acquire(() => { + const factory = item.factory; + factory.create( + { + contextInfo: { + issuer: module.nameForCondition && module.nameForCondition(), + compiler: this.compiler.name + }, + resolveOptions: module.resolveOptions, + context: module.context, + dependencies: dependencies + }, + (err, dependentModule) => { + let afterFactory; -function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = serialize(parse(uriA, options), options); - } else if (typeOf(uriA) === "object") { - uriA = serialize(uriA, options); - } - if (typeof uriB === "string") { - uriB = serialize(parse(uriB, options), options); - } else if (typeOf(uriB) === "object") { - uriB = serialize(uriB, options); - } - return uriA === uriB; -} + const isOptional = () => { + return dependencies.every(d => d.optional); + }; -function escapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); -} + const errorOrWarningAndCallback = err => { + if (isOptional()) { + return warningAndCallback(err); + } else { + return errorAndCallback(err); + } + }; -function unescapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); -} + if (err) { + semaphore.release(); + return errorOrWarningAndCallback( + new ModuleNotFoundError(module, err) + ); + } + if (!dependentModule) { + semaphore.release(); + return process.nextTick(callback); + } + if (currentProfile) { + afterFactory = Date.now(); + currentProfile.factory = afterFactory - start; + } -var handler = { - scheme: "http", - domainHost: true, - parse: function parse(components, options) { - //report missing host - if (!components.host) { - components.error = components.error || "HTTP URIs must have a host."; - } - return components; - }, - serialize: function serialize(components, options) { - //normalize the default port - if (components.port === (String(components.scheme).toLowerCase() !== "https" ? 80 : 443) || components.port === "") { - components.port = undefined; - } - //normalize the empty path - if (!components.path) { - components.path = "/"; - } - //NOTE: We do not parse query strings for HTTP URIs - //as WWW Form Url Encoded query strings are part of the HTML4+ spec, - //and not the HTTP spec. - return components; - } -}; + const iterationDependencies = depend => { + for (let index = 0; index < depend.length; index++) { + const dep = depend[index]; + dep.module = dependentModule; + dependentModule.addReason(module, dep); + } + }; -var handler$1 = { - scheme: "https", - domainHost: handler.domainHost, - parse: handler.parse, - serialize: handler.serialize -}; + const addModuleResult = this.addModule( + dependentModule, + cacheGroup + ); + dependentModule = addModuleResult.module; + iterationDependencies(dependencies); -var O = {}; -var isIRI = true; -//RFC 3986 -var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]"; -var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive -var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded -//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = -//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; -//const WSP$$ = "[\\x20\\x09]"; -//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) -//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext -//const VCHAR$$ = "[\\x21-\\x7E]"; -//const WSP$$ = "[\\x20\\x09]"; -//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext -//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); -//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); -//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); -var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; -var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; -var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); -var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; -var UNRESERVED = new RegExp(UNRESERVED$$, "g"); -var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); -var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); -var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); -var NOT_HFVALUE = NOT_HFNAME; -function decodeUnreserved(str) { - var decStr = pctDecChars(str); - return !decStr.match(UNRESERVED) ? str : decStr; -} -var handler$2 = { - scheme: "mailto", - parse: function parse$$1(components, options) { - var mailtoComponents = components; - var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; - mailtoComponents.path = undefined; - if (mailtoComponents.query) { - var unknownHeaders = false; - var headers = {}; - var hfields = mailtoComponents.query.split("&"); - for (var x = 0, xl = hfields.length; x < xl; ++x) { - var hfield = hfields[x].split("="); - switch (hfield[0]) { - case "to": - var toAddrs = hfield[1].split(","); - for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { - to.push(toAddrs[_x]); - } - break; - case "subject": - mailtoComponents.subject = unescapeComponent(hfield[1], options); - break; - case "body": - mailtoComponents.body = unescapeComponent(hfield[1], options); - break; - default: - unknownHeaders = true; - headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); - break; - } - } - if (unknownHeaders) mailtoComponents.headers = headers; - } - mailtoComponents.query = undefined; - for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { - var addr = to[_x2].split("@"); - addr[0] = unescapeComponent(addr[0]); - if (!options.unicodeSupport) { - //convert Unicode IDN -> ASCII IDN - try { - addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); - } catch (e) { - mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; - } - } else { - addr[1] = unescapeComponent(addr[1], options).toLowerCase(); - } - to[_x2] = addr.join("@"); - } - return mailtoComponents; - }, - serialize: function serialize$$1(mailtoComponents, options) { - var components = mailtoComponents; - var to = toArray(mailtoComponents.to); - if (to) { - for (var x = 0, xl = to.length; x < xl; ++x) { - var toAddr = String(to[x]); - var atIdx = toAddr.lastIndexOf("@"); - var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); - var domain = toAddr.slice(atIdx + 1); - //convert IDN via punycode - try { - domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); - } catch (e) { - components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; - } - to[x] = localPart + "@" + domain; - } - components.path = to.join(","); - } - var headers = mailtoComponents.headers = mailtoComponents.headers || {}; - if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; - if (mailtoComponents.body) headers["body"] = mailtoComponents.body; - var fields = []; - for (var name in headers) { - if (headers[name] !== O[name]) { - fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); - } - } - if (fields.length) { - components.query = fields.join("&"); - } - return components; - } -}; + const afterBuild = () => { + if (recursive && addModuleResult.dependencies) { + this.processModuleDependencies(dependentModule, callback); + } else { + return callback(); + } + }; -var URN_PARSE = /^([^\:]+)\:(.*)/; -//RFC 2141 -var handler$3 = { - scheme: "urn", - parse: function parse$$1(components, options) { - var matches = components.path && components.path.match(URN_PARSE); - var urnComponents = components; - if (matches) { - var scheme = options.scheme || urnComponents.scheme || "urn"; - var nid = matches[1].toLowerCase(); - var nss = matches[2]; - var urnScheme = scheme + ":" + (options.nid || nid); - var schemeHandler = SCHEMES[urnScheme]; - urnComponents.nid = nid; - urnComponents.nss = nss; - urnComponents.path = undefined; - if (schemeHandler) { - urnComponents = schemeHandler.parse(urnComponents, options); - } - } else { - urnComponents.error = urnComponents.error || "URN can not be parsed."; - } - return urnComponents; - }, - serialize: function serialize$$1(urnComponents, options) { - var scheme = options.scheme || urnComponents.scheme || "urn"; - var nid = urnComponents.nid; - var urnScheme = scheme + ":" + (options.nid || nid); - var schemeHandler = SCHEMES[urnScheme]; - if (schemeHandler) { - urnComponents = schemeHandler.serialize(urnComponents, options); - } - var uriComponents = urnComponents; - var nss = urnComponents.nss; - uriComponents.path = (nid || options.nid) + ":" + nss; - return uriComponents; - } -}; + if (addModuleResult.issuer) { + if (currentProfile) { + dependentModule.profile = currentProfile; + } -var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; -//RFC 4122 -var handler$4 = { - scheme: "urn:uuid", - parse: function parse(urnComponents, options) { - var uuidComponents = urnComponents; - uuidComponents.uuid = uuidComponents.nss; - uuidComponents.nss = undefined; - if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { - uuidComponents.error = uuidComponents.error || "UUID is not valid."; - } - return uuidComponents; - }, - serialize: function serialize(uuidComponents, options) { - var urnComponents = uuidComponents; - //normalize UUID - urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); - return urnComponents; - } -}; + dependentModule.issuer = module; + } else { + if (this.profile) { + if (module.profile) { + const time = Date.now() - start; + if ( + !module.profile.dependencies || + time > module.profile.dependencies + ) { + module.profile.dependencies = time; + } + } + } + } -SCHEMES[handler.scheme] = handler; -SCHEMES[handler$1.scheme] = handler$1; -SCHEMES[handler$2.scheme] = handler$2; -SCHEMES[handler$3.scheme] = handler$3; -SCHEMES[handler$4.scheme] = handler$4; + if (addModuleResult.build) { + this.buildModule( + dependentModule, + isOptional(), + module, + dependencies, + err => { + if (err) { + semaphore.release(); + return errorOrWarningAndCallback(err); + } -exports.SCHEMES = SCHEMES; -exports.pctEncChar = pctEncChar; -exports.pctDecChars = pctDecChars; -exports.parse = parse; -exports.removeDotSegments = removeDotSegments; -exports.serialize = serialize; -exports.resolveComponents = resolveComponents; -exports.resolve = resolve; -exports.normalize = normalize; -exports.equal = equal; -exports.escapeComponent = escapeComponent; -exports.unescapeComponent = unescapeComponent; + if (currentProfile) { + const afterBuilding = Date.now(); + currentProfile.building = afterBuilding - afterFactory; + } -Object.defineProperty(exports, '__esModule', { value: true }); + semaphore.release(); + afterBuild(); + } + ); + } else { + semaphore.release(); + this.waitForBuildingFinished(dependentModule, afterBuild); + } + } + ); + }); + }, + err => { + // In V8, the Error objects keep a reference to the functions on the stack. These warnings & + // errors are created inside closures that keep a reference to the Compilation, so errors are + // leaking the Compilation object. -}))); -//# sourceMappingURL=uri.all.js.map + if (err) { + // eslint-disable-next-line no-self-assign + err.stack = err.stack; + return callback(err); + } + return process.nextTick(callback); + } + ); + } -/***/ }), + /** + * + * @param {string} context context string path + * @param {Dependency} dependency dependency used to create Module chain + * @param {OnModuleCallback} onModule function invoked on modules creation + * @param {ModuleChainCallback} callback callback for when module chain is complete + * @returns {void} will throw if dependency instance is not a valid Dependency + */ + _addModuleChain(context, dependency, onModule, callback) { + const start = this.profile && Date.now(); + const currentProfile = this.profile && {}; -/***/ 67806: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const errorAndCallback = this.bail + ? err => { + callback(err); + } + : err => { + err.dependencies = [dependency]; + this.errors.push(err); + callback(); + }; -// Copyright 2014 Simon Lydell -// X11 (“MIT”) Licensed. (See LICENSE.) - -var path = __webpack_require__(85622) - -"use strict" - -function urix(aPath) { - if (path.sep === "\\") { - return aPath - .replace(/\\/g, "/") - .replace(/^[a-z]:\/?/i, "/") - } - return aPath -} - -module.exports = urix + if ( + typeof dependency !== "object" || + dependency === null || + !dependency.constructor + ) { + throw new Error("Parameter 'dependency' must be a Dependency"); + } + const Dep = /** @type {DepConstructor} */ (dependency.constructor); + const moduleFactory = this.dependencyFactories.get(Dep); + if (!moduleFactory) { + throw new Error( + `No dependency factory available for this dependency type: ${dependency.constructor.name}` + ); + } + this.semaphore.acquire(() => { + moduleFactory.create( + { + contextInfo: { + issuer: "", + compiler: this.compiler.name + }, + context: context, + dependencies: [dependency] + }, + (err, module) => { + if (err) { + this.semaphore.release(); + return errorAndCallback(new EntryModuleNotFoundError(err)); + } -/***/ }), + let afterFactory; -/***/ 77709: -/***/ (function(module) { + if (currentProfile) { + afterFactory = Date.now(); + currentProfile.factory = afterFactory - start; + } -"use strict"; -/*! - * use - * - * Copyright (c) 2015-2017, Jon Schlinkert. - * Released under the MIT License. - */ + const addModuleResult = this.addModule(module); + module = addModuleResult.module; + onModule(module); + dependency.module = module; + module.addReason(null, dependency); -module.exports = function base(app, options) { - if (!isObject(app) && typeof app !== 'function') { - throw new TypeError('expected an object or function'); - } - - var opts = isObject(options) ? options : {}; - var prop = typeof opts.prop === 'string' ? opts.prop : 'fns'; - if (!Array.isArray(app[prop])) { - define(app, prop, []); - } - - /** - * Define a plugin function to be passed to use. The only - * parameter exposed to the plugin is `app`, the object or function. - * passed to `use(app)`. `app` is also exposed as `this` in plugins. - * - * Additionally, **if a plugin returns a function, the function will - * be pushed onto the `fns` array**, allowing the plugin to be - * called at a later point by the `run` method. - * - * ```js - * var use = require('use'); - * - * // define a plugin - * function foo(app) { - * // do stuff - * } - * - * var app = function(){}; - * use(app); - * - * // register plugins - * app.use(foo); - * app.use(bar); - * app.use(baz); - * ``` - * @name .use - * @param {Function} `fn` plugin function to call - * @api public - */ + const afterBuild = () => { + if (addModuleResult.dependencies) { + this.processModuleDependencies(module, err => { + if (err) return callback(err); + callback(null, module); + }); + } else { + return callback(null, module); + } + }; - define(app, 'use', use); + if (addModuleResult.issuer) { + if (currentProfile) { + module.profile = currentProfile; + } + } - /** - * Run all plugins on `fns`. Any plugin that returns a function - * when called by `use` is pushed onto the `fns` array. - * - * ```js - * var config = {}; - * app.run(config); - * ``` - * @name .run - * @param {Object} `value` Object to be modified by plugins. - * @return {Object} Returns the object passed to `run` - * @api public - */ + if (addModuleResult.build) { + this.buildModule(module, false, null, null, err => { + if (err) { + this.semaphore.release(); + return errorAndCallback(err); + } - define(app, 'run', function(val) { - if (!isObject(val)) return; + if (currentProfile) { + const afterBuilding = Date.now(); + currentProfile.building = afterBuilding - afterFactory; + } - if (!val.use || !val.run) { - define(val, prop, val[prop] || []); - define(val, 'use', use); - } + this.semaphore.release(); + afterBuild(); + }); + } else { + this.semaphore.release(); + this.waitForBuildingFinished(module, afterBuild); + } + } + ); + }); + } - if (!val[prop] || val[prop].indexOf(base) === -1) { - val.use(base); - } + /** + * + * @param {string} context context path for entry + * @param {Dependency} entry entry dependency being created + * @param {string} name name of entry + * @param {ModuleCallback} callback callback function + * @returns {void} returns + */ + addEntry(context, entry, name, callback) { + this.hooks.addEntry.call(entry, name); - var self = this || app; - var fns = self[prop]; - var len = fns.length; - var idx = -1; + const slot = { + name: name, + // TODO webpack 5 remove `request` + request: null, + module: null + }; - while (++idx < len) { - val.use(fns[idx]); - } - return val; - }); + if (entry instanceof ModuleDependency) { + slot.request = entry.request; + } - /** - * Call plugin `fn`. If a function is returned push it into the - * `fns` array to be called by the `run` method. - */ + // TODO webpack 5: merge modules instead when multiple entry modules are supported + const idx = this._preparedEntrypoints.findIndex(slot => slot.name === name); + if (idx >= 0) { + // Overwrite existing entrypoint + this._preparedEntrypoints[idx] = slot; + } else { + this._preparedEntrypoints.push(slot); + } + this._addModuleChain( + context, + entry, + module => { + this.entries.push(module); + }, + (err, module) => { + if (err) { + this.hooks.failedEntry.call(entry, name, err); + return callback(err); + } - function use(type, fn, options) { - var offset = 1; + if (module) { + slot.module = module; + } else { + const idx = this._preparedEntrypoints.indexOf(slot); + if (idx >= 0) { + this._preparedEntrypoints.splice(idx, 1); + } + } + this.hooks.succeedEntry.call(entry, name, module); + return callback(null, module); + } + ); + } - if (typeof type === 'string' || Array.isArray(type)) { - fn = wrap(type, fn); - offset++; - } else { - options = fn; - fn = type; - } + /** + * @param {string} context context path string + * @param {Dependency} dependency dep used to create module + * @param {ModuleCallback} callback module callback sending module up a level + * @returns {void} + */ + prefetch(context, dependency, callback) { + this._addModuleChain( + context, + dependency, + module => { + module.prefetched = true; + }, + callback + ); + } - if (typeof fn !== 'function') { - throw new TypeError('expected a function'); - } + /** + * @param {Module} module module to be rebuilt + * @param {Callback} thisCallback callback when module finishes rebuilding + * @returns {void} + */ + rebuildModule(module, thisCallback) { + let callbackList = this._rebuildingModules.get(module); + if (callbackList) { + callbackList.push(thisCallback); + return; + } + this._rebuildingModules.set(module, (callbackList = [thisCallback])); - var self = this || app; - var fns = self[prop]; + const callback = err => { + this._rebuildingModules.delete(module); + for (const cb of callbackList) { + cb(err); + } + }; - var args = [].slice.call(arguments, offset); - args.unshift(self); + this.hooks.rebuildModule.call(module); + const oldDependencies = module.dependencies.slice(); + const oldVariables = module.variables.slice(); + const oldBlocks = module.blocks.slice(); + module.unbuild(); + this.buildModule(module, false, module, null, err => { + if (err) { + this.hooks.finishRebuildingModule.call(module); + return callback(err); + } - if (typeof opts.hook === 'function') { - opts.hook.apply(self, args); - } + this.processModuleDependencies(module, err => { + if (err) return callback(err); + this.removeReasonsOfDependencyBlock(module, { + dependencies: oldDependencies, + variables: oldVariables, + blocks: oldBlocks + }); + this.hooks.finishRebuildingModule.call(module); + callback(); + }); + }); + } - var val = fn.apply(self, args); - if (typeof val === 'function' && fns.indexOf(val) === -1) { - fns.push(val); - } - return self; - } + finish(callback) { + const modules = this.modules; + this.hooks.finishModules.callAsync(modules, err => { + if (err) return callback(err); - /** - * Wrap a named plugin function so that it's only called on objects of the - * given `type` - * - * @param {String} `type` - * @param {Function} `fn` Plugin function - * @return {Function} - */ + for (let index = 0; index < modules.length; index++) { + const module = modules[index]; + this.reportDependencyErrorsAndWarnings(module, [module]); + } - function wrap(type, fn) { - return function plugin() { - return this.type === type ? fn.apply(this, arguments) : plugin; - }; - } + callback(); + }); + } - return app; -}; + unseal() { + this.hooks.unseal.call(); + this.chunks.length = 0; + this.chunkGroups.length = 0; + this.namedChunks.clear(); + this.namedChunkGroups.clear(); + this.additionalChunkAssets.length = 0; + this.assets = {}; + this.assetsInfo.clear(); + for (const module of this.modules) { + module.unseal(); + } + } -function isObject(val) { - return val && typeof val === 'object' && !Array.isArray(val); -} + /** + * @param {Callback} callback signals when the seal method is finishes + * @returns {void} + */ + seal(callback) { + this.hooks.seal.call(); -function define(obj, key, val) { - Object.defineProperty(obj, key, { - configurable: true, - writable: true, - value: val - }); -} + while ( + this.hooks.optimizeDependenciesBasic.call(this.modules) || + this.hooks.optimizeDependencies.call(this.modules) || + this.hooks.optimizeDependenciesAdvanced.call(this.modules) + ) { + /* empty */ + } + this.hooks.afterOptimizeDependencies.call(this.modules); + this.hooks.beforeChunks.call(); + for (const preparedEntrypoint of this._preparedEntrypoints) { + const module = preparedEntrypoint.module; + const name = preparedEntrypoint.name; + const chunk = this.addChunk(name); + const entrypoint = new Entrypoint(name); + entrypoint.setRuntimeChunk(chunk); + entrypoint.addOrigin(null, name, preparedEntrypoint.request); + this.namedChunkGroups.set(name, entrypoint); + this.entrypoints.set(name, entrypoint); + this.chunkGroups.push(entrypoint); -/***/ }), + GraphHelpers.connectChunkGroupAndChunk(entrypoint, chunk); + GraphHelpers.connectChunkAndModule(chunk, module); -/***/ 92262: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + chunk.entryModule = module; + chunk.name = name; + this.assignDepth(module); + } + buildChunkGraph( + this, + /** @type {Entrypoint[]} */ (this.chunkGroups.slice()) + ); + this.sortModules(this.modules); + this.hooks.afterChunks.call(this.chunks); -/** - * For Node.js, simply re-export the core `util.deprecate` function. - */ + this.hooks.optimize.call(); -module.exports = __webpack_require__(31669).deprecate; + while ( + this.hooks.optimizeModulesBasic.call(this.modules) || + this.hooks.optimizeModules.call(this.modules) || + this.hooks.optimizeModulesAdvanced.call(this.modules) + ) { + /* empty */ + } + this.hooks.afterOptimizeModules.call(this.modules); + while ( + this.hooks.optimizeChunksBasic.call(this.chunks, this.chunkGroups) || + this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups) || + this.hooks.optimizeChunksAdvanced.call(this.chunks, this.chunkGroups) + ) { + /* empty */ + } + this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups); -/***/ }), + this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { + if (err) { + return callback(err); + } -/***/ 24059: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.hooks.afterOptimizeTree.call(this.chunks, this.modules); -module.exports = __webpack_require__(47257); + while ( + this.hooks.optimizeChunkModulesBasic.call(this.chunks, this.modules) || + this.hooks.optimizeChunkModules.call(this.chunks, this.modules) || + this.hooks.optimizeChunkModulesAdvanced.call(this.chunks, this.modules) + ) { + /* empty */ + } + this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules); + const shouldRecord = this.hooks.shouldRecord.call() !== false; -/***/ }), + this.hooks.reviveModules.call(this.modules, this.records); + this.hooks.optimizeModuleOrder.call(this.modules); + this.hooks.advancedOptimizeModuleOrder.call(this.modules); + this.hooks.beforeModuleIds.call(this.modules); + this.hooks.moduleIds.call(this.modules); + this.applyModuleIds(); + this.hooks.optimizeModuleIds.call(this.modules); + this.hooks.afterOptimizeModuleIds.call(this.modules); -/***/ 71118: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.sortItemsWithModuleIds(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.hooks.reviveChunks.call(this.chunks, this.records); + this.hooks.optimizeChunkOrder.call(this.chunks); + this.hooks.beforeChunkIds.call(this.chunks); + this.applyChunkIds(); + this.hooks.optimizeChunkIds.call(this.chunks); + this.hooks.afterOptimizeChunkIds.call(this.chunks); + this.sortItemsWithChunkIds(); -const ConstDependency = __webpack_require__(71101); -const ParserHelpers = __webpack_require__(23999); + if (shouldRecord) { + this.hooks.recordModules.call(this.modules, this.records); + this.hooks.recordChunks.call(this.chunks, this.records); + } -const NullFactory = __webpack_require__(40438); + this.hooks.beforeHash.call(); + this.createHash(); + this.hooks.afterHash.call(); -/* eslint-disable camelcase */ -const REPLACEMENTS = { - __webpack_require__: "__webpack_require__", - __webpack_public_path__: "__webpack_require__.p", - __webpack_modules__: "__webpack_require__.m", - __webpack_chunk_load__: "__webpack_require__.e", - __non_webpack_require__: "require", - __webpack_nonce__: "__webpack_require__.nc", - "require.onError": "__webpack_require__.oe" -}; -const NO_WEBPACK_REQUIRE = { - __non_webpack_require__: true -}; -const REPLACEMENT_TYPES = { - __webpack_public_path__: "string", - __webpack_require__: "function", - __webpack_modules__: "object", - __webpack_chunk_load__: "function", - __webpack_nonce__: "string" -}; -/* eslint-enable camelcase */ + if (shouldRecord) { + this.hooks.recordHash.call(this.records); + } -class APIPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "APIPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set(ConstDependency, new NullFactory()); - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); + this.hooks.beforeModuleAssets.call(); + this.createModuleAssets(); + if (this.hooks.shouldGenerateChunkAssets.call() !== false) { + this.hooks.beforeChunkAssets.call(); + this.createChunkAssets(); + } + this.hooks.additionalChunkAssets.call(this.chunks); + this.summarizeDependencies(); + if (shouldRecord) { + this.hooks.record.call(this, this.records); + } - const handler = parser => { - Object.keys(REPLACEMENTS).forEach(key => { - parser.hooks.expression - .for(key) - .tap( - "APIPlugin", - NO_WEBPACK_REQUIRE[key] - ? ParserHelpers.toConstantDependency( - parser, - REPLACEMENTS[key] - ) - : ParserHelpers.toConstantDependencyWithWebpackRequire( - parser, - REPLACEMENTS[key] - ) - ); - const type = REPLACEMENT_TYPES[key]; - if (type) { - parser.hooks.evaluateTypeof - .for(key) - .tap("APIPlugin", ParserHelpers.evaluateToString(type)); + this.hooks.additionalAssets.callAsync(err => { + if (err) { + return callback(err); + } + this.hooks.optimizeChunkAssets.callAsync(this.chunks, err => { + if (err) { + return callback(err); + } + this.hooks.afterOptimizeChunkAssets.call(this.chunks); + this.hooks.optimizeAssets.callAsync(this.assets, err => { + if (err) { + return callback(err); + } + this.hooks.afterOptimizeAssets.call(this.assets); + if (this.hooks.needAdditionalSeal.call()) { + this.unseal(); + return this.seal(callback); } + return this.hooks.afterSeal.callAsync(callback); }); - }; - - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("APIPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("APIPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("APIPlugin", handler); - } - ); + }); + }); + }); } -} - -module.exports = APIPlugin; - -/***/ }), - -/***/ 36104: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -const WebpackError = __webpack_require__(97391); -const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/; - -/** - * @param {string=} method method name - * @returns {string} message - */ -function createMessage(method) { - return `Abstract method${method ? " " + method : ""}. Must be overridden.`; -} - -/** - * @constructor - */ -function Message() { - this.stack = undefined; - Error.captureStackTrace(this); - /** @type {RegExpMatchArray} */ - const match = this.stack.split("\n")[3].match(CURRENT_METHOD_REGEXP); - - this.message = match && match[1] ? createMessage(match[1]) : createMessage(); -} - -/** - * Error for abstract method - * @example - * class FooClass { - * abstractMethod() { - * throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overriden. - * } - * } - * - */ -class AbstractMethodError extends WebpackError { - constructor() { - super(new Message().message); - this.name = "AbstractMethodError"; + /** + * @param {Module[]} modules the modules array on compilation to perform the sort for + * @returns {void} + */ + sortModules(modules) { + // TODO webpack 5: this should only be enabled when `moduleIds: "natural"` + // TODO move it into a plugin (NaturalModuleIdsPlugin) and use this in WebpackOptionsApply + // TODO remove this method + modules.sort(byIndexOrIdentifier); } -} - -module.exports = AbstractMethodError; + /** + * @param {Module} module moulde to report from + * @param {DependenciesBlock[]} blocks blocks to report from + * @returns {void} + */ + reportDependencyErrorsAndWarnings(module, blocks) { + for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { + const block = blocks[indexBlock]; + const dependencies = block.dependencies; -/***/ }), + for (let indexDep = 0; indexDep < dependencies.length; indexDep++) { + const d = dependencies[indexDep]; -/***/ 9701: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const warnings = d.getWarnings(); + if (warnings) { + for (let indexWar = 0; indexWar < warnings.length; indexWar++) { + const w = warnings[indexWar]; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ + const warning = new ModuleDependencyWarning(module, w, d.loc); + this.warnings.push(warning); + } + } + const errors = d.getErrors(); + if (errors) { + for (let indexErr = 0; indexErr < errors.length; indexErr++) { + const e = errors[indexErr]; + const error = new ModuleDependencyError(module, e, d.loc); + this.errors.push(error); + } + } + } + this.reportDependencyErrorsAndWarnings(module, block.blocks); + } + } -const { ConcatSource } = __webpack_require__(53665); -const Template = __webpack_require__(96066); + /** + * @param {TODO} groupOptions options for the chunk group + * @param {Module} module the module the references the chunk group + * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module) + * @param {string} request the request from which the the chunk group is referenced + * @returns {ChunkGroup} the new or existing chunk group + */ + addChunkInGroup(groupOptions, module, loc, request) { + if (typeof groupOptions === "string") { + groupOptions = { name: groupOptions }; + } + const name = groupOptions.name; + if (name) { + const chunkGroup = this.namedChunkGroups.get(name); + if (chunkGroup !== undefined) { + chunkGroup.addOptions(groupOptions); + if (module) { + chunkGroup.addOrigin(module, loc, request); + } + return chunkGroup; + } + } + const chunkGroup = new ChunkGroup(groupOptions); + if (module) chunkGroup.addOrigin(module, loc, request); + const chunk = this.addChunk(name); -/** @typedef {import("./Compilation")} Compilation */ + GraphHelpers.connectChunkGroupAndChunk(chunkGroup, chunk); -/** - * @typedef {Object} AmdMainTemplatePluginOptions - * @param {string=} name the library name - * @property {boolean=} requireAsWrapper - */ + this.chunkGroups.push(chunkGroup); + if (name) { + this.namedChunkGroups.set(name, chunkGroup); + } + return chunkGroup; + } -class AmdMainTemplatePlugin { /** - * @param {AmdMainTemplatePluginOptions} options the plugin options + * This method first looks to see if a name is provided for a new chunk, + * and first looks to see if any named chunks already exist and reuse that chunk instead. + * + * @param {string=} name optional chunk name to be provided + * @returns {Chunk} create a chunk (invoked during seal event) */ - constructor(options) { - if (!options || typeof options === "string") { - this.name = options; - this.requireAsWrapper = false; - } else { - this.name = options.name; - this.requireAsWrapper = options.requireAsWrapper; + addChunk(name) { + if (name) { + const chunk = this.namedChunks.get(name); + if (chunk !== undefined) { + return chunk; + } } + const chunk = new Chunk(name); + this.chunks.push(chunk); + if (name) { + this.namedChunks.set(name, chunk); + } + return chunk; } /** - * @param {Compilation} compilation the compilation instance + * @param {Module} module module to assign depth * @returns {void} */ - apply(compilation) { - const { mainTemplate, chunkTemplate } = compilation; + assignDepth(module) { + const queue = new Set([module]); + let depth; - const onRenderWithEntry = (source, chunk, hash) => { - const externals = chunk.getModules().filter(m => m.external); - const externalsDepsArray = JSON.stringify( - externals.map(m => - typeof m.request === "object" ? m.request.amd : m.request - ) - ); - const externalsArguments = externals - .map( - m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` - ) - .join(", "); + module.depth = 0; - if (this.requireAsWrapper) { - return new ConcatSource( - `require(${externalsDepsArray}, function(${externalsArguments}) { return `, - source, - "});" - ); - } else if (this.name) { - const name = mainTemplate.getAssetPath(this.name, { - hash, - chunk - }); + /** + * @param {Module} module module for processeing + * @returns {void} + */ + const enqueueJob = module => { + const d = module.depth; + if (typeof d === "number" && d <= depth) return; + queue.add(module); + module.depth = depth; + }; - return new ConcatSource( - `define(${JSON.stringify( - name - )}, ${externalsDepsArray}, function(${externalsArguments}) { return `, - source, - "});" - ); - } else if (externalsArguments) { - return new ConcatSource( - `define(${externalsDepsArray}, function(${externalsArguments}) { return `, - source, - "});" - ); - } else { - return new ConcatSource("define(function() { return ", source, "});"); + /** + * @param {Dependency} dependency dependency to assign depth to + * @returns {void} + */ + const assignDepthToDependency = dependency => { + if (dependency.module) { + enqueueJob(dependency.module); } }; - for (const template of [mainTemplate, chunkTemplate]) { - template.hooks.renderWithEntry.tap( - "AmdMainTemplatePlugin", - onRenderWithEntry - ); - } - - mainTemplate.hooks.globalHashPaths.tap("AmdMainTemplatePlugin", paths => { - if (this.name) { - paths.push(this.name); + /** + * @param {DependenciesBlock} block block to assign depth to + * @returns {void} + */ + const assignDepthToDependencyBlock = block => { + if (block.variables) { + iterationBlockVariable(block.variables, assignDepthToDependency); } - return paths; - }); - mainTemplate.hooks.hash.tap("AmdMainTemplatePlugin", hash => { - hash.update("exports amd"); - if (this.name) { - hash.update(this.name); + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, assignDepthToDependency); } - }); - } -} - -module.exports = AmdMainTemplatePlugin; - - -/***/ }), - -/***/ 22814: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const DependenciesBlock = __webpack_require__(16071); + if (block.blocks) { + iterationOfArrayCallback(block.blocks, assignDepthToDependencyBlock); + } + }; -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./util/createHash").Hash} Hash */ -/** @typedef {TODO} GroupOptions */ + for (module of queue) { + queue.delete(module); + depth = module.depth; -module.exports = class AsyncDependenciesBlock extends DependenciesBlock { - /** - * @param {GroupOptions} groupOptions options for the group - * @param {Module} module the Module object - * @param {DependencyLocation=} loc the line of code - * @param {TODO=} request the request - */ - constructor(groupOptions, module, loc, request) { - super(); - if (typeof groupOptions === "string") { - groupOptions = { name: groupOptions }; - } else if (!groupOptions) { - groupOptions = { name: undefined }; + depth++; + assignDepthToDependencyBlock(module); } - this.groupOptions = groupOptions; - /** @type {ChunkGroup=} */ - this.chunkGroup = undefined; - this.module = module; - this.loc = loc; - this.request = request; - /** @type {DependenciesBlock} */ - this.parent = undefined; } /** - * @returns {string} The name of the chunk + * @param {Module} module the module containing the dependency + * @param {Dependency} dependency the dependency + * @returns {DependencyReference} a reference for the dependency */ - get chunkName() { - return this.groupOptions.name; + getDependencyReference(module, dependency) { + // TODO remove dep.getReference existence check in webpack 5 + if (typeof dependency.getReference !== "function") return null; + const ref = dependency.getReference(); + if (!ref) return null; + return this.hooks.dependencyReference.call(ref, dependency, module); } /** - * @param {string} value The new chunk name + * + * @param {Module} module module relationship for removal + * @param {DependenciesBlockLike} block //TODO: good description * @returns {void} */ - set chunkName(value) { - this.groupOptions.name = value; - } - - /** - * @returns {never} this throws and should never be called - */ - get chunks() { - throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); - } + removeReasonsOfDependencyBlock(module, block) { + const iteratorDependency = d => { + if (!d.module) { + return; + } + if (d.module.removeReason(module, d)) { + for (const chunk of d.module.chunksIterable) { + this.patchChunksAfterReasonRemoval(d.module, chunk); + } + } + }; - /** - * @param {never} value setter value - * @returns {never} this is going to throw therefore we should throw type - * assertions by returning never - */ - set chunks(value) { - throw new Error("Moved to AsyncDependenciesBlock.chunkGroup"); - } + if (block.blocks) { + iterationOfArrayCallback(block.blocks, block => + this.removeReasonsOfDependencyBlock(module, block) + ); + } - /** - * @param {Hash} hash the hash used to track block changes, from "crypto" module - * @returns {void} - */ - updateHash(hash) { - hash.update(JSON.stringify(this.groupOptions)); - hash.update( - (this.chunkGroup && - this.chunkGroup.chunks - .map(chunk => { - return chunk.id !== null ? chunk.id : ""; - }) - .join(",")) || - "" - ); - super.updateHash(hash); - } + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, iteratorDependency); + } - /** - * @returns {void} - */ - disconnect() { - this.chunkGroup = undefined; - super.disconnect(); + if (block.variables) { + iterationBlockVariable(block.variables, iteratorDependency); + } } /** + * @param {Module} module module to patch tie + * @param {Chunk} chunk chunk to patch tie * @returns {void} */ - unseal() { - this.chunkGroup = undefined; - super.unseal(); + patchChunksAfterReasonRemoval(module, chunk) { + if (!module.hasReasons()) { + this.removeReasonsOfDependencyBlock(module, module); + } + if (!module.hasReasonForChunk(chunk)) { + if (module.removeChunk(chunk)) { + this.removeChunkFromDependencies(module, chunk); + } + } } /** + * + * @param {DependenciesBlock} block block tie for Chunk + * @param {Chunk} chunk chunk to remove from dep * @returns {void} */ - sortItems() { - super.sortItems(); - } -}; + removeChunkFromDependencies(block, chunk) { + const iteratorDependency = d => { + if (!d.module) { + return; + } + this.patchChunksAfterReasonRemoval(d.module, chunk); + }; + const blocks = block.blocks; + for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { + const asyncBlock = blocks[indexBlock]; + // Grab all chunks from the first Block's AsyncDepBlock + const chunks = asyncBlock.chunkGroup.chunks; + // For each chunk in chunkGroup + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const iteratedChunk = chunks[indexChunk]; + asyncBlock.chunkGroup.removeChunk(iteratedChunk); + asyncBlock.chunkGroup.removeParent(iteratedChunk); + // Recurse + this.removeChunkFromDependencies(block, iteratedChunk); + } + } -/***/ }), + if (block.dependencies) { + iterationOfArrayCallback(block.dependencies, iteratorDependency); + } -/***/ 67089: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (block.variables) { + iterationBlockVariable(block.variables, iteratorDependency); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ + applyModuleIds() { + const unusedIds = []; + let nextFreeModuleId = 0; + const usedIds = new Set(); + if (this.usedModuleIds) { + for (const id of this.usedModuleIds) { + usedIds.add(id); + } + } + const modules1 = this.modules; + for (let indexModule1 = 0; indexModule1 < modules1.length; indexModule1++) { + const module1 = modules1[indexModule1]; + if (module1.id !== null) { + usedIds.add(module1.id); + } + } -const WebpackError = __webpack_require__(97391); + if (usedIds.size > 0) { + let usedIdMax = -1; + for (const usedIdKey of usedIds) { + if (typeof usedIdKey !== "number") { + continue; + } -/** @typedef {import("./Module")} Module */ + usedIdMax = Math.max(usedIdMax, usedIdKey); + } -class AsyncDependencyToInitialChunkError extends WebpackError { - /** - * Creates an instance of AsyncDependencyToInitialChunkError. - * @param {string} chunkName Name of Chunk - * @param {Module} module module tied to dependency - * @param {TODO} loc location of dependency - */ - constructor(chunkName, module, loc) { - super( - `It's not allowed to load an initial chunk on demand. The chunk name "${chunkName}" is already used by an entrypoint.` - ); + let lengthFreeModules = (nextFreeModuleId = usedIdMax + 1); - this.name = "AsyncDependencyToInitialChunkError"; - this.module = module; - this.loc = loc; + while (lengthFreeModules--) { + if (!usedIds.has(lengthFreeModules)) { + unusedIds.push(lengthFreeModules); + } + } + } - Error.captureStackTrace(this, this.constructor); + const modules2 = this.modules; + for (let indexModule2 = 0; indexModule2 < modules2.length; indexModule2++) { + const module2 = modules2[indexModule2]; + if (module2.id === null) { + if (unusedIds.length > 0) { + module2.id = unusedIds.pop(); + } else { + module2.id = nextFreeModuleId++; + } + } + } } -} -module.exports = AsyncDependencyToInitialChunkError; + applyChunkIds() { + /** @type {Set} */ + const usedIds = new Set(); + // Get used ids from usedChunkIds property (i. e. from records) + if (this.usedChunkIds) { + for (const id of this.usedChunkIds) { + if (typeof id !== "number") { + continue; + } -/***/ }), + usedIds.add(id); + } + } -/***/ 51596: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Get used ids from existing chunks + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const chunk = chunks[indexChunk]; + const usedIdValue = chunk.id; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (typeof usedIdValue !== "number") { + continue; + } + usedIds.add(usedIdValue); + } -const asyncLib = __webpack_require__(36386); -const PrefetchDependency = __webpack_require__(14237); -const NormalModule = __webpack_require__(25963); + // Calculate maximum assigned chunk id + let nextFreeChunkId = -1; + for (const id of usedIds) { + nextFreeChunkId = Math.max(nextFreeChunkId, id); + } + nextFreeChunkId++; -/** @typedef {import("./Compiler")} Compiler */ + // Determine free chunk ids from 0 to maximum + /** @type {number[]} */ + const unusedIds = []; + if (nextFreeChunkId > 0) { + let index = nextFreeChunkId; + while (index--) { + if (!usedIds.has(index)) { + unusedIds.push(index); + } + } + } -class AutomaticPrefetchPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler Webpack Compiler - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "AutomaticPrefetchPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - PrefetchDependency, - normalModuleFactory - ); + // Assign ids to chunk which has no id + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const chunk = chunks[indexChunk]; + if (chunk.id === null) { + if (unusedIds.length > 0) { + chunk.id = unusedIds.pop(); + } else { + chunk.id = nextFreeChunkId++; + } } - ); - let lastModules = null; - compiler.hooks.afterCompile.tap("AutomaticPrefetchPlugin", compilation => { - lastModules = compilation.modules - .filter(m => m instanceof NormalModule) - .map((/** @type {NormalModule} */ m) => ({ - context: m.context, - request: m.request - })); - }); - compiler.hooks.make.tapAsync( - "AutomaticPrefetchPlugin", - (compilation, callback) => { - if (!lastModules) return callback(); - asyncLib.forEach( - lastModules, - (m, callback) => { - compilation.prefetch( - m.context || compiler.context, - new PrefetchDependency(m.request), - callback - ); - }, - callback - ); + if (!chunk.ids) { + chunk.ids = [chunk.id]; } - ); + } } -} -module.exports = AutomaticPrefetchPlugin; - - -/***/ }), - -/***/ 4009: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ - - - -const { ConcatSource } = __webpack_require__(53665); -const ModuleFilenameHelpers = __webpack_require__(71474); -const Template = __webpack_require__(96066); + sortItemsWithModuleIds() { + this.modules.sort(byIdOrIdentifier); -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(10171); + const modules = this.modules; + for (let indexModule = 0; indexModule < modules.length; indexModule++) { + modules[indexModule].sortItems(false); + } -/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginArgument} BannerPluginArgument */ -/** @typedef {import("../declarations/plugins/BannerPlugin").BannerPluginOptions} BannerPluginOptions */ + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + chunks[indexChunk].sortItems(); + } -const wrapComment = str => { - if (!str.includes("\n")) { - return Template.toComment(str); + chunks.sort((a, b) => a.compareTo(b)); } - return `/*!\n * ${str - .replace(/\*\//g, "* /") - .split("\n") - .join("\n * ")}\n */`; -}; -class BannerPlugin { - /** - * @param {BannerPluginArgument} options options object - */ - constructor(options) { - if (arguments.length > 1) { - throw new Error( - "BannerPlugin only takes one argument (pass an options object)" - ); + sortItemsWithChunkIds() { + for (const chunkGroup of this.chunkGroups) { + chunkGroup.sortItems(); } - validateOptions(schema, options, "Banner Plugin"); + this.chunks.sort(byId); - if (typeof options === "string" || typeof options === "function") { - options = { - banner: options - }; + for ( + let indexModule = 0; + indexModule < this.modules.length; + indexModule++ + ) { + this.modules[indexModule].sortItems(true); } - /** @type {BannerPluginOptions} */ - this.options = options; - - const bannerOption = options.banner; - if (typeof bannerOption === "function") { - const getBanner = bannerOption; - this.banner = this.options.raw - ? getBanner - : data => wrapComment(getBanner(data)); - } else { - const banner = this.options.raw - ? bannerOption - : wrapComment(bannerOption); - this.banner = () => banner; + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + chunks[indexChunk].sortItems(); } - } - - apply(compiler) { - const options = this.options; - const banner = this.banner; - const matchObject = ModuleFilenameHelpers.matchObject.bind( - undefined, - options - ); - - compiler.hooks.compilation.tap("BannerPlugin", compilation => { - compilation.hooks.optimizeChunkAssets.tap("BannerPlugin", chunks => { - for (const chunk of chunks) { - if (options.entryOnly && !chunk.canBeInitial()) { - continue; - } - - for (const file of chunk.files) { - if (!matchObject(file)) { - continue; - } - let query = ""; - let filename = file; - const hash = compilation.hash; - const querySplit = filename.indexOf("?"); - - if (querySplit >= 0) { - query = filename.substr(querySplit); - filename = filename.substr(0, querySplit); - } - - const lastSlashIndex = filename.lastIndexOf("/"); - - const basename = - lastSlashIndex === -1 - ? filename - : filename.substr(lastSlashIndex + 1); - - const data = { - hash, - chunk, - filename, - basename, - query - }; - - const comment = compilation.getPath(banner(data), data); + /** + * Used to sort errors and warnings in compilation. this.warnings, and + * this.errors contribute to the compilation hash and therefore should be + * updated whenever other references (having a chunk id) are sorted. This preserves the hash + * integrity + * + * @param {WebpackError} a first WebpackError instance (including subclasses) + * @param {WebpackError} b second WebpackError instance (including subclasses) + * @returns {-1|0|1} sort order index + */ + const byMessage = (a, b) => { + const ma = `${a.message}`; + const mb = `${b.message}`; + if (ma < mb) return -1; + if (mb < ma) return 1; + return 0; + }; - compilation.updateAsset( - file, - old => new ConcatSource(comment, "\n", old) - ); - } - } - }); - }); + this.errors.sort(byMessage); + this.warnings.sort(byMessage); + this.children.sort(byNameOrHash); } -} - -module.exports = BannerPlugin; - - -/***/ }), -/***/ 96770: -/***/ (function(module) { + summarizeDependencies() { + this.fileDependencies = new SortableSet(this.compilationDependencies); + this.contextDependencies = new SortableSet(); + this.missingDependencies = new SortableSet(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + for ( + let indexChildren = 0; + indexChildren < this.children.length; + indexChildren++ + ) { + const child = this.children[indexChildren]; + addAllToSet(this.fileDependencies, child.fileDependencies); + addAllToSet(this.contextDependencies, child.contextDependencies); + addAllToSet(this.missingDependencies, child.missingDependencies); + } + for ( + let indexModule = 0; + indexModule < this.modules.length; + indexModule++ + ) { + const module = this.modules[indexModule]; -const TypeUnknown = 0; -const TypeNull = 1; -const TypeString = 2; -const TypeNumber = 3; -const TypeBoolean = 4; -const TypeRegExp = 5; -const TypeConditional = 6; -const TypeArray = 7; -const TypeConstArray = 8; -const TypeIdentifier = 9; -const TypeWrapped = 10; -const TypeTemplateString = 11; + if (module.buildInfo.fileDependencies) { + addAllToSet(this.fileDependencies, module.buildInfo.fileDependencies); + } + if (module.buildInfo.contextDependencies) { + addAllToSet( + this.contextDependencies, + module.buildInfo.contextDependencies + ); + } + } + for (const error of this.errors) { + if ( + typeof error.missing === "object" && + error.missing && + error.missing[Symbol.iterator] + ) { + addAllToSet(this.missingDependencies, error.missing); + } + } + this.fileDependencies.sort(); + this.contextDependencies.sort(); + this.missingDependencies.sort(); + } -class BasicEvaluatedExpression { - constructor() { - this.type = TypeUnknown; - this.range = null; - this.falsy = false; - this.truthy = false; - this.bool = null; - this.number = null; - this.regExp = null; - this.string = null; - this.quasis = null; - this.parts = null; - this.array = null; - this.items = null; - this.options = null; - this.prefix = null; - this.postfix = null; - this.wrappedInnerExpressions = null; - this.expression = null; + createHash() { + const outputOptions = this.outputOptions; + const hashFunction = outputOptions.hashFunction; + const hashDigest = outputOptions.hashDigest; + const hashDigestLength = outputOptions.hashDigestLength; + const hash = createHash(hashFunction); + if (outputOptions.hashSalt) { + hash.update(outputOptions.hashSalt); + } + this.mainTemplate.updateHash(hash); + this.chunkTemplate.updateHash(hash); + for (const key of Object.keys(this.moduleTemplates).sort()) { + this.moduleTemplates[key].updateHash(hash); + } + for (const child of this.children) { + hash.update(child.hash); + } + for (const warning of this.warnings) { + hash.update(`${warning.message}`); + } + for (const error of this.errors) { + hash.update(`${error.message}`); + } + const modules = this.modules; + for (let i = 0; i < modules.length; i++) { + const module = modules[i]; + const moduleHash = createHash(hashFunction); + module.updateHash(moduleHash); + module.hash = /** @type {string} */ (moduleHash.digest(hashDigest)); + module.renderedHash = module.hash.substr(0, hashDigestLength); + } + // clone needed as sort below is inplace mutation + const chunks = this.chunks.slice(); + /** + * sort here will bring all "falsy" values to the beginning + * this is needed as the "hasRuntime()" chunks are dependent on the + * hashes of the non-runtime chunks. + */ + chunks.sort((a, b) => { + const aEntry = a.hasRuntime(); + const bEntry = b.hasRuntime(); + if (aEntry && !bEntry) return 1; + if (!aEntry && bEntry) return -1; + return byId(a, b); + }); + for (let i = 0; i < chunks.length; i++) { + const chunk = chunks[i]; + const chunkHash = createHash(hashFunction); + try { + if (outputOptions.hashSalt) { + chunkHash.update(outputOptions.hashSalt); + } + chunk.updateHash(chunkHash); + const template = chunk.hasRuntime() + ? this.mainTemplate + : this.chunkTemplate; + template.updateHashForChunk( + chunkHash, + chunk, + this.moduleTemplates.javascript, + this.dependencyTemplates + ); + this.hooks.chunkHash.call(chunk, chunkHash); + chunk.hash = /** @type {string} */ (chunkHash.digest(hashDigest)); + hash.update(chunk.hash); + chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); + this.hooks.contentHash.call(chunk); + } catch (err) { + this.errors.push(new ChunkRenderError(chunk, "", err)); + } + } + this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); + this.hash = this.fullHash.substr(0, hashDigestLength); } - isNull() { - return this.type === TypeNull; + /** + * @param {string} update extra information + * @returns {void} + */ + modifyHash(update) { + const outputOptions = this.outputOptions; + const hashFunction = outputOptions.hashFunction; + const hashDigest = outputOptions.hashDigest; + const hashDigestLength = outputOptions.hashDigestLength; + const hash = createHash(hashFunction); + hash.update(this.fullHash); + hash.update(update); + this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); + this.hash = this.fullHash.substr(0, hashDigestLength); } - isString() { - return this.type === TypeString; + /** + * @param {string} file file name + * @param {Source} source asset source + * @param {AssetInfo} assetInfo extra asset information + * @returns {void} + */ + emitAsset(file, source, assetInfo = {}) { + if (this.assets[file]) { + if (!isSourceEqual(this.assets[file], source)) { + // TODO webpack 5: make this an error instead + this.warnings.push( + new WebpackError( + `Conflict: Multiple assets emit different content to the same filename ${file}` + ) + ); + this.assets[file] = source; + this.assetsInfo.set(file, assetInfo); + return; + } + const oldInfo = this.assetsInfo.get(file); + this.assetsInfo.set(file, Object.assign({}, oldInfo, assetInfo)); + return; + } + this.assets[file] = source; + this.assetsInfo.set(file, assetInfo); } - isNumber() { - return this.type === TypeNumber; + /** + * @param {string} file file name + * @param {Source | function(Source): Source} newSourceOrFunction new asset source or function converting old to new + * @param {AssetInfo | function(AssetInfo | undefined): AssetInfo} assetInfoUpdateOrFunction new asset info or function converting old to new + */ + updateAsset( + file, + newSourceOrFunction, + assetInfoUpdateOrFunction = undefined + ) { + if (!this.assets[file]) { + throw new Error( + `Called Compilation.updateAsset for not existing filename ${file}` + ); + } + if (typeof newSourceOrFunction === "function") { + this.assets[file] = newSourceOrFunction(this.assets[file]); + } else { + this.assets[file] = newSourceOrFunction; + } + if (assetInfoUpdateOrFunction !== undefined) { + const oldInfo = this.assetsInfo.get(file); + if (typeof assetInfoUpdateOrFunction === "function") { + this.assetsInfo.set(file, assetInfoUpdateOrFunction(oldInfo || {})); + } else { + this.assetsInfo.set( + file, + Object.assign({}, oldInfo, assetInfoUpdateOrFunction) + ); + } + } } - isBoolean() { - return this.type === TypeBoolean; + getAssets() { + /** @type {Asset[]} */ + const array = []; + for (const assetName of Object.keys(this.assets)) { + if (Object.prototype.hasOwnProperty.call(this.assets, assetName)) { + array.push({ + name: assetName, + source: this.assets[assetName], + info: this.assetsInfo.get(assetName) || {} + }); + } + } + return array; } - isRegExp() { - return this.type === TypeRegExp; + /** + * @param {string} name the name of the asset + * @returns {Asset | undefined} the asset or undefined when not found + */ + getAsset(name) { + if (!Object.prototype.hasOwnProperty.call(this.assets, name)) + return undefined; + return { + name, + source: this.assets[name], + info: this.assetsInfo.get(name) || {} + }; } - isConditional() { - return this.type === TypeConditional; - } - - isArray() { - return this.type === TypeArray; - } - - isConstArray() { - return this.type === TypeConstArray; + createModuleAssets() { + for (let i = 0; i < this.modules.length; i++) { + const module = this.modules[i]; + if (module.buildInfo.assets) { + const assetsInfo = module.buildInfo.assetsInfo; + for (const assetName of Object.keys(module.buildInfo.assets)) { + const fileName = this.getPath(assetName); + this.emitAsset( + fileName, + module.buildInfo.assets[assetName], + assetsInfo ? assetsInfo.get(assetName) : undefined + ); + this.hooks.moduleAsset.call(module, fileName); + } + } + } } - isIdentifier() { - return this.type === TypeIdentifier; - } + createChunkAssets() { + const outputOptions = this.outputOptions; + const cachedSourceMap = new Map(); + /** @type {Map} */ + const alreadyWrittenFiles = new Map(); + for (let i = 0; i < this.chunks.length; i++) { + const chunk = this.chunks[i]; + chunk.files = []; + let source; + let file; + let filenameTemplate; + try { + const template = chunk.hasRuntime() + ? this.mainTemplate + : this.chunkTemplate; + const manifest = template.getRenderManifest({ + chunk, + hash: this.hash, + fullHash: this.fullHash, + outputOptions, + moduleTemplates: this.moduleTemplates, + dependencyTemplates: this.dependencyTemplates + }); // [{ render(), filenameTemplate, pathOptions, identifier, hash }] + for (const fileManifest of manifest) { + const cacheName = fileManifest.identifier; + const usedHash = fileManifest.hash; + filenameTemplate = fileManifest.filenameTemplate; + const pathAndInfo = this.getPathWithInfo( + filenameTemplate, + fileManifest.pathOptions + ); + file = pathAndInfo.path; + const assetInfo = pathAndInfo.info; - isWrapped() { - return this.type === TypeWrapped; + // check if the same filename was already written by another chunk + const alreadyWritten = alreadyWrittenFiles.get(file); + if (alreadyWritten !== undefined) { + if (alreadyWritten.hash === usedHash) { + if (this.cache) { + this.cache[cacheName] = { + hash: usedHash, + source: alreadyWritten.source + }; + } + chunk.files.push(file); + this.hooks.chunkAsset.call(chunk, file); + continue; + } else { + throw new Error( + `Conflict: Multiple chunks emit assets to the same filename ${file}` + + ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})` + ); + } + } + if ( + this.cache && + this.cache[cacheName] && + this.cache[cacheName].hash === usedHash + ) { + source = this.cache[cacheName].source; + } else { + source = fileManifest.render(); + // Ensure that source is a cached source to avoid additional cost because of repeated access + if (!(source instanceof CachedSource)) { + const cacheEntry = cachedSourceMap.get(source); + if (cacheEntry) { + source = cacheEntry; + } else { + const cachedSource = new CachedSource(source); + cachedSourceMap.set(source, cachedSource); + source = cachedSource; + } + } + if (this.cache) { + this.cache[cacheName] = { + hash: usedHash, + source + }; + } + } + this.emitAsset(file, source, assetInfo); + chunk.files.push(file); + this.hooks.chunkAsset.call(chunk, file); + alreadyWrittenFiles.set(file, { + hash: usedHash, + source, + chunk + }); + } + } catch (err) { + this.errors.push( + new ChunkRenderError(chunk, file || filenameTemplate, err) + ); + } + } } - isTemplateString() { - return this.type === TypeTemplateString; + /** + * @param {string} filename used to get asset path with hash + * @param {TODO=} data // TODO: figure out this param type + * @returns {string} interpolated path + */ + getPath(filename, data) { + data = data || {}; + data.hash = data.hash || this.hash; + return this.mainTemplate.getAssetPath(filename, data); } - isTruthy() { - return this.truthy; + /** + * @param {string} filename used to get asset path with hash + * @param {TODO=} data // TODO: figure out this param type + * @returns {{ path: string, info: AssetInfo }} interpolated path and asset info + */ + getPathWithInfo(filename, data) { + data = data || {}; + data.hash = data.hash || this.hash; + return this.mainTemplate.getAssetPathWithInfo(filename, data); } - isFalsy() { - return this.falsy; + /** + * This function allows you to run another instance of webpack inside of webpack however as + * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins + * from parent (or top level compiler) and creates a child Compilation + * + * @param {string} name name of the child compiler + * @param {TODO} outputOptions // Need to convert config schema to types for this + * @param {Plugin[]} plugins webpack plugins that will be applied + * @returns {Compiler} creates a child Compiler instance + */ + createChildCompiler(name, outputOptions, plugins) { + const idx = this.childrenCounters[name] || 0; + this.childrenCounters[name] = idx + 1; + return this.compiler.createChildCompiler( + this, + name, + idx, + outputOptions, + plugins + ); } - asBool() { - if (this.truthy) return true; - if (this.falsy) return false; - if (this.isBoolean()) return this.bool; - if (this.isNull()) return false; - if (this.isString()) return this.string !== ""; - if (this.isNumber()) return this.number !== 0; - if (this.isRegExp()) return true; - if (this.isArray()) return true; - if (this.isConstArray()) return true; - if (this.isWrapped()) { - return (this.prefix && this.prefix.asBool()) || - (this.postfix && this.postfix.asBool()) - ? true - : undefined; - } - if (this.isTemplateString()) { - const str = this.asString(); - if (typeof str === "string") return str !== ""; - } - return undefined; - } + checkConstraints() { + /** @type {Set} */ + const usedIds = new Set(); - asString() { - if (this.isBoolean()) return `${this.bool}`; - if (this.isNull()) return "null"; - if (this.isString()) return this.string; - if (this.isNumber()) return `${this.number}`; - if (this.isRegExp()) return `${this.regExp}`; - if (this.isArray()) { - let array = []; - for (const item of this.items) { - const itemStr = item.asString(); - if (itemStr === undefined) return undefined; - array.push(itemStr); + const modules = this.modules; + for (let indexModule = 0; indexModule < modules.length; indexModule++) { + const moduleId = modules[indexModule].id; + if (moduleId === null) continue; + if (usedIds.has(moduleId)) { + throw new Error(`checkConstraints: duplicate module id ${moduleId}`); } - return `${array}`; + usedIds.add(moduleId); } - if (this.isConstArray()) return `${this.array}`; - if (this.isTemplateString()) { - let str = ""; - for (const part of this.parts) { - const partStr = part.asString(); - if (partStr === undefined) return undefined; - str += partStr; + + const chunks = this.chunks; + for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { + const chunk = chunks[indexChunk]; + if (chunks.indexOf(chunk) !== indexChunk) { + throw new Error( + `checkConstraints: duplicate chunk in compilation ${chunk.debugId}` + ); } - return str; } - return undefined; - } - - setString(string) { - this.type = TypeString; - this.string = string; - return this; - } - - setNull() { - this.type = TypeNull; - return this; - } - - setNumber(number) { - this.type = TypeNumber; - this.number = number; - return this; - } - - setBoolean(bool) { - this.type = TypeBoolean; - this.bool = bool; - return this; - } - - setRegExp(regExp) { - this.type = TypeRegExp; - this.regExp = regExp; - return this; - } - - setIdentifier(identifier) { - this.type = TypeIdentifier; - this.identifier = identifier; - return this; - } - - setWrapped(prefix, postfix, innerExpressions) { - this.type = TypeWrapped; - this.prefix = prefix; - this.postfix = postfix; - this.wrappedInnerExpressions = innerExpressions; - return this; - } - - setOptions(options) { - this.type = TypeConditional; - this.options = options; - return this; - } - addOptions(options) { - if (!this.options) { - this.type = TypeConditional; - this.options = []; - } - for (const item of options) { - this.options.push(item); + for (const chunkGroup of this.chunkGroups) { + chunkGroup.checkConstraints(); } - return this; - } - - setItems(items) { - this.type = TypeArray; - this.items = items; - return this; - } - - setArray(array) { - this.type = TypeConstArray; - this.array = array; - return this; - } - - setTemplateString(quasis, parts, kind) { - this.type = TypeTemplateString; - this.quasis = quasis; - this.parts = parts; - this.templateStringKind = kind; - return this; - } - - setTruthy() { - this.falsy = false; - this.truthy = true; - return this; - } - - setFalsy() { - this.falsy = true; - this.truthy = false; - return this; } +} - setRange(range) { - this.range = range; - return this; - } +// TODO remove in webpack 5 +Compilation.prototype.applyPlugins = util.deprecate( + /** + * @deprecated + * @param {string} name Name + * @param {any[]} args Other arguments + * @returns {void} + * @this {Compilation} + */ + function(name, ...args) { + this.hooks[ + name.replace(/[- ]([a-z])/g, match => match[1].toUpperCase()) + ].call(...args); + }, + "Compilation.applyPlugins is deprecated. Use new API on `.hooks` instead" +); - setExpression(expression) { - this.expression = expression; - return this; - } -} +// TODO remove in webpack 5 +Object.defineProperty(Compilation.prototype, "moduleTemplate", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {Compilation} + * @returns {TODO} module template + */ + function() { + return this.moduleTemplates.javascript; + }, + "Compilation.moduleTemplate: Use Compilation.moduleTemplates.javascript instead" + ), + set: util.deprecate( + /** + * @deprecated + * @param {ModuleTemplate} value Template value + * @this {Compilation} + * @returns {void} + */ + function(value) { + this.moduleTemplates.javascript = value; + }, + "Compilation.moduleTemplate: Use Compilation.moduleTemplates.javascript instead." + ) +}); -module.exports = BasicEvaluatedExpression; +module.exports = Compilation; /***/ }), -/***/ 6465: +/***/ 58705: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -69873,1063 +70420,767 @@ module.exports = BasicEvaluatedExpression; */ +const parseJson = __webpack_require__(48335); const asyncLib = __webpack_require__(36386); +const path = __webpack_require__(85622); +const { Source } = __webpack_require__(53665); +const util = __webpack_require__(31669); +const { + Tapable, + SyncHook, + SyncBailHook, + AsyncParallelHook, + AsyncSeriesHook +} = __webpack_require__(56758); -class CachePlugin { - constructor(cache) { - this.cache = cache || {}; - this.FS_ACCURACY = 2000; - } - - apply(compiler) { - if (Array.isArray(compiler.compilers)) { - compiler.compilers.forEach((c, idx) => { - new CachePlugin((this.cache[idx] = this.cache[idx] || {})).apply(c); - }); - } else { - const registerCacheToCompiler = (compiler, cache) => { - compiler.hooks.thisCompilation.tap("CachePlugin", compilation => { - compilation.cache = cache; - compilation.hooks.childCompiler.tap( - "CachePlugin", - (childCompiler, compilerName, compilerIndex) => { - let childCache; - if (!cache.children) { - cache.children = {}; - } - if (!cache.children[compilerName]) { - cache.children[compilerName] = []; - } - if (cache.children[compilerName][compilerIndex]) { - childCache = cache.children[compilerName][compilerIndex]; - } else { - cache.children[compilerName].push((childCache = {})); - } - registerCacheToCompiler(childCompiler, childCache); - } - ); - }); - }; - registerCacheToCompiler(compiler, this.cache); - compiler.hooks.watchRun.tap("CachePlugin", () => { - this.watching = true; - }); - compiler.hooks.run.tapAsync("CachePlugin", (compiler, callback) => { - if (!compiler._lastCompilationFileDependencies) { - return callback(); - } - const fs = compiler.inputFileSystem; - const fileTs = (compiler.fileTimestamps = new Map()); - asyncLib.forEach( - compiler._lastCompilationFileDependencies, - (file, callback) => { - fs.stat(file, (err, stat) => { - if (err) { - if (err.code === "ENOENT") return callback(); - return callback(err); - } +const Compilation = __webpack_require__(34968); +const Stats = __webpack_require__(99977); +const Watching = __webpack_require__(29580); +const NormalModuleFactory = __webpack_require__(22298); +const ContextModuleFactory = __webpack_require__(88239); +const ResolverFactory = __webpack_require__(50588); - if (stat.mtime) this.applyMtime(+stat.mtime); +const RequestShortener = __webpack_require__(54254); +const { makePathsRelative } = __webpack_require__(94658); +const ConcurrentCompilationError = __webpack_require__(18933); +const { Logger } = __webpack_require__(47194); - fileTs.set(file, +stat.mtime || Infinity); +/** @typedef {import("../declarations/WebpackOptions").Entry} Entry */ +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ - callback(); - }); - }, - err => { - if (err) return callback(err); +/** + * @typedef {Object} CompilationParams + * @property {NormalModuleFactory} normalModuleFactory + * @property {ContextModuleFactory} contextModuleFactory + * @property {Set} compilationDependencies + */ - for (const [file, ts] of fileTs) { - fileTs.set(file, ts + this.FS_ACCURACY); - } +class Compiler extends Tapable { + constructor(context) { + super(); + this.hooks = { + /** @type {SyncBailHook} */ + shouldEmit: new SyncBailHook(["compilation"]), + /** @type {AsyncSeriesHook} */ + done: new AsyncSeriesHook(["stats"]), + /** @type {AsyncSeriesHook<>} */ + additionalPass: new AsyncSeriesHook([]), + /** @type {AsyncSeriesHook} */ + beforeRun: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook} */ + run: new AsyncSeriesHook(["compiler"]), + /** @type {AsyncSeriesHook} */ + emit: new AsyncSeriesHook(["compilation"]), + /** @type {AsyncSeriesHook} */ + assetEmitted: new AsyncSeriesHook(["file", "content"]), + /** @type {AsyncSeriesHook} */ + afterEmit: new AsyncSeriesHook(["compilation"]), - callback(); - } - ); - }); - compiler.hooks.afterCompile.tap("CachePlugin", compilation => { - compilation.compiler._lastCompilationFileDependencies = - compilation.fileDependencies; - compilation.compiler._lastCompilationContextDependencies = - compilation.contextDependencies; - }); - } - } - - /* istanbul ignore next */ - applyMtime(mtime) { - if (this.FS_ACCURACY > 1 && mtime % 2 !== 0) this.FS_ACCURACY = 1; - else if (this.FS_ACCURACY > 10 && mtime % 20 !== 0) this.FS_ACCURACY = 10; - else if (this.FS_ACCURACY > 100 && mtime % 200 !== 0) - this.FS_ACCURACY = 100; - else if (this.FS_ACCURACY > 1000 && mtime % 2000 !== 0) - this.FS_ACCURACY = 1000; - } -} -module.exports = CachePlugin; + /** @type {SyncHook} */ + thisCompilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook} */ + compilation: new SyncHook(["compilation", "params"]), + /** @type {SyncHook} */ + normalModuleFactory: new SyncHook(["normalModuleFactory"]), + /** @type {SyncHook} */ + contextModuleFactory: new SyncHook(["contextModulefactory"]), + /** @type {AsyncSeriesHook} */ + beforeCompile: new AsyncSeriesHook(["params"]), + /** @type {SyncHook} */ + compile: new SyncHook(["params"]), + /** @type {AsyncParallelHook} */ + make: new AsyncParallelHook(["compilation"]), + /** @type {AsyncSeriesHook} */ + afterCompile: new AsyncSeriesHook(["compilation"]), -/***/ }), + /** @type {AsyncSeriesHook} */ + watchRun: new AsyncSeriesHook(["compiler"]), + /** @type {SyncHook} */ + failed: new SyncHook(["error"]), + /** @type {SyncHook} */ + invalid: new SyncHook(["filename", "changeTime"]), + /** @type {SyncHook} */ + watchClose: new SyncHook([]), -/***/ 8335: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** @type {SyncBailHook} */ + infrastructureLog: new SyncBailHook(["origin", "type", "args"]), -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // TODO the following hooks are weirdly located here + // TODO move them for webpack 5 + /** @type {SyncHook} */ + environment: new SyncHook([]), + /** @type {SyncHook} */ + afterEnvironment: new SyncHook([]), + /** @type {SyncHook} */ + afterPlugins: new SyncHook(["compiler"]), + /** @type {SyncHook} */ + afterResolvers: new SyncHook(["compiler"]), + /** @type {SyncBailHook} */ + entryOption: new SyncBailHook(["context", "entry"]) + }; + // TODO webpack 5 remove this + this.hooks.infrastructurelog = this.hooks.infrastructureLog; + this._pluginCompat.tap("Compiler", options => { + switch (options.name) { + case "additional-pass": + case "before-run": + case "run": + case "emit": + case "after-emit": + case "before-compile": + case "make": + case "after-compile": + case "watch-run": + options.async = true; + break; + } + }); -const WebpackError = __webpack_require__(97391); + /** @type {string=} */ + this.name = undefined; + /** @type {Compilation=} */ + this.parentCompilation = undefined; + /** @type {string} */ + this.outputPath = ""; -/** @typedef {import("./Module")} Module */ + this.outputFileSystem = null; + this.inputFileSystem = null; -/** - * @param {Module[]} modules the modules to be sorted - * @returns {Module[]} sorted version of original modules - */ -const sortModules = modules => { - return modules.slice().sort((a, b) => { - const aIdent = a.identifier(); - const bIdent = b.identifier(); - /* istanbul ignore next */ - if (aIdent < bIdent) return -1; - /* istanbul ignore next */ - if (aIdent > bIdent) return 1; - /* istanbul ignore next */ - return 0; - }); -}; + /** @type {string|null} */ + this.recordsInputPath = null; + /** @type {string|null} */ + this.recordsOutputPath = null; + this.records = {}; + this.removedFiles = new Set(); + /** @type {Map} */ + this.fileTimestamps = new Map(); + /** @type {Map} */ + this.contextTimestamps = new Map(); + /** @type {ResolverFactory} */ + this.resolverFactory = new ResolverFactory(); -/** - * @param {Module[]} modules each module from throw - * @returns {string} each message from provided moduels - */ -const createModulesListMessage = modules => { - return modules - .map(m => { - let message = `* ${m.identifier()}`; - const validReasons = m.reasons.filter(reason => reason.module); + this.infrastructureLogger = undefined; - if (validReasons.length > 0) { - message += `\n Used by ${validReasons.length} module(s), i. e.`; - message += `\n ${validReasons[0].module.identifier()}`; + // TODO remove in webpack 5 + this.resolvers = { + normal: { + plugins: util.deprecate((hook, fn) => { + this.resolverFactory.plugin("resolver normal", resolver => { + resolver.plugin(hook, fn); + }); + }, "webpack: Using compiler.resolvers.normal is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver normal", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), + apply: util.deprecate((...args) => { + this.resolverFactory.plugin("resolver normal", resolver => { + resolver.apply(...args); + }); + }, "webpack: Using compiler.resolvers.normal is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver normal", resolver => {\n resolver.apply(/* … */);\n}); instead.') + }, + loader: { + plugins: util.deprecate((hook, fn) => { + this.resolverFactory.plugin("resolver loader", resolver => { + resolver.plugin(hook, fn); + }); + }, "webpack: Using compiler.resolvers.loader is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver loader", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), + apply: util.deprecate((...args) => { + this.resolverFactory.plugin("resolver loader", resolver => { + resolver.apply(...args); + }); + }, "webpack: Using compiler.resolvers.loader is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver loader", resolver => {\n resolver.apply(/* … */);\n}); instead.') + }, + context: { + plugins: util.deprecate((hook, fn) => { + this.resolverFactory.plugin("resolver context", resolver => { + resolver.plugin(hook, fn); + }); + }, "webpack: Using compiler.resolvers.context is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver context", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), + apply: util.deprecate((...args) => { + this.resolverFactory.plugin("resolver context", resolver => { + resolver.apply(...args); + }); + }, "webpack: Using compiler.resolvers.context is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver context", resolver => {\n resolver.apply(/* … */);\n}); instead.') } - return message; - }) - .join("\n"); -}; + }; -class CaseSensitiveModulesWarning extends WebpackError { - /** - * Creates an instance of CaseSensitiveModulesWarning. - * @param {Module[]} modules modules that were detected - */ - constructor(modules) { - const sortedModules = sortModules(modules); - const modulesList = createModulesListMessage(sortedModules); - super(`There are multiple modules with names that only differ in casing. -This can lead to unexpected behavior when compiling on a filesystem with other case-semantic. -Use equal casing. Compare these module identifiers: -${modulesList}`); + /** @type {WebpackOptions} */ + this.options = /** @type {WebpackOptions} */ ({}); - this.name = "CaseSensitiveModulesWarning"; - this.origin = this.module = sortedModules[0]; + this.context = context; - Error.captureStackTrace(this, this.constructor); + this.requestShortener = new RequestShortener(context); + + /** @type {boolean} */ + this.running = false; + + /** @type {boolean} */ + this.watchMode = false; + + /** @private @type {WeakMap }>} */ + this._assetEmittingSourceCache = new WeakMap(); + /** @private @type {Map} */ + this._assetEmittingWrittenFiles = new Map(); } -} -module.exports = CaseSensitiveModulesWarning; + /** + * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name + * @returns {Logger} a logger with that name + */ + getInfrastructureLogger(name) { + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called without a name" + ); + } + return new Logger((type, args) => { + if (typeof name === "function") { + name = name(); + if (!name) { + throw new TypeError( + "Compiler.getInfrastructureLogger(name) called with a function not returning a name" + ); + } + } + if (this.hooks.infrastructureLog.call(name, type, args) === undefined) { + if (this.infrastructureLogger !== undefined) { + this.infrastructureLogger(name, type, args); + } + } + }); + } + watch(watchOptions, handler) { + if (this.running) return handler(new ConcurrentCompilationError()); -/***/ }), + this.running = true; + this.watchMode = true; + this.fileTimestamps = new Map(); + this.contextTimestamps = new Map(); + this.removedFiles = new Set(); + return new Watching(this, watchOptions, handler); + } -/***/ 2919: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + run(callback) { + if (this.running) return callback(new ConcurrentCompilationError()); -"use strict"; -/* -MIT License http://www.opensource.org/licenses/mit-license.php -Author Tobias Koppers @sokra -*/ + const finalCallback = (err, stats) => { + this.running = false; + if (err) { + this.hooks.failed.call(err); + } -const util = __webpack_require__(31669); -const SortableSet = __webpack_require__(50071); -const intersect = __webpack_require__(54262).intersect; -const GraphHelpers = __webpack_require__(32973); -const Entrypoint = __webpack_require__(71931); -let debugId = 1000; -const ERR_CHUNK_ENTRY = "Chunk.entry was removed. Use hasRuntime()"; -const ERR_CHUNK_INITIAL = - "Chunk.initial was removed. Use canBeInitial/isOnlyInitial()"; + if (callback !== undefined) return callback(err, stats); + }; -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./ModuleReason")} ModuleReason */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./util/createHash").Hash} Hash */ + const startTime = Date.now(); -/** - * @typedef {Object} WithId an object who has an id property * - * @property {string | number} id the id of the object - */ + this.running = true; -/** - * Compare two Modules based on their ids for sorting - * @param {Module} a module - * @param {Module} b module - * @returns {-1|0|1} sort value - */ + const onCompiled = (err, compilation) => { + if (err) return finalCallback(err); -// TODO use @callback -/** @typedef {(a: Module, b: Module) => -1|0|1} ModuleSortPredicate */ -/** @typedef {(m: Module) => boolean} ModuleFilterPredicate */ -/** @typedef {(c: Chunk) => boolean} ChunkFilterPredicate */ + if (this.hooks.shouldEmit.call(compilation) === false) { + const stats = new Stats(compilation); + stats.startTime = startTime; + stats.endTime = Date.now(); + this.hooks.done.callAsync(stats, err => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + }); + return; + } -const sortModuleById = (a, b) => { - if (a.id < b.id) return -1; - if (b.id < a.id) return 1; - return 0; -}; + this.emitAssets(compilation, err => { + if (err) return finalCallback(err); -/** - * Compare two ChunkGroups based on their ids for sorting - * @param {ChunkGroup} a chunk group - * @param {ChunkGroup} b chunk group - * @returns {-1|0|1} sort value - */ -const sortChunkGroupById = (a, b) => { - if (a.id < b.id) return -1; - if (b.id < a.id) return 1; - return 0; -}; + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; -/** - * Compare two Identifiables , based on their ids for sorting - * @param {Module} a first object with ident fn - * @param {Module} b second object with ident fn - * @returns {-1|0|1} The order number of the sort - */ -const sortByIdentifier = (a, b) => { - if (a.identifier() > b.identifier()) return 1; - if (a.identifier() < b.identifier()) return -1; - return 0; -}; + const stats = new Stats(compilation); + stats.startTime = startTime; + stats.endTime = Date.now(); + this.hooks.done.callAsync(stats, err => { + if (err) return finalCallback(err); -/** - * @returns {string} a concatenation of module identifiers sorted - * @param {SortableSet} set to pull module identifiers from - */ -const getModulesIdent = set => { - set.sort(); - let str = ""; - for (const m of set) { - str += m.identifier() + "#"; - } - return str; -}; + this.hooks.additionalPass.callAsync(err => { + if (err) return finalCallback(err); + this.compile(onCompiled); + }); + }); + return; + } -/** - * @template T - * @param {SortableSet} set the sortable set to convert to array - * @returns {Array} the array returned from Array.from(set) - */ -const getArray = set => Array.from(set); + this.emitRecords(err => { + if (err) return finalCallback(err); -/** - * @param {SortableSet} set the sortable Set to get the count/size of - * @returns {number} the size of the modules - */ -const getModulesSize = set => { - let size = 0; - for (const module of set) { - size += module.size(); - } - return size; -}; + const stats = new Stats(compilation); + stats.startTime = startTime; + stats.endTime = Date.now(); + this.hooks.done.callAsync(stats, err => { + if (err) return finalCallback(err); + return finalCallback(null, stats); + }); + }); + }); + }; -/** - * A Chunk is a unit of encapsulation for Modules. - * Chunks are "rendered" into bundles that get emitted when the build completes. - */ -class Chunk { - /** - * @param {string=} name of chunk being created, is optional (for subclasses) - */ - constructor(name) { - /** @type {number | null} */ - this.id = null; - /** @type {number[] | null} */ - this.ids = null; - /** @type {number} */ - this.debugId = debugId++; - /** @type {string} */ - this.name = name; - /** @type {boolean} */ - this.preventIntegration = false; - /** @type {Module=} */ - this.entryModule = undefined; - /** @private @type {SortableSet} */ - this._modules = new SortableSet(undefined, sortByIdentifier); - /** @type {string?} */ - this.filenameTemplate = undefined; - /** @private @type {SortableSet} */ - this._groups = new SortableSet(undefined, sortChunkGroupById); - /** @type {string[]} */ - this.files = []; - /** @type {boolean} */ - this.rendered = false; - /** @type {string=} */ - this.hash = undefined; - /** @type {Object} */ - this.contentHash = Object.create(null); - /** @type {string=} */ - this.renderedHash = undefined; - /** @type {string=} */ - this.chunkReason = undefined; - /** @type {boolean} */ - this.extraAsync = false; - this.removedModules = undefined; - } + this.hooks.beforeRun.callAsync(this, err => { + if (err) return finalCallback(err); - /** - * @deprecated Chunk.entry has been deprecated. Please use .hasRuntime() instead - * @returns {never} Throws an error trying to access this property - */ - get entry() { - throw new Error(ERR_CHUNK_ENTRY); - } + this.hooks.run.callAsync(this, err => { + if (err) return finalCallback(err); - /** - * @deprecated .entry has been deprecated. Please use .hasRuntime() instead - * @param {never} data The data that was attempting to be set - * @returns {never} Throws an error trying to access this property - */ - set entry(data) { - throw new Error(ERR_CHUNK_ENTRY); - } + this.readRecords(err => { + if (err) return finalCallback(err); - /** - * @deprecated Chunk.initial was removed. Use canBeInitial/isOnlyInitial() - * @returns {never} Throws an error trying to access this property - */ - get initial() { - throw new Error(ERR_CHUNK_INITIAL); + this.compile(onCompiled); + }); + }); + }); } - /** - * @deprecated Chunk.initial was removed. Use canBeInitial/isOnlyInitial() - * @param {never} data The data attempting to be set - * @returns {never} Throws an error trying to access this property - */ - set initial(data) { - throw new Error(ERR_CHUNK_INITIAL); - } + runAsChild(callback) { + this.compile((err, compilation) => { + if (err) return callback(err); - /** - * @returns {boolean} whether or not the Chunk will have a runtime - */ - hasRuntime() { - for (const chunkGroup of this._groups) { - if ( - chunkGroup.isInitial() && - chunkGroup instanceof Entrypoint && - chunkGroup.getRuntimeChunk() === this - ) { - return true; + this.parentCompilation.children.push(compilation); + for (const { name, source, info } of compilation.getAssets()) { + this.parentCompilation.emitAsset(name, source, info); } - } - return false; - } - /** - * @returns {boolean} whether or not this chunk can be an initial chunk - */ - canBeInitial() { - for (const chunkGroup of this._groups) { - if (chunkGroup.isInitial()) return true; - } - return false; + const entries = Array.from( + compilation.entrypoints.values(), + ep => ep.chunks + ).reduce((array, chunks) => { + return array.concat(chunks); + }, []); + + return callback(null, entries, compilation); + }); } - /** - * @returns {boolean} whether this chunk can only be an initial chunk - */ - isOnlyInitial() { - if (this._groups.size <= 0) return false; - for (const chunkGroup of this._groups) { - if (!chunkGroup.isInitial()) return false; + purgeInputFileSystem() { + if (this.inputFileSystem && this.inputFileSystem.purge) { + this.inputFileSystem.purge(); } - return true; } - /** - * @returns {boolean} if this chunk contains the entry module - */ - hasEntryModule() { - return !!this.entryModule; - } + emitAssets(compilation, callback) { + let outputPath; + const emitFiles = err => { + if (err) return callback(err); - /** - * @param {Module} module the module that will be added to this chunk. - * @returns {boolean} returns true if the chunk doesn't have the module and it was added - */ - addModule(module) { - if (!this._modules.has(module)) { - this._modules.add(module); - return true; - } - return false; - } + asyncLib.forEachLimit( + compilation.getAssets(), + 15, + ({ name: file, source }, callback) => { + let targetFile = file; + const queryStringIdx = targetFile.indexOf("?"); + if (queryStringIdx >= 0) { + targetFile = targetFile.substr(0, queryStringIdx); + } - /** - * @param {Module} module the module that will be removed from this chunk - * @returns {boolean} returns true if chunk exists and is successfully deleted - */ - removeModule(module) { - if (this._modules.delete(module)) { - module.removeChunk(this); - return true; - } - return false; - } + const writeOut = err => { + if (err) return callback(err); + const targetPath = this.outputFileSystem.join( + outputPath, + targetFile + ); + // TODO webpack 5 remove futureEmitAssets option and make it on by default + if (this.options.output.futureEmitAssets) { + // check if the target file has already been written by this Compiler + const targetFileGeneration = this._assetEmittingWrittenFiles.get( + targetPath + ); - /** - * @param {Module[]} modules the new modules to be set - * @returns {void} set new modules to this chunk and return nothing - */ - setModules(modules) { - this._modules = new SortableSet(modules, sortByIdentifier); - } + // create an cache entry for this Source if not already existing + let cacheEntry = this._assetEmittingSourceCache.get(source); + if (cacheEntry === undefined) { + cacheEntry = { + sizeOnlySource: undefined, + writtenTo: new Map() + }; + this._assetEmittingSourceCache.set(source, cacheEntry); + } - /** - * @returns {number} the amount of modules in chunk - */ - getNumberOfModules() { - return this._modules.size; - } + // if the target file has already been written + if (targetFileGeneration !== undefined) { + // check if the Source has been written to this target file + const writtenGeneration = cacheEntry.writtenTo.get(targetPath); + if (writtenGeneration === targetFileGeneration) { + // if yes, we skip writing the file + // as it's already there + // (we assume one doesn't remove files while the Compiler is running) - /** - * @returns {SortableSet} return the modules SortableSet for this chunk - */ - get modulesIterable() { - return this._modules; - } + compilation.updateAsset(file, cacheEntry.sizeOnlySource, { + size: cacheEntry.sizeOnlySource.size() + }); - /** - * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being added - * @returns {boolean} returns true if chunk is not apart of chunkGroup and is added successfully - */ - addGroup(chunkGroup) { - if (this._groups.has(chunkGroup)) return false; - this._groups.add(chunkGroup); - return true; - } + return callback(); + } + } - /** - * @param {ChunkGroup} chunkGroup the chunkGroup the chunk is being removed from - * @returns {boolean} returns true if chunk does exist in chunkGroup and is removed - */ - removeGroup(chunkGroup) { - if (!this._groups.has(chunkGroup)) return false; - this._groups.delete(chunkGroup); - return true; - } + // TODO webpack 5: if info.immutable check if file already exists in output + // skip emitting if it's already there - /** - * @param {ChunkGroup} chunkGroup the chunkGroup to check - * @returns {boolean} returns true if chunk has chunkGroup reference and exists in chunkGroup - */ - isInGroup(chunkGroup) { - return this._groups.has(chunkGroup); - } + // get the binary (Buffer) content from the Source + /** @type {Buffer} */ + let content; + if (typeof source.buffer === "function") { + content = source.buffer(); + } else { + const bufferOrString = source.source(); + if (Buffer.isBuffer(bufferOrString)) { + content = bufferOrString; + } else { + content = Buffer.from(bufferOrString, "utf8"); + } + } - /** - * @returns {number} the amount of groups said chunk is in - */ - getNumberOfGroups() { - return this._groups.size; - } + // Create a replacement resource which only allows to ask for size + // This allows to GC all memory allocated by the Source + // (expect when the Source is stored in any other cache) + cacheEntry.sizeOnlySource = new SizeOnlySource(content.length); + compilation.updateAsset(file, cacheEntry.sizeOnlySource, { + size: content.length + }); - /** - * @returns {SortableSet} the chunkGroups that said chunk is referenced in - */ - get groupsIterable() { - return this._groups; - } + // Write the file to output file system + this.outputFileSystem.writeFile(targetPath, content, err => { + if (err) return callback(err); - /** - * @param {Chunk} otherChunk the chunk to compare itself with - * @returns {-1|0|1} this is a comparitor function like sort and returns -1, 0, or 1 based on sort order - */ - compareTo(otherChunk) { - if (this.name && !otherChunk.name) return -1; - if (!this.name && otherChunk.name) return 1; - if (this.name < otherChunk.name) return -1; - if (this.name > otherChunk.name) return 1; - if (this._modules.size > otherChunk._modules.size) return -1; - if (this._modules.size < otherChunk._modules.size) return 1; - this._modules.sort(); - otherChunk._modules.sort(); - const a = this._modules[Symbol.iterator](); - const b = otherChunk._modules[Symbol.iterator](); - // eslint-disable-next-line no-constant-condition - while (true) { - const aItem = a.next(); - if (aItem.done) return 0; - const bItem = b.next(); - const aModuleIdentifier = aItem.value.identifier(); - const bModuleIdentifier = bItem.value.identifier(); - if (aModuleIdentifier < bModuleIdentifier) return -1; - if (aModuleIdentifier > bModuleIdentifier) return 1; - } - } + // information marker that the asset has been emitted + compilation.emittedAssets.add(file); - /** - * @param {Module} module Module to check - * @returns {boolean} returns true if module does exist in this chunk - */ - containsModule(module) { - return this._modules.has(module); - } + // cache the information that the Source has been written to that location + const newGeneration = + targetFileGeneration === undefined + ? 1 + : targetFileGeneration + 1; + cacheEntry.writtenTo.set(targetPath, newGeneration); + this._assetEmittingWrittenFiles.set(targetPath, newGeneration); + this.hooks.assetEmitted.callAsync(file, content, callback); + }); + } else { + if (source.existsAt === targetPath) { + source.emitted = false; + return callback(); + } + let content = source.source(); - /** - * @returns {Module[]} an array of modules (do not modify) - */ - getModules() { - return this._modules.getFromCache(getArray); - } + if (!Buffer.isBuffer(content)) { + content = Buffer.from(content, "utf8"); + } - getModulesIdent() { - return this._modules.getFromUnorderedCache(getModulesIdent); + source.existsAt = targetPath; + source.emitted = true; + this.outputFileSystem.writeFile(targetPath, content, err => { + if (err) return callback(err); + this.hooks.assetEmitted.callAsync(file, content, callback); + }); + } + }; + + if (targetFile.match(/\/|\\/)) { + const dir = path.dirname(targetFile); + this.outputFileSystem.mkdirp( + this.outputFileSystem.join(outputPath, dir), + writeOut + ); + } else { + writeOut(); + } + }, + err => { + if (err) return callback(err); + + this.hooks.afterEmit.callAsync(compilation, err => { + if (err) return callback(err); + + return callback(); + }); + } + ); + }; + + this.hooks.emit.callAsync(compilation, err => { + if (err) return callback(err); + outputPath = compilation.getPath(this.outputPath); + this.outputFileSystem.mkdirp(outputPath, emitFiles); + }); } - /** - * @param {string=} reason reason why chunk is removed - * @returns {void} - */ - remove(reason) { - // cleanup modules - // Array.from is used here to create a clone, because removeChunk modifies this._modules - for (const module of Array.from(this._modules)) { - module.removeChunk(this); + emitRecords(callback) { + if (!this.recordsOutputPath) return callback(); + const idx1 = this.recordsOutputPath.lastIndexOf("/"); + const idx2 = this.recordsOutputPath.lastIndexOf("\\"); + let recordsOutputPathDirectory = null; + if (idx1 > idx2) { + recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1); + } else if (idx1 < idx2) { + recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2); } - for (const chunkGroup of this._groups) { - chunkGroup.removeChunk(this); + + const writeFile = () => { + this.outputFileSystem.writeFile( + this.recordsOutputPath, + JSON.stringify(this.records, undefined, 2), + callback + ); + }; + + if (!recordsOutputPathDirectory) { + return writeFile(); } + this.outputFileSystem.mkdirp(recordsOutputPathDirectory, err => { + if (err) return callback(err); + writeFile(); + }); } - /** - * - * @param {Module} module module to move - * @param {Chunk} otherChunk other chunk to move it to - * @returns {void} - */ - moveModule(module, otherChunk) { - GraphHelpers.disconnectChunkAndModule(this, module); - GraphHelpers.connectChunkAndModule(otherChunk, module); - module.rewriteChunkInReasons(this, [otherChunk]); + readRecords(callback) { + if (!this.recordsInputPath) { + this.records = {}; + return callback(); + } + this.inputFileSystem.stat(this.recordsInputPath, err => { + // It doesn't exist + // We can ignore this. + if (err) return callback(); + + this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => { + if (err) return callback(err); + + try { + this.records = parseJson(content.toString("utf-8")); + } catch (e) { + e.message = "Cannot parse records: " + e.message; + return callback(e); + } + + return callback(); + }); + }); } - /** - * - * @param {Chunk} otherChunk the chunk to integrate with - * @param {string} reason reason why the module is being integrated - * @returns {boolean} returns true or false if integration succeeds or fails - */ - integrate(otherChunk, reason) { - if (!this.canBeIntegrated(otherChunk)) { - return false; + createChildCompiler( + compilation, + compilerName, + compilerIndex, + outputOptions, + plugins + ) { + const childCompiler = new Compiler(this.context); + if (Array.isArray(plugins)) { + for (const plugin of plugins) { + plugin.apply(childCompiler); + } } - - // Pick a new name for the integrated chunk - if (this.name && otherChunk.name) { - if (this.hasEntryModule() === otherChunk.hasEntryModule()) { - // When both chunks have entry modules or none have one, use - // shortest name - if (this.name.length !== otherChunk.name.length) { - this.name = - this.name.length < otherChunk.name.length - ? this.name - : otherChunk.name; - } else { - this.name = this.name < otherChunk.name ? this.name : otherChunk.name; + for (const name in this.hooks) { + if ( + ![ + "make", + "compile", + "emit", + "afterEmit", + "invalid", + "done", + "thisCompilation" + ].includes(name) + ) { + if (childCompiler.hooks[name]) { + childCompiler.hooks[name].taps = this.hooks[name].taps.slice(); } - } else if (otherChunk.hasEntryModule()) { - // Pick the name of the chunk with the entry module - this.name = otherChunk.name; } - } else if (otherChunk.name) { - this.name = otherChunk.name; } + childCompiler.name = compilerName; + childCompiler.outputPath = this.outputPath; + childCompiler.inputFileSystem = this.inputFileSystem; + childCompiler.outputFileSystem = null; + childCompiler.resolverFactory = this.resolverFactory; + childCompiler.fileTimestamps = this.fileTimestamps; + childCompiler.contextTimestamps = this.contextTimestamps; - // Array.from is used here to create a clone, because moveModule modifies otherChunk._modules - for (const module of Array.from(otherChunk._modules)) { - otherChunk.moveModule(module, this); + const relativeCompilerName = makePathsRelative(this.context, compilerName); + if (!this.records[relativeCompilerName]) { + this.records[relativeCompilerName] = []; } - otherChunk._modules.clear(); - - if (otherChunk.entryModule) { - this.entryModule = otherChunk.entryModule; + if (this.records[relativeCompilerName][compilerIndex]) { + childCompiler.records = this.records[relativeCompilerName][compilerIndex]; + } else { + this.records[relativeCompilerName].push((childCompiler.records = {})); } - for (const chunkGroup of otherChunk._groups) { - chunkGroup.replaceChunk(otherChunk, this); - this.addGroup(chunkGroup); + childCompiler.options = Object.create(this.options); + childCompiler.options.output = Object.create(childCompiler.options.output); + for (const name in outputOptions) { + childCompiler.options.output[name] = outputOptions[name]; } - otherChunk._groups.clear(); + childCompiler.parentCompilation = compilation; - return true; + compilation.hooks.childCompiler.call( + childCompiler, + compilerName, + compilerIndex + ); + + return childCompiler; } - /** - * @param {Chunk} newChunk the new chunk that will be split out of the current chunk - * @returns {void} - */ - split(newChunk) { - for (const chunkGroup of this._groups) { - chunkGroup.insertChunk(newChunk, this); - newChunk.addGroup(chunkGroup); - } + isChild() { + return !!this.parentCompilation; } - isEmpty() { - return this._modules.size === 0; + createCompilation() { + return new Compilation(this); } - updateHash(hash) { - hash.update(`${this.id} `); - hash.update(this.ids ? this.ids.join(",") : ""); - hash.update(`${this.name || ""} `); - for (const m of this._modules) { - hash.update(m.hash); - } + newCompilation(params) { + const compilation = this.createCompilation(); + compilation.fileTimestamps = this.fileTimestamps; + compilation.contextTimestamps = this.contextTimestamps; + compilation.name = this.name; + compilation.records = this.records; + compilation.compilationDependencies = params.compilationDependencies; + this.hooks.thisCompilation.call(compilation, params); + this.hooks.compilation.call(compilation, params); + return compilation; } - canBeIntegrated(otherChunk) { - if (this.preventIntegration || otherChunk.preventIntegration) { - return false; - } + createNormalModuleFactory() { + const normalModuleFactory = new NormalModuleFactory( + this.options.context, + this.resolverFactory, + this.options.module || {} + ); + this.hooks.normalModuleFactory.call(normalModuleFactory); + return normalModuleFactory; + } - /** - * @param {Chunk} a chunk - * @param {Chunk} b chunk - * @returns {boolean} true, if a is always available when b is reached - */ - const isAvailable = (a, b) => { - const queue = new Set(b.groupsIterable); - for (const chunkGroup of queue) { - if (a.isInGroup(chunkGroup)) continue; - if (chunkGroup.isInitial()) return false; - for (const parent of chunkGroup.parentsIterable) { - queue.add(parent); - } - } - return true; + createContextModuleFactory() { + const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); + this.hooks.contextModuleFactory.call(contextModuleFactory); + return contextModuleFactory; + } + + newCompilationParams() { + const params = { + normalModuleFactory: this.createNormalModuleFactory(), + contextModuleFactory: this.createContextModuleFactory(), + compilationDependencies: new Set() }; + return params; + } - const selfHasRuntime = this.hasRuntime(); - const otherChunkHasRuntime = otherChunk.hasRuntime(); + compile(callback) { + const params = this.newCompilationParams(); + this.hooks.beforeCompile.callAsync(params, err => { + if (err) return callback(err); - if (selfHasRuntime !== otherChunkHasRuntime) { - if (selfHasRuntime) { - return isAvailable(this, otherChunk); - } else if (otherChunkHasRuntime) { - return isAvailable(otherChunk, this); - } else { - return false; - } - } + this.hooks.compile.call(params); - if (this.hasEntryModule() || otherChunk.hasEntryModule()) { - return false; - } + const compilation = this.newCompilation(params); - return true; - } + this.hooks.make.callAsync(compilation, err => { + if (err) return callback(err); - /** - * - * @param {number} size the size - * @param {Object} options the options passed in - * @returns {number} the multiplier returned - */ - addMultiplierAndOverhead(size, options) { - const overhead = - typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; - const multiplicator = this.canBeInitial() - ? options.entryChunkMultiplicator || 10 - : 1; + compilation.finish(err => { + if (err) return callback(err); - return size * multiplicator + overhead; - } + compilation.seal(err => { + if (err) return callback(err); - /** - * @returns {number} the size of all modules - */ - modulesSize() { - return this._modules.getFromUnorderedCache(getModulesSize); - } + this.hooks.afterCompile.callAsync(compilation, err => { + if (err) return callback(err); - /** - * @param {Object} options the size display options - * @returns {number} the chunk size - */ - size(options = {}) { - return this.addMultiplierAndOverhead(this.modulesSize(), options); + return callback(null, compilation); + }); + }); + }); + }); + }); } +} - /** - * @param {Chunk} otherChunk the other chunk - * @param {TODO} options the options for this function - * @returns {number | false} the size, or false if it can't be integrated - */ - integratedSize(otherChunk, options) { - // Chunk if it's possible to integrate this chunk - if (!this.canBeIntegrated(otherChunk)) { - return false; - } - - let integratedModulesSize = this.modulesSize(); - // only count modules that do not exist in this chunk! - for (const otherModule of otherChunk._modules) { - if (!this._modules.has(otherModule)) { - integratedModulesSize += otherModule.size(); - } - } +module.exports = Compiler; - return this.addMultiplierAndOverhead(integratedModulesSize, options); +class SizeOnlySource extends Source { + constructor(size) { + super(); + this._size = size; } - /** - * @param {function(Module, Module): -1|0|1=} sortByFn a predicate function used to sort modules - * @returns {void} - */ - sortModules(sortByFn) { - this._modules.sortWith(sortByFn || sortModuleById); + _error() { + return new Error( + "Content and Map of this Source is no longer available (only size() is supported)" + ); } - sortItems() { - this.sortModules(); + size() { + return this._size; } /** - * @returns {Set} a set of all the async chunks + * @param {any} options options + * @returns {string} the source */ - getAllAsyncChunks() { - const queue = new Set(); - const chunks = new Set(); - - const initialChunks = intersect( - Array.from(this.groupsIterable, g => new Set(g.chunks)) - ); - - for (const chunkGroup of this.groupsIterable) { - for (const child of chunkGroup.childrenIterable) { - queue.add(child); - } - } - - for (const chunkGroup of queue) { - for (const chunk of chunkGroup.chunks) { - if (!initialChunks.has(chunk)) { - chunks.add(chunk); - } - } - for (const child of chunkGroup.childrenIterable) { - queue.add(child); - } - } - - return chunks; + source(options) { + throw this._error(); } - /** - * @typedef {Object} ChunkMaps - * @property {Record} hash - * @property {Record>} contentHash - * @property {Record} name - */ - - /** - * @param {boolean} realHash should the full hash or the rendered hash be used - * @returns {ChunkMaps} the chunk map information - */ - getChunkMaps(realHash) { - /** @type {Record} */ - const chunkHashMap = Object.create(null); - /** @type {Record>} */ - const chunkContentHashMap = Object.create(null); - /** @type {Record} */ - const chunkNameMap = Object.create(null); - - for (const chunk of this.getAllAsyncChunks()) { - chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash; - for (const key of Object.keys(chunk.contentHash)) { - if (!chunkContentHashMap[key]) { - chunkContentHashMap[key] = Object.create(null); - } - chunkContentHashMap[key][chunk.id] = chunk.contentHash[key]; - } - if (chunk.name) { - chunkNameMap[chunk.id] = chunk.name; - } - } - - return { - hash: chunkHashMap, - contentHash: chunkContentHashMap, - name: chunkNameMap - }; + node() { + throw this._error(); } - /** - * @returns {Record[]>} a record object of names to lists of child ids(?) - */ - getChildIdsByOrders() { - const lists = new Map(); - for (const group of this.groupsIterable) { - if (group.chunks[group.chunks.length - 1] === this) { - for (const childGroup of group.childrenIterable) { - // TODO webpack 5 remove this check for options - if (typeof childGroup.options === "object") { - for (const key of Object.keys(childGroup.options)) { - if (key.endsWith("Order")) { - const name = key.substr(0, key.length - "Order".length); - let list = lists.get(name); - if (list === undefined) lists.set(name, (list = [])); - list.push({ - order: childGroup.options[key], - group: childGroup - }); - } - } - } - } - } - } - const result = Object.create(null); - for (const [name, list] of lists) { - list.sort((a, b) => { - const cmp = b.order - a.order; - if (cmp !== 0) return cmp; - // TODO webpack 5 remove this check of compareTo - if (a.group.compareTo) { - return a.group.compareTo(b.group); - } - return 0; - }); - result[name] = Array.from( - list.reduce((set, item) => { - for (const chunk of item.group.chunks) { - set.add(chunk.id); - } - return set; - }, new Set()) - ); - } - return result; + listMap() { + throw this._error(); } - getChildIdsByOrdersMap(includeDirectChildren) { - const chunkMaps = Object.create(null); - - const addChildIdsByOrdersToMap = chunk => { - const data = chunk.getChildIdsByOrders(); - for (const key of Object.keys(data)) { - let chunkMap = chunkMaps[key]; - if (chunkMap === undefined) { - chunkMaps[key] = chunkMap = Object.create(null); - } - chunkMap[chunk.id] = data[key]; - } - }; - - if (includeDirectChildren) { - const chunks = new Set(); - for (const chunkGroup of this.groupsIterable) { - for (const chunk of chunkGroup.chunks) { - chunks.add(chunk); - } - } - for (const chunk of chunks) { - addChildIdsByOrdersToMap(chunk); - } - } - - for (const chunk of this.getAllAsyncChunks()) { - addChildIdsByOrdersToMap(chunk); - } - - return chunkMaps; + map() { + throw this._error(); } - /** - * @typedef {Object} ChunkModuleMaps - * @property {Record} id - * @property {Record} hash - */ - - /** - * @param {ModuleFilterPredicate} filterFn function used to filter modules - * @returns {ChunkModuleMaps} module map information - */ - getChunkModuleMaps(filterFn) { - /** @type {Record} */ - const chunkModuleIdMap = Object.create(null); - /** @type {Record} */ - const chunkModuleHashMap = Object.create(null); - - for (const chunk of this.getAllAsyncChunks()) { - /** @type {(string|number)[]} */ - let array; - for (const module of chunk.modulesIterable) { - if (filterFn(module)) { - if (array === undefined) { - array = []; - chunkModuleIdMap[chunk.id] = array; - } - array.push(module.id); - chunkModuleHashMap[module.id] = module.renderedHash; - } - } - if (array !== undefined) { - array.sort(); - } - } + listNode() { + throw this._error(); + } - return { - id: chunkModuleIdMap, - hash: chunkModuleHashMap - }; + updateHash() { + throw this._error(); } +} - /** - * - * @param {function(Module): boolean} filterFn predicate function used to filter modules - * @param {function(Chunk): boolean} filterChunkFn predicate function used to filter chunks - * @returns {boolean} return true if module exists in graph - */ - hasModuleInGraph(filterFn, filterChunkFn) { - const queue = new Set(this.groupsIterable); - const chunksProcessed = new Set(); - for (const chunkGroup of queue) { - for (const chunk of chunkGroup.chunks) { - if (!chunksProcessed.has(chunk)) { - chunksProcessed.add(chunk); - if (!filterChunkFn || filterChunkFn(chunk)) { - for (const module of chunk.modulesIterable) { - if (filterFn(module)) { - return true; - } - } - } - } - } - for (const child of chunkGroup.childrenIterable) { - queue.add(child); - } - } - return false; - } +/***/ }), - toString() { - return `Chunk[${Array.from(this._modules).join()}]`; - } -} +/***/ 18933: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -// TODO remove in webpack 5 -Object.defineProperty(Chunk.prototype, "forEachModule", { - configurable: false, - value: util.deprecate( - /** - * @deprecated - * @this {Chunk} - * @typedef {function(any, any, Set): void} ForEachModuleCallback - * @param {ForEachModuleCallback} fn Callback function - * @returns {void} - */ - function(fn) { - this._modules.forEach(fn); - }, - "Chunk.forEachModule: Use for(const module of chunk.modulesIterable) instead" - ) -}); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Maksim Nazarjev @acupofspirt +*/ -// TODO remove in webpack 5 -Object.defineProperty(Chunk.prototype, "mapModules", { - configurable: false, - value: util.deprecate( - /** - * @deprecated - * @this {Chunk} - * @typedef {function(any, number): any} MapModulesCallback - * @param {MapModulesCallback} fn Callback function - * @returns {TODO[]} result of mapped modules - */ - function(fn) { - return Array.from(this._modules, fn); - }, - "Chunk.mapModules: Use Array.from(chunk.modulesIterable, fn) instead" - ) -}); -// TODO remove in webpack 5 -Object.defineProperty(Chunk.prototype, "chunks", { - configurable: false, - get() { - throw new Error("Chunk.chunks: Use ChunkGroup.getChildren() instead"); - }, - set() { - throw new Error("Chunk.chunks: Use ChunkGroup.add/removeChild() instead"); - } -}); +const WebpackError = __webpack_require__(97391); -// TODO remove in webpack 5 -Object.defineProperty(Chunk.prototype, "parents", { - configurable: false, - get() { - throw new Error("Chunk.parents: Use ChunkGroup.getParents() instead"); - }, - set() { - throw new Error("Chunk.parents: Use ChunkGroup.add/removeParent() instead"); - } -}); +module.exports = class ConcurrentCompilationError extends WebpackError { + constructor() { + super(); -// TODO remove in webpack 5 -Object.defineProperty(Chunk.prototype, "blocks", { - configurable: false, - get() { - throw new Error("Chunk.blocks: Use ChunkGroup.getBlocks() instead"); - }, - set() { - throw new Error("Chunk.blocks: Use ChunkGroup.add/removeBlock() instead"); - } -}); + this.name = "ConcurrentCompilationError"; + this.message = + "You ran Webpack twice. Each instance only supports a single concurrent compilation at a time."; -// TODO remove in webpack 5 -Object.defineProperty(Chunk.prototype, "entrypoints", { - configurable: false, - get() { - throw new Error( - "Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead" - ); - }, - set() { - throw new Error("Chunk.entrypoints: Use Chunks.addGroup instead"); + Error.captureStackTrace(this, this.constructor); } -}); - -module.exports = Chunk; +}; /***/ }), -/***/ 52911: +/***/ 84072: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -70938,813 +71189,1270 @@ module.exports = Chunk; Author Tobias Koppers @sokra */ +const ConstDependency = __webpack_require__(71101); +const NullFactory = __webpack_require__(40438); +const ParserHelpers = __webpack_require__(23999); -const SortableSet = __webpack_require__(50071); -const compareLocations = __webpack_require__(22562); - -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./ModuleReason")} ModuleReason */ - -/** @typedef {{module: Module, loc: TODO, request: string}} OriginRecord */ -/** @typedef {string|{name: string}} ChunkGroupOptions */ - -let debugId = 5000; - -/** - * @template T - * @param {SortableSet} set set to convert to array. - * @returns {T[]} the array format of existing set - */ -const getArray = set => Array.from(set); - -/** - * A convenience method used to sort chunks based on their id's - * @param {ChunkGroup} a first sorting comparator - * @param {ChunkGroup} b second sorting comparator - * @returns {1|0|-1} a sorting index to determine order - */ -const sortById = (a, b) => { - if (a.id < b.id) return -1; - if (b.id < a.id) return 1; - return 0; -}; - -/** - * @param {OriginRecord} a the first comparator in sort - * @param {OriginRecord} b the second comparator in sort - * @returns {1|-1|0} returns sorting order as index - */ -const sortOrigin = (a, b) => { - const aIdent = a.module ? a.module.identifier() : ""; - const bIdent = b.module ? b.module.identifier() : ""; - if (aIdent < bIdent) return -1; - if (aIdent > bIdent) return 1; - return compareLocations(a.loc, b.loc); +const getQuery = request => { + const i = request.indexOf("?"); + return i !== -1 ? request.substr(i) : ""; }; -class ChunkGroup { - /** - * Creates an instance of ChunkGroup. - * @param {ChunkGroupOptions=} options chunk group options passed to chunkGroup - */ - constructor(options) { - if (typeof options === "string") { - options = { name: options }; - } else if (!options) { - options = { name: undefined }; - } - /** @type {number} */ - this.groupDebugId = debugId++; - this.options = options; - /** @type {SortableSet} */ - this._children = new SortableSet(undefined, sortById); - this._parents = new SortableSet(undefined, sortById); - this._blocks = new SortableSet(); - /** @type {Chunk[]} */ - this.chunks = []; - /** @type {OriginRecord[]} */ - this.origins = []; - /** Indices in top-down order */ - /** @private @type {Map} */ - this._moduleIndices = new Map(); - /** Indices in bottom-up order */ - /** @private @type {Map} */ - this._moduleIndices2 = new Map(); - } - - /** - * when a new chunk is added to a chunkGroup, addingOptions will occur. - * @param {ChunkGroupOptions} options the chunkGroup options passed to addOptions - * @returns {void} - */ - addOptions(options) { - for (const key of Object.keys(options)) { - if (this.options[key] === undefined) { - this.options[key] = options[key]; - } else if (this.options[key] !== options[key]) { - if (key.endsWith("Order")) { - this.options[key] = Math.max(this.options[key], options[key]); - } else { - throw new Error( - `ChunkGroup.addOptions: No option merge strategy for ${key}` - ); +const collectDeclaration = (declarations, pattern) => { + const stack = [pattern]; + while (stack.length > 0) { + const node = stack.pop(); + switch (node.type) { + case "Identifier": + declarations.add(node.name); + break; + case "ArrayPattern": + for (const element of node.elements) { + if (element) { + stack.push(element); + } } - } + break; + case "AssignmentPattern": + stack.push(node.left); + break; + case "ObjectPattern": + for (const property of node.properties) { + stack.push(property.value); + } + break; + case "RestElement": + stack.push(node.argument); + break; } } +}; - /** - * returns the name of current ChunkGroup - * @returns {string|undefined} returns the ChunkGroup name - */ - get name() { - return this.options.name; +const getHoistedDeclarations = (branch, includeFunctionDeclarations) => { + const declarations = new Set(); + const stack = [branch]; + while (stack.length > 0) { + const node = stack.pop(); + // Some node could be `null` or `undefined`. + if (!node) continue; + switch (node.type) { + // Walk through control statements to look for hoisted declarations. + // Some branches are skipped since they do not allow declarations. + case "BlockStatement": + for (const stmt of node.body) { + stack.push(stmt); + } + break; + case "IfStatement": + stack.push(node.consequent); + stack.push(node.alternate); + break; + case "ForStatement": + stack.push(node.init); + stack.push(node.body); + break; + case "ForInStatement": + case "ForOfStatement": + stack.push(node.left); + stack.push(node.body); + break; + case "DoWhileStatement": + case "WhileStatement": + case "LabeledStatement": + stack.push(node.body); + break; + case "SwitchStatement": + for (const cs of node.cases) { + for (const consequent of cs.consequent) { + stack.push(consequent); + } + } + break; + case "TryStatement": + stack.push(node.block); + if (node.handler) { + stack.push(node.handler.body); + } + stack.push(node.finalizer); + break; + case "FunctionDeclaration": + if (includeFunctionDeclarations) { + collectDeclaration(declarations, node.id); + } + break; + case "VariableDeclaration": + if (node.kind === "var") { + for (const decl of node.declarations) { + collectDeclaration(declarations, decl.id); + } + } + break; + } } + return Array.from(declarations); +}; - /** - * sets a new name for current ChunkGroup - * @param {string} value the new name for ChunkGroup - * @returns {void} - */ - set name(value) { - this.options.name = value; - } +class ConstPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "ConstPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); - /** - * get a uniqueId for ChunkGroup, made up of its member Chunk debugId's - * @returns {string} a unique concatenation of chunk debugId's - */ - get debugId() { - return Array.from(this.chunks, x => x.debugId).join("+"); - } + const handler = parser => { + parser.hooks.statementIf.tap("ConstPlugin", statement => { + if (parser.scope.isAsmJs) return; + const param = parser.evaluateExpression(statement.test); + const bool = param.asBool(); + if (typeof bool === "boolean") { + if (statement.test.type !== "Literal") { + const dep = new ConstDependency(`${bool}`, param.range); + dep.loc = statement.loc; + parser.state.current.addDependency(dep); + } + const branchToRemove = bool + ? statement.alternate + : statement.consequent; + if (branchToRemove) { + // Before removing the dead branch, the hoisted declarations + // must be collected. + // + // Given the following code: + // + // if (true) f() else g() + // if (false) { + // function f() {} + // const g = function g() {} + // if (someTest) { + // let a = 1 + // var x, {y, z} = obj + // } + // } else { + // … + // } + // + // the generated code is: + // + // if (true) f() else {} + // if (false) { + // var f, x, y, z; (in loose mode) + // var x, y, z; (in strict mode) + // } else { + // … + // } + // + // NOTE: When code runs in strict mode, `var` declarations + // are hoisted but `function` declarations don't. + // + let declarations; + if (parser.scope.isStrict) { + // If the code runs in strict mode, variable declarations + // using `var` must be hoisted. + declarations = getHoistedDeclarations(branchToRemove, false); + } else { + // Otherwise, collect all hoisted declaration. + declarations = getHoistedDeclarations(branchToRemove, true); + } + let replacement; + if (declarations.length > 0) { + replacement = `{ var ${declarations.join(", ")}; }`; + } else { + replacement = "{}"; + } + const dep = new ConstDependency( + replacement, + branchToRemove.range + ); + dep.loc = branchToRemove.loc; + parser.state.current.addDependency(dep); + } + return bool; + } + }); + parser.hooks.expressionConditionalOperator.tap( + "ConstPlugin", + expression => { + if (parser.scope.isAsmJs) return; + const param = parser.evaluateExpression(expression.test); + const bool = param.asBool(); + if (typeof bool === "boolean") { + if (expression.test.type !== "Literal") { + const dep = new ConstDependency(` ${bool}`, param.range); + dep.loc = expression.loc; + parser.state.current.addDependency(dep); + } + // Expressions do not hoist. + // It is safe to remove the dead branch. + // + // Given the following code: + // + // false ? someExpression() : otherExpression(); + // + // the generated code is: + // + // false ? undefined : otherExpression(); + // + const branchToRemove = bool + ? expression.alternate + : expression.consequent; + const dep = new ConstDependency( + "undefined", + branchToRemove.range + ); + dep.loc = branchToRemove.loc; + parser.state.current.addDependency(dep); + return bool; + } + } + ); + parser.hooks.expressionLogicalOperator.tap( + "ConstPlugin", + expression => { + if (parser.scope.isAsmJs) return; + if ( + expression.operator === "&&" || + expression.operator === "||" + ) { + const param = parser.evaluateExpression(expression.left); + const bool = param.asBool(); + if (typeof bool === "boolean") { + // Expressions do not hoist. + // It is safe to remove the dead branch. + // + // ------------------------------------------ + // + // Given the following code: + // + // falsyExpression() && someExpression(); + // + // the generated code is: + // + // falsyExpression() && false; + // + // ------------------------------------------ + // + // Given the following code: + // + // truthyExpression() && someExpression(); + // + // the generated code is: + // + // true && someExpression(); + // + // ------------------------------------------ + // + // Given the following code: + // + // truthyExpression() || someExpression(); + // + // the generated code is: + // + // truthyExpression() || false; + // + // ------------------------------------------ + // + // Given the following code: + // + // falsyExpression() || someExpression(); + // + // the generated code is: + // + // false && someExpression(); + // + const keepRight = + (expression.operator === "&&" && bool) || + (expression.operator === "||" && !bool); - /** - * get a unique id for ChunkGroup, made up of its member Chunk id's - * @returns {string} a unique concatenation of chunk ids - */ - get id() { - return Array.from(this.chunks, x => x.id).join("+"); - } + if (param.isBoolean() || keepRight) { + // for case like + // + // return'development'===process.env.NODE_ENV&&'foo' + // + // we need a space before the bool to prevent result like + // + // returnfalse&&'foo' + // + const dep = new ConstDependency(` ${bool}`, param.range); + dep.loc = expression.loc; + parser.state.current.addDependency(dep); + } else { + parser.walkExpression(expression.left); + } + if (!keepRight) { + const dep = new ConstDependency( + "false", + expression.right.range + ); + dep.loc = expression.loc; + parser.state.current.addDependency(dep); + } + return keepRight; + } + } + } + ); + parser.hooks.evaluateIdentifier + .for("__resourceQuery") + .tap("ConstPlugin", expr => { + if (parser.scope.isAsmJs) return; + if (!parser.state.module) return; + return ParserHelpers.evaluateToString( + getQuery(parser.state.module.resource) + )(expr); + }); + parser.hooks.expression + .for("__resourceQuery") + .tap("ConstPlugin", () => { + if (parser.scope.isAsmJs) return; + if (!parser.state.module) return; + parser.state.current.addVariable( + "__resourceQuery", + JSON.stringify(getQuery(parser.state.module.resource)) + ); + return true; + }); + }; - /** - * Performs an unshift of a specific chunk - * @param {Chunk} chunk chunk being unshifted - * @returns {boolean} returns true if attempted chunk shift is accepted - */ - unshiftChunk(chunk) { - const oldIdx = this.chunks.indexOf(chunk); - if (oldIdx > 0) { - this.chunks.splice(oldIdx, 1); - this.chunks.unshift(chunk); - } else if (oldIdx < 0) { - this.chunks.unshift(chunk); - return true; - } - return false; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ConstPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ConstPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ConstPlugin", handler); + } + ); } +} + +module.exports = ConstPlugin; + +/***/ }), + +/***/ 10706: +/***/ (function(module) { + +"use strict"; + + +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./ContextModuleFactory")} ContextModuleFactory */ + +class ContextExclusionPlugin { /** - * inserts a chunk before another existing chunk in group - * @param {Chunk} chunk Chunk being inserted - * @param {Chunk} before Placeholder/target chunk marking new chunk insertion point - * @returns {boolean} return true if insertion was successful + * @param {RegExp} negativeMatcher Matcher regular expression */ - insertChunk(chunk, before) { - const oldIdx = this.chunks.indexOf(chunk); - const idx = this.chunks.indexOf(before); - if (idx < 0) { - throw new Error("before chunk not found"); - } - if (oldIdx >= 0 && oldIdx > idx) { - this.chunks.splice(oldIdx, 1); - this.chunks.splice(idx, 0, chunk); - } else if (oldIdx < 0) { - this.chunks.splice(idx, 0, chunk); - return true; - } - return false; + constructor(negativeMatcher) { + this.negativeMatcher = negativeMatcher; } /** - * add a chunk into ChunkGroup. Is pushed on or prepended - * @param {Chunk} chunk chunk being pushed into ChunkGroupS - * @returns {boolean} returns true if chunk addition was successful. + * Apply the plugin + * @param {Compiler} compiler Webpack Compiler + * @returns {void} */ - pushChunk(chunk) { - const oldIdx = this.chunks.indexOf(chunk); - if (oldIdx >= 0) { - return false; - } - this.chunks.push(chunk); - return true; + apply(compiler) { + compiler.hooks.contextModuleFactory.tap("ContextExclusionPlugin", cmf => { + cmf.hooks.contextModuleFiles.tap("ContextExclusionPlugin", files => { + return files.filter(filePath => !this.negativeMatcher.test(filePath)); + }); + }); } +} + +module.exports = ContextExclusionPlugin; + + +/***/ }), + +/***/ 20090: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const util = __webpack_require__(31669); +const { OriginalSource, RawSource } = __webpack_require__(53665); +const Module = __webpack_require__(75993); +const AsyncDependenciesBlock = __webpack_require__(22814); +const Template = __webpack_require__(96066); +const contextify = __webpack_require__(94658).contextify; + +/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */ +/** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */ + +/** + * @callback ResolveDependenciesCallback + * @param {Error=} err + * @param {ContextElementDependency[]} dependencies + */ + +/** + * @callback ResolveDependencies + * @param {TODO} fs + * @param {TODO} options + * @param {ResolveDependenciesCallback} callback + */ +class ContextModule extends Module { + // type ContextMode = "sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once" + // type ContextOptions = { resource: string, recursive: boolean, regExp: RegExp, addon?: string, mode?: ContextMode, chunkName?: string, include?: RegExp, exclude?: RegExp, groupOptions?: Object } + // resolveDependencies: (fs: FS, options: ContextOptions, (err: Error?, dependencies: Dependency[]) => void) => void + // options: ContextOptions /** - * @param {Chunk} oldChunk chunk to be replaced - * @param {Chunk} newChunk New chunk that will be replaced with - * @returns {boolean} returns true if the replacement was successful + * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context + * @param {TODO} options options object */ - replaceChunk(oldChunk, newChunk) { - const oldIdx = this.chunks.indexOf(oldChunk); - if (oldIdx < 0) return false; - const newIdx = this.chunks.indexOf(newChunk); - if (newIdx < 0) { - this.chunks[oldIdx] = newChunk; - return true; - } - if (newIdx < oldIdx) { - this.chunks.splice(oldIdx, 1); - return true; - } else if (newIdx !== oldIdx) { - this.chunks[oldIdx] = newChunk; - this.chunks.splice(newIdx, 1); - return true; + constructor(resolveDependencies, options) { + let resource; + let resourceQuery; + const queryIdx = options.resource.indexOf("?"); + if (queryIdx >= 0) { + resource = options.resource.substr(0, queryIdx); + resourceQuery = options.resource.substr(queryIdx); + } else { + resource = options.resource; + resourceQuery = ""; } - } - removeChunk(chunk) { - const idx = this.chunks.indexOf(chunk); - if (idx >= 0) { - this.chunks.splice(idx, 1); - return true; + super("javascript/dynamic", resource); + + // Info from Factory + this.resolveDependencies = resolveDependencies; + this.options = Object.assign({}, options, { + resource: resource, + resourceQuery: resourceQuery + }); + if (options.resolveOptions !== undefined) { + this.resolveOptions = options.resolveOptions; } - return false; - } - isInitial() { - return false; - } + // Info from Build + this._contextDependencies = new Set([this.context]); - addChild(chunk) { - if (this._children.has(chunk)) { - return false; + if (typeof options.mode !== "string") { + throw new Error("options.mode is a required option"); } - this._children.add(chunk); - return true; - } - getChildren() { - return this._children.getFromCache(getArray); + this._identifier = this._createIdentifier(); } - getNumberOfChildren() { - return this._children.size; + updateCacheModule(module) { + this.resolveDependencies = module.resolveDependencies; + this.options = module.options; + this.resolveOptions = module.resolveOptions; } - get childrenIterable() { - return this._children; + prettyRegExp(regexString) { + // remove the "/" at the front and the beginning + // "/foo/" -> "foo" + return regexString.substring(1, regexString.length - 1); } - removeChild(chunk) { - if (!this._children.has(chunk)) { - return false; - } - - this._children.delete(chunk); - chunk.removeParent(this); - return true; - } - - addParent(parentChunk) { - if (!this._parents.has(parentChunk)) { - this._parents.add(parentChunk); - return true; + _createIdentifier() { + let identifier = this.context; + if (this.options.resourceQuery) { + identifier += ` ${this.options.resourceQuery}`; } - return false; - } - - getParents() { - return this._parents.getFromCache(getArray); - } - - setParents(newParents) { - this._parents.clear(); - for (const p of newParents) { - this._parents.add(p); + if (this.options.mode) { + identifier += ` ${this.options.mode}`; } - } - - getNumberOfParents() { - return this._parents.size; - } - - hasParent(parent) { - return this._parents.has(parent); - } - - get parentsIterable() { - return this._parents; - } - - removeParent(chunk) { - if (this._parents.delete(chunk)) { - chunk.removeChunk(this); - return true; + if (!this.options.recursive) { + identifier += " nonrecursive"; + } + if (this.options.addon) { + identifier += ` ${this.options.addon}`; + } + if (this.options.regExp) { + identifier += ` ${this.options.regExp}`; + } + if (this.options.include) { + identifier += ` include: ${this.options.include}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this.options.exclude}`; + } + if (this.options.groupOptions) { + identifier += ` groupOptions: ${JSON.stringify( + this.options.groupOptions + )}`; + } + if (this.options.namespaceObject === "strict") { + identifier += " strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; } - return false; - } - - /** - * @returns {Array} - an array containing the blocks - */ - getBlocks() { - return this._blocks.getFromCache(getArray); - } - - getNumberOfBlocks() { - return this._blocks.size; - } - hasBlock(block) { - return this._blocks.has(block); + return identifier; } - get blocksIterable() { - return this._blocks; + identifier() { + return this._identifier; } - addBlock(block) { - if (!this._blocks.has(block)) { - this._blocks.add(block); - return true; + readableIdentifier(requestShortener) { + let identifier = requestShortener.shorten(this.context); + if (this.options.resourceQuery) { + identifier += ` ${this.options.resourceQuery}`; } - return false; - } - - addOrigin(module, loc, request) { - this.origins.push({ - module, - loc, - request - }); - } - - containsModule(module) { - for (const chunk of this.chunks) { - if (chunk.containsModule(module)) return true; + if (this.options.mode) { + identifier += ` ${this.options.mode}`; } - return false; - } - - getFiles() { - const files = new Set(); - - for (const chunk of this.chunks) { - for (const file of chunk.files) { - files.add(file); + if (!this.options.recursive) { + identifier += " nonrecursive"; + } + if (this.options.addon) { + identifier += ` ${requestShortener.shorten(this.options.addon)}`; + } + if (this.options.regExp) { + identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; + } + if (this.options.include) { + identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; + } + if (this.options.groupOptions) { + const groupOptions = this.options.groupOptions; + for (const key of Object.keys(groupOptions)) { + identifier += ` ${key}: ${groupOptions[key]}`; } } + if (this.options.namespaceObject === "strict") { + identifier += " strict namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; + } - return Array.from(files); + return identifier; } - /** - * @param {string=} reason reason for removing ChunkGroup - * @returns {void} - */ - remove(reason) { - // cleanup parents - for (const parentChunkGroup of this._parents) { - // remove this chunk from its parents - parentChunkGroup._children.delete(this); - - // cleanup "sub chunks" - for (const chunkGroup of this._children) { - /** - * remove this chunk as "intermediary" and connect - * it "sub chunks" and parents directly - */ - // add parent to each "sub chunk" - chunkGroup.addParent(parentChunkGroup); - // add "sub chunk" to parent - parentChunkGroup.addChild(chunkGroup); - } + libIdent(options) { + let identifier = contextify(options.context, this.context); + if (this.options.mode) { + identifier += ` ${this.options.mode}`; } - - /** - * we need to iterate again over the children - * to remove this from the child's parents. - * This can not be done in the above loop - * as it is not guaranteed that `this._parents` contains anything. - */ - for (const chunkGroup of this._children) { - // remove this as parent of every "sub chunk" - chunkGroup._parents.delete(this); + if (this.options.recursive) { + identifier += " recursive"; } - - // cleanup blocks - for (const block of this._blocks) { - block.chunkGroup = null; + if (this.options.addon) { + identifier += ` ${contextify(options.context, this.options.addon)}`; } - - // remove chunks - for (const chunk of this.chunks) { - chunk.removeGroup(this); + if (this.options.regExp) { + identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; + } + if (this.options.include) { + identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; } - } - sortItems() { - this.origins.sort(sortOrigin); - this._parents.sort(); - this._children.sort(); + return identifier; } - /** - * Sorting predicate which allows current ChunkGroup to be compared against another. - * Sorting values are based off of number of chunks in ChunkGroup. - * - * @param {ChunkGroup} otherGroup the chunkGroup to compare this against - * @returns {-1|0|1} sort position for comparison - */ - compareTo(otherGroup) { - if (this.chunks.length > otherGroup.chunks.length) return -1; - if (this.chunks.length < otherGroup.chunks.length) return 1; - const a = this.chunks[Symbol.iterator](); - const b = otherGroup.chunks[Symbol.iterator](); - // eslint-disable-next-line no-constant-condition - while (true) { - const aItem = a.next(); - const bItem = b.next(); - if (aItem.done) return 0; - const cmp = aItem.value.compareTo(bItem.value); - if (cmp !== 0) return cmp; + needRebuild(fileTimestamps, contextTimestamps) { + const ts = contextTimestamps.get(this.context); + if (!ts) { + return true; } + + return ts >= this.buildInfo.builtTime; } - getChildrenByOrders() { - const lists = new Map(); - for (const childGroup of this._children) { - // TODO webpack 5 remove this check for options - if (typeof childGroup.options === "object") { - for (const key of Object.keys(childGroup.options)) { - if (key.endsWith("Order")) { - const name = key.substr(0, key.length - "Order".length); - let list = lists.get(name); - if (list === undefined) { - lists.set(name, (list = [])); + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = { + builtTime: Date.now(), + contextDependencies: this._contextDependencies + }; + this.resolveDependencies(fs, this.options, (err, dependencies) => { + if (err) return callback(err); + + // abort if something failed + // this will create an empty context + if (!dependencies) { + callback(); + return; + } + + // enhance dependencies with meta info + for (const dep of dependencies) { + dep.loc = { + name: dep.userRequest + }; + dep.request = this.options.addon + dep.request; + } + + if (this.options.mode === "sync" || this.options.mode === "eager") { + // if we have an sync or eager context + // just add all dependencies and continue + this.dependencies = dependencies; + } else if (this.options.mode === "lazy-once") { + // for the lazy-once mode create a new async dependency block + // and add that block to this context + if (dependencies.length > 0) { + const block = new AsyncDependenciesBlock( + Object.assign({}, this.options.groupOptions, { + name: this.options.chunkName + }), + this + ); + for (const dep of dependencies) { + block.addDependency(dep); + } + this.addBlock(block); + } + } else if ( + this.options.mode === "weak" || + this.options.mode === "async-weak" + ) { + // we mark all dependencies as weak + for (const dep of dependencies) { + dep.weak = true; + } + this.dependencies = dependencies; + } else if (this.options.mode === "lazy") { + // if we are lazy create a new async dependency block per dependency + // and add all blocks to this context + let index = 0; + for (const dep of dependencies) { + let chunkName = this.options.chunkName; + if (chunkName) { + if (!/\[(index|request)\]/.test(chunkName)) { + chunkName += "[index]"; } - list.push({ - order: childGroup.options[key], - group: childGroup - }); + chunkName = chunkName.replace(/\[index\]/g, index++); + chunkName = chunkName.replace( + /\[request\]/g, + Template.toPath(dep.userRequest) + ); } + const block = new AsyncDependenciesBlock( + Object.assign({}, this.options.groupOptions, { + name: chunkName + }), + dep.module, + dep.loc, + dep.userRequest + ); + block.addDependency(dep); + this.addBlock(block); } + } else { + callback( + new Error(`Unsupported mode "${this.options.mode}" in context`) + ); + return; } - } - const result = Object.create(null); - for (const [name, list] of lists) { - list.sort((a, b) => { - const cmp = b.order - a.order; - if (cmp !== 0) return cmp; - // TODO webpack 5 remove this check of compareTo - if (a.group.compareTo) { - return a.group.compareTo(b.group); - } - return 0; - }); - result[name] = list.map(i => i.group); - } - return result; + callback(); + }); } - /** - * Sets the top-down index of a module in this ChunkGroup - * @param {Module} module module for which the index should be set - * @param {number} index the index of the module - * @returns {void} - */ - setModuleIndex(module, index) { - this._moduleIndices.set(module, index); + getUserRequestMap(dependencies) { + // if we filter first we get a new array + // therefor we dont need to create a clone of dependencies explicitly + // therefore the order of this is !important! + return dependencies + .filter(dependency => dependency.module) + .sort((a, b) => { + if (a.userRequest === b.userRequest) { + return 0; + } + return a.userRequest < b.userRequest ? -1 : 1; + }) + .reduce((map, dep) => { + map[dep.userRequest] = dep.module.id; + return map; + }, Object.create(null)); } - /** - * Gets the top-down index of a module in this ChunkGroup - * @param {Module} module the module - * @returns {number} index - */ - getModuleIndex(module) { - return this._moduleIndices.get(module); + getFakeMap(dependencies) { + if (!this.options.namespaceObject) { + return 9; + } + // if we filter first we get a new array + // therefor we dont need to create a clone of dependencies explicitly + // therefore the order of this is !important! + let hasNonHarmony = false; + let hasNamespace = false; + let hasNamed = false; + const fakeMap = dependencies + .filter(dependency => dependency.module) + .sort((a, b) => { + return b.module.id - a.module.id; + }) + .reduce((map, dep) => { + const exportsType = + dep.module.buildMeta && dep.module.buildMeta.exportsType; + const id = dep.module.id; + if (!exportsType) { + map[id] = this.options.namespaceObject === "strict" ? 1 : 7; + hasNonHarmony = true; + } else if (exportsType === "namespace") { + map[id] = 9; + hasNamespace = true; + } else if (exportsType === "named") { + map[id] = 3; + hasNamed = true; + } + return map; + }, Object.create(null)); + if (!hasNamespace && hasNonHarmony && !hasNamed) { + return this.options.namespaceObject === "strict" ? 1 : 7; + } + if (hasNamespace && !hasNonHarmony && !hasNamed) { + return 9; + } + if (!hasNamespace && !hasNonHarmony && hasNamed) { + return 3; + } + if (!hasNamespace && !hasNonHarmony && !hasNamed) { + return 9; + } + return fakeMap; } - /** - * Sets the bottom-up index of a module in this ChunkGroup - * @param {Module} module module for which the index should be set - * @param {number} index the index of the module - * @returns {void} - */ - setModuleIndex2(module, index) { - this._moduleIndices2.set(module, index); + getFakeMapInitStatement(fakeMap) { + return typeof fakeMap === "object" + ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` + : ""; } - /** - * Gets the bottom-up index of a module in this ChunkGroup - * @param {Module} module the module - * @returns {number} index - */ - getModuleIndex2(module) { - return this._moduleIndices2.get(module); + getReturn(type) { + if (type === 9) { + return "__webpack_require__(id)"; + } + return `__webpack_require__.t(id, ${type})`; } - checkConstraints() { - const chunk = this; - for (const child of chunk._children) { - if (!child._parents.has(chunk)) { - throw new Error( - `checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}` - ); - } - } - for (const parentChunk of chunk._parents) { - if (!parentChunk._children.has(chunk)) { - throw new Error( - `checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}` - ); - } + getReturnModuleObjectSource(fakeMap, fakeMapDataExpression = "fakeMap[id]") { + if (typeof fakeMap === "number") { + return `return ${this.getReturn(fakeMap)};`; } + return `return __webpack_require__.t(id, ${fakeMapDataExpression})`; } -} - -module.exports = ChunkGroup; + getSyncSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); -/***/ }), - -/***/ 69865: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} +function webpackContext(req) { + var id = webpackContextResolve(req); + ${returnModuleObject} +} +function webpackContextResolve(req) { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); +}; +webpackContext.resolve = webpackContextResolve; +module.exports = webpackContext; +webpackContext.id = ${JSON.stringify(id)};`; + } -const WebpackError = __webpack_require__(97391); + getWeakSyncSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); -/** @typedef {import("./Chunk")} Chunk */ + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} -class ChunkRenderError extends WebpackError { - /** - * Create a new ChunkRenderError - * @param {Chunk} chunk A chunk - * @param {string} file Related file - * @param {Error} error Original error - */ - constructor(chunk, file, error) { - super(); - - this.name = "ChunkRenderError"; - this.error = error; - this.message = error.message; - this.details = error.stack; - this.file = file; - this.chunk = chunk; - - Error.captureStackTrace(this, this.constructor); +function webpackContext(req) { + var id = webpackContextResolve(req); + if(!__webpack_require__.m[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; } + ${returnModuleObject} } - -module.exports = ChunkRenderError; - - -/***/ }), - -/***/ 6170: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(56758); - -/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Module")} Module} */ -/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate} */ -/** @typedef {import("./util/createHash").Hash} Hash} */ - -/** - * @typedef {Object} RenderManifestOptions - * @property {Chunk} chunk the chunk used to render - * @property {string} hash - * @property {string} fullHash - * @property {TODO} outputOptions - * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates - * @property {Map} dependencyTemplates - */ - -module.exports = class ChunkTemplate extends Tapable { - constructor(outputOptions) { - super(); - this.outputOptions = outputOptions || {}; - this.hooks = { - /** @type {SyncWaterfallHook} */ - renderManifest: new SyncWaterfallHook(["result", "options"]), - modules: new SyncWaterfallHook([ - "source", - "chunk", - "moduleTemplate", - "dependencyTemplates" - ]), - render: new SyncWaterfallHook([ - "source", - "chunk", - "moduleTemplate", - "dependencyTemplates" - ]), - renderWithEntry: new SyncWaterfallHook(["source", "chunk"]), - hash: new SyncHook(["hash"]), - hashForChunk: new SyncHook(["hash", "chunk"]) - }; +function webpackContextResolve(req) { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; +} +webpackContext.keys = function webpackContextKeys() { + return Object.keys(map); +}; +webpackContext.resolve = webpackContextResolve; +webpackContext.id = ${JSON.stringify(id)}; +module.exports = webpackContext;`; } - /** - * - * @param {RenderManifestOptions} options render manifest options - * @returns {TODO[]} returns render manifest - */ - getRenderManifest(options) { - const result = []; + getAsyncWeakSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); - this.hooks.renderManifest.call(result, options); + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} - return result; +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(function(id) { + if(!__webpack_require__.m[id]) { + var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + ${returnModuleObject} + }); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(function() { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; } - /** - * Updates hash with information from this template - * @param {Hash} hash the hash to update - * @returns {void} - */ - updateHash(hash) { - hash.update("ChunkTemplate"); - hash.update("2"); - this.hooks.hash.call(hash); - } + getEagerSource(dependencies, id) { + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const thenFunction = + fakeMap !== 9 + ? `function(id) { + ${this.getReturnModuleObjectSource(fakeMap)} + }` + : "__webpack_require__"; + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} - /** - * TODO webpack 5: remove moduleTemplate and dependencyTemplates - * Updates hash with chunk-specific information from this template - * @param {Hash} hash the hash to update - * @param {Chunk} chunk the chunk - * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render - * @param {Map} dependencyTemplates dependency templates - * @returns {void} - */ - updateHashForChunk(hash, chunk, moduleTemplate, dependencyTemplates) { - this.updateHash(hash); - this.hooks.hashForChunk.call(hash, chunk); - } +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(function() { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); }; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } + getLazyOnceSource(block, dependencies, id, runtimeTemplate) { + const promise = runtimeTemplate.blockPromise({ + block, + message: "lazy-once context" + }); + const map = this.getUserRequestMap(dependencies); + const fakeMap = this.getFakeMap(dependencies); + const thenFunction = + fakeMap !== 9 + ? `function(id) { + ${this.getReturnModuleObjectSource(fakeMap)}; + }` + : "__webpack_require__"; -/***/ }), + return `var map = ${JSON.stringify(map, null, "\t")}; +${this.getFakeMapInitStatement(fakeMap)} -/***/ 51760: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +function webpackAsyncContext(req) { + return webpackAsyncContextResolve(req).then(${thenFunction}); +} +function webpackAsyncContextResolve(req) { + return ${promise}.then(function() { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } + return map[req]; + }); +} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.resolve = webpackAsyncContextResolve; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + getLazySource(blocks, id) { + let hasMultipleOrNoChunks = false; + let hasNoChunk = true; + const fakeMap = this.getFakeMap(blocks.map(b => b.dependencies[0])); + const hasFakeMap = typeof fakeMap === "object"; + const map = blocks + .filter(block => block.dependencies[0].module) + .map(block => { + const chunks = block.chunkGroup ? block.chunkGroup.chunks : []; + if (chunks.length > 0) { + hasNoChunk = false; + } + if (chunks.length !== 1) { + hasMultipleOrNoChunks = true; + } + return { + dependency: block.dependencies[0], + block: block, + userRequest: block.dependencies[0].userRequest, + chunks + }; + }) + .sort((a, b) => { + if (a.userRequest === b.userRequest) return 0; + return a.userRequest < b.userRequest ? -1 : 1; + }) + .reduce((map, item) => { + const chunks = item.chunks; + if (hasNoChunk && !hasFakeMap) { + map[item.userRequest] = item.dependency.module.id; + } else { + const arrayStart = [item.dependency.module.id]; + if (typeof fakeMap === "object") { + arrayStart.push(fakeMap[item.dependency.module.id]); + } + map[item.userRequest] = arrayStart.concat( + chunks.map(chunk => chunk.id) + ); + } -const WebpackError = __webpack_require__(97391); + return map; + }, Object.create(null)); -/** @typedef {import("./Module")} Module */ + const shortMode = hasNoChunk && !hasFakeMap; + const chunksStartPosition = hasFakeMap ? 2 : 1; + const requestPrefix = hasNoChunk + ? "Promise.resolve()" + : hasMultipleOrNoChunks + ? `Promise.all(ids.slice(${chunksStartPosition}).map(__webpack_require__.e))` + : `__webpack_require__.e(ids[${chunksStartPosition}])`; + const returnModuleObject = this.getReturnModuleObjectSource( + fakeMap, + shortMode ? "invalid" : "ids[1]" + ); -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + const webpackAsyncContext = + requestPrefix === "Promise.resolve()" + ? `${shortMode ? "" : ""} +function webpackAsyncContext(req) { + return Promise.resolve().then(function() { + if(!__webpack_require__.o(map, req)) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + } -class CommentCompilationWarning extends WebpackError { - /** - * - * @param {string} message warning message - * @param {Module} module affected module - * @param {DependencyLocation} loc affected lines of code - */ - constructor(message, module, loc) { - super(message); + ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"} + ${returnModuleObject} + }); +}` + : `function webpackAsyncContext(req) { + if(!__webpack_require__.o(map, req)) { + return Promise.resolve().then(function() { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); + } - this.name = "CommentCompilationWarning"; + var ids = map[req], id = ids[0]; + return ${requestPrefix}.then(function() { + ${returnModuleObject} + }); +}`; - this.module = module; - this.loc = loc; + return `var map = ${JSON.stringify(map, null, "\t")}; +${webpackAsyncContext} +webpackAsyncContext.keys = function webpackAsyncContextKeys() { + return Object.keys(map); +}; +webpackAsyncContext.id = ${JSON.stringify(id)}; +module.exports = webpackAsyncContext;`; + } - Error.captureStackTrace(this, this.constructor); + getSourceForEmptyContext(id) { + return `function webpackEmptyContext(req) { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; +} +webpackEmptyContext.keys = function() { return []; }; +webpackEmptyContext.resolve = webpackEmptyContext; +module.exports = webpackEmptyContext; +webpackEmptyContext.id = ${JSON.stringify(id)};`; } + + getSourceForEmptyAsyncContext(id) { + return `function webpackEmptyAsyncContext(req) { + // Here Promise.resolve().then() is used instead of new Promise() to prevent + // uncaught exception popping up in devtools + return Promise.resolve().then(function() { + var e = new Error("Cannot find module '" + req + "'"); + e.code = 'MODULE_NOT_FOUND'; + throw e; + }); } +webpackEmptyAsyncContext.keys = function() { return []; }; +webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; +module.exports = webpackEmptyAsyncContext; +webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`; + } -module.exports = CommentCompilationWarning; + getSourceString(asyncMode, runtimeTemplate) { + if (asyncMode === "lazy") { + if (this.blocks && this.blocks.length > 0) { + return this.getLazySource(this.blocks, this.id); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "eager") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getEagerSource(this.dependencies, this.id); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "lazy-once") { + const block = this.blocks[0]; + if (block) { + return this.getLazyOnceSource( + block, + block.dependencies, + this.id, + runtimeTemplate + ); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "async-weak") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getAsyncWeakSource(this.dependencies, this.id); + } + return this.getSourceForEmptyAsyncContext(this.id); + } + if (asyncMode === "weak") { + if (this.dependencies && this.dependencies.length > 0) { + return this.getWeakSyncSource(this.dependencies, this.id); + } + } + if (this.dependencies && this.dependencies.length > 0) { + return this.getSyncSource(this.dependencies, this.id); + } + return this.getSourceForEmptyContext(this.id); + } + getSource(sourceString) { + if (this.useSourceMap) { + return new OriginalSource(sourceString, this.identifier()); + } + return new RawSource(sourceString); + } -/***/ }), + source(dependencyTemplates, runtimeTemplate) { + return this.getSource( + this.getSourceString(this.options.mode, runtimeTemplate) + ); + } -/***/ 85736: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + size() { + // base penalty + const initialSize = 160; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // if we dont have dependencies we stop here. + return this.dependencies.reduce((size, dependency) => { + const element = /** @type {ContextElementDependency} */ (dependency); + return size + 5 + element.userRequest.length; + }, initialSize); + } +} +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "recursive", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {boolean} is recursive + */ + function() { + return this.options.recursive; + }, + "ContextModule.recursive has been moved to ContextModule.options.recursive" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {boolean} value is recursive + * @returns {void} + */ + function(value) { + this.options.recursive = value; + }, + "ContextModule.recursive has been moved to ContextModule.options.recursive" + ) +}); -const path = __webpack_require__(85622); -const ParserHelpers = __webpack_require__(23999); +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "regExp", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {RegExp} regular expression + */ + function() { + return this.options.regExp; + }, + "ContextModule.regExp has been moved to ContextModule.options.regExp" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {RegExp} value Regular expression + * @returns {void} + */ + function(value) { + this.options.regExp = value; + }, + "ContextModule.regExp has been moved to ContextModule.options.regExp" + ) +}); -class CommonJsStuffPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "CommonJsStuffPlugin", - (compilation, { normalModuleFactory }) => { - const handler = (parser, parserOptions) => { - parser.hooks.expression - .for("require.main.require") - .tap( - "CommonJsStuffPlugin", - ParserHelpers.expressionIsUnsupported( - parser, - "require.main.require is not supported by webpack." - ) - ); - parser.hooks.expression - .for("module.parent.require") - .tap( - "CommonJsStuffPlugin", - ParserHelpers.expressionIsUnsupported( - parser, - "module.parent.require is not supported by webpack." - ) - ); - parser.hooks.expression - .for("require.main") - .tap( - "CommonJsStuffPlugin", - ParserHelpers.toConstantDependencyWithWebpackRequire( - parser, - "__webpack_require__.c[__webpack_require__.s]" - ) - ); - parser.hooks.expression - .for("module.loaded") - .tap("CommonJsStuffPlugin", expr => { - parser.state.module.buildMeta.moduleConcatenationBailout = - "module.loaded"; - return ParserHelpers.toConstantDependency( - parser, - "module.l" - )(expr); - }); - parser.hooks.expression - .for("module.id") - .tap("CommonJsStuffPlugin", expr => { - parser.state.module.buildMeta.moduleConcatenationBailout = - "module.id"; - return ParserHelpers.toConstantDependency( - parser, - "module.i" - )(expr); - }); - parser.hooks.expression - .for("module.exports") - .tap("CommonJsStuffPlugin", () => { - const module = parser.state.module; - const isHarmony = - module.buildMeta && module.buildMeta.exportsType; - if (!isHarmony) return true; - }); - parser.hooks.evaluateIdentifier - .for("module.hot") - .tap( - "CommonJsStuffPlugin", - ParserHelpers.evaluateToIdentifier("module.hot", false) - ); - parser.hooks.expression - .for("module") - .tap("CommonJsStuffPlugin", () => { - const module = parser.state.module; - const isHarmony = - module.buildMeta && module.buildMeta.exportsType; - let moduleJsPath = isHarmony ? __webpack_require__.ab + "harmony-module.js" : __webpack_require__.ab + "module.js"; - if (module.context) { - moduleJsPath = path.relative( - parser.state.module.context, - moduleJsPath - ); - if (!/^[A-Z]:/i.test(moduleJsPath)) { - moduleJsPath = `./${moduleJsPath.replace(/\\/g, "/")}`; - } - } - return ParserHelpers.addParsedVariableToModule( - parser, - "module", - `require(${JSON.stringify(moduleJsPath)})(module)` - ); - }); - }; +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "addon", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {string} addon + */ + function() { + return this.options.addon; + }, + "ContextModule.addon has been moved to ContextModule.options.addon" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {string} value addon + * @returns {void} + */ + function(value) { + this.options.addon = value; + }, + "ContextModule.addon has been moved to ContextModule.options.addon" + ) +}); - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("CommonJsStuffPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("CommonJsStuffPlugin", handler); - } - ); - } -} -module.exports = CommonJsStuffPlugin; +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "async", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {boolean} is async + */ + function() { + return this.options.mode; + }, + "ContextModule.async has been moved to ContextModule.options.mode" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {ContextMode} value Context mode + * @returns {void} + */ + function(value) { + this.options.mode = value; + }, + "ContextModule.async has been moved to ContextModule.options.mode" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(ContextModule.prototype, "chunkName", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @returns {string} chunk name + */ + function() { + return this.options.chunkName; + }, + "ContextModule.chunkName has been moved to ContextModule.options.chunkName" + ), + set: util.deprecate( + /** + * @deprecated + * @this {ContextModule} + * @param {string} value chunk name + * @returns {void} + */ + function(value) { + this.options.chunkName = value; + }, + "ContextModule.chunkName has been moved to ContextModule.options.chunkName" + ) +}); + +module.exports = ContextModule; /***/ }), -/***/ 85918: +/***/ 88239: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -71754,2410 +72462,2032 @@ module.exports = CommonJsStuffPlugin; */ -const ConstDependency = __webpack_require__(71101); +const asyncLib = __webpack_require__(36386); +const path = __webpack_require__(85622); -const NullFactory = __webpack_require__(40438); +const { + Tapable, + AsyncSeriesWaterfallHook, + SyncWaterfallHook +} = __webpack_require__(56758); +const ContextModule = __webpack_require__(20090); +const ContextElementDependency = __webpack_require__(89079); -/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Module")} Module */ -class CompatibilityPlugin { - /** - * Apply the plugin - * @param {Compiler} compiler Webpack Compiler - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "CompatibilityPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set(ConstDependency, new NullFactory()); - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); +const EMPTY_RESOLVE_OPTIONS = {}; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("CompatibilityPlugin", (parser, parserOptions) => { - if ( - parserOptions.browserify !== undefined && - !parserOptions.browserify - ) - return; +module.exports = class ContextModuleFactory extends Tapable { + constructor(resolverFactory) { + super(); + this.hooks = { + /** @type {AsyncSeriesWaterfallHook} */ + beforeResolve: new AsyncSeriesWaterfallHook(["data"]), + /** @type {AsyncSeriesWaterfallHook} */ + afterResolve: new AsyncSeriesWaterfallHook(["data"]), + /** @type {SyncWaterfallHook} */ + contextModuleFiles: new SyncWaterfallHook(["files"]), + /** @type {SyncWaterfallHook} */ + alternatives: new AsyncSeriesWaterfallHook(["modules"]) + }; + this._pluginCompat.tap("ContextModuleFactory", options => { + switch (options.name) { + case "before-resolve": + case "after-resolve": + case "alternatives": + options.async = true; + break; + } + }); + this.resolverFactory = resolverFactory; + } - parser.hooks.call - .for("require") - .tap("CompatibilityPlugin", expr => { - // support for browserify style require delegator: "require(o, !0)" - if (expr.arguments.length !== 2) return; - const second = parser.evaluateExpression(expr.arguments[1]); - if (!second.isBoolean()) return; - if (second.asBool() !== true) return; - const dep = new ConstDependency("require", expr.callee.range); - dep.loc = expr.loc; - if (parser.state.current.dependencies.length > 1) { - const last = - parser.state.current.dependencies[ - parser.state.current.dependencies.length - 1 - ]; - if ( - last.critical && - last.options && - last.options.request === "." && - last.userRequest === "." && - last.options.recursive - ) - parser.state.current.dependencies.pop(); + create(data, callback) { + const context = data.context; + const dependencies = data.dependencies; + const resolveOptions = data.resolveOptions; + const dependency = dependencies[0]; + this.hooks.beforeResolve.callAsync( + Object.assign( + { + context: context, + dependencies: dependencies, + resolveOptions + }, + dependency.options + ), + (err, beforeResolveResult) => { + if (err) return callback(err); + + // Ignored + if (!beforeResolveResult) return callback(); + + const context = beforeResolveResult.context; + const request = beforeResolveResult.request; + const resolveOptions = beforeResolveResult.resolveOptions; + + let loaders, + resource, + loadersPrefix = ""; + const idx = request.lastIndexOf("!"); + if (idx >= 0) { + let loadersRequest = request.substr(0, idx + 1); + let i; + for ( + i = 0; + i < loadersRequest.length && loadersRequest[i] === "!"; + i++ + ) { + loadersPrefix += "!"; + } + loadersRequest = loadersRequest + .substr(i) + .replace(/!+$/, "") + .replace(/!!+/g, "!"); + if (loadersRequest === "") { + loaders = []; + } else { + loaders = loadersRequest.split("!"); + } + resource = request.substr(idx + 1); + } else { + loaders = []; + resource = request; + } + + const contextResolver = this.resolverFactory.get( + "context", + resolveOptions || EMPTY_RESOLVE_OPTIONS + ); + const loaderResolver = this.resolverFactory.get( + "loader", + EMPTY_RESOLVE_OPTIONS + ); + + asyncLib.parallel( + [ + callback => { + contextResolver.resolve( + {}, + context, + resource, + {}, + (err, result) => { + if (err) return callback(err); + callback(null, result); } - parser.state.current.addDependency(dep); - return true; - }); - }); + ); + }, + callback => { + asyncLib.map( + loaders, + (loader, callback) => { + loaderResolver.resolve( + {}, + context, + loader, + {}, + (err, result) => { + if (err) return callback(err); + callback(null, result); + } + ); + }, + callback + ); + } + ], + (err, result) => { + if (err) return callback(err); + + this.hooks.afterResolve.callAsync( + Object.assign( + { + addon: + loadersPrefix + + result[1].join("!") + + (result[1].length > 0 ? "!" : ""), + resource: result[0], + resolveDependencies: this.resolveDependencies.bind(this) + }, + beforeResolveResult + ), + (err, result) => { + if (err) return callback(err); + + // Ignored + if (!result) return callback(); + + return callback( + null, + new ContextModule(result.resolveDependencies, result) + ); + } + ); + } + ); } ); } -} -module.exports = CompatibilityPlugin; + + resolveDependencies(fs, options, callback) { + const cmf = this; + let resource = options.resource; + let resourceQuery = options.resourceQuery; + let recursive = options.recursive; + let regExp = options.regExp; + let include = options.include; + let exclude = options.exclude; + if (!regExp || !resource) return callback(null, []); + + const addDirectory = (directory, callback) => { + fs.readdir(directory, (err, files) => { + if (err) return callback(err); + files = cmf.hooks.contextModuleFiles.call(files); + if (!files || files.length === 0) return callback(null, []); + asyncLib.map( + files.filter(p => p.indexOf(".") !== 0), + (segment, callback) => { + const subResource = path.join(directory, segment); + + if (!exclude || !subResource.match(exclude)) { + fs.stat(subResource, (err, stat) => { + if (err) { + if (err.code === "ENOENT") { + // ENOENT is ok here because the file may have been deleted between + // the readdir and stat calls. + return callback(); + } else { + return callback(err); + } + } + + if (stat.isDirectory()) { + if (!recursive) return callback(); + addDirectory.call(this, subResource, callback); + } else if ( + stat.isFile() && + (!include || subResource.match(include)) + ) { + const obj = { + context: resource, + request: + "." + + subResource.substr(resource.length).replace(/\\/g, "/") + }; + + this.hooks.alternatives.callAsync( + [obj], + (err, alternatives) => { + if (err) return callback(err); + alternatives = alternatives + .filter(obj => regExp.test(obj.request)) + .map(obj => { + const dep = new ContextElementDependency( + obj.request + resourceQuery, + obj.request + ); + dep.optional = true; + return dep; + }); + callback(null, alternatives); + } + ); + } else { + callback(); + } + }); + } else { + callback(); + } + }, + (err, result) => { + if (err) return callback(err); + + if (!result) return callback(null, []); + + callback( + null, + result.filter(Boolean).reduce((a, i) => a.concat(i), []) + ); + } + ); + }); + }; + + addDirectory(resource, callback); + } +}; /***/ }), -/***/ 34968: +/***/ 27295: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra - */ +*/ -const asyncLib = __webpack_require__(36386); -const util = __webpack_require__(31669); -const { CachedSource } = __webpack_require__(53665); -const { - Tapable, - SyncHook, - SyncBailHook, - SyncWaterfallHook, - AsyncSeriesHook -} = __webpack_require__(56758); -const EntryModuleNotFoundError = __webpack_require__(99531); -const ModuleNotFoundError = __webpack_require__(71638); -const ModuleDependencyWarning = __webpack_require__(59136); -const ModuleDependencyError = __webpack_require__(14953); -const ChunkGroup = __webpack_require__(52911); -const Chunk = __webpack_require__(2919); -const Entrypoint = __webpack_require__(71931); -const MainTemplate = __webpack_require__(43626); -const ChunkTemplate = __webpack_require__(6170); -const HotUpdateChunkTemplate = __webpack_require__(66062); -const ModuleTemplate = __webpack_require__(75100); -const RuntimeTemplate = __webpack_require__(44006); -const ChunkRenderError = __webpack_require__(69865); -const Stats = __webpack_require__(99977); -const Semaphore = __webpack_require__(33349); -const createHash = __webpack_require__(15660); -const SortableSet = __webpack_require__(50071); -const GraphHelpers = __webpack_require__(32973); -const ModuleDependency = __webpack_require__(90865); -const compareLocations = __webpack_require__(22562); -const { Logger, LogType } = __webpack_require__(47194); -const ErrorHelpers = __webpack_require__(80140); -const buildChunkGraph = __webpack_require__(52337); -const WebpackError = __webpack_require__(97391); +const path = __webpack_require__(85622); +const ContextElementDependency = __webpack_require__(89079); -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./DependenciesBlockVariable")} DependenciesBlockVariable */ -/** @typedef {import("./dependencies/SingleEntryDependency")} SingleEntryDependency */ -/** @typedef {import("./dependencies/MultiEntryDependency")} MultiEntryDependency */ -/** @typedef {import("./dependencies/DllEntryDependency")} DllEntryDependency */ -/** @typedef {import("./dependencies/DependencyReference")} DependencyReference */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ -/** @typedef {import("./util/createHash").Hash} Hash */ +class ContextReplacementPlugin { + constructor( + resourceRegExp, + newContentResource, + newContentRecursive, + newContentRegExp + ) { + this.resourceRegExp = resourceRegExp; -// TODO use @callback -/** @typedef {{[assetName: string]: Source}} CompilationAssets */ -/** @typedef {(err: Error|null, result?: Module) => void } ModuleCallback */ -/** @typedef {(err?: Error|null, result?: Module) => void } ModuleChainCallback */ -/** @typedef {(module: Module) => void} OnModuleCallback */ -/** @typedef {(err?: Error|null) => void} Callback */ -/** @typedef {(d: Dependency) => any} DepBlockVarDependenciesCallback */ -/** @typedef {new (...args: any[]) => Dependency} DepConstructor */ -/** @typedef {{apply: () => void}} Plugin */ + if (typeof newContentResource === "function") { + this.newContentCallback = newContentResource; + } else if ( + typeof newContentResource === "string" && + typeof newContentRecursive === "object" + ) { + this.newContentResource = newContentResource; + this.newContentCreateContextMap = (fs, callback) => { + callback(null, newContentRecursive); + }; + } else if ( + typeof newContentResource === "string" && + typeof newContentRecursive === "function" + ) { + this.newContentResource = newContentResource; + this.newContentCreateContextMap = newContentRecursive; + } else { + if (typeof newContentResource !== "string") { + newContentRegExp = newContentRecursive; + newContentRecursive = newContentResource; + newContentResource = undefined; + } + if (typeof newContentRecursive !== "boolean") { + newContentRegExp = newContentRecursive; + newContentRecursive = undefined; + } + this.newContentResource = newContentResource; + this.newContentRecursive = newContentRecursive; + this.newContentRegExp = newContentRegExp; + } + } -/** - * @typedef {Object} ModuleFactoryCreateDataContextInfo - * @property {string} issuer - * @property {string} compiler - */ + apply(compiler) { + const resourceRegExp = this.resourceRegExp; + const newContentCallback = this.newContentCallback; + const newContentResource = this.newContentResource; + const newContentRecursive = this.newContentRecursive; + const newContentRegExp = this.newContentRegExp; + const newContentCreateContextMap = this.newContentCreateContextMap; -/** - * @typedef {Object} ModuleFactoryCreateData - * @property {ModuleFactoryCreateDataContextInfo} contextInfo - * @property {any=} resolveOptions - * @property {string} context - * @property {Dependency[]} dependencies - */ + compiler.hooks.contextModuleFactory.tap("ContextReplacementPlugin", cmf => { + cmf.hooks.beforeResolve.tap("ContextReplacementPlugin", result => { + if (!result) return; + if (resourceRegExp.test(result.request)) { + if (newContentResource !== undefined) { + result.request = newContentResource; + } + if (newContentRecursive !== undefined) { + result.recursive = newContentRecursive; + } + if (newContentRegExp !== undefined) { + result.regExp = newContentRegExp; + } + if (typeof newContentCallback === "function") { + newContentCallback(result); + } else { + for (const d of result.dependencies) { + if (d.critical) d.critical = false; + } + } + } + return result; + }); + cmf.hooks.afterResolve.tap("ContextReplacementPlugin", result => { + if (!result) return; + if (resourceRegExp.test(result.resource)) { + if (newContentResource !== undefined) { + result.resource = path.resolve(result.resource, newContentResource); + } + if (newContentRecursive !== undefined) { + result.recursive = newContentRecursive; + } + if (newContentRegExp !== undefined) { + result.regExp = newContentRegExp; + } + if (typeof newContentCreateContextMap === "function") { + result.resolveDependencies = createResolveDependenciesFromContextMap( + newContentCreateContextMap + ); + } + if (typeof newContentCallback === "function") { + const origResource = result.resource; + newContentCallback(result); + if (result.resource !== origResource) { + result.resource = path.resolve(origResource, result.resource); + } + } else { + for (const d of result.dependencies) { + if (d.critical) d.critical = false; + } + } + } + return result; + }); + }); + } +} -/** - * @typedef {Object} ModuleFactory - * @property {(data: ModuleFactoryCreateData, callback: ModuleCallback) => any} create - */ +const createResolveDependenciesFromContextMap = createContextMap => { + const resolveDependenciesFromContextMap = (fs, options, callback) => { + createContextMap(fs, (err, map) => { + if (err) return callback(err); + const dependencies = Object.keys(map).map(key => { + return new ContextElementDependency( + map[key] + options.resourceQuery, + key + ); + }); + callback(null, dependencies); + }); + }; + return resolveDependenciesFromContextMap; +}; -/** - * @typedef {Object} SortedDependency - * @property {ModuleFactory} factory - * @property {Dependency[]} dependencies - */ +module.exports = ContextReplacementPlugin; -/** - * @typedef {Object} DependenciesBlockLike - * @property {Dependency[]} dependencies - * @property {AsyncDependenciesBlock[]} blocks - * @property {DependenciesBlockVariable[]} variables - */ -/** - * @typedef {Object} LogEntry - * @property {string} type - * @property {any[]} args - * @property {number} time - * @property {string[]=} trace - */ +/***/ }), -/** - * @typedef {Object} AssetInfo - * @property {boolean=} immutable true, if the asset can be long term cached forever (contains a hash) - * @property {number=} size size in bytes, only set after asset has been emitted - * @property {boolean=} development true, when asset is only used for development and doesn't count towards user-facing assets - * @property {boolean=} hotModuleReplacement true, when asset ships data for updating an existing application (HMR) - */ +/***/ 97374: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * @typedef {Object} Asset - * @property {string} name the filename of the asset - * @property {Source} source source of the asset - * @property {AssetInfo} info info about the asset - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * @param {Chunk} a first chunk to sort by id - * @param {Chunk} b second chunk to sort by id - * @returns {-1|0|1} sort value - */ -const byId = (a, b) => { - if (typeof a.id !== typeof b.id) { - return typeof a.id < typeof b.id ? -1 : 1; - } - if (a.id < b.id) return -1; - if (a.id > b.id) return 1; - return 0; -}; -/** - * @param {Module} a first module to sort by - * @param {Module} b second module to sort by - * @returns {-1|0|1} sort value - */ -const byIdOrIdentifier = (a, b) => { - if (typeof a.id !== typeof b.id) { - return typeof a.id < typeof b.id ? -1 : 1; - } - if (a.id < b.id) return -1; - if (a.id > b.id) return 1; - const identA = a.identifier(); - const identB = b.identifier(); - if (identA < identB) return -1; - if (identA > identB) return 1; - return 0; -}; +const ConstDependency = __webpack_require__(71101); +const BasicEvaluatedExpression = __webpack_require__(96770); +const ParserHelpers = __webpack_require__(23999); +const NullFactory = __webpack_require__(40438); -/** - * @param {Module} a first module to sort by - * @param {Module} b second module to sort by - * @returns {-1|0|1} sort value - */ -const byIndexOrIdentifier = (a, b) => { - if (a.index < b.index) return -1; - if (a.index > b.index) return 1; - const identA = a.identifier(); - const identB = b.identifier(); - if (identA < identB) return -1; - if (identA > identB) return 1; - return 0; -}; +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Parser")} Parser */ +/** @typedef {null|undefined|RegExp|Function|string|number} CodeValuePrimitive */ +/** @typedef {CodeValuePrimitive|Record|RuntimeValue} CodeValue */ -/** - * @param {Compilation} a first compilation to sort by - * @param {Compilation} b second compilation to sort by - * @returns {-1|0|1} sort value - */ -const byNameOrHash = (a, b) => { - if (a.name < b.name) return -1; - if (a.name > b.name) return 1; - if (a.fullHash < b.fullHash) return -1; - if (a.fullHash > b.fullHash) return 1; - return 0; -}; +class RuntimeValue { + constructor(fn, fileDependencies) { + this.fn = fn; + this.fileDependencies = fileDependencies || []; + } -/** - * @param {DependenciesBlockVariable[]} variables DepBlock Variables to iterate over - * @param {DepBlockVarDependenciesCallback} fn callback to apply on iterated elements - * @returns {void} - */ -const iterationBlockVariable = (variables, fn) => { - for ( - let indexVariable = 0; - indexVariable < variables.length; - indexVariable++ - ) { - const varDep = variables[indexVariable].dependencies; - for (let indexVDep = 0; indexVDep < varDep.length; indexVDep++) { - fn(varDep[indexVDep]); + exec(parser) { + if (this.fileDependencies === true) { + parser.state.module.buildInfo.cacheable = false; + } else { + for (const fileDependency of this.fileDependencies) { + parser.state.module.buildInfo.fileDependencies.add(fileDependency); + } } - } -}; -/** - * @template T - * @param {T[]} arr array of elements to iterate over - * @param {function(T): void} fn callback applied to each element - * @returns {void} - */ -const iterationOfArrayCallback = (arr, fn) => { - for (let index = 0; index < arr.length; index++) { - fn(arr[index]); + return this.fn({ module: parser.state.module }); } -}; +} -/** - * @template T - * @param {Set} set set to add items to - * @param {Set} otherSet set to add items from - * @returns {void} - */ -const addAllToSet = (set, otherSet) => { - for (const item of otherSet) { - set.add(item); - } +const stringifyObj = (obj, parser) => { + return ( + "Object({" + + Object.keys(obj) + .map(key => { + const code = obj[key]; + return JSON.stringify(key) + ":" + toCode(code, parser); + }) + .join(",") + + "})" + ); }; /** - * @param {Source} a a source - * @param {Source} b another source - * @returns {boolean} true, when both sources are equal + * Convert code to a string that evaluates + * @param {CodeValue} code Code to evaluate + * @param {Parser} parser Parser + * @returns {string} code converted to string that evaluates */ -const isSourceEqual = (a, b) => { - if (a === b) return true; - // TODO webpack 5: check .buffer() instead, it's called anyway during emit - /** @type {Buffer|string} */ - let aSource = a.source(); - /** @type {Buffer|string} */ - let bSource = b.source(); - if (aSource === bSource) return true; - if (typeof aSource === "string" && typeof bSource === "string") return false; - if (!Buffer.isBuffer(aSource)) aSource = Buffer.from(aSource, "utf-8"); - if (!Buffer.isBuffer(bSource)) bSource = Buffer.from(bSource, "utf-8"); - return aSource.equals(bSource); +const toCode = (code, parser) => { + if (code === null) { + return "null"; + } + if (code === undefined) { + return "undefined"; + } + if (code instanceof RuntimeValue) { + return toCode(code.exec(parser), parser); + } + if (code instanceof RegExp && code.toString) { + return code.toString(); + } + if (typeof code === "function" && code.toString) { + return "(" + code.toString() + ")"; + } + if (typeof code === "object") { + return stringifyObj(code, parser); + } + return code + ""; }; -class Compilation extends Tapable { +class DefinePlugin { /** - * Creates an instance of Compilation. - * @param {Compiler} compiler the compiler which created the compilation + * Create a new define plugin + * @param {Record} definitions A map of global object definitions */ - constructor(compiler) { - super(); - this.hooks = { - /** @type {SyncHook} */ - buildModule: new SyncHook(["module"]), - /** @type {SyncHook} */ - rebuildModule: new SyncHook(["module"]), - /** @type {SyncHook} */ - failedModule: new SyncHook(["module", "error"]), - /** @type {SyncHook} */ - succeedModule: new SyncHook(["module"]), - - /** @type {SyncHook} */ - addEntry: new SyncHook(["entry", "name"]), - /** @type {SyncHook} */ - failedEntry: new SyncHook(["entry", "name", "error"]), - /** @type {SyncHook} */ - succeedEntry: new SyncHook(["entry", "name", "module"]), - - /** @type {SyncWaterfallHook} */ - dependencyReference: new SyncWaterfallHook([ - "dependencyReference", - "dependency", - "module" - ]), - - /** @type {AsyncSeriesHook} */ - finishModules: new AsyncSeriesHook(["modules"]), - /** @type {SyncHook} */ - finishRebuildingModule: new SyncHook(["module"]), - /** @type {SyncHook} */ - unseal: new SyncHook([]), - /** @type {SyncHook} */ - seal: new SyncHook([]), - - /** @type {SyncHook} */ - beforeChunks: new SyncHook([]), - /** @type {SyncHook} */ - afterChunks: new SyncHook(["chunks"]), - - /** @type {SyncBailHook} */ - optimizeDependenciesBasic: new SyncBailHook(["modules"]), - /** @type {SyncBailHook} */ - optimizeDependencies: new SyncBailHook(["modules"]), - /** @type {SyncBailHook} */ - optimizeDependenciesAdvanced: new SyncBailHook(["modules"]), - /** @type {SyncBailHook} */ - afterOptimizeDependencies: new SyncHook(["modules"]), + constructor(definitions) { + this.definitions = definitions; + } - /** @type {SyncHook} */ - optimize: new SyncHook([]), - /** @type {SyncBailHook} */ - optimizeModulesBasic: new SyncBailHook(["modules"]), - /** @type {SyncBailHook} */ - optimizeModules: new SyncBailHook(["modules"]), - /** @type {SyncBailHook} */ - optimizeModulesAdvanced: new SyncBailHook(["modules"]), - /** @type {SyncHook} */ - afterOptimizeModules: new SyncHook(["modules"]), + static runtimeValue(fn, fileDependencies) { + return new RuntimeValue(fn, fileDependencies); + } - /** @type {SyncBailHook} */ - optimizeChunksBasic: new SyncBailHook(["chunks", "chunkGroups"]), - /** @type {SyncBailHook} */ - optimizeChunks: new SyncBailHook(["chunks", "chunkGroups"]), - /** @type {SyncBailHook} */ - optimizeChunksAdvanced: new SyncBailHook(["chunks", "chunkGroups"]), - /** @type {SyncHook} */ - afterOptimizeChunks: new SyncHook(["chunks", "chunkGroups"]), + /** + * Apply the plugin + * @param {Compiler} compiler Webpack compiler + * @returns {void} + */ + apply(compiler) { + const definitions = this.definitions; + compiler.hooks.compilation.tap( + "DefinePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); - /** @type {AsyncSeriesHook} */ - optimizeTree: new AsyncSeriesHook(["chunks", "modules"]), - /** @type {SyncHook} */ - afterOptimizeTree: new SyncHook(["chunks", "modules"]), + /** + * Handler + * @param {Parser} parser Parser + * @returns {void} + */ + const handler = parser => { + /** + * Walk definitions + * @param {Object} definitions Definitions map + * @param {string} prefix Prefix string + * @returns {void} + */ + const walkDefinitions = (definitions, prefix) => { + Object.keys(definitions).forEach(key => { + const code = definitions[key]; + if ( + code && + typeof code === "object" && + !(code instanceof RuntimeValue) && + !(code instanceof RegExp) + ) { + walkDefinitions(code, prefix + key + "."); + applyObjectDefine(prefix + key, code); + return; + } + applyDefineKey(prefix, key); + applyDefine(prefix + key, code); + }); + }; - /** @type {SyncBailHook} */ - optimizeChunkModulesBasic: new SyncBailHook(["chunks", "modules"]), - /** @type {SyncBailHook} */ - optimizeChunkModules: new SyncBailHook(["chunks", "modules"]), - /** @type {SyncBailHook} */ - optimizeChunkModulesAdvanced: new SyncBailHook(["chunks", "modules"]), - /** @type {SyncHook} */ - afterOptimizeChunkModules: new SyncHook(["chunks", "modules"]), - /** @type {SyncBailHook} */ - shouldRecord: new SyncBailHook([]), + /** + * Apply define key + * @param {string} prefix Prefix + * @param {string} key Key + * @returns {void} + */ + const applyDefineKey = (prefix, key) => { + const splittedKey = key.split("."); + splittedKey.slice(1).forEach((_, i) => { + const fullKey = prefix + splittedKey.slice(0, i + 1).join("."); + parser.hooks.canRename + .for(fullKey) + .tap("DefinePlugin", ParserHelpers.approve); + }); + }; - /** @type {SyncHook} */ - reviveModules: new SyncHook(["modules", "records"]), - /** @type {SyncHook} */ - optimizeModuleOrder: new SyncHook(["modules"]), - /** @type {SyncHook} */ - advancedOptimizeModuleOrder: new SyncHook(["modules"]), - /** @type {SyncHook} */ - beforeModuleIds: new SyncHook(["modules"]), - /** @type {SyncHook} */ - moduleIds: new SyncHook(["modules"]), - /** @type {SyncHook} */ - optimizeModuleIds: new SyncHook(["modules"]), - /** @type {SyncHook} */ - afterOptimizeModuleIds: new SyncHook(["modules"]), + /** + * Apply Code + * @param {string} key Key + * @param {CodeValue} code Code + * @returns {void} + */ + const applyDefine = (key, code) => { + const isTypeof = /^typeof\s+/.test(key); + if (isTypeof) key = key.replace(/^typeof\s+/, ""); + let recurse = false; + let recurseTypeof = false; + if (!isTypeof) { + parser.hooks.canRename + .for(key) + .tap("DefinePlugin", ParserHelpers.approve); + parser.hooks.evaluateIdentifier + .for(key) + .tap("DefinePlugin", expr => { + /** + * this is needed in case there is a recursion in the DefinePlugin + * to prevent an endless recursion + * e.g.: new DefinePlugin({ + * "a": "b", + * "b": "a" + * }); + */ + if (recurse) return; + recurse = true; + const res = parser.evaluate(toCode(code, parser)); + recurse = false; + res.setRange(expr.range); + return res; + }); + parser.hooks.expression.for(key).tap("DefinePlugin", expr => { + const strCode = toCode(code, parser); + if (/__webpack_require__/.test(strCode)) { + return ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + strCode + )(expr); + } else { + return ParserHelpers.toConstantDependency( + parser, + strCode + )(expr); + } + }); + } + parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => { + /** + * this is needed in case there is a recursion in the DefinePlugin + * to prevent an endless recursion + * e.g.: new DefinePlugin({ + * "typeof a": "typeof b", + * "typeof b": "typeof a" + * }); + */ + if (recurseTypeof) return; + recurseTypeof = true; + const typeofCode = isTypeof + ? toCode(code, parser) + : "typeof (" + toCode(code, parser) + ")"; + const res = parser.evaluate(typeofCode); + recurseTypeof = false; + res.setRange(expr.range); + return res; + }); + parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { + const typeofCode = isTypeof + ? toCode(code, parser) + : "typeof (" + toCode(code, parser) + ")"; + const res = parser.evaluate(typeofCode); + if (!res.isString()) return; + return ParserHelpers.toConstantDependency( + parser, + JSON.stringify(res.string) + ).bind(parser)(expr); + }); + }; - /** @type {SyncHook} */ - reviveChunks: new SyncHook(["chunks", "records"]), - /** @type {SyncHook} */ - optimizeChunkOrder: new SyncHook(["chunks"]), - /** @type {SyncHook} */ - beforeChunkIds: new SyncHook(["chunks"]), - /** @type {SyncHook} */ - optimizeChunkIds: new SyncHook(["chunks"]), - /** @type {SyncHook} */ - afterOptimizeChunkIds: new SyncHook(["chunks"]), + /** + * Apply Object + * @param {string} key Key + * @param {Object} obj Object + * @returns {void} + */ + const applyObjectDefine = (key, obj) => { + parser.hooks.canRename + .for(key) + .tap("DefinePlugin", ParserHelpers.approve); + parser.hooks.evaluateIdentifier + .for(key) + .tap("DefinePlugin", expr => + new BasicEvaluatedExpression().setTruthy().setRange(expr.range) + ); + parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => { + return ParserHelpers.evaluateToString("object")(expr); + }); + parser.hooks.expression.for(key).tap("DefinePlugin", expr => { + const strCode = stringifyObj(obj, parser); - /** @type {SyncHook} */ - recordModules: new SyncHook(["modules", "records"]), - /** @type {SyncHook} */ - recordChunks: new SyncHook(["chunks", "records"]), + if (/__webpack_require__/.test(strCode)) { + return ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + strCode + )(expr); + } else { + return ParserHelpers.toConstantDependency( + parser, + strCode + )(expr); + } + }); + parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { + return ParserHelpers.toConstantDependency( + parser, + JSON.stringify("object") + )(expr); + }); + }; - /** @type {SyncHook} */ - beforeHash: new SyncHook([]), - /** @type {SyncHook} */ - contentHash: new SyncHook(["chunk"]), - /** @type {SyncHook} */ - afterHash: new SyncHook([]), - /** @type {SyncHook} */ - recordHash: new SyncHook(["records"]), - /** @type {SyncHook} */ - record: new SyncHook(["compilation", "records"]), + walkDefinitions(definitions, ""); + }; - /** @type {SyncHook} */ - beforeModuleAssets: new SyncHook([]), - /** @type {SyncBailHook} */ - shouldGenerateChunkAssets: new SyncBailHook([]), - /** @type {SyncHook} */ - beforeChunkAssets: new SyncHook([]), - /** @type {SyncHook} */ - additionalChunkAssets: new SyncHook(["chunks"]), + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("DefinePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("DefinePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("DefinePlugin", handler); + } + ); + } +} +module.exports = DefinePlugin; - /** @type {AsyncSeriesHook} */ - additionalAssets: new AsyncSeriesHook([]), - /** @type {AsyncSeriesHook} */ - optimizeChunkAssets: new AsyncSeriesHook(["chunks"]), - /** @type {SyncHook} */ - afterOptimizeChunkAssets: new SyncHook(["chunks"]), - /** @type {AsyncSeriesHook} */ - optimizeAssets: new AsyncSeriesHook(["assets"]), - /** @type {SyncHook} */ - afterOptimizeAssets: new SyncHook(["assets"]), - /** @type {SyncBailHook} */ - needAdditionalSeal: new SyncBailHook([]), - /** @type {AsyncSeriesHook} */ - afterSeal: new AsyncSeriesHook([]), +/***/ }), - /** @type {SyncHook} */ - chunkHash: new SyncHook(["chunk", "chunkHash"]), - /** @type {SyncHook} */ - moduleAsset: new SyncHook(["module", "filename"]), - /** @type {SyncHook} */ - chunkAsset: new SyncHook(["chunk", "filename"]), +/***/ 42173: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {SyncWaterfallHook} */ - assetPath: new SyncWaterfallHook(["filename", "data"]), // TODO MainTemplate +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {SyncBailHook} */ - needAdditionalPass: new SyncBailHook([]), - /** @type {SyncHook} */ - childCompiler: new SyncHook([ - "childCompiler", - "compilerName", - "compilerIndex" - ]), +const { OriginalSource, RawSource } = __webpack_require__(53665); - /** @type {SyncBailHook} */ - log: new SyncBailHook(["origin", "logEntry"]), +const Module = __webpack_require__(75993); +const WebpackMissingModule = __webpack_require__(75386); +const DelegatedSourceDependency = __webpack_require__(25930); +const DelegatedExportsDependency = __webpack_require__(53104); - // TODO the following hooks are weirdly located here - // TODO move them for webpack 5 - /** @type {SyncHook} */ - normalModuleLoader: new SyncHook(["loaderContext", "module"]), +/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ +/** @typedef {import("./util/createHash").Hash} Hash */ - /** @type {SyncBailHook} */ - optimizeExtractedChunksBasic: new SyncBailHook(["chunks"]), - /** @type {SyncBailHook} */ - optimizeExtractedChunks: new SyncBailHook(["chunks"]), - /** @type {SyncBailHook} */ - optimizeExtractedChunksAdvanced: new SyncBailHook(["chunks"]), - /** @type {SyncHook} */ - afterOptimizeExtractedChunks: new SyncHook(["chunks"]) - }; - this._pluginCompat.tap("Compilation", options => { - switch (options.name) { - case "optimize-tree": - case "additional-assets": - case "optimize-chunk-assets": - case "optimize-assets": - case "after-seal": - options.async = true; - break; - } - }); - /** @type {string=} */ - this.name = undefined; - /** @type {Compiler} */ - this.compiler = compiler; - this.resolverFactory = compiler.resolverFactory; - this.inputFileSystem = compiler.inputFileSystem; - this.requestShortener = compiler.requestShortener; +class DelegatedModule extends Module { + constructor(sourceRequest, data, type, userRequest, originalRequest) { + super("javascript/dynamic", null); - const options = compiler.options; - this.options = options; - this.outputOptions = options && options.output; - /** @type {boolean=} */ - this.bail = options && options.bail; - this.profile = options && options.profile; - this.performance = options && options.performance; + // Info from Factory + this.sourceRequest = sourceRequest; + this.request = data.id; + this.type = type; + this.userRequest = userRequest; + this.originalRequest = originalRequest; + this.delegateData = data; - this.mainTemplate = new MainTemplate(this.outputOptions); - this.chunkTemplate = new ChunkTemplate(this.outputOptions); - this.hotUpdateChunkTemplate = new HotUpdateChunkTemplate( - this.outputOptions - ); - this.runtimeTemplate = new RuntimeTemplate( - this.outputOptions, - this.requestShortener - ); - this.moduleTemplates = { - javascript: new ModuleTemplate(this.runtimeTemplate, "javascript"), - webassembly: new ModuleTemplate(this.runtimeTemplate, "webassembly") - }; + // Build info + this.delegatedSourceDependency = undefined; + } - this.semaphore = new Semaphore(options.parallelism || 100); + libIdent(options) { + return typeof this.originalRequest === "string" + ? this.originalRequest + : this.originalRequest.libIdent(options); + } - this.entries = []; - /** @private @type {{name: string, request: string, module: Module}[]} */ - this._preparedEntrypoints = []; - /** @type {Map} */ - this.entrypoints = new Map(); - /** @type {Chunk[]} */ - this.chunks = []; - /** @type {ChunkGroup[]} */ - this.chunkGroups = []; - /** @type {Map} */ - this.namedChunkGroups = new Map(); - /** @type {Map} */ - this.namedChunks = new Map(); - /** @type {Module[]} */ - this.modules = []; - /** @private @type {Map} */ - this._modules = new Map(); - this.cache = null; - this.records = null; - /** @type {string[]} */ - this.additionalChunkAssets = []; - /** @type {CompilationAssets} */ - this.assets = {}; - /** @type {Map} */ - this.assetsInfo = new Map(); - /** @type {WebpackError[]} */ - this.errors = []; - /** @type {WebpackError[]} */ - this.warnings = []; - /** @type {Compilation[]} */ - this.children = []; - /** @type {Map} */ - this.logging = new Map(); - /** @type {Map} */ - this.dependencyFactories = new Map(); - /** @type {Map} */ - this.dependencyTemplates = new Map(); - // TODO refactor this in webpack 5 to a custom DependencyTemplates class with a hash property - // @ts-ignore - this.dependencyTemplates.set("hash", ""); - this.childrenCounters = {}; - /** @type {Set} */ - this.usedChunkIds = null; - /** @type {Set} */ - this.usedModuleIds = null; - /** @type {Map=} */ - this.fileTimestamps = undefined; - /** @type {Map=} */ - this.contextTimestamps = undefined; - /** @type {Set=} */ - this.compilationDependencies = undefined; - /** @private @type {Map} */ - this._buildingModules = new Map(); - /** @private @type {Map} */ - this._rebuildingModules = new Map(); - /** @type {Set} */ - this.emittedAssets = new Set(); + identifier() { + return `delegated ${JSON.stringify(this.request)} from ${ + this.sourceRequest + }`; } - getStats() { - return new Stats(this); + readableIdentifier() { + return `delegated ${this.userRequest} from ${this.sourceRequest}`; } - /** - * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name - * @returns {Logger} a logger with that name - */ - getLogger(name) { - if (!name) { - throw new TypeError("Compilation.getLogger(name) called without a name"); - } - /** @type {LogEntry[] | undefined} */ - let logEntries; - return new Logger((type, args) => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compilation.getLogger(name) called with a function not returning a name" - ); - } - } - let trace; - switch (type) { - case LogType.warn: - case LogType.error: - case LogType.trace: - trace = ErrorHelpers.cutOffLoaderExecution(new Error("Trace").stack) - .split("\n") - .slice(3); + needRebuild() { + return false; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = Object.assign({}, this.delegateData.buildMeta); + this.buildInfo = {}; + this.delegatedSourceDependency = new DelegatedSourceDependency( + this.sourceRequest + ); + this.addDependency(this.delegatedSourceDependency); + this.addDependency( + new DelegatedExportsDependency(this, this.delegateData.exports || true) + ); + callback(); + } + + source(depTemplates, runtime) { + const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]); + const sourceModule = dep.module; + let str; + + if (!sourceModule) { + str = WebpackMissingModule.moduleCode(this.sourceRequest); + } else { + str = `module.exports = (${runtime.moduleExports({ + module: sourceModule, + request: dep.request + })})`; + + switch (this.type) { + case "require": + str += `(${JSON.stringify(this.request)})`; + break; + case "object": + str += `[${JSON.stringify(this.request)}]`; break; } - /** @type {LogEntry} */ - const logEntry = { - time: Date.now(), - type, - args, - trace - }; - if (this.hooks.log.call(name, logEntry) === undefined) { - if (logEntry.type === LogType.profileEnd) { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profileEnd === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profileEnd(`[${name}] ${logEntry.args[0]}`); - } - } - if (logEntries === undefined) { - logEntries = this.logging.get(name); - if (logEntries === undefined) { - logEntries = []; - this.logging.set(name, logEntries); - } - } - logEntries.push(logEntry); - if (logEntry.type === LogType.profile) { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profile === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profile(`[${name}] ${logEntry.args[0]}`); - } - } - } - }); + + str += ";"; + } + + if (this.useSourceMap) { + return new OriginalSource(str, this.identifier()); + } else { + return new RawSource(str); + } } - /** - * @typedef {Object} AddModuleResult - * @property {Module} module the added or existing module - * @property {boolean} issuer was this the first request for this module - * @property {boolean} build should the module be build - * @property {boolean} dependencies should dependencies be walked - */ + size() { + return 42; + } /** - * @param {Module} module module to be added that was created - * @param {any=} cacheGroup cacheGroup it is apart of - * @returns {AddModuleResult} returns meta about whether or not the module had built - * had an issuer, or any dependnecies + * @param {Hash} hash the hash used to track dependencies + * @returns {void} */ - addModule(module, cacheGroup) { - const identifier = module.identifier(); - const alreadyAddedModule = this._modules.get(identifier); - if (alreadyAddedModule) { - return { - module: alreadyAddedModule, - issuer: false, - build: false, - dependencies: false - }; - } - const cacheName = (cacheGroup || "m") + identifier; - if (this.cache && this.cache[cacheName]) { - const cacheModule = this.cache[cacheName]; + updateHash(hash) { + hash.update(this.type); + hash.update(JSON.stringify(this.request)); + super.updateHash(hash); + } +} - if (typeof cacheModule.updateCacheModule === "function") { - cacheModule.updateCacheModule(module); - } +module.exports = DelegatedModule; - let rebuild = true; - if (this.fileTimestamps && this.contextTimestamps) { - rebuild = cacheModule.needRebuild( - this.fileTimestamps, - this.contextTimestamps - ); - } - if (!rebuild) { - cacheModule.disconnect(); - this._modules.set(identifier, cacheModule); - this.modules.push(cacheModule); - for (const err of cacheModule.errors) { - this.errors.push(err); +/***/ }), + +/***/ 81002: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const DelegatedModule = __webpack_require__(42173); + +// options.source +// options.type +// options.context +// options.scope +// options.content +class DelegatedModuleFactoryPlugin { + constructor(options) { + this.options = options; + options.type = options.type || "require"; + options.extensions = options.extensions || [ + "", + ".wasm", + ".mjs", + ".js", + ".json" + ]; + } + + apply(normalModuleFactory) { + const scope = this.options.scope; + if (scope) { + normalModuleFactory.hooks.factory.tap( + "DelegatedModuleFactoryPlugin", + factory => (data, callback) => { + const dependency = data.dependencies[0]; + const request = dependency.request; + if (request && request.indexOf(scope + "/") === 0) { + const innerRequest = "." + request.substr(scope.length); + let resolved; + if (innerRequest in this.options.content) { + resolved = this.options.content[innerRequest]; + return callback( + null, + new DelegatedModule( + this.options.source, + resolved, + this.options.type, + innerRequest, + request + ) + ); + } + for (let i = 0; i < this.options.extensions.length; i++) { + const extension = this.options.extensions[i]; + const requestPlusExt = innerRequest + extension; + if (requestPlusExt in this.options.content) { + resolved = this.options.content[requestPlusExt]; + return callback( + null, + new DelegatedModule( + this.options.source, + resolved, + this.options.type, + requestPlusExt, + request + extension + ) + ); + } + } + } + return factory(data, callback); } - for (const err of cacheModule.warnings) { - this.warnings.push(err); + ); + } else { + normalModuleFactory.hooks.module.tap( + "DelegatedModuleFactoryPlugin", + module => { + if (module.libIdent) { + const request = module.libIdent(this.options); + if (request && request in this.options.content) { + const resolved = this.options.content[request]; + return new DelegatedModule( + this.options.source, + resolved, + this.options.type, + request, + module + ); + } + } + return module; } - return { - module: cacheModule, - issuer: true, - build: false, - dependencies: true - }; - } - cacheModule.unbuild(); - module = cacheModule; - } - this._modules.set(identifier, module); - if (this.cache) { - this.cache[cacheName] = module; + ); } - this.modules.push(module); - return { - module: module, - issuer: true, - build: true, - dependencies: true - }; + } +} +module.exports = DelegatedModuleFactoryPlugin; + + +/***/ }), + +/***/ 16071: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ + + +const DependenciesBlockVariable = __webpack_require__(82904); + +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./DependenciesBlockVariable")} DependenciesBlockVariable */ +/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */ +/** @typedef {import("./util/createHash").Hash} Hash */ + +class DependenciesBlock { + constructor() { + /** @type {Dependency[]} */ + this.dependencies = []; + /** @type {AsyncDependenciesBlock[]} */ + this.blocks = []; + /** @type {DependenciesBlockVariable[]} */ + this.variables = []; } /** - * Fetches a module from a compilation by its identifier - * @param {Module} module the module provided - * @returns {Module} the module requested + * Adds a DependencyBlock to DependencyBlock relationship. + * This is used for when a Module has a AsyncDependencyBlock tie (for code-splitting) + * + * @param {AsyncDependenciesBlock} block block being added + * @returns {void} */ - getModule(module) { - const identifier = module.identifier(); - return this._modules.get(identifier); + addBlock(block) { + this.blocks.push(block); + block.parent = this; } /** - * Attempts to search for a module by its identifier - * @param {string} identifier identifier (usually path) for module - * @returns {Module|undefined} attempt to search for module and return it, else undefined + * @param {string} name name of dependency + * @param {string} expression expression string for variable + * @param {Dependency[]} dependencies dependency instances tied to variable + * @returns {void} */ - findModule(identifier) { - return this._modules.get(identifier); + addVariable(name, expression, dependencies) { + for (let v of this.variables) { + if (v.name === name && v.expression === expression) { + return; + } + } + this.variables.push( + new DependenciesBlockVariable(name, expression, dependencies) + ); } /** - * @param {Module} module module with its callback list - * @param {Callback} callback the callback function + * @param {Dependency} dependency dependency being tied to block. + * This is an "edge" pointing to another "node" on module graph. * @returns {void} */ - waitForBuildingFinished(module, callback) { - let callbackList = this._buildingModules.get(module); - if (callbackList) { - callbackList.push(() => callback()); - } else { - process.nextTick(callback); - } + addDependency(dependency) { + this.dependencies.push(dependency); } /** - * Builds the module object - * - * @param {Module} module module to be built - * @param {boolean} optional optional flag - * @param {Module=} origin origin module this module build was requested from - * @param {Dependency[]=} dependencies optional dependencies from the module to be built - * @param {TODO} thisCallback the callback - * @returns {TODO} returns the callback function with results + * @param {Dependency} dependency dependency being removed + * @returns {void} */ - buildModule(module, optional, origin, dependencies, thisCallback) { - let callbackList = this._buildingModules.get(module); - if (callbackList) { - callbackList.push(thisCallback); - return; + removeDependency(dependency) { + const idx = this.dependencies.indexOf(dependency); + if (idx >= 0) { + this.dependencies.splice(idx, 1); } - this._buildingModules.set(module, (callbackList = [thisCallback])); - - const callback = err => { - this._buildingModules.delete(module); - for (const cb of callbackList) { - cb(err); - } - }; - - this.hooks.buildModule.call(module); - module.build( - this.options, - this, - this.resolverFactory.get("normal", module.resolveOptions), - this.inputFileSystem, - error => { - const errors = module.errors; - for (let indexError = 0; indexError < errors.length; indexError++) { - const err = errors[indexError]; - err.origin = origin; - err.dependencies = dependencies; - if (optional) { - this.warnings.push(err); - } else { - this.errors.push(err); - } - } - - const warnings = module.warnings; - for ( - let indexWarning = 0; - indexWarning < warnings.length; - indexWarning++ - ) { - const war = warnings[indexWarning]; - war.origin = origin; - war.dependencies = dependencies; - this.warnings.push(war); - } - const originalMap = module.dependencies.reduce((map, v, i) => { - map.set(v, i); - return map; - }, new Map()); - module.dependencies.sort((a, b) => { - const cmp = compareLocations(a.loc, b.loc); - if (cmp) return cmp; - return originalMap.get(a) - originalMap.get(b); - }); - if (error) { - this.hooks.failedModule.call(module, error); - return callback(error); - } - this.hooks.succeedModule.call(module); - return callback(); - } - ); } /** - * @param {Module} module to be processed for deps - * @param {ModuleCallback} callback callback to be triggered + * @param {Hash} hash the hash used to track dependencies * @returns {void} */ - processModuleDependencies(module, callback) { - const dependencies = new Map(); + updateHash(hash) { + for (const dep of this.dependencies) dep.updateHash(hash); + for (const block of this.blocks) block.updateHash(hash); + for (const variable of this.variables) variable.updateHash(hash); + } - const addDependency = dep => { - const resourceIdent = dep.getResourceIdentifier(); - if (resourceIdent) { - const factory = this.dependencyFactories.get(dep.constructor); - if (factory === undefined) { - throw new Error( - `No module factory available for dependency type: ${dep.constructor.name}` - ); - } - let innerMap = dependencies.get(factory); - if (innerMap === undefined) { - dependencies.set(factory, (innerMap = new Map())); - } - let list = innerMap.get(resourceIdent); - if (list === undefined) innerMap.set(resourceIdent, (list = [])); - list.push(dep); - } - }; + disconnect() { + for (const dep of this.dependencies) dep.disconnect(); + for (const block of this.blocks) block.disconnect(); + for (const variable of this.variables) variable.disconnect(); + } - const addDependenciesBlock = block => { - if (block.dependencies) { - iterationOfArrayCallback(block.dependencies, addDependency); - } - if (block.blocks) { - iterationOfArrayCallback(block.blocks, addDependenciesBlock); + unseal() { + for (const block of this.blocks) block.unseal(); + } + + /** + * @param {DependencyFilterFunction} filter filter function for dependencies, gets passed all dependency ties from current instance + * @returns {boolean} returns boolean for filter + */ + hasDependencies(filter) { + if (filter) { + for (const dep of this.dependencies) { + if (filter(dep)) return true; } - if (block.variables) { - iterationBlockVariable(block.variables, addDependency); + } else { + if (this.dependencies.length > 0) { + return true; } - }; + } - try { - addDependenciesBlock(module); - } catch (e) { - callback(e); + for (const block of this.blocks) { + if (block.hasDependencies(filter)) return true; + } + for (const variable of this.variables) { + if (variable.hasDependencies(filter)) return true; } + return false; + } - const sortedDependencies = []; + sortItems() { + for (const block of this.blocks) block.sortItems(); + } +} - for (const pair1 of dependencies) { - for (const pair2 of pair1[1]) { - sortedDependencies.push({ - factory: pair1[0], - dependencies: pair2[1] - }); - } - } +module.exports = DependenciesBlock; - this.addModuleDependencies( - module, - sortedDependencies, - this.bail, - null, - true, - callback - ); + +/***/ }), + +/***/ 82904: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const { RawSource, ReplaceSource } = __webpack_require__(53665); + +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./util/createHash").Hash} Hash */ +/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */ +/** @typedef {Map} DependencyTemplates */ + +class DependenciesBlockVariable { + /** + * Creates an instance of DependenciesBlockVariable. + * @param {string} name name of DependenciesBlockVariable + * @param {string} expression expression string + * @param {Dependency[]=} dependencies dependencies tied to this varaiable + */ + constructor(name, expression, dependencies) { + this.name = name; + this.expression = expression; + this.dependencies = dependencies || []; } /** - * @param {Module} module module to add deps to - * @param {SortedDependency[]} dependencies set of sorted dependencies to iterate through - * @param {(boolean|null)=} bail whether to bail or not - * @param {TODO} cacheGroup optional cacheGroup - * @param {boolean} recursive whether it is recursive traversal - * @param {function} callback callback for when dependencies are finished being added + * @param {Hash} hash hash for instance to update * @returns {void} */ - addModuleDependencies( - module, - dependencies, - bail, - cacheGroup, - recursive, - callback - ) { - const start = this.profile && Date.now(); - const currentProfile = this.profile && {}; + updateHash(hash) { + hash.update(this.name); + hash.update(this.expression); + for (const d of this.dependencies) { + d.updateHash(hash); + } + } - asyncLib.forEach( - dependencies, - (item, callback) => { - const dependencies = item.dependencies; + /** + * @param {DependencyTemplates} dependencyTemplates Dependency constructors and templates Map. + * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate to generate expression souce + * @returns {ReplaceSource} returns constructed source for expression via templates + */ + expressionSource(dependencyTemplates, runtimeTemplate) { + const source = new ReplaceSource(new RawSource(this.expression)); + for (const dep of this.dependencies) { + const template = dependencyTemplates.get(dep.constructor); + if (!template) { + throw new Error(`No template for dependency: ${dep.constructor.name}`); + } + template.apply(dep, source, runtimeTemplate, dependencyTemplates); + } + return source; + } - const errorAndCallback = err => { - err.origin = module; - err.dependencies = dependencies; - this.errors.push(err); - if (bail) { - callback(err); - } else { - callback(); - } - }; - const warningAndCallback = err => { - err.origin = module; - this.warnings.push(err); - callback(); - }; + disconnect() { + for (const d of this.dependencies) { + d.disconnect(); + } + } - const semaphore = this.semaphore; - semaphore.acquire(() => { - const factory = item.factory; - factory.create( - { - contextInfo: { - issuer: module.nameForCondition && module.nameForCondition(), - compiler: this.compiler.name - }, - resolveOptions: module.resolveOptions, - context: module.context, - dependencies: dependencies - }, - (err, dependentModule) => { - let afterFactory; + hasDependencies(filter) { + if (filter) { + return this.dependencies.some(filter); + } + return this.dependencies.length > 0; + } +} - const isOptional = () => { - return dependencies.every(d => d.optional); - }; +module.exports = DependenciesBlockVariable; - const errorOrWarningAndCallback = err => { - if (isOptional()) { - return warningAndCallback(err); - } else { - return errorAndCallback(err); - } - }; - if (err) { - semaphore.release(); - return errorOrWarningAndCallback( - new ModuleNotFoundError(module, err) - ); - } - if (!dependentModule) { - semaphore.release(); - return process.nextTick(callback); - } - if (currentProfile) { - afterFactory = Date.now(); - currentProfile.factory = afterFactory - start; - } +/***/ }), - const iterationDependencies = depend => { - for (let index = 0; index < depend.length; index++) { - const dep = depend[index]; - dep.module = dependentModule; - dependentModule.addReason(module, dep); - } - }; +/***/ 57282: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const addModuleResult = this.addModule( - dependentModule, - cacheGroup - ); - dependentModule = addModuleResult.module; - iterationDependencies(dependencies); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const afterBuild = () => { - if (recursive && addModuleResult.dependencies) { - this.processModuleDependencies(dependentModule, callback); - } else { - return callback(); - } - }; - if (addModuleResult.issuer) { - if (currentProfile) { - dependentModule.profile = currentProfile; - } +const util = __webpack_require__(31669); +const compareLocations = __webpack_require__(22562); +const DependencyReference = __webpack_require__(71722); - dependentModule.issuer = module; - } else { - if (this.profile) { - if (module.profile) { - const time = Date.now() - start; - if ( - !module.profile.dependencies || - time > module.profile.dependencies - ) { - module.profile.dependencies = time; - } - } - } - } +/** @typedef {import("./Module")} Module */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ - if (addModuleResult.build) { - this.buildModule( - dependentModule, - isOptional(), - module, - dependencies, - err => { - if (err) { - semaphore.release(); - return errorOrWarningAndCallback(err); - } +/** + * @typedef {Object} DependencyTemplate + * @property {function(Dependency, Source, RuntimeTemplate, Map): void} apply + */ - if (currentProfile) { - const afterBuilding = Date.now(); - currentProfile.building = afterBuilding - afterFactory; - } +/** @typedef {Object} SourcePosition + * @property {number} line + * @property {number=} column + */ - semaphore.release(); - afterBuild(); - } - ); - } else { - semaphore.release(); - this.waitForBuildingFinished(dependentModule, afterBuild); - } - } - ); - }); - }, - err => { - // In V8, the Error objects keep a reference to the functions on the stack. These warnings & - // errors are created inside closures that keep a reference to the Compilation, so errors are - // leaking the Compilation object. +/** @typedef {Object} RealDependencyLocation + * @property {SourcePosition} start + * @property {SourcePosition=} end + * @property {number=} index + */ - if (err) { - // eslint-disable-next-line no-self-assign - err.stack = err.stack; - return callback(err); - } +/** @typedef {Object} SynteticDependencyLocation + * @property {string} name + * @property {number=} index + */ - return process.nextTick(callback); - } - ); +/** @typedef {SynteticDependencyLocation|RealDependencyLocation} DependencyLocation */ + +class Dependency { + constructor() { + /** @type {Module|null} */ + this.module = null; + // TODO remove in webpack 5 + /** @type {boolean} */ + this.weak = false; + /** @type {boolean} */ + this.optional = false; + /** @type {DependencyLocation} */ + this.loc = undefined; } - /** - * - * @param {string} context context string path - * @param {Dependency} dependency dependency used to create Module chain - * @param {OnModuleCallback} onModule function invoked on modules creation - * @param {ModuleChainCallback} callback callback for when module chain is complete - * @returns {void} will throw if dependency instance is not a valid Dependency - */ - _addModuleChain(context, dependency, onModule, callback) { - const start = this.profile && Date.now(); - const currentProfile = this.profile && {}; + getResourceIdentifier() { + return null; + } - const errorAndCallback = this.bail - ? err => { - callback(err); - } - : err => { - err.dependencies = [dependency]; - this.errors.push(err); - callback(); - }; + // Returns the referenced module and export + getReference() { + if (!this.module) return null; + return new DependencyReference(this.module, true, this.weak); + } - if ( - typeof dependency !== "object" || - dependency === null || - !dependency.constructor - ) { - throw new Error("Parameter 'dependency' must be a Dependency"); - } - const Dep = /** @type {DepConstructor} */ (dependency.constructor); - const moduleFactory = this.dependencyFactories.get(Dep); - if (!moduleFactory) { - throw new Error( - `No dependency factory available for this dependency type: ${dependency.constructor.name}` - ); - } + // Returns the exported names + getExports() { + return null; + } - this.semaphore.acquire(() => { - moduleFactory.create( - { - contextInfo: { - issuer: "", - compiler: this.compiler.name - }, - context: context, - dependencies: [dependency] - }, - (err, module) => { - if (err) { - this.semaphore.release(); - return errorAndCallback(new EntryModuleNotFoundError(err)); - } + getWarnings() { + return null; + } - let afterFactory; + getErrors() { + return null; + } - if (currentProfile) { - afterFactory = Date.now(); - currentProfile.factory = afterFactory - start; - } + updateHash(hash) { + hash.update((this.module && this.module.id) + ""); + } - const addModuleResult = this.addModule(module); - module = addModuleResult.module; + disconnect() { + this.module = null; + } +} - onModule(module); +// TODO remove in webpack 5 +Dependency.compare = util.deprecate( + (a, b) => compareLocations(a.loc, b.loc), + "Dependency.compare is deprecated and will be removed in the next major version" +); - dependency.module = module; - module.addReason(null, dependency); +module.exports = Dependency; - const afterBuild = () => { - if (addModuleResult.dependencies) { - this.processModuleDependencies(module, err => { - if (err) return callback(err); - callback(null, module); - }); - } else { - return callback(null, module); - } - }; - if (addModuleResult.issuer) { - if (currentProfile) { - module.profile = currentProfile; - } - } +/***/ }), - if (addModuleResult.build) { - this.buildModule(module, false, null, null, err => { - if (err) { - this.semaphore.release(); - return errorAndCallback(err); - } +/***/ 6659: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (currentProfile) { - const afterBuilding = Date.now(); - currentProfile.building = afterBuilding - afterFactory; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - this.semaphore.release(); - afterBuild(); - }); - } else { - this.semaphore.release(); - this.waitForBuildingFinished(module, afterBuild); - } - } + +const DllEntryDependency = __webpack_require__(66279); +const SingleEntryDependency = __webpack_require__(84828); +const DllModuleFactory = __webpack_require__(62468); + +class DllEntryPlugin { + constructor(context, entries, name) { + this.context = context; + this.entries = entries; + this.name = name; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "DllEntryPlugin", + (compilation, { normalModuleFactory }) => { + const dllModuleFactory = new DllModuleFactory(); + compilation.dependencyFactories.set( + DllEntryDependency, + dllModuleFactory + ); + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); + } + ); + compiler.hooks.make.tapAsync("DllEntryPlugin", (compilation, callback) => { + compilation.addEntry( + this.context, + new DllEntryDependency( + this.entries.map((e, idx) => { + const dep = new SingleEntryDependency(e); + dep.loc = { + name: this.name, + index: idx + }; + return dep; + }), + this.name + ), + this.name, + callback ); }); } +} - /** - * - * @param {string} context context path for entry - * @param {Dependency} entry entry dependency being created - * @param {string} name name of entry - * @param {ModuleCallback} callback callback function - * @returns {void} returns - */ - addEntry(context, entry, name, callback) { - this.hooks.addEntry.call(entry, name); +module.exports = DllEntryPlugin; - const slot = { - name: name, - // TODO webpack 5 remove `request` - request: null, - module: null - }; - if (entry instanceof ModuleDependency) { - slot.request = entry.request; - } +/***/ }), - // TODO webpack 5: merge modules instead when multiple entry modules are supported - const idx = this._preparedEntrypoints.findIndex(slot => slot.name === name); - if (idx >= 0) { - // Overwrite existing entrypoint - this._preparedEntrypoints[idx] = slot; - } else { - this._preparedEntrypoints.push(slot); - } - this._addModuleChain( - context, - entry, - module => { - this.entries.push(module); - }, - (err, module) => { - if (err) { - this.hooks.failedEntry.call(entry, name, err); - return callback(err); - } +/***/ 24803: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (module) { - slot.module = module; - } else { - const idx = this._preparedEntrypoints.indexOf(slot); - if (idx >= 0) { - this._preparedEntrypoints.splice(idx, 1); - } - } - this.hooks.succeedEntry.call(entry, name, module); - return callback(null, module); - } - ); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ - /** - * @param {string} context context path string - * @param {Dependency} dependency dep used to create module - * @param {ModuleCallback} callback module callback sending module up a level - * @returns {void} - */ - prefetch(context, dependency, callback) { - this._addModuleChain( - context, - dependency, - module => { - module.prefetched = true; - }, - callback - ); - } - /** - * @param {Module} module module to be rebuilt - * @param {Callback} thisCallback callback when module finishes rebuilding - * @returns {void} - */ - rebuildModule(module, thisCallback) { - let callbackList = this._rebuildingModules.get(module); - if (callbackList) { - callbackList.push(thisCallback); - return; - } - this._rebuildingModules.set(module, (callbackList = [thisCallback])); +const { RawSource } = __webpack_require__(53665); +const Module = __webpack_require__(75993); - const callback = err => { - this._rebuildingModules.delete(module); - for (const cb of callbackList) { - cb(err); - } - }; +/** @typedef {import("./util/createHash").Hash} Hash */ - this.hooks.rebuildModule.call(module); - const oldDependencies = module.dependencies.slice(); - const oldVariables = module.variables.slice(); - const oldBlocks = module.blocks.slice(); - module.unbuild(); - this.buildModule(module, false, module, null, err => { - if (err) { - this.hooks.finishRebuildingModule.call(module); - return callback(err); - } +class DllModule extends Module { + constructor(context, dependencies, name, type) { + super("javascript/dynamic", context); - this.processModuleDependencies(module, err => { - if (err) return callback(err); - this.removeReasonsOfDependencyBlock(module, { - dependencies: oldDependencies, - variables: oldVariables, - blocks: oldBlocks - }); - this.hooks.finishRebuildingModule.call(module); - callback(); - }); - }); + // Info from Factory + this.dependencies = dependencies; + this.name = name; + this.type = type; } - finish(callback) { - const modules = this.modules; - this.hooks.finishModules.callAsync(modules, err => { - if (err) return callback(err); + identifier() { + return `dll ${this.name}`; + } - for (let index = 0; index < modules.length; index++) { - const module = modules[index]; - this.reportDependencyErrorsAndWarnings(module, [module]); - } + readableIdentifier() { + return `dll ${this.name}`; + } - callback(); - }); + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + return callback(); } - unseal() { - this.hooks.unseal.call(); - this.chunks.length = 0; - this.chunkGroups.length = 0; - this.namedChunks.clear(); - this.namedChunkGroups.clear(); - this.additionalChunkAssets.length = 0; - this.assets = {}; - this.assetsInfo.clear(); - for (const module of this.modules) { - module.unseal(); - } + source() { + return new RawSource("module.exports = __webpack_require__;"); + } + + needRebuild() { + return false; + } + + size() { + return 12; } /** - * @param {Callback} callback signals when the seal method is finishes + * @param {Hash} hash the hash used to track dependencies * @returns {void} */ - seal(callback) { - this.hooks.seal.call(); + updateHash(hash) { + hash.update("dll module"); + hash.update(this.name || ""); + super.updateHash(hash); + } +} - while ( - this.hooks.optimizeDependenciesBasic.call(this.modules) || - this.hooks.optimizeDependencies.call(this.modules) || - this.hooks.optimizeDependenciesAdvanced.call(this.modules) - ) { - /* empty */ - } - this.hooks.afterOptimizeDependencies.call(this.modules); +module.exports = DllModule; - this.hooks.beforeChunks.call(); - for (const preparedEntrypoint of this._preparedEntrypoints) { - const module = preparedEntrypoint.module; - const name = preparedEntrypoint.name; - const chunk = this.addChunk(name); - const entrypoint = new Entrypoint(name); - entrypoint.setRuntimeChunk(chunk); - entrypoint.addOrigin(null, name, preparedEntrypoint.request); - this.namedChunkGroups.set(name, entrypoint); - this.entrypoints.set(name, entrypoint); - this.chunkGroups.push(entrypoint); - GraphHelpers.connectChunkGroupAndChunk(entrypoint, chunk); - GraphHelpers.connectChunkAndModule(chunk, module); +/***/ }), - chunk.entryModule = module; - chunk.name = name; +/***/ 62468: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - this.assignDepth(module); - } - buildChunkGraph( - this, - /** @type {Entrypoint[]} */ (this.chunkGroups.slice()) - ); - this.sortModules(this.modules); - this.hooks.afterChunks.call(this.chunks); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - this.hooks.optimize.call(); - - while ( - this.hooks.optimizeModulesBasic.call(this.modules) || - this.hooks.optimizeModules.call(this.modules) || - this.hooks.optimizeModulesAdvanced.call(this.modules) - ) { - /* empty */ - } - this.hooks.afterOptimizeModules.call(this.modules); - - while ( - this.hooks.optimizeChunksBasic.call(this.chunks, this.chunkGroups) || - this.hooks.optimizeChunks.call(this.chunks, this.chunkGroups) || - this.hooks.optimizeChunksAdvanced.call(this.chunks, this.chunkGroups) - ) { - /* empty */ - } - this.hooks.afterOptimizeChunks.call(this.chunks, this.chunkGroups); - this.hooks.optimizeTree.callAsync(this.chunks, this.modules, err => { - if (err) { - return callback(err); - } +const { Tapable } = __webpack_require__(56758); +const DllModule = __webpack_require__(24803); - this.hooks.afterOptimizeTree.call(this.chunks, this.modules); +class DllModuleFactory extends Tapable { + constructor() { + super(); + this.hooks = {}; + } + create(data, callback) { + const dependency = data.dependencies[0]; + callback( + null, + new DllModule( + data.context, + dependency.dependencies, + dependency.name, + dependency.type + ) + ); + } +} - while ( - this.hooks.optimizeChunkModulesBasic.call(this.chunks, this.modules) || - this.hooks.optimizeChunkModules.call(this.chunks, this.modules) || - this.hooks.optimizeChunkModulesAdvanced.call(this.chunks, this.modules) - ) { - /* empty */ - } - this.hooks.afterOptimizeChunkModules.call(this.chunks, this.modules); +module.exports = DllModuleFactory; - const shouldRecord = this.hooks.shouldRecord.call() !== false; - this.hooks.reviveModules.call(this.modules, this.records); - this.hooks.optimizeModuleOrder.call(this.modules); - this.hooks.advancedOptimizeModuleOrder.call(this.modules); - this.hooks.beforeModuleIds.call(this.modules); - this.hooks.moduleIds.call(this.modules); - this.applyModuleIds(); - this.hooks.optimizeModuleIds.call(this.modules); - this.hooks.afterOptimizeModuleIds.call(this.modules); +/***/ }), - this.sortItemsWithModuleIds(); +/***/ 45255: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - this.hooks.reviveChunks.call(this.chunks, this.records); - this.hooks.optimizeChunkOrder.call(this.chunks); - this.hooks.beforeChunkIds.call(this.chunks); - this.applyChunkIds(); - this.hooks.optimizeChunkIds.call(this.chunks); - this.hooks.afterOptimizeChunkIds.call(this.chunks); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ - this.sortItemsWithChunkIds(); - if (shouldRecord) { - this.hooks.recordModules.call(this.modules, this.records); - this.hooks.recordChunks.call(this.chunks, this.records); - } +const DllEntryPlugin = __webpack_require__(6659); +const FlagAllModulesAsUsedPlugin = __webpack_require__(47163); +const LibManifestPlugin = __webpack_require__(30735); - this.hooks.beforeHash.call(); - this.createHash(); - this.hooks.afterHash.call(); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(7303); - if (shouldRecord) { - this.hooks.recordHash.call(this.records); - } +/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ - this.hooks.beforeModuleAssets.call(); - this.createModuleAssets(); - if (this.hooks.shouldGenerateChunkAssets.call() !== false) { - this.hooks.beforeChunkAssets.call(); - this.createChunkAssets(); - } - this.hooks.additionalChunkAssets.call(this.chunks); - this.summarizeDependencies(); - if (shouldRecord) { - this.hooks.record.call(this, this.records); - } +class DllPlugin { + /** + * @param {DllPluginOptions} options options object + */ + constructor(options) { + validateOptions(schema, options, "Dll Plugin"); + this.options = options; + } - this.hooks.additionalAssets.callAsync(err => { - if (err) { - return callback(err); + apply(compiler) { + compiler.hooks.entryOption.tap("DllPlugin", (context, entry) => { + const itemToPlugin = (item, name) => { + if (Array.isArray(item)) { + return new DllEntryPlugin(context, item, name); } - this.hooks.optimizeChunkAssets.callAsync(this.chunks, err => { - if (err) { - return callback(err); - } - this.hooks.afterOptimizeChunkAssets.call(this.chunks); - this.hooks.optimizeAssets.callAsync(this.assets, err => { - if (err) { - return callback(err); - } - this.hooks.afterOptimizeAssets.call(this.assets); - if (this.hooks.needAdditionalSeal.call()) { - this.unseal(); - return this.seal(callback); - } - return this.hooks.afterSeal.callAsync(callback); - }); + throw new Error("DllPlugin: supply an Array as entry"); + }; + if (typeof entry === "object" && !Array.isArray(entry)) { + Object.keys(entry).forEach(name => { + itemToPlugin(entry[name], name).apply(compiler); }); - }); + } else { + itemToPlugin(entry, "main").apply(compiler); + } + return true; }); + new LibManifestPlugin(this.options).apply(compiler); + if (!this.options.entryOnly) { + new FlagAllModulesAsUsedPlugin("DllPlugin").apply(compiler); + } } +} + +module.exports = DllPlugin; + + +/***/ }), + +/***/ 86231: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * @param {Module[]} modules the modules array on compilation to perform the sort for - * @returns {void} - */ - sortModules(modules) { - // TODO webpack 5: this should only be enabled when `moduleIds: "natural"` - // TODO move it into a plugin (NaturalModuleIdsPlugin) and use this in WebpackOptionsApply - // TODO remove this method - modules.sort(byIndexOrIdentifier); - } +const parseJson = __webpack_require__(48335); +const DelegatedSourceDependency = __webpack_require__(25930); +const DelegatedModuleFactoryPlugin = __webpack_require__(81002); +const ExternalModuleFactoryPlugin = __webpack_require__(67876); +const DelegatedExportsDependency = __webpack_require__(53104); +const NullFactory = __webpack_require__(40438); +const makePathsRelative = __webpack_require__(94658).makePathsRelative; +const WebpackError = __webpack_require__(97391); + +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(61112); + +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ +/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ + +class DllReferencePlugin { /** - * @param {Module} module moulde to report from - * @param {DependenciesBlock[]} blocks blocks to report from - * @returns {void} + * @param {DllReferencePluginOptions} options options object */ - reportDependencyErrorsAndWarnings(module, blocks) { - for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { - const block = blocks[indexBlock]; - const dependencies = block.dependencies; - - for (let indexDep = 0; indexDep < dependencies.length; indexDep++) { - const d = dependencies[indexDep]; + constructor(options) { + validateOptions(schema, options, "Dll Reference Plugin"); + this.options = options; + } - const warnings = d.getWarnings(); - if (warnings) { - for (let indexWar = 0; indexWar < warnings.length; indexWar++) { - const w = warnings[indexWar]; + apply(compiler) { + compiler.hooks.compilation.tap( + "DllReferencePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + DelegatedSourceDependency, + normalModuleFactory + ); + compilation.dependencyFactories.set( + DelegatedExportsDependency, + new NullFactory() + ); + } + ); - const warning = new ModuleDependencyWarning(module, w, d.loc); - this.warnings.push(warning); + compiler.hooks.beforeCompile.tapAsync( + "DllReferencePlugin", + (params, callback) => { + if ("manifest" in this.options) { + const manifest = this.options.manifest; + if (typeof manifest === "string") { + params.compilationDependencies.add(manifest); + compiler.inputFileSystem.readFile(manifest, (err, result) => { + if (err) return callback(err); + // Catch errors parsing the manifest so that blank + // or malformed manifest files don't kill the process. + try { + params["dll reference " + manifest] = parseJson( + result.toString("utf-8") + ); + } catch (e) { + // Store the error in the params so that it can + // be added as a compilation error later on. + const manifestPath = makePathsRelative( + compiler.options.context, + manifest + ); + params[ + "dll reference parse error " + manifest + ] = new DllManifestError(manifestPath, e.message); + } + return callback(); + }); + return; } } - const errors = d.getErrors(); - if (errors) { - for (let indexErr = 0; indexErr < errors.length; indexErr++) { - const e = errors[indexErr]; + return callback(); + } + ); - const error = new ModuleDependencyError(module, e, d.loc); - this.errors.push(error); + compiler.hooks.compile.tap("DllReferencePlugin", params => { + let name = this.options.name; + let sourceType = this.options.sourceType; + let content = + "content" in this.options ? this.options.content : undefined; + if ("manifest" in this.options) { + let manifestParameter = this.options.manifest; + let manifest; + if (typeof manifestParameter === "string") { + // If there was an error parsing the manifest + // file, exit now because the error will be added + // as a compilation error in the "compilation" hook. + if (params["dll reference parse error " + manifestParameter]) { + return; } + manifest = + /** @type {DllReferencePluginOptionsManifest} */ (params[ + "dll reference " + manifestParameter + ]); + } else { + manifest = manifestParameter; + } + if (manifest) { + if (!name) name = manifest.name; + if (!sourceType) sourceType = manifest.type; + if (!content) content = manifest.content; } } + const externals = {}; + const source = "dll-reference " + name; + externals[source] = name; + const normalModuleFactory = params.normalModuleFactory; + new ExternalModuleFactoryPlugin(sourceType || "var", externals).apply( + normalModuleFactory + ); + new DelegatedModuleFactoryPlugin({ + source: source, + type: this.options.type, + scope: this.options.scope, + context: this.options.context || compiler.options.context, + content, + extensions: this.options.extensions + }).apply(normalModuleFactory); + }); - this.reportDependencyErrorsAndWarnings(module, block.blocks); - } - } - - /** - * @param {TODO} groupOptions options for the chunk group - * @param {Module} module the module the references the chunk group - * @param {DependencyLocation} loc the location from with the chunk group is referenced (inside of module) - * @param {string} request the request from which the the chunk group is referenced - * @returns {ChunkGroup} the new or existing chunk group - */ - addChunkInGroup(groupOptions, module, loc, request) { - if (typeof groupOptions === "string") { - groupOptions = { name: groupOptions }; - } - const name = groupOptions.name; - if (name) { - const chunkGroup = this.namedChunkGroups.get(name); - if (chunkGroup !== undefined) { - chunkGroup.addOptions(groupOptions); - if (module) { - chunkGroup.addOrigin(module, loc, request); + compiler.hooks.compilation.tap( + "DllReferencePlugin", + (compilation, params) => { + if ("manifest" in this.options) { + let manifest = this.options.manifest; + if (typeof manifest === "string") { + // If there was an error parsing the manifest file, add the + // error as a compilation error to make the compilation fail. + let e = params["dll reference parse error " + manifest]; + if (e) { + compilation.errors.push(e); + } + } } - return chunkGroup; } - } - const chunkGroup = new ChunkGroup(groupOptions); - if (module) chunkGroup.addOrigin(module, loc, request); - const chunk = this.addChunk(name); + ); + } +} - GraphHelpers.connectChunkGroupAndChunk(chunkGroup, chunk); +class DllManifestError extends WebpackError { + constructor(filename, message) { + super(); - this.chunkGroups.push(chunkGroup); - if (name) { - this.namedChunkGroups.set(name, chunkGroup); - } - return chunkGroup; - } + this.name = "DllManifestError"; + this.message = `Dll manifest ${filename}\n${message}`; - /** - * This method first looks to see if a name is provided for a new chunk, - * and first looks to see if any named chunks already exist and reuse that chunk instead. - * - * @param {string=} name optional chunk name to be provided - * @returns {Chunk} create a chunk (invoked during seal event) - */ - addChunk(name) { - if (name) { - const chunk = this.namedChunks.get(name); - if (chunk !== undefined) { - return chunk; - } - } - const chunk = new Chunk(name); - this.chunks.push(chunk); - if (name) { - this.namedChunks.set(name, chunk); - } - return chunk; + Error.captureStackTrace(this, this.constructor); } +} - /** - * @param {Module} module module to assign depth - * @returns {void} - */ - assignDepth(module) { - const queue = new Set([module]); - let depth; - - module.depth = 0; +module.exports = DllReferencePlugin; - /** - * @param {Module} module module for processeing - * @returns {void} - */ - const enqueueJob = module => { - const d = module.depth; - if (typeof d === "number" && d <= depth) return; - queue.add(module); - module.depth = depth; - }; - /** - * @param {Dependency} dependency dependency to assign depth to - * @returns {void} - */ - const assignDepthToDependency = dependency => { - if (dependency.module) { - enqueueJob(dependency.module); - } - }; +/***/ }), - /** - * @param {DependenciesBlock} block block to assign depth to - * @returns {void} - */ - const assignDepthToDependencyBlock = block => { - if (block.variables) { - iterationBlockVariable(block.variables, assignDepthToDependency); - } +/***/ 49784: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (block.dependencies) { - iterationOfArrayCallback(block.dependencies, assignDepthToDependency); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Naoyuki Kanezawa @nkzawa +*/ - if (block.blocks) { - iterationOfArrayCallback(block.blocks, assignDepthToDependencyBlock); - } - }; - for (module of queue) { - queue.delete(module); - depth = module.depth; +const MultiEntryDependency = __webpack_require__(7791); +const SingleEntryDependency = __webpack_require__(84828); +const MultiModuleFactory = __webpack_require__(24005); +const MultiEntryPlugin = __webpack_require__(98046); +const SingleEntryPlugin = __webpack_require__(19070); - depth++; - assignDepthToDependencyBlock(module); - } - } +/** @typedef {import("../declarations/WebpackOptions").EntryDynamic} EntryDynamic */ +/** @typedef {import("../declarations/WebpackOptions").EntryStatic} EntryStatic */ +/** @typedef {import("./Compiler")} Compiler */ +class DynamicEntryPlugin { /** - * @param {Module} module the module containing the dependency - * @param {Dependency} dependency the dependency - * @returns {DependencyReference} a reference for the dependency + * @param {string} context the context path + * @param {EntryDynamic} entry the entry value */ - getDependencyReference(module, dependency) { - // TODO remove dep.getReference existence check in webpack 5 - if (typeof dependency.getReference !== "function") return null; - const ref = dependency.getReference(); - if (!ref) return null; - return this.hooks.dependencyReference.call(ref, dependency, module); + constructor(context, entry) { + this.context = context; + this.entry = entry; } /** - * - * @param {Module} module module relationship for removal - * @param {DependenciesBlockLike} block //TODO: good description + * @param {Compiler} compiler the compiler instance * @returns {void} */ - removeReasonsOfDependencyBlock(module, block) { - const iteratorDependency = d => { - if (!d.module) { - return; - } - if (d.module.removeReason(module, d)) { - for (const chunk of d.module.chunksIterable) { - this.patchChunksAfterReasonRemoval(d.module, chunk); - } - } - }; - - if (block.blocks) { - iterationOfArrayCallback(block.blocks, block => - this.removeReasonsOfDependencyBlock(module, block) - ); - } - - if (block.dependencies) { - iterationOfArrayCallback(block.dependencies, iteratorDependency); - } + apply(compiler) { + compiler.hooks.compilation.tap( + "DynamicEntryPlugin", + (compilation, { normalModuleFactory }) => { + const multiModuleFactory = new MultiModuleFactory(); - if (block.variables) { - iterationBlockVariable(block.variables, iteratorDependency); - } - } + compilation.dependencyFactories.set( + MultiEntryDependency, + multiModuleFactory + ); + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); + } + ); - /** - * @param {Module} module module to patch tie - * @param {Chunk} chunk chunk to patch tie - * @returns {void} - */ - patchChunksAfterReasonRemoval(module, chunk) { - if (!module.hasReasons()) { - this.removeReasonsOfDependencyBlock(module, module); - } - if (!module.hasReasonForChunk(chunk)) { - if (module.removeChunk(chunk)) { - this.removeChunkFromDependencies(module, chunk); - } - } - } + compiler.hooks.make.tapAsync( + "DynamicEntryPlugin", + (compilation, callback) => { + /** + * @param {string|string[]} entry entry value or array of entry values + * @param {string} name name of entry + * @returns {Promise} returns the promise resolving the Compilation#addEntry function + */ + const addEntry = (entry, name) => { + const dep = DynamicEntryPlugin.createDependency(entry, name); + return new Promise((resolve, reject) => { + compilation.addEntry(this.context, dep, name, err => { + if (err) return reject(err); + resolve(); + }); + }); + }; - /** - * - * @param {DependenciesBlock} block block tie for Chunk - * @param {Chunk} chunk chunk to remove from dep - * @returns {void} - */ - removeChunkFromDependencies(block, chunk) { - const iteratorDependency = d => { - if (!d.module) { - return; + Promise.resolve(this.entry()).then(entry => { + if (typeof entry === "string" || Array.isArray(entry)) { + addEntry(entry, "main").then(() => callback(), callback); + } else if (typeof entry === "object") { + Promise.all( + Object.keys(entry).map(name => { + return addEntry(entry[name], name); + }) + ).then(() => callback(), callback); + } + }); } - this.patchChunksAfterReasonRemoval(d.module, chunk); - }; + ); + } +} - const blocks = block.blocks; - for (let indexBlock = 0; indexBlock < blocks.length; indexBlock++) { - const asyncBlock = blocks[indexBlock]; - // Grab all chunks from the first Block's AsyncDepBlock - const chunks = asyncBlock.chunkGroup.chunks; - // For each chunk in chunkGroup - for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { - const iteratedChunk = chunks[indexChunk]; - asyncBlock.chunkGroup.removeChunk(iteratedChunk); - asyncBlock.chunkGroup.removeParent(iteratedChunk); - // Recurse - this.removeChunkFromDependencies(block, iteratedChunk); - } - } +module.exports = DynamicEntryPlugin; +/** + * @param {string|string[]} entry entry value or array of entry paths + * @param {string} name name of entry + * @returns {SingleEntryDependency|MultiEntryDependency} returns dep + */ +DynamicEntryPlugin.createDependency = (entry, name) => { + if (Array.isArray(entry)) { + return MultiEntryPlugin.createDependency(entry, name); + } else { + return SingleEntryPlugin.createDependency(entry, name); + } +}; - if (block.dependencies) { - iterationOfArrayCallback(block.dependencies, iteratorDependency); - } - if (block.variables) { - iterationBlockVariable(block.variables, iteratorDependency); - } - } +/***/ }), - applyModuleIds() { - const unusedIds = []; - let nextFreeModuleId = 0; - const usedIds = new Set(); - if (this.usedModuleIds) { - for (const id of this.usedModuleIds) { - usedIds.add(id); - } - } +/***/ 99531: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const modules1 = this.modules; - for (let indexModule1 = 0; indexModule1 < modules1.length; indexModule1++) { - const module1 = modules1[indexModule1]; - if (module1.id !== null) { - usedIds.add(module1.id); - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (usedIds.size > 0) { - let usedIdMax = -1; - for (const usedIdKey of usedIds) { - if (typeof usedIdKey !== "number") { - continue; - } - usedIdMax = Math.max(usedIdMax, usedIdKey); - } +const WebpackError = __webpack_require__(97391); - let lengthFreeModules = (nextFreeModuleId = usedIdMax + 1); +class EntryModuleNotFoundError extends WebpackError { + constructor(err) { + super("Entry module not found: " + err); - while (lengthFreeModules--) { - if (!usedIds.has(lengthFreeModules)) { - unusedIds.push(lengthFreeModules); - } - } - } + this.name = "EntryModuleNotFoundError"; + this.details = err.details; + this.error = err; - const modules2 = this.modules; - for (let indexModule2 = 0; indexModule2 < modules2.length; indexModule2++) { - const module2 = modules2[indexModule2]; - if (module2.id === null) { - if (unusedIds.length > 0) { - module2.id = unusedIds.pop(); - } else { - module2.id = nextFreeModuleId++; - } - } - } + Error.captureStackTrace(this, this.constructor); } +} - applyChunkIds() { - /** @type {Set} */ - const usedIds = new Set(); +module.exports = EntryModuleNotFoundError; - // Get used ids from usedChunkIds property (i. e. from records) - if (this.usedChunkIds) { - for (const id of this.usedChunkIds) { - if (typeof id !== "number") { - continue; - } - usedIds.add(id); - } - } +/***/ }), - // Get used ids from existing chunks - const chunks = this.chunks; - for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { - const chunk = chunks[indexChunk]; - const usedIdValue = chunk.id; +/***/ 14604: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (typeof usedIdValue !== "number") { - continue; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - usedIds.add(usedIdValue); - } - // Calculate maximum assigned chunk id - let nextFreeChunkId = -1; - for (const id of usedIds) { - nextFreeChunkId = Math.max(nextFreeChunkId, id); - } - nextFreeChunkId++; +const SingleEntryPlugin = __webpack_require__(19070); +const MultiEntryPlugin = __webpack_require__(98046); +const DynamicEntryPlugin = __webpack_require__(49784); - // Determine free chunk ids from 0 to maximum - /** @type {number[]} */ - const unusedIds = []; - if (nextFreeChunkId > 0) { - let index = nextFreeChunkId; - while (index--) { - if (!usedIds.has(index)) { - unusedIds.push(index); - } - } - } +/** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */ +/** @typedef {import("./Compiler")} Compiler */ - // Assign ids to chunk which has no id - for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { - const chunk = chunks[indexChunk]; - if (chunk.id === null) { - if (unusedIds.length > 0) { - chunk.id = unusedIds.pop(); - } else { - chunk.id = nextFreeChunkId++; - } - } - if (!chunk.ids) { - chunk.ids = [chunk.id]; - } - } +/** + * @param {string} context context path + * @param {EntryItem} item entry array or single path + * @param {string} name entry key name + * @returns {SingleEntryPlugin | MultiEntryPlugin} returns either a single or multi entry plugin + */ +const itemToPlugin = (context, item, name) => { + if (Array.isArray(item)) { + return new MultiEntryPlugin(context, item, name); } + return new SingleEntryPlugin(context, item, name); +}; - sortItemsWithModuleIds() { - this.modules.sort(byIdOrIdentifier); - - const modules = this.modules; - for (let indexModule = 0; indexModule < modules.length; indexModule++) { - modules[indexModule].sortItems(false); - } - - const chunks = this.chunks; - for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { - chunks[indexChunk].sortItems(); - } - - chunks.sort((a, b) => a.compareTo(b)); +module.exports = class EntryOptionPlugin { + /** + * @param {Compiler} compiler the compiler instance one is tapping into + * @returns {void} + */ + apply(compiler) { + compiler.hooks.entryOption.tap("EntryOptionPlugin", (context, entry) => { + if (typeof entry === "string" || Array.isArray(entry)) { + itemToPlugin(context, entry, "main").apply(compiler); + } else if (typeof entry === "object") { + for (const name of Object.keys(entry)) { + itemToPlugin(context, entry[name], name).apply(compiler); + } + } else if (typeof entry === "function") { + new DynamicEntryPlugin(context, entry).apply(compiler); + } + return true; + }); } +}; - sortItemsWithChunkIds() { - for (const chunkGroup of this.chunkGroups) { - chunkGroup.sortItems(); - } - - this.chunks.sort(byId); - - for ( - let indexModule = 0; - indexModule < this.modules.length; - indexModule++ - ) { - this.modules[indexModule].sortItems(true); - } - - const chunks = this.chunks; - for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { - chunks[indexChunk].sortItems(); - } - /** - * Used to sort errors and warnings in compilation. this.warnings, and - * this.errors contribute to the compilation hash and therefore should be - * updated whenever other references (having a chunk id) are sorted. This preserves the hash - * integrity - * - * @param {WebpackError} a first WebpackError instance (including subclasses) - * @param {WebpackError} b second WebpackError instance (including subclasses) - * @returns {-1|0|1} sort order index - */ - const byMessage = (a, b) => { - const ma = `${a.message}`; - const mb = `${b.message}`; - if (ma < mb) return -1; - if (mb < ma) return 1; - return 0; - }; +/***/ }), - this.errors.sort(byMessage); - this.warnings.sort(byMessage); - this.children.sort(byNameOrHash); - } +/***/ 71931: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - summarizeDependencies() { - this.fileDependencies = new SortableSet(this.compilationDependencies); - this.contextDependencies = new SortableSet(); - this.missingDependencies = new SortableSet(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - for ( - let indexChildren = 0; - indexChildren < this.children.length; - indexChildren++ - ) { - const child = this.children[indexChildren]; - addAllToSet(this.fileDependencies, child.fileDependencies); - addAllToSet(this.contextDependencies, child.contextDependencies); - addAllToSet(this.missingDependencies, child.missingDependencies); - } +const ChunkGroup = __webpack_require__(52911); - for ( - let indexModule = 0; - indexModule < this.modules.length; - indexModule++ - ) { - const module = this.modules[indexModule]; +/** @typedef {import("./Chunk")} Chunk */ - if (module.buildInfo.fileDependencies) { - addAllToSet(this.fileDependencies, module.buildInfo.fileDependencies); - } - if (module.buildInfo.contextDependencies) { - addAllToSet( - this.contextDependencies, - module.buildInfo.contextDependencies - ); - } - } - for (const error of this.errors) { - if ( - typeof error.missing === "object" && - error.missing && - error.missing[Symbol.iterator] - ) { - addAllToSet(this.missingDependencies, error.missing); - } - } - this.fileDependencies.sort(); - this.contextDependencies.sort(); - this.missingDependencies.sort(); +/** + * Entrypoint serves as an encapsulation primitive for chunks that are + * a part of a single ChunkGroup. They represent all bundles that need to be loaded for a + * single instance of a page. Multi-page application architectures will typically yield multiple Entrypoint objects + * inside of the compilation, whereas a Single Page App may only contain one with many lazy-loaded chunks. + */ +class Entrypoint extends ChunkGroup { + /** + * Creates an instance of Entrypoint. + * @param {string} name the name of the entrypoint + */ + constructor(name) { + super(name); + /** @type {Chunk=} */ + this.runtimeChunk = undefined; } - createHash() { - const outputOptions = this.outputOptions; - const hashFunction = outputOptions.hashFunction; - const hashDigest = outputOptions.hashDigest; - const hashDigestLength = outputOptions.hashDigestLength; - const hash = createHash(hashFunction); - if (outputOptions.hashSalt) { - hash.update(outputOptions.hashSalt); - } - this.mainTemplate.updateHash(hash); - this.chunkTemplate.updateHash(hash); - for (const key of Object.keys(this.moduleTemplates).sort()) { - this.moduleTemplates[key].updateHash(hash); - } - for (const child of this.children) { - hash.update(child.hash); - } - for (const warning of this.warnings) { - hash.update(`${warning.message}`); - } - for (const error of this.errors) { - hash.update(`${error.message}`); - } - const modules = this.modules; - for (let i = 0; i < modules.length; i++) { - const module = modules[i]; - const moduleHash = createHash(hashFunction); - module.updateHash(moduleHash); - module.hash = /** @type {string} */ (moduleHash.digest(hashDigest)); - module.renderedHash = module.hash.substr(0, hashDigestLength); - } - // clone needed as sort below is inplace mutation - const chunks = this.chunks.slice(); - /** - * sort here will bring all "falsy" values to the beginning - * this is needed as the "hasRuntime()" chunks are dependent on the - * hashes of the non-runtime chunks. - */ - chunks.sort((a, b) => { - const aEntry = a.hasRuntime(); - const bEntry = b.hasRuntime(); - if (aEntry && !bEntry) return 1; - if (!aEntry && bEntry) return -1; - return byId(a, b); - }); - for (let i = 0; i < chunks.length; i++) { - const chunk = chunks[i]; - const chunkHash = createHash(hashFunction); - try { - if (outputOptions.hashSalt) { - chunkHash.update(outputOptions.hashSalt); - } - chunk.updateHash(chunkHash); - const template = chunk.hasRuntime() - ? this.mainTemplate - : this.chunkTemplate; - template.updateHashForChunk( - chunkHash, - chunk, - this.moduleTemplates.javascript, - this.dependencyTemplates - ); - this.hooks.chunkHash.call(chunk, chunkHash); - chunk.hash = /** @type {string} */ (chunkHash.digest(hashDigest)); - hash.update(chunk.hash); - chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); - this.hooks.contentHash.call(chunk); - } catch (err) { - this.errors.push(new ChunkRenderError(chunk, "", err)); - } - } - this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); - this.hash = this.fullHash.substr(0, hashDigestLength); + /** + * isInitial will always return true for Entrypoint ChunkGroup. + * @returns {true} returns true as all entrypoints are initial ChunkGroups + */ + isInitial() { + return true; } /** - * @param {string} update extra information + * Sets the runtimeChunk for an entrypoint. + * @param {Chunk} chunk the chunk being set as the runtime chunk. * @returns {void} */ - modifyHash(update) { - const outputOptions = this.outputOptions; - const hashFunction = outputOptions.hashFunction; - const hashDigest = outputOptions.hashDigest; - const hashDigestLength = outputOptions.hashDigestLength; - const hash = createHash(hashFunction); - hash.update(this.fullHash); - hash.update(update); - this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); - this.hash = this.fullHash.substr(0, hashDigestLength); + setRuntimeChunk(chunk) { + this.runtimeChunk = chunk; } /** - * @param {string} file file name - * @param {Source} source asset source - * @param {AssetInfo} assetInfo extra asset information - * @returns {void} + * Fetches the chunk reference containing the webpack bootstrap code + * @returns {Chunk} returns the runtime chunk or first chunk in `this.chunks` */ - emitAsset(file, source, assetInfo = {}) { - if (this.assets[file]) { - if (!isSourceEqual(this.assets[file], source)) { - // TODO webpack 5: make this an error instead - this.warnings.push( - new WebpackError( - `Conflict: Multiple assets emit different content to the same filename ${file}` - ) - ); - this.assets[file] = source; - this.assetsInfo.set(file, assetInfo); - return; - } - const oldInfo = this.assetsInfo.get(file); - this.assetsInfo.set(file, Object.assign({}, oldInfo, assetInfo)); - return; - } - this.assets[file] = source; - this.assetsInfo.set(file, assetInfo); + getRuntimeChunk() { + return this.runtimeChunk || this.chunks[0]; } /** - * @param {string} file file name - * @param {Source | function(Source): Source} newSourceOrFunction new asset source or function converting old to new - * @param {AssetInfo | function(AssetInfo | undefined): AssetInfo} assetInfoUpdateOrFunction new asset info or function converting old to new + * @param {Chunk} oldChunk chunk to be replaced + * @param {Chunk} newChunk New chunk that will be replaced with + * @returns {boolean} returns true if the replacement was successful */ - updateAsset( - file, - newSourceOrFunction, - assetInfoUpdateOrFunction = undefined - ) { - if (!this.assets[file]) { - throw new Error( - `Called Compilation.updateAsset for not existing filename ${file}` - ); - } - if (typeof newSourceOrFunction === "function") { - this.assets[file] = newSourceOrFunction(this.assets[file]); - } else { - this.assets[file] = newSourceOrFunction; - } - if (assetInfoUpdateOrFunction !== undefined) { - const oldInfo = this.assetsInfo.get(file); - if (typeof assetInfoUpdateOrFunction === "function") { - this.assetsInfo.set(file, assetInfoUpdateOrFunction(oldInfo || {})); - } else { - this.assetsInfo.set( - file, - Object.assign({}, oldInfo, assetInfoUpdateOrFunction) - ); - } - } + replaceChunk(oldChunk, newChunk) { + if (this.runtimeChunk === oldChunk) this.runtimeChunk = newChunk; + return super.replaceChunk(oldChunk, newChunk); } +} - getAssets() { - /** @type {Asset[]} */ - const array = []; - for (const assetName of Object.keys(this.assets)) { - if (Object.prototype.hasOwnProperty.call(this.assets, assetName)) { - array.push({ - name: assetName, - source: this.assets[assetName], - info: this.assetsInfo.get(assetName) || {} - }); - } +module.exports = Entrypoint; + + +/***/ }), + +/***/ 6098: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Authors Simen Brekken @simenbrekken, Einar Löve @einarlove +*/ + + + +/** @typedef {import("./Compiler")} Compiler */ + +const WebpackError = __webpack_require__(97391); +const DefinePlugin = __webpack_require__(97374); + +const needsEnvVarFix = + ["8", "9"].indexOf(process.versions.node.split(".")[0]) >= 0 && + process.platform === "win32"; + +class EnvironmentPlugin { + constructor(...keys) { + if (keys.length === 1 && Array.isArray(keys[0])) { + this.keys = keys[0]; + this.defaultValues = {}; + } else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") { + this.keys = Object.keys(keys[0]); + this.defaultValues = keys[0]; + } else { + this.keys = keys; + this.defaultValues = {}; } - return array; } /** - * @param {string} name the name of the asset - * @returns {Asset | undefined} the asset or undefined when not found + * @param {Compiler} compiler webpack compiler instance + * @returns {void} */ - getAsset(name) { - if (!Object.prototype.hasOwnProperty.call(this.assets, name)) - return undefined; - return { - name, - source: this.assets[name], - info: this.assetsInfo.get(name) || {} - }; - } + apply(compiler) { + const definitions = this.keys.reduce((defs, key) => { + // TODO remove once the fix has made its way into Node 8. + // Work around https://github.com/nodejs/node/pull/18463, + // affecting Node 8 & 9 by performing an OS-level + // operation that always succeeds before reading + // environment variables: + if (needsEnvVarFix) __webpack_require__(12087).cpus(); - createModuleAssets() { - for (let i = 0; i < this.modules.length; i++) { - const module = this.modules[i]; - if (module.buildInfo.assets) { - const assetsInfo = module.buildInfo.assetsInfo; - for (const assetName of Object.keys(module.buildInfo.assets)) { - const fileName = this.getPath(assetName); - this.emitAsset( - fileName, - module.buildInfo.assets[assetName], - assetsInfo ? assetsInfo.get(assetName) : undefined - ); - this.hooks.moduleAsset.call(module, fileName); - } - } - } - } + const value = + process.env[key] !== undefined + ? process.env[key] + : this.defaultValues[key]; - createChunkAssets() { - const outputOptions = this.outputOptions; - const cachedSourceMap = new Map(); - /** @type {Map} */ - const alreadyWrittenFiles = new Map(); - for (let i = 0; i < this.chunks.length; i++) { - const chunk = this.chunks[i]; - chunk.files = []; - let source; - let file; - let filenameTemplate; - try { - const template = chunk.hasRuntime() - ? this.mainTemplate - : this.chunkTemplate; - const manifest = template.getRenderManifest({ - chunk, - hash: this.hash, - fullHash: this.fullHash, - outputOptions, - moduleTemplates: this.moduleTemplates, - dependencyTemplates: this.dependencyTemplates - }); // [{ render(), filenameTemplate, pathOptions, identifier, hash }] - for (const fileManifest of manifest) { - const cacheName = fileManifest.identifier; - const usedHash = fileManifest.hash; - filenameTemplate = fileManifest.filenameTemplate; - const pathAndInfo = this.getPathWithInfo( - filenameTemplate, - fileManifest.pathOptions + if (value === undefined) { + compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => { + const error = new WebpackError( + `EnvironmentPlugin - ${key} environment variable is undefined.\n\n` + + "You can pass an object with default values to suppress this warning.\n" + + "See https://webpack.js.org/plugins/environment-plugin for example." ); - file = pathAndInfo.path; - const assetInfo = pathAndInfo.info; - // check if the same filename was already written by another chunk - const alreadyWritten = alreadyWrittenFiles.get(file); - if (alreadyWritten !== undefined) { - if (alreadyWritten.hash === usedHash) { - if (this.cache) { - this.cache[cacheName] = { - hash: usedHash, - source: alreadyWritten.source - }; - } - chunk.files.push(file); - this.hooks.chunkAsset.call(chunk, file); - continue; - } else { - throw new Error( - `Conflict: Multiple chunks emit assets to the same filename ${file}` + - ` (chunks ${alreadyWritten.chunk.id} and ${chunk.id})` - ); - } - } - if ( - this.cache && - this.cache[cacheName] && - this.cache[cacheName].hash === usedHash - ) { - source = this.cache[cacheName].source; - } else { - source = fileManifest.render(); - // Ensure that source is a cached source to avoid additional cost because of repeated access - if (!(source instanceof CachedSource)) { - const cacheEntry = cachedSourceMap.get(source); - if (cacheEntry) { - source = cacheEntry; - } else { - const cachedSource = new CachedSource(source); - cachedSourceMap.set(source, cachedSource); - source = cachedSource; - } - } - if (this.cache) { - this.cache[cacheName] = { - hash: usedHash, - source - }; - } - } - this.emitAsset(file, source, assetInfo); - chunk.files.push(file); - this.hooks.chunkAsset.call(chunk, file); - alreadyWrittenFiles.set(file, { - hash: usedHash, - source, - chunk - }); - } - } catch (err) { - this.errors.push( - new ChunkRenderError(chunk, file || filenameTemplate, err) - ); + error.name = "EnvVariableNotDefinedError"; + compilation.warnings.push(error); + }); } - } - } - /** - * @param {string} filename used to get asset path with hash - * @param {TODO=} data // TODO: figure out this param type - * @returns {string} interpolated path - */ - getPath(filename, data) { - data = data || {}; - data.hash = data.hash || this.hash; - return this.mainTemplate.getAssetPath(filename, data); - } + defs[`process.env.${key}`] = + value === undefined ? "undefined" : JSON.stringify(value); - /** - * @param {string} filename used to get asset path with hash - * @param {TODO=} data // TODO: figure out this param type - * @returns {{ path: string, info: AssetInfo }} interpolated path and asset info - */ - getPathWithInfo(filename, data) { - data = data || {}; - data.hash = data.hash || this.hash; - return this.mainTemplate.getAssetPathWithInfo(filename, data); - } + return defs; + }, {}); - /** - * This function allows you to run another instance of webpack inside of webpack however as - * a child with different settings and configurations (if desired) applied. It copies all hooks, plugins - * from parent (or top level compiler) and creates a child Compilation - * - * @param {string} name name of the child compiler - * @param {TODO} outputOptions // Need to convert config schema to types for this - * @param {Plugin[]} plugins webpack plugins that will be applied - * @returns {Compiler} creates a child Compiler instance - */ - createChildCompiler(name, outputOptions, plugins) { - const idx = this.childrenCounters[name] || 0; - this.childrenCounters[name] = idx + 1; - return this.compiler.createChildCompiler( - this, - name, - idx, - outputOptions, - plugins - ); + new DefinePlugin(definitions).apply(compiler); } +} - checkConstraints() { - /** @type {Set} */ - const usedIds = new Set(); +module.exports = EnvironmentPlugin; - const modules = this.modules; - for (let indexModule = 0; indexModule < modules.length; indexModule++) { - const moduleId = modules[indexModule].id; - if (moduleId === null) continue; - if (usedIds.has(moduleId)) { - throw new Error(`checkConstraints: duplicate module id ${moduleId}`); - } - usedIds.add(moduleId); - } - const chunks = this.chunks; - for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { - const chunk = chunks[indexChunk]; - if (chunks.indexOf(chunk) !== indexChunk) { - throw new Error( - `checkConstraints: duplicate chunk in compilation ${chunk.debugId}` - ); - } - } +/***/ }), - for (const chunkGroup of this.chunkGroups) { - chunkGroup.checkConstraints(); +/***/ 80140: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const loaderFlag = "LOADER_EXECUTION"; + +const webpackOptionsFlag = "WEBPACK_OPTIONS"; + +exports.cutOffByFlag = (stack, flag) => { + stack = stack.split("\n"); + for (let i = 0; i < stack.length; i++) { + if (stack[i].includes(flag)) { + stack.length = i; } } -} + return stack.join("\n"); +}; -// TODO remove in webpack 5 -Compilation.prototype.applyPlugins = util.deprecate( - /** - * @deprecated - * @param {string} name Name - * @param {any[]} args Other arguments - * @returns {void} - * @this {Compilation} - */ - function(name, ...args) { - this.hooks[ - name.replace(/[- ]([a-z])/g, match => match[1].toUpperCase()) - ].call(...args); - }, - "Compilation.applyPlugins is deprecated. Use new API on `.hooks` instead" -); +exports.cutOffLoaderExecution = stack => + exports.cutOffByFlag(stack, loaderFlag); -// TODO remove in webpack 5 -Object.defineProperty(Compilation.prototype, "moduleTemplate", { - configurable: false, - get: util.deprecate( - /** - * @deprecated - * @this {Compilation} - * @returns {TODO} module template - */ - function() { - return this.moduleTemplates.javascript; - }, - "Compilation.moduleTemplate: Use Compilation.moduleTemplates.javascript instead" - ), - set: util.deprecate( - /** - * @deprecated - * @param {ModuleTemplate} value Template value - * @this {Compilation} - * @returns {void} - */ - function(value) { - this.moduleTemplates.javascript = value; - }, - "Compilation.moduleTemplate: Use Compilation.moduleTemplates.javascript instead." - ) -}); +exports.cutOffWebpackOptions = stack => + exports.cutOffByFlag(stack, webpackOptionsFlag); -module.exports = Compilation; +exports.cutOffMultilineMessage = (stack, message) => { + stack = stack.split("\n"); + message = message.split("\n"); + + return stack + .reduce( + (acc, line, idx) => + line.includes(message[idx]) ? acc : acc.concat(line), + [] + ) + .join("\n"); +}; + +exports.cutOffMessage = (stack, message) => { + const nextLine = stack.indexOf("\n"); + if (nextLine === -1) { + return stack === message ? "" : stack; + } else { + const firstLine = stack.substr(0, nextLine); + return firstLine === message ? stack.substr(nextLine + 1) : stack; + } +}; + +exports.cleanUp = (stack, message) => { + stack = exports.cutOffLoaderExecution(stack); + stack = exports.cutOffMessage(stack, message); + return stack; +}; + +exports.cleanUpWebpackOptions = (stack, message) => { + stack = exports.cutOffWebpackOptions(stack); + stack = exports.cutOffMultilineMessage(stack, message); + return stack; +}; /***/ }), -/***/ 58705: +/***/ 65200: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -74167,1159 +74497,817 @@ module.exports = Compilation; */ -const parseJson = __webpack_require__(48335); -const asyncLib = __webpack_require__(36386); -const path = __webpack_require__(85622); -const { Source } = __webpack_require__(53665); -const util = __webpack_require__(31669); -const { - Tapable, - SyncHook, - SyncBailHook, - AsyncParallelHook, - AsyncSeriesHook -} = __webpack_require__(56758); +const EvalDevToolModuleTemplatePlugin = __webpack_require__(24157); -const Compilation = __webpack_require__(34968); -const Stats = __webpack_require__(99977); -const Watching = __webpack_require__(29580); -const NormalModuleFactory = __webpack_require__(22298); -const ContextModuleFactory = __webpack_require__(88239); -const ResolverFactory = __webpack_require__(50588); +class EvalDevToolModulePlugin { + constructor(options) { + this.sourceUrlComment = options.sourceUrlComment; + this.moduleFilenameTemplate = options.moduleFilenameTemplate; + this.namespace = options.namespace; + } -const RequestShortener = __webpack_require__(54254); -const { makePathsRelative } = __webpack_require__(94658); -const ConcurrentCompilationError = __webpack_require__(18933); -const { Logger } = __webpack_require__(47194); + apply(compiler) { + compiler.hooks.compilation.tap("EvalDevToolModulePlugin", compilation => { + new EvalDevToolModuleTemplatePlugin({ + sourceUrlComment: this.sourceUrlComment, + moduleFilenameTemplate: this.moduleFilenameTemplate, + namespace: this.namespace + }).apply(compilation.moduleTemplates.javascript); + }); + } +} -/** @typedef {import("../declarations/WebpackOptions").Entry} Entry */ -/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +module.exports = EvalDevToolModulePlugin; -/** - * @typedef {Object} CompilationParams - * @property {NormalModuleFactory} normalModuleFactory - * @property {ContextModuleFactory} contextModuleFactory - * @property {Set} compilationDependencies - */ -class Compiler extends Tapable { - constructor(context) { - super(); - this.hooks = { - /** @type {SyncBailHook} */ - shouldEmit: new SyncBailHook(["compilation"]), - /** @type {AsyncSeriesHook} */ - done: new AsyncSeriesHook(["stats"]), - /** @type {AsyncSeriesHook<>} */ - additionalPass: new AsyncSeriesHook([]), - /** @type {AsyncSeriesHook} */ - beforeRun: new AsyncSeriesHook(["compiler"]), - /** @type {AsyncSeriesHook} */ - run: new AsyncSeriesHook(["compiler"]), - /** @type {AsyncSeriesHook} */ - emit: new AsyncSeriesHook(["compilation"]), - /** @type {AsyncSeriesHook} */ - assetEmitted: new AsyncSeriesHook(["file", "content"]), - /** @type {AsyncSeriesHook} */ - afterEmit: new AsyncSeriesHook(["compilation"]), +/***/ }), - /** @type {SyncHook} */ - thisCompilation: new SyncHook(["compilation", "params"]), - /** @type {SyncHook} */ - compilation: new SyncHook(["compilation", "params"]), - /** @type {SyncHook} */ - normalModuleFactory: new SyncHook(["normalModuleFactory"]), - /** @type {SyncHook} */ - contextModuleFactory: new SyncHook(["contextModulefactory"]), +/***/ 24157: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {AsyncSeriesHook} */ - beforeCompile: new AsyncSeriesHook(["params"]), - /** @type {SyncHook} */ - compile: new SyncHook(["params"]), - /** @type {AsyncParallelHook} */ - make: new AsyncParallelHook(["compilation"]), - /** @type {AsyncSeriesHook} */ - afterCompile: new AsyncSeriesHook(["compilation"]), +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {AsyncSeriesHook} */ - watchRun: new AsyncSeriesHook(["compiler"]), - /** @type {SyncHook} */ - failed: new SyncHook(["error"]), - /** @type {SyncHook} */ - invalid: new SyncHook(["filename", "changeTime"]), - /** @type {SyncHook} */ - watchClose: new SyncHook([]), - /** @type {SyncBailHook} */ - infrastructureLog: new SyncBailHook(["origin", "type", "args"]), +const { RawSource } = __webpack_require__(53665); +const ModuleFilenameHelpers = __webpack_require__(71474); - // TODO the following hooks are weirdly located here - // TODO move them for webpack 5 - /** @type {SyncHook} */ - environment: new SyncHook([]), - /** @type {SyncHook} */ - afterEnvironment: new SyncHook([]), - /** @type {SyncHook} */ - afterPlugins: new SyncHook(["compiler"]), - /** @type {SyncHook} */ - afterResolvers: new SyncHook(["compiler"]), - /** @type {SyncBailHook} */ - entryOption: new SyncBailHook(["context", "entry"]) - }; - // TODO webpack 5 remove this - this.hooks.infrastructurelog = this.hooks.infrastructureLog; +const cache = new WeakMap(); - this._pluginCompat.tap("Compiler", options => { - switch (options.name) { - case "additional-pass": - case "before-run": - case "run": - case "emit": - case "after-emit": - case "before-compile": - case "make": - case "after-compile": - case "watch-run": - options.async = true; - break; +class EvalDevToolModuleTemplatePlugin { + constructor(options) { + this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || + "webpack://[namespace]/[resourcePath]?[loaders]"; + this.namespace = options.namespace || ""; + } + + apply(moduleTemplate) { + moduleTemplate.hooks.module.tap( + "EvalDevToolModuleTemplatePlugin", + (source, module) => { + const cacheEntry = cache.get(source); + if (cacheEntry !== undefined) return cacheEntry; + const content = source.source(); + const str = ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: this.moduleFilenameTemplate, + namespace: this.namespace + }, + moduleTemplate.runtimeTemplate.requestShortener + ); + const footer = + "\n" + + this.sourceUrlComment.replace( + /\[url\]/g, + encodeURI(str) + .replace(/%2F/g, "/") + .replace(/%20/g, "_") + .replace(/%5E/g, "^") + .replace(/%5C/g, "\\") + .replace(/^\//, "") + ); + const result = new RawSource( + `eval(${JSON.stringify(content + footer)});` + ); + cache.set(source, result); + return result; } + ); + moduleTemplate.hooks.hash.tap("EvalDevToolModuleTemplatePlugin", hash => { + hash.update("EvalDevToolModuleTemplatePlugin"); + hash.update("2"); }); + } +} - /** @type {string=} */ - this.name = undefined; - /** @type {Compilation=} */ - this.parentCompilation = undefined; - /** @type {string} */ - this.outputPath = ""; +module.exports = EvalDevToolModuleTemplatePlugin; - this.outputFileSystem = null; - this.inputFileSystem = null; - /** @type {string|null} */ - this.recordsInputPath = null; - /** @type {string|null} */ - this.recordsOutputPath = null; - this.records = {}; - this.removedFiles = new Set(); - /** @type {Map} */ - this.fileTimestamps = new Map(); - /** @type {Map} */ - this.contextTimestamps = new Map(); - /** @type {ResolverFactory} */ - this.resolverFactory = new ResolverFactory(); +/***/ }), - this.infrastructureLogger = undefined; +/***/ 51352: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // TODO remove in webpack 5 - this.resolvers = { - normal: { - plugins: util.deprecate((hook, fn) => { - this.resolverFactory.plugin("resolver normal", resolver => { - resolver.plugin(hook, fn); - }); - }, "webpack: Using compiler.resolvers.normal is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver normal", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), - apply: util.deprecate((...args) => { - this.resolverFactory.plugin("resolver normal", resolver => { - resolver.apply(...args); - }); - }, "webpack: Using compiler.resolvers.normal is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver normal", resolver => {\n resolver.apply(/* … */);\n}); instead.') - }, - loader: { - plugins: util.deprecate((hook, fn) => { - this.resolverFactory.plugin("resolver loader", resolver => { - resolver.plugin(hook, fn); - }); - }, "webpack: Using compiler.resolvers.loader is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver loader", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), - apply: util.deprecate((...args) => { - this.resolverFactory.plugin("resolver loader", resolver => { - resolver.apply(...args); - }); - }, "webpack: Using compiler.resolvers.loader is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver loader", resolver => {\n resolver.apply(/* … */);\n}); instead.') - }, - context: { - plugins: util.deprecate((hook, fn) => { - this.resolverFactory.plugin("resolver context", resolver => { - resolver.plugin(hook, fn); - }); - }, "webpack: Using compiler.resolvers.context is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver context", resolver => {\n resolver.plugin(/* … */);\n}); instead.'), - apply: util.deprecate((...args) => { - this.resolverFactory.plugin("resolver context", resolver => { - resolver.apply(...args); - }); - }, "webpack: Using compiler.resolvers.context is deprecated.\n" + 'Use compiler.resolverFactory.plugin("resolver context", resolver => {\n resolver.apply(/* … */);\n}); instead.') - } - }; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** @type {WebpackOptions} */ - this.options = /** @type {WebpackOptions} */ ({}); - this.context = context; +const { RawSource } = __webpack_require__(53665); +const ModuleFilenameHelpers = __webpack_require__(71474); +const { absolutify } = __webpack_require__(94658); - this.requestShortener = new RequestShortener(context); +const cache = new WeakMap(); - /** @type {boolean} */ - this.running = false; +class EvalSourceMapDevToolModuleTemplatePlugin { + constructor(compilation, options) { + this.compilation = compilation; + this.sourceMapComment = + options.append || "//# sourceURL=[module]\n//# sourceMappingURL=[url]"; + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || + "webpack://[namespace]/[resource-path]?[hash]"; + this.namespace = options.namespace || ""; + this.options = options; + } - /** @type {boolean} */ - this.watchMode = false; + apply(moduleTemplate) { + const self = this; + const options = this.options; + const matchModule = ModuleFilenameHelpers.matchObject.bind( + ModuleFilenameHelpers, + options + ); + moduleTemplate.hooks.module.tap( + "EvalSourceMapDevToolModuleTemplatePlugin", + (source, module) => { + const cachedSource = cache.get(source); + if (cachedSource !== undefined) { + return cachedSource; + } - /** @private @type {WeakMap }>} */ - this._assetEmittingSourceCache = new WeakMap(); - /** @private @type {Map} */ - this._assetEmittingWrittenFiles = new Map(); - } + if (!matchModule(module.resource)) { + return source; + } - /** - * @param {string | (function(): string)} name name of the logger, or function called once to get the logger name - * @returns {Logger} a logger with that name - */ - getInfrastructureLogger(name) { - if (!name) { - throw new TypeError( - "Compiler.getInfrastructureLogger(name) called without a name" - ); - } - return new Logger((type, args) => { - if (typeof name === "function") { - name = name(); - if (!name) { - throw new TypeError( - "Compiler.getInfrastructureLogger(name) called with a function not returning a name" - ); + /** @type {{ [key: string]: TODO; }} */ + let sourceMap; + let content; + if (source.sourceAndMap) { + const sourceAndMap = source.sourceAndMap(options); + sourceMap = sourceAndMap.map; + content = sourceAndMap.source; + } else { + sourceMap = source.map(options); + content = source.source(); } - } - if (this.hooks.infrastructureLog.call(name, type, args) === undefined) { - if (this.infrastructureLogger !== undefined) { - this.infrastructureLogger(name, type, args); + if (!sourceMap) { + return source; } - } - }); - } - watch(watchOptions, handler) { - if (this.running) return handler(new ConcurrentCompilationError()); + // Clone (flat) the sourcemap to ensure that the mutations below do not persist. + sourceMap = Object.keys(sourceMap).reduce((obj, key) => { + obj[key] = sourceMap[key]; + return obj; + }, {}); + const context = this.compilation.compiler.options.context; + const modules = sourceMap.sources.map(source => { + if (source.startsWith("webpack://")) { + source = absolutify(context, source.slice(10)); + } + const module = self.compilation.findModule(source); + return module || source; + }); + let moduleFilenames = modules.map(module => { + return ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: self.moduleFilenameTemplate, + namespace: self.namespace + }, + moduleTemplate.runtimeTemplate.requestShortener + ); + }); + moduleFilenames = ModuleFilenameHelpers.replaceDuplicates( + moduleFilenames, + (filename, i, n) => { + for (let j = 0; j < n; j++) filename += "*"; + return filename; + } + ); + sourceMap.sources = moduleFilenames; + sourceMap.sourceRoot = options.sourceRoot || ""; + sourceMap.file = `${module.id}.js`; - this.running = true; - this.watchMode = true; - this.fileTimestamps = new Map(); - this.contextTimestamps = new Map(); - this.removedFiles = new Set(); - return new Watching(this, watchOptions, handler); - } + const footer = + self.sourceMapComment.replace( + /\[url\]/g, + `data:application/json;charset=utf-8;base64,${Buffer.from( + JSON.stringify(sourceMap), + "utf8" + ).toString("base64")}` + ) + `\n//# sourceURL=webpack-internal:///${module.id}\n`; // workaround for chrome bug - run(callback) { - if (this.running) return callback(new ConcurrentCompilationError()); + const evalSource = new RawSource( + `eval(${JSON.stringify(content + footer)});` + ); - const finalCallback = (err, stats) => { - this.running = false; + cache.set(source, evalSource); - if (err) { - this.hooks.failed.call(err); + return evalSource; + } + ); + moduleTemplate.hooks.hash.tap( + "EvalSourceMapDevToolModuleTemplatePlugin", + hash => { + hash.update("eval-source-map"); + hash.update("2"); } + ); + } +} +module.exports = EvalSourceMapDevToolModuleTemplatePlugin; - if (callback !== undefined) return callback(err, stats); - }; - const startTime = Date.now(); +/***/ }), - this.running = true; +/***/ 99994: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const onCompiled = (err, compilation) => { - if (err) return finalCallback(err); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (this.hooks.shouldEmit.call(compilation) === false) { - const stats = new Stats(compilation); - stats.startTime = startTime; - stats.endTime = Date.now(); - this.hooks.done.callAsync(stats, err => { - if (err) return finalCallback(err); - return finalCallback(null, stats); - }); - return; + +const EvalSourceMapDevToolModuleTemplatePlugin = __webpack_require__(51352); +const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(24113); + +class EvalSourceMapDevToolPlugin { + constructor(options) { + if (arguments.length > 1) { + throw new Error( + "EvalSourceMapDevToolPlugin only takes one argument (pass an options object)" + ); + } + if (typeof options === "string") { + options = { + append: options + }; + } + if (!options) options = {}; + this.options = options; + } + + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "EvalSourceMapDevToolPlugin", + compilation => { + new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); + new EvalSourceMapDevToolModuleTemplatePlugin( + compilation, + options + ).apply(compilation.moduleTemplates.javascript); } + ); + } +} - this.emitAssets(compilation, err => { - if (err) return finalCallback(err); +module.exports = EvalSourceMapDevToolPlugin; - if (compilation.hooks.needAdditionalPass.call()) { - compilation.needAdditionalPass = true; - const stats = new Stats(compilation); - stats.startTime = startTime; - stats.endTime = Date.now(); - this.hooks.done.callAsync(stats, err => { - if (err) return finalCallback(err); +/***/ }), - this.hooks.additionalPass.callAsync(err => { - if (err) return finalCallback(err); - this.compile(onCompiled); - }); - }); - return; - } +/***/ 50471: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - this.emitRecords(err => { - if (err) return finalCallback(err); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const stats = new Stats(compilation); - stats.startTime = startTime; - stats.endTime = Date.now(); - this.hooks.done.callAsync(stats, err => { - if (err) return finalCallback(err); - return finalCallback(null, stats); - }); - }); - }); - }; - this.hooks.beforeRun.callAsync(this, err => { - if (err) return finalCallback(err); +const { ConcatSource } = __webpack_require__(53665); - this.hooks.run.callAsync(this, err => { - if (err) return finalCallback(err); +/** @typedef {import("./Compilation")} Compilation */ - this.readRecords(err => { - if (err) return finalCallback(err); +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; - this.compile(onCompiled); - }); - }); - }); +class ExportPropertyMainTemplatePlugin { + /** + * @param {string|string[]} property the name of the property to export + */ + constructor(property) { + this.property = property; } - runAsChild(callback) { - this.compile((err, compilation) => { - if (err) return callback(err); + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; - this.parentCompilation.children.push(compilation); - for (const { name, source, info } of compilation.getAssets()) { - this.parentCompilation.emitAsset(name, source, info); - } + const onRenderWithEntry = (source, chunk, hash) => { + const postfix = `${accessorToObjectAccess([].concat(this.property))}`; + return new ConcatSource(source, postfix); + }; - const entries = Array.from( - compilation.entrypoints.values(), - ep => ep.chunks - ).reduce((array, chunks) => { - return array.concat(chunks); - }, []); + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "ExportPropertyMainTemplatePlugin", + onRenderWithEntry + ); + } - return callback(null, entries, compilation); + mainTemplate.hooks.hash.tap("ExportPropertyMainTemplatePlugin", hash => { + hash.update("export property"); + hash.update(`${this.property}`); }); } +} - purgeInputFileSystem() { - if (this.inputFileSystem && this.inputFileSystem.purge) { - this.inputFileSystem.purge(); - } - } +module.exports = ExportPropertyMainTemplatePlugin; - emitAssets(compilation, callback) { - let outputPath; - const emitFiles = err => { - if (err) return callback(err); - asyncLib.forEachLimit( - compilation.getAssets(), - 15, - ({ name: file, source }, callback) => { - let targetFile = file; - const queryStringIdx = targetFile.indexOf("?"); - if (queryStringIdx >= 0) { - targetFile = targetFile.substr(0, queryStringIdx); - } +/***/ }), - const writeOut = err => { - if (err) return callback(err); - const targetPath = this.outputFileSystem.join( - outputPath, - targetFile - ); - // TODO webpack 5 remove futureEmitAssets option and make it on by default - if (this.options.output.futureEmitAssets) { - // check if the target file has already been written by this Compiler - const targetFileGeneration = this._assetEmittingWrittenFiles.get( - targetPath - ); +/***/ 17270: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // create an cache entry for this Source if not already existing - let cacheEntry = this._assetEmittingSourceCache.get(source); - if (cacheEntry === undefined) { - cacheEntry = { - sizeOnlySource: undefined, - writtenTo: new Map() - }; - this._assetEmittingSourceCache.set(source, cacheEntry); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // if the target file has already been written - if (targetFileGeneration !== undefined) { - // check if the Source has been written to this target file - const writtenGeneration = cacheEntry.writtenTo.get(targetPath); - if (writtenGeneration === targetFileGeneration) { - // if yes, we skip writing the file - // as it's already there - // (we assume one doesn't remove files while the Compiler is running) - compilation.updateAsset(file, cacheEntry.sizeOnlySource, { - size: cacheEntry.sizeOnlySource.size() - }); +const Template = __webpack_require__(96066); +const ConstDependency = __webpack_require__(71101); +const ParserHelpers = __webpack_require__(23999); +const NullFactory = __webpack_require__(40438); - return callback(); - } - } +const REPLACEMENTS = { + // eslint-disable-next-line camelcase + __webpack_hash__: "__webpack_require__.h", + // eslint-disable-next-line camelcase + __webpack_chunkname__: "__webpack_require__.cn" +}; +const REPLACEMENT_TYPES = { + // eslint-disable-next-line camelcase + __webpack_hash__: "string", + // eslint-disable-next-line camelcase + __webpack_chunkname__: "string" +}; - // TODO webpack 5: if info.immutable check if file already exists in output - // skip emitting if it's already there +class ExtendedAPIPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "ExtendedAPIPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); - // get the binary (Buffer) content from the Source - /** @type {Buffer} */ - let content; - if (typeof source.buffer === "function") { - content = source.buffer(); - } else { - const bufferOrString = source.source(); - if (Buffer.isBuffer(bufferOrString)) { - content = bufferOrString; - } else { - content = Buffer.from(bufferOrString, "utf8"); - } - } - - // Create a replacement resource which only allows to ask for size - // This allows to GC all memory allocated by the Source - // (expect when the Source is stored in any other cache) - cacheEntry.sizeOnlySource = new SizeOnlySource(content.length); - compilation.updateAsset(file, cacheEntry.sizeOnlySource, { - size: content.length - }); - - // Write the file to output file system - this.outputFileSystem.writeFile(targetPath, content, err => { - if (err) return callback(err); - - // information marker that the asset has been emitted - compilation.emittedAssets.add(file); - - // cache the information that the Source has been written to that location - const newGeneration = - targetFileGeneration === undefined - ? 1 - : targetFileGeneration + 1; - cacheEntry.writtenTo.set(targetPath, newGeneration); - this._assetEmittingWrittenFiles.set(targetPath, newGeneration); - this.hooks.assetEmitted.callAsync(file, content, callback); - }); - } else { - if (source.existsAt === targetPath) { - source.emitted = false; - return callback(); - } - let content = source.source(); - - if (!Buffer.isBuffer(content)) { - content = Buffer.from(content, "utf8"); - } - - source.existsAt = targetPath; - source.emitted = true; - this.outputFileSystem.writeFile(targetPath, content, err => { - if (err) return callback(err); - this.hooks.assetEmitted.callAsync(file, content, callback); - }); - } - }; - - if (targetFile.match(/\/|\\/)) { - const dir = path.dirname(targetFile); - this.outputFileSystem.mkdirp( - this.outputFileSystem.join(outputPath, dir), - writeOut + const mainTemplate = compilation.mainTemplate; + mainTemplate.hooks.requireExtensions.tap( + "ExtendedAPIPlugin", + (source, chunk, hash) => { + const buf = [source]; + buf.push(""); + buf.push("// __webpack_hash__"); + buf.push(`${mainTemplate.requireFn}.h = ${JSON.stringify(hash)};`); + buf.push(""); + buf.push("// __webpack_chunkname__"); + buf.push( + `${mainTemplate.requireFn}.cn = ${JSON.stringify(chunk.name)};` ); - } else { - writeOut(); + return Template.asString(buf); } - }, - err => { - if (err) return callback(err); - - this.hooks.afterEmit.callAsync(compilation, err => { - if (err) return callback(err); + ); + mainTemplate.hooks.globalHash.tap("ExtendedAPIPlugin", () => true); - return callback(); + const handler = (parser, parserOptions) => { + Object.keys(REPLACEMENTS).forEach(key => { + parser.hooks.expression + .for(key) + .tap( + "ExtendedAPIPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + REPLACEMENTS[key] + ) + ); + parser.hooks.evaluateTypeof + .for(key) + .tap( + "ExtendedAPIPlugin", + ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]) + ); }); - } - ); - }; + }; - this.hooks.emit.callAsync(compilation, err => { - if (err) return callback(err); - outputPath = compilation.getPath(this.outputPath); - this.outputFileSystem.mkdirp(outputPath, emitFiles); - }); + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ExtendedAPIPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ExtendedAPIPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ExtendedAPIPlugin", handler); + } + ); } +} - emitRecords(callback) { - if (!this.recordsOutputPath) return callback(); - const idx1 = this.recordsOutputPath.lastIndexOf("/"); - const idx2 = this.recordsOutputPath.lastIndexOf("\\"); - let recordsOutputPathDirectory = null; - if (idx1 > idx2) { - recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1); - } else if (idx1 < idx2) { - recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2); - } - - const writeFile = () => { - this.outputFileSystem.writeFile( - this.recordsOutputPath, - JSON.stringify(this.records, undefined, 2), - callback - ); - }; - - if (!recordsOutputPathDirectory) { - return writeFile(); - } - this.outputFileSystem.mkdirp(recordsOutputPathDirectory, err => { - if (err) return callback(err); - writeFile(); - }); - } +module.exports = ExtendedAPIPlugin; - readRecords(callback) { - if (!this.recordsInputPath) { - this.records = {}; - return callback(); - } - this.inputFileSystem.stat(this.recordsInputPath, err => { - // It doesn't exist - // We can ignore this. - if (err) return callback(); - this.inputFileSystem.readFile(this.recordsInputPath, (err, content) => { - if (err) return callback(err); +/***/ }), - try { - this.records = parseJson(content.toString("utf-8")); - } catch (e) { - e.message = "Cannot parse records: " + e.message; - return callback(e); - } +/***/ 17204: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return callback(); - }); - }); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - createChildCompiler( - compilation, - compilerName, - compilerIndex, - outputOptions, - plugins - ) { - const childCompiler = new Compiler(this.context); - if (Array.isArray(plugins)) { - for (const plugin of plugins) { - plugin.apply(childCompiler); - } - } - for (const name in this.hooks) { - if ( - ![ - "make", - "compile", - "emit", - "afterEmit", - "invalid", - "done", - "thisCompilation" - ].includes(name) - ) { - if (childCompiler.hooks[name]) { - childCompiler.hooks[name].taps = this.hooks[name].taps.slice(); - } - } - } - childCompiler.name = compilerName; - childCompiler.outputPath = this.outputPath; - childCompiler.inputFileSystem = this.inputFileSystem; - childCompiler.outputFileSystem = null; - childCompiler.resolverFactory = this.resolverFactory; - childCompiler.fileTimestamps = this.fileTimestamps; - childCompiler.contextTimestamps = this.contextTimestamps; - const relativeCompilerName = makePathsRelative(this.context, compilerName); - if (!this.records[relativeCompilerName]) { - this.records[relativeCompilerName] = []; - } - if (this.records[relativeCompilerName][compilerIndex]) { - childCompiler.records = this.records[relativeCompilerName][compilerIndex]; - } else { - this.records[relativeCompilerName].push((childCompiler.records = {})); - } +const { OriginalSource, RawSource } = __webpack_require__(53665); +const Module = __webpack_require__(75993); +const WebpackMissingModule = __webpack_require__(75386); +const Template = __webpack_require__(96066); - childCompiler.options = Object.create(this.options); - childCompiler.options.output = Object.create(childCompiler.options.output); - for (const name in outputOptions) { - childCompiler.options.output[name] = outputOptions[name]; - } - childCompiler.parentCompilation = compilation; +/** @typedef {import("./util/createHash").Hash} Hash */ - compilation.hooks.childCompiler.call( - childCompiler, - compilerName, - compilerIndex - ); +class ExternalModule extends Module { + constructor(request, type, userRequest) { + super("javascript/dynamic", null); - return childCompiler; + // Info from Factory + this.request = request; + this.externalType = type; + this.userRequest = userRequest; + this.external = true; } - isChild() { - return !!this.parentCompilation; + libIdent() { + return this.userRequest; } - createCompilation() { - return new Compilation(this); + chunkCondition(chunk) { + return chunk.hasEntryModule(); } - newCompilation(params) { - const compilation = this.createCompilation(); - compilation.fileTimestamps = this.fileTimestamps; - compilation.contextTimestamps = this.contextTimestamps; - compilation.name = this.name; - compilation.records = this.records; - compilation.compilationDependencies = params.compilationDependencies; - this.hooks.thisCompilation.call(compilation, params); - this.hooks.compilation.call(compilation, params); - return compilation; + identifier() { + return "external " + JSON.stringify(this.request); } - createNormalModuleFactory() { - const normalModuleFactory = new NormalModuleFactory( - this.options.context, - this.resolverFactory, - this.options.module || {} - ); - this.hooks.normalModuleFactory.call(normalModuleFactory); - return normalModuleFactory; + readableIdentifier() { + return "external " + JSON.stringify(this.request); } - createContextModuleFactory() { - const contextModuleFactory = new ContextModuleFactory(this.resolverFactory); - this.hooks.contextModuleFactory.call(contextModuleFactory); - return contextModuleFactory; + needRebuild() { + return false; } - newCompilationParams() { - const params = { - normalModuleFactory: this.createNormalModuleFactory(), - contextModuleFactory: this.createContextModuleFactory(), - compilationDependencies: new Set() - }; - return params; + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + callback(); } - compile(callback) { - const params = this.newCompilationParams(); - this.hooks.beforeCompile.callAsync(params, err => { - if (err) return callback(err); - - this.hooks.compile.call(params); - - const compilation = this.newCompilation(params); - - this.hooks.make.callAsync(compilation, err => { - if (err) return callback(err); - - compilation.finish(err => { - if (err) return callback(err); - - compilation.seal(err => { - if (err) return callback(err); - - this.hooks.afterCompile.callAsync(compilation, err => { - if (err) return callback(err); + getSourceForGlobalVariableExternal(variableName, type) { + if (!Array.isArray(variableName)) { + // make it an array as the look up works the same basically + variableName = [variableName]; + } - return callback(null, compilation); - }); - }); - }); - }); - }); + // needed for e.g. window["some"]["thing"] + const objectLookup = variableName + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + return `(function() { module.exports = ${type}${objectLookup}; }());`; } -} -module.exports = Compiler; + getSourceForCommonJsExternal(moduleAndSpecifiers) { + if (!Array.isArray(moduleAndSpecifiers)) { + return `module.exports = require(${JSON.stringify( + moduleAndSpecifiers + )});`; + } -class SizeOnlySource extends Source { - constructor(size) { - super(); - this._size = size; + const moduleName = moduleAndSpecifiers[0]; + const objectLookup = moduleAndSpecifiers + .slice(1) + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + return `module.exports = require(${JSON.stringify( + moduleName + )})${objectLookup};`; } - _error() { - return new Error( - "Content and Map of this Source is no longer available (only size() is supported)" - ); + checkExternalVariable(variableToCheck, request) { + return `if(typeof ${variableToCheck} === 'undefined') {${WebpackMissingModule.moduleCode( + request + )}}\n`; } - size() { - return this._size; + getSourceForAmdOrUmdExternal(id, optional, request) { + const externalVariable = `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( + `${id}` + )}__`; + const missingModuleError = optional + ? this.checkExternalVariable(externalVariable, request) + : ""; + return `${missingModuleError}module.exports = ${externalVariable};`; } - /** - * @param {any} options options - * @returns {string} the source - */ - source(options) { - throw this._error(); + getSourceForDefaultCase(optional, request) { + if (!Array.isArray(request)) { + // make it an array as the look up works the same basically + request = [request]; + } + + const variableName = request[0]; + const missingModuleError = optional + ? this.checkExternalVariable(variableName, request.join(".")) + : ""; + const objectLookup = request + .slice(1) + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + return `${missingModuleError}module.exports = ${variableName}${objectLookup};`; } - node() { - throw this._error(); + getSourceString(runtime) { + const request = + typeof this.request === "object" && !Array.isArray(this.request) + ? this.request[this.externalType] + : this.request; + switch (this.externalType) { + case "this": + case "window": + case "self": + return this.getSourceForGlobalVariableExternal( + request, + this.externalType + ); + case "global": + return this.getSourceForGlobalVariableExternal( + request, + runtime.outputOptions.globalObject + ); + case "commonjs": + case "commonjs2": + return this.getSourceForCommonJsExternal(request); + case "amd": + case "amd-require": + case "umd": + case "umd2": + case "system": + return this.getSourceForAmdOrUmdExternal( + this.id, + this.optional, + request + ); + default: + return this.getSourceForDefaultCase(this.optional, request); + } } - listMap() { - throw this._error(); + getSource(sourceString) { + if (this.useSourceMap) { + return new OriginalSource(sourceString, this.identifier()); + } + + return new RawSource(sourceString); } - map() { - throw this._error(); + source(dependencyTemplates, runtime) { + return this.getSource(this.getSourceString(runtime)); } - listNode() { - throw this._error(); + size() { + return 42; } - updateHash() { - throw this._error(); + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update(this.externalType); + hash.update(JSON.stringify(this.request)); + hash.update(JSON.stringify(Boolean(this.optional))); + super.updateHash(hash); } } +module.exports = ExternalModule; + /***/ }), -/***/ 18933: +/***/ 67876: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Maksim Nazarjev @acupofspirt + Author Tobias Koppers @sokra */ -const WebpackError = __webpack_require__(97391); - -module.exports = class ConcurrentCompilationError extends WebpackError { - constructor() { - super(); - - this.name = "ConcurrentCompilationError"; - this.message = - "You ran Webpack twice. Each instance only supports a single concurrent compilation at a time."; +const ExternalModule = __webpack_require__(17204); - Error.captureStackTrace(this, this.constructor); +class ExternalModuleFactoryPlugin { + constructor(type, externals) { + this.type = type; + this.externals = externals; } -}; + apply(normalModuleFactory) { + const globalType = this.type; + normalModuleFactory.hooks.factory.tap( + "ExternalModuleFactoryPlugin", + factory => (data, callback) => { + const context = data.context; + const dependency = data.dependencies[0]; -/***/ }), - -/***/ 84072: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const handleExternal = (value, type, callback) => { + if (typeof type === "function") { + callback = type; + type = undefined; + } + if (value === false) return factory(data, callback); + if (value === true) value = dependency.request; + if (type === undefined && /^[a-z0-9]+ /.test(value)) { + const idx = value.indexOf(" "); + type = value.substr(0, idx); + value = value.substr(idx + 1); + } + callback( + null, + new ExternalModule(value, type || globalType, dependency.request) + ); + return true; + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const ConstDependency = __webpack_require__(71101); -const NullFactory = __webpack_require__(40438); -const ParserHelpers = __webpack_require__(23999); - -const getQuery = request => { - const i = request.indexOf("?"); - return i !== -1 ? request.substr(i) : ""; -}; - -const collectDeclaration = (declarations, pattern) => { - const stack = [pattern]; - while (stack.length > 0) { - const node = stack.pop(); - switch (node.type) { - case "Identifier": - declarations.add(node.name); - break; - case "ArrayPattern": - for (const element of node.elements) { - if (element) { - stack.push(element); - } - } - break; - case "AssignmentPattern": - stack.push(node.left); - break; - case "ObjectPattern": - for (const property of node.properties) { - stack.push(property.value); - } - break; - case "RestElement": - stack.push(node.argument); - break; - } - } -}; - -const getHoistedDeclarations = (branch, includeFunctionDeclarations) => { - const declarations = new Set(); - const stack = [branch]; - while (stack.length > 0) { - const node = stack.pop(); - // Some node could be `null` or `undefined`. - if (!node) continue; - switch (node.type) { - // Walk through control statements to look for hoisted declarations. - // Some branches are skipped since they do not allow declarations. - case "BlockStatement": - for (const stmt of node.body) { - stack.push(stmt); - } - break; - case "IfStatement": - stack.push(node.consequent); - stack.push(node.alternate); - break; - case "ForStatement": - stack.push(node.init); - stack.push(node.body); - break; - case "ForInStatement": - case "ForOfStatement": - stack.push(node.left); - stack.push(node.body); - break; - case "DoWhileStatement": - case "WhileStatement": - case "LabeledStatement": - stack.push(node.body); - break; - case "SwitchStatement": - for (const cs of node.cases) { - for (const consequent of cs.consequent) { - stack.push(consequent); - } - } - break; - case "TryStatement": - stack.push(node.block); - if (node.handler) { - stack.push(node.handler.body); - } - stack.push(node.finalizer); - break; - case "FunctionDeclaration": - if (includeFunctionDeclarations) { - collectDeclaration(declarations, node.id); - } - break; - case "VariableDeclaration": - if (node.kind === "var") { - for (const decl of node.declarations) { - collectDeclaration(declarations, decl.id); - } - } - break; - } - } - return Array.from(declarations); -}; - -class ConstPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "ConstPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set(ConstDependency, new NullFactory()); - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); - - const handler = parser => { - parser.hooks.statementIf.tap("ConstPlugin", statement => { - if (parser.scope.isAsmJs) return; - const param = parser.evaluateExpression(statement.test); - const bool = param.asBool(); - if (typeof bool === "boolean") { - if (statement.test.type !== "Literal") { - const dep = new ConstDependency(`${bool}`, param.range); - dep.loc = statement.loc; - parser.state.current.addDependency(dep); - } - const branchToRemove = bool - ? statement.alternate - : statement.consequent; - if (branchToRemove) { - // Before removing the dead branch, the hoisted declarations - // must be collected. - // - // Given the following code: - // - // if (true) f() else g() - // if (false) { - // function f() {} - // const g = function g() {} - // if (someTest) { - // let a = 1 - // var x, {y, z} = obj - // } - // } else { - // … - // } - // - // the generated code is: - // - // if (true) f() else {} - // if (false) { - // var f, x, y, z; (in loose mode) - // var x, y, z; (in strict mode) - // } else { - // … - // } - // - // NOTE: When code runs in strict mode, `var` declarations - // are hoisted but `function` declarations don't. - // - let declarations; - if (parser.scope.isStrict) { - // If the code runs in strict mode, variable declarations - // using `var` must be hoisted. - declarations = getHoistedDeclarations(branchToRemove, false); - } else { - // Otherwise, collect all hoisted declaration. - declarations = getHoistedDeclarations(branchToRemove, true); - } - let replacement; - if (declarations.length > 0) { - replacement = `{ var ${declarations.join(", ")}; }`; - } else { - replacement = "{}"; - } - const dep = new ConstDependency( - replacement, - branchToRemove.range - ); - dep.loc = branchToRemove.loc; - parser.state.current.addDependency(dep); - } - return bool; + const handleExternals = (externals, callback) => { + if (typeof externals === "string") { + if (externals === dependency.request) { + return handleExternal(dependency.request, callback); } - }); - parser.hooks.expressionConditionalOperator.tap( - "ConstPlugin", - expression => { - if (parser.scope.isAsmJs) return; - const param = parser.evaluateExpression(expression.test); - const bool = param.asBool(); - if (typeof bool === "boolean") { - if (expression.test.type !== "Literal") { - const dep = new ConstDependency(` ${bool}`, param.range); - dep.loc = expression.loc; - parser.state.current.addDependency(dep); + } else if (Array.isArray(externals)) { + let i = 0; + const next = () => { + let asyncFlag; + const handleExternalsAndCallback = (err, module) => { + if (err) return callback(err); + if (!module) { + if (asyncFlag) { + asyncFlag = false; + return; + } + return next(); } - // Expressions do not hoist. - // It is safe to remove the dead branch. - // - // Given the following code: - // - // false ? someExpression() : otherExpression(); - // - // the generated code is: - // - // false ? undefined : otherExpression(); - // - const branchToRemove = bool - ? expression.alternate - : expression.consequent; - const dep = new ConstDependency( - "undefined", - branchToRemove.range - ); - dep.loc = branchToRemove.loc; - parser.state.current.addDependency(dep); - return bool; - } - } - ); - parser.hooks.expressionLogicalOperator.tap( - "ConstPlugin", - expression => { - if (parser.scope.isAsmJs) return; - if ( - expression.operator === "&&" || - expression.operator === "||" - ) { - const param = parser.evaluateExpression(expression.left); - const bool = param.asBool(); - if (typeof bool === "boolean") { - // Expressions do not hoist. - // It is safe to remove the dead branch. - // - // ------------------------------------------ - // - // Given the following code: - // - // falsyExpression() && someExpression(); - // - // the generated code is: - // - // falsyExpression() && false; - // - // ------------------------------------------ - // - // Given the following code: - // - // truthyExpression() && someExpression(); - // - // the generated code is: - // - // true && someExpression(); - // - // ------------------------------------------ - // - // Given the following code: - // - // truthyExpression() || someExpression(); - // - // the generated code is: - // - // truthyExpression() || false; - // - // ------------------------------------------ - // - // Given the following code: - // - // falsyExpression() || someExpression(); - // - // the generated code is: - // - // false && someExpression(); - // - const keepRight = - (expression.operator === "&&" && bool) || - (expression.operator === "||" && !bool); + callback(null, module); + }; - if (param.isBoolean() || keepRight) { - // for case like - // - // return'development'===process.env.NODE_ENV&&'foo' - // - // we need a space before the bool to prevent result like - // - // returnfalse&&'foo' - // - const dep = new ConstDependency(` ${bool}`, param.range); - dep.loc = expression.loc; - parser.state.current.addDependency(dep); - } else { - parser.walkExpression(expression.left); - } - if (!keepRight) { - const dep = new ConstDependency( - "false", - expression.right.range - ); - dep.loc = expression.loc; - parser.state.current.addDependency(dep); - } - return keepRight; + do { + asyncFlag = true; + if (i >= externals.length) return callback(); + handleExternals(externals[i++], handleExternalsAndCallback); + } while (!asyncFlag); + asyncFlag = false; + }; + + next(); + return; + } else if (externals instanceof RegExp) { + if (externals.test(dependency.request)) { + return handleExternal(dependency.request, callback); + } + } else if (typeof externals === "function") { + externals.call( + null, + context, + dependency.request, + (err, value, type) => { + if (err) return callback(err); + if (value !== undefined) { + handleExternal(value, type, callback); + } else { + callback(); } } - } - ); - parser.hooks.evaluateIdentifier - .for("__resourceQuery") - .tap("ConstPlugin", expr => { - if (parser.scope.isAsmJs) return; - if (!parser.state.module) return; - return ParserHelpers.evaluateToString( - getQuery(parser.state.module.resource) - )(expr); - }); - parser.hooks.expression - .for("__resourceQuery") - .tap("ConstPlugin", () => { - if (parser.scope.isAsmJs) return; - if (!parser.state.module) return; - parser.state.current.addVariable( - "__resourceQuery", - JSON.stringify(getQuery(parser.state.module.resource)) - ); - return true; - }); + ); + return; + } else if ( + typeof externals === "object" && + Object.prototype.hasOwnProperty.call(externals, dependency.request) + ) { + return handleExternal(externals[dependency.request], callback); + } + callback(); }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("ConstPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("ConstPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("ConstPlugin", handler); + handleExternals(this.externals, (err, module) => { + if (err) return callback(err); + if (!module) return handleExternal(false, callback); + return callback(null, module); + }); } ); } } +module.exports = ExternalModuleFactoryPlugin; -module.exports = ConstPlugin; + +/***/ }), + +/***/ 75705: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ExternalModuleFactoryPlugin = __webpack_require__(67876); + +class ExternalsPlugin { + constructor(type, externals) { + this.type = type; + this.externals = externals; + } + apply(compiler) { + compiler.hooks.compile.tap("ExternalsPlugin", ({ normalModuleFactory }) => { + new ExternalModuleFactoryPlugin(this.type, this.externals).apply( + normalModuleFactory + ); + }); + } +} + +module.exports = ExternalsPlugin; /***/ }), -/***/ 10706: +/***/ 47163: /***/ (function(module) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + /** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./ContextModuleFactory")} ContextModuleFactory */ -class ContextExclusionPlugin { - /** - * @param {RegExp} negativeMatcher Matcher regular expression - */ - constructor(negativeMatcher) { - this.negativeMatcher = negativeMatcher; +class FlagAllModulesAsUsedPlugin { + constructor(explanation) { + this.explanation = explanation; } /** - * Apply the plugin - * @param {Compiler} compiler Webpack Compiler + * @param {Compiler} compiler webpack compiler * @returns {void} */ apply(compiler) { - compiler.hooks.contextModuleFactory.tap("ContextExclusionPlugin", cmf => { - cmf.hooks.contextModuleFiles.tap("ContextExclusionPlugin", files => { - return files.filter(filePath => !this.negativeMatcher.test(filePath)); - }); - }); + compiler.hooks.compilation.tap( + "FlagAllModulesAsUsedPlugin", + compilation => { + compilation.hooks.optimizeDependencies.tap( + "FlagAllModulesAsUsedPlugin", + modules => { + for (const module of modules) { + module.used = true; + module.usedExports = true; + module.addReason(null, null, this.explanation); + } + } + ); + } + ); } } -module.exports = ContextExclusionPlugin; +module.exports = FlagAllModulesAsUsedPlugin; /***/ }), -/***/ 20090: +/***/ 73599: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -75328,878 +75316,606 @@ module.exports = ContextExclusionPlugin; Author Tobias Koppers @sokra */ -const util = __webpack_require__(31669); -const { OriginalSource, RawSource } = __webpack_require__(53665); -const Module = __webpack_require__(75993); -const AsyncDependenciesBlock = __webpack_require__(22814); -const Template = __webpack_require__(96066); -const contextify = __webpack_require__(94658).contextify; -/** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */ -/** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */ +const Queue = __webpack_require__(38637); -/** - * @callback ResolveDependenciesCallback - * @param {Error=} err - * @param {ContextElementDependency[]} dependencies - */ +const addToSet = (a, b) => { + for (const item of b) { + a.add(item); + } +}; -/** - * @callback ResolveDependencies - * @param {TODO} fs - * @param {TODO} options - * @param {ResolveDependenciesCallback} callback - */ +class FlagDependencyExportsPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "FlagDependencyExportsPlugin", + compilation => { + compilation.hooks.finishModules.tap( + "FlagDependencyExportsPlugin", + modules => { + const dependencies = new Map(); -class ContextModule extends Module { - // type ContextMode = "sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once" - // type ContextOptions = { resource: string, recursive: boolean, regExp: RegExp, addon?: string, mode?: ContextMode, chunkName?: string, include?: RegExp, exclude?: RegExp, groupOptions?: Object } - // resolveDependencies: (fs: FS, options: ContextOptions, (err: Error?, dependencies: Dependency[]) => void) => void - // options: ContextOptions - /** - * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context - * @param {TODO} options options object - */ - constructor(resolveDependencies, options) { - let resource; - let resourceQuery; - const queryIdx = options.resource.indexOf("?"); - if (queryIdx >= 0) { - resource = options.resource.substr(0, queryIdx); - resourceQuery = options.resource.substr(queryIdx); - } else { - resource = options.resource; - resourceQuery = ""; - } + const queue = new Queue(); - super("javascript/dynamic", resource); + let module; + let moduleWithExports; + let moduleProvidedExports; + let providedExportsAreTemporary; - // Info from Factory - this.resolveDependencies = resolveDependencies; - this.options = Object.assign({}, options, { - resource: resource, - resourceQuery: resourceQuery - }); - if (options.resolveOptions !== undefined) { - this.resolveOptions = options.resolveOptions; - } + const processDependenciesBlock = depBlock => { + for (const dep of depBlock.dependencies) { + if (processDependency(dep)) return true; + } + for (const variable of depBlock.variables) { + for (const dep of variable.dependencies) { + if (processDependency(dep)) return true; + } + } + for (const block of depBlock.blocks) { + if (processDependenciesBlock(block)) return true; + } + return false; + }; - // Info from Build - this._contextDependencies = new Set([this.context]); + const processDependency = dep => { + const exportDesc = dep.getExports && dep.getExports(); + if (!exportDesc) return; + moduleWithExports = true; + const exports = exportDesc.exports; + // break early if it's only in the worst state + if (module.buildMeta.providedExports === true) { + return true; + } + // break if it should move to the worst state + if (exports === true) { + module.buildMeta.providedExports = true; + return true; + } + // merge in new exports + if (Array.isArray(exports)) { + addToSet(moduleProvidedExports, exports); + } + // store dependencies + const exportDeps = exportDesc.dependencies; + if (exportDeps) { + providedExportsAreTemporary = true; + for (const exportDependency of exportDeps) { + // add dependency for this module + const set = dependencies.get(exportDependency); + if (set === undefined) { + dependencies.set(exportDependency, new Set([module])); + } else { + set.add(module); + } + } + } + return false; + }; - if (typeof options.mode !== "string") { - throw new Error("options.mode is a required option"); - } + const notifyDependencies = () => { + const deps = dependencies.get(module); + if (deps !== undefined) { + for (const dep of deps) { + queue.enqueue(dep); + } + } + }; - this._identifier = this._createIdentifier(); - } + const notifyDependenciesIfDifferent = (set, array) => { + const deps = dependencies.get(module); + if (deps !== undefined) { + if (set.size === array.length) { + let i = 0; + let different = false; + for (const item of set) { + if (item !== array[i++]) { + different = true; + break; + } + } + if (!different) return; + } + for (const dep of deps) { + queue.enqueue(dep); + } + } + }; - updateCacheModule(module) { - this.resolveDependencies = module.resolveDependencies; - this.options = module.options; - this.resolveOptions = module.resolveOptions; - } + // Start with all modules without provided exports + for (const module of modules) { + if (module.buildInfo.temporaryProvidedExports) { + // Clear exports when they are temporary + // and recreate them + module.buildMeta.providedExports = null; + queue.enqueue(module); + } else if (!module.buildMeta.providedExports) { + queue.enqueue(module); + } + } - prettyRegExp(regexString) { - // remove the "/" at the front and the beginning - // "/foo/" -> "foo" - return regexString.substring(1, regexString.length - 1); + while (queue.length > 0) { + module = queue.dequeue(); + + if (module.buildMeta.providedExports !== true) { + moduleWithExports = + module.buildMeta && module.buildMeta.exportsType; + moduleProvidedExports = new Set(); + providedExportsAreTemporary = false; + processDependenciesBlock(module); + module.buildInfo.temporaryProvidedExports = providedExportsAreTemporary; + if (!moduleWithExports) { + notifyDependencies(); + module.buildMeta.providedExports = true; + } else if (module.buildMeta.providedExports === true) { + notifyDependencies(); + } else if (!module.buildMeta.providedExports) { + notifyDependencies(); + module.buildMeta.providedExports = Array.from( + moduleProvidedExports + ); + } else { + notifyDependenciesIfDifferent( + moduleProvidedExports, + module.buildMeta.providedExports + ); + module.buildMeta.providedExports = Array.from( + moduleProvidedExports + ); + } + } + } + } + ); + const providedExportsCache = new WeakMap(); + compilation.hooks.rebuildModule.tap( + "FlagDependencyExportsPlugin", + module => { + providedExportsCache.set(module, module.buildMeta.providedExports); + } + ); + compilation.hooks.finishRebuildingModule.tap( + "FlagDependencyExportsPlugin", + module => { + module.buildMeta.providedExports = providedExportsCache.get(module); + } + ); + } + ); } +} - _createIdentifier() { - let identifier = this.context; - if (this.options.resourceQuery) { - identifier += ` ${this.options.resourceQuery}`; - } - if (this.options.mode) { - identifier += ` ${this.options.mode}`; - } - if (!this.options.recursive) { - identifier += " nonrecursive"; - } - if (this.options.addon) { - identifier += ` ${this.options.addon}`; - } - if (this.options.regExp) { - identifier += ` ${this.options.regExp}`; - } - if (this.options.include) { - identifier += ` include: ${this.options.include}`; - } - if (this.options.exclude) { - identifier += ` exclude: ${this.options.exclude}`; - } - if (this.options.groupOptions) { - identifier += ` groupOptions: ${JSON.stringify( - this.options.groupOptions - )}`; - } - if (this.options.namespaceObject === "strict") { - identifier += " strict namespace object"; - } else if (this.options.namespaceObject) { - identifier += " namespace object"; - } +module.exports = FlagDependencyExportsPlugin; - return identifier; - } - identifier() { - return this._identifier; - } +/***/ }), - readableIdentifier(requestShortener) { - let identifier = requestShortener.shorten(this.context); - if (this.options.resourceQuery) { - identifier += ` ${this.options.resourceQuery}`; - } - if (this.options.mode) { - identifier += ` ${this.options.mode}`; - } - if (!this.options.recursive) { - identifier += " nonrecursive"; - } - if (this.options.addon) { - identifier += ` ${requestShortener.shorten(this.options.addon)}`; - } - if (this.options.regExp) { - identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; - } - if (this.options.include) { - identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; - } - if (this.options.exclude) { - identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; - } - if (this.options.groupOptions) { - const groupOptions = this.options.groupOptions; - for (const key of Object.keys(groupOptions)) { - identifier += ` ${key}: ${groupOptions[key]}`; - } - } - if (this.options.namespaceObject === "strict") { - identifier += " strict namespace object"; - } else if (this.options.namespaceObject) { - identifier += " namespace object"; - } +/***/ 33632: +/***/ (function(module) { - return identifier; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - libIdent(options) { - let identifier = contextify(options.context, this.context); - if (this.options.mode) { - identifier += ` ${this.options.mode}`; - } - if (this.options.recursive) { - identifier += " recursive"; - } - if (this.options.addon) { - identifier += ` ${contextify(options.context, this.options.addon)}`; - } - if (this.options.regExp) { - identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; - } - if (this.options.include) { - identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; - } - if (this.options.exclude) { - identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; - } - return identifier; - } +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ - needRebuild(fileTimestamps, contextTimestamps) { - const ts = contextTimestamps.get(this.context); - if (!ts) { - return true; - } +/** @typedef {false | true | string[]} UsedExports */ - return ts >= this.buildInfo.builtTime; +const addToSet = (a, b) => { + for (const item of b) { + if (!a.includes(item)) a.push(item); } + return a; +}; - build(options, compilation, resolver, fs, callback) { - this.built = true; - this.buildMeta = {}; - this.buildInfo = { - builtTime: Date.now(), - contextDependencies: this._contextDependencies - }; - this.resolveDependencies(fs, this.options, (err, dependencies) => { - if (err) return callback(err); +const isSubset = (biggerSet, subset) => { + if (biggerSet === true) return true; + if (subset === true) return false; + return subset.every(item => biggerSet.indexOf(item) >= 0); +}; - // abort if something failed - // this will create an empty context - if (!dependencies) { - callback(); - return; - } +class FlagDependencyUsagePlugin { + apply(compiler) { + compiler.hooks.compilation.tap("FlagDependencyUsagePlugin", compilation => { + compilation.hooks.optimizeDependencies.tap( + "FlagDependencyUsagePlugin", + modules => { + const processModule = (module, usedExports) => { + module.used = true; + if (module.usedExports === true) return; + if (usedExports === true) { + module.usedExports = true; + } else if (Array.isArray(usedExports)) { + const old = module.usedExports ? module.usedExports.length : -1; + module.usedExports = addToSet( + module.usedExports || [], + usedExports + ); + if (module.usedExports.length === old) { + return; + } + } else if (Array.isArray(module.usedExports)) { + return; + } else { + module.usedExports = false; + } - // enhance dependencies with meta info - for (const dep of dependencies) { - dep.loc = { - name: dep.userRequest - }; - dep.request = this.options.addon + dep.request; - } + // for a module without side effects we stop tracking usage here when no export is used + // This module won't be evaluated in this case + if (module.factoryMeta.sideEffectFree) { + if (module.usedExports === false) return; + if ( + Array.isArray(module.usedExports) && + module.usedExports.length === 0 + ) + return; + } - if (this.options.mode === "sync" || this.options.mode === "eager") { - // if we have an sync or eager context - // just add all dependencies and continue - this.dependencies = dependencies; - } else if (this.options.mode === "lazy-once") { - // for the lazy-once mode create a new async dependency block - // and add that block to this context - if (dependencies.length > 0) { - const block = new AsyncDependenciesBlock( - Object.assign({}, this.options.groupOptions, { - name: this.options.chunkName - }), - this - ); - for (const dep of dependencies) { - block.addDependency(dep); + queue.push([module, module, module.usedExports]); + }; + + const processDependenciesBlock = (module, depBlock, usedExports) => { + for (const dep of depBlock.dependencies) { + processDependency(module, dep); + } + for (const variable of depBlock.variables) { + for (const dep of variable.dependencies) { + processDependency(module, dep); + } + } + for (const block of depBlock.blocks) { + queue.push([module, block, usedExports]); + } + }; + + const processDependency = (module, dep) => { + const reference = compilation.getDependencyReference(module, dep); + if (!reference) return; + const referenceModule = reference.module; + const importedNames = reference.importedNames; + const oldUsed = referenceModule.used; + const oldUsedExports = referenceModule.usedExports; + if ( + !oldUsed || + (importedNames && + (!oldUsedExports || !isSubset(oldUsedExports, importedNames))) + ) { + processModule(referenceModule, importedNames); + } + }; + + for (const module of modules) { + if (!module.used) module.used = false; } - this.addBlock(block); - } - } else if ( - this.options.mode === "weak" || - this.options.mode === "async-weak" - ) { - // we mark all dependencies as weak - for (const dep of dependencies) { - dep.weak = true; - } - this.dependencies = dependencies; - } else if (this.options.mode === "lazy") { - // if we are lazy create a new async dependency block per dependency - // and add all blocks to this context - let index = 0; - for (const dep of dependencies) { - let chunkName = this.options.chunkName; - if (chunkName) { - if (!/\[(index|request)\]/.test(chunkName)) { - chunkName += "[index]"; + + /** @type {[Module, DependenciesBlock, UsedExports][]} */ + const queue = []; + for (const preparedEntrypoint of compilation._preparedEntrypoints) { + if (preparedEntrypoint.module) { + processModule(preparedEntrypoint.module, true); } - chunkName = chunkName.replace(/\[index\]/g, index++); - chunkName = chunkName.replace( - /\[request\]/g, - Template.toPath(dep.userRequest) - ); } - const block = new AsyncDependenciesBlock( - Object.assign({}, this.options.groupOptions, { - name: chunkName - }), - dep.module, - dep.loc, - dep.userRequest - ); - block.addDependency(dep); - this.addBlock(block); + + while (queue.length) { + const queueItem = queue.pop(); + processDependenciesBlock(queueItem[0], queueItem[1], queueItem[2]); + } } - } else { - callback( - new Error(`Unsupported mode "${this.options.mode}" in context`) - ); - return; - } - callback(); + ); }); } +} +module.exports = FlagDependencyUsagePlugin; - getUserRequestMap(dependencies) { - // if we filter first we get a new array - // therefor we dont need to create a clone of dependencies explicitly - // therefore the order of this is !important! - return dependencies - .filter(dependency => dependency.module) - .sort((a, b) => { - if (a.userRequest === b.userRequest) { - return 0; - } - return a.userRequest < b.userRequest ? -1 : 1; - }) - .reduce((map, dep) => { - map[dep.userRequest] = dep.module.id; - return map; - }, Object.create(null)); + +/***/ }), + +/***/ 31221: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const FunctionModuleTemplatePlugin = __webpack_require__(18864); + +class FunctionModulePlugin { + apply(compiler) { + compiler.hooks.compilation.tap("FunctionModulePlugin", compilation => { + new FunctionModuleTemplatePlugin().apply( + compilation.moduleTemplates.javascript + ); + }); } +} - getFakeMap(dependencies) { - if (!this.options.namespaceObject) { - return 9; - } - // if we filter first we get a new array - // therefor we dont need to create a clone of dependencies explicitly - // therefore the order of this is !important! - let hasNonHarmony = false; - let hasNamespace = false; - let hasNamed = false; - const fakeMap = dependencies - .filter(dependency => dependency.module) - .sort((a, b) => { - return b.module.id - a.module.id; - }) - .reduce((map, dep) => { - const exportsType = - dep.module.buildMeta && dep.module.buildMeta.exportsType; - const id = dep.module.id; - if (!exportsType) { - map[id] = this.options.namespaceObject === "strict" ? 1 : 7; - hasNonHarmony = true; - } else if (exportsType === "namespace") { - map[id] = 9; - hasNamespace = true; - } else if (exportsType === "named") { - map[id] = 3; - hasNamed = true; - } - return map; - }, Object.create(null)); - if (!hasNamespace && hasNonHarmony && !hasNamed) { - return this.options.namespaceObject === "strict" ? 1 : 7; - } - if (hasNamespace && !hasNonHarmony && !hasNamed) { - return 9; - } - if (!hasNamespace && !hasNonHarmony && hasNamed) { - return 3; - } - if (!hasNamespace && !hasNonHarmony && !hasNamed) { - return 9; - } - return fakeMap; - } +module.exports = FunctionModulePlugin; - getFakeMapInitStatement(fakeMap) { - return typeof fakeMap === "object" - ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` - : ""; - } - getReturn(type) { - if (type === 9) { - return "__webpack_require__(id)"; - } - return `__webpack_require__.t(id, ${type})`; - } +/***/ }), - getReturnModuleObjectSource(fakeMap, fakeMapDataExpression = "fakeMap[id]") { - if (typeof fakeMap === "number") { - return `return ${this.getReturn(fakeMap)};`; - } - return `return __webpack_require__.t(id, ${fakeMapDataExpression})`; - } +/***/ 18864: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - getSyncSource(dependencies, id) { - const map = this.getUserRequestMap(dependencies); - const fakeMap = this.getFakeMap(dependencies); - const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} -function webpackContext(req) { - var id = webpackContextResolve(req); - ${returnModuleObject} -} -function webpackContextResolve(req) { - if(!__webpack_require__.o(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; -} -webpackContext.keys = function webpackContextKeys() { - return Object.keys(map); -}; -webpackContext.resolve = webpackContextResolve; -module.exports = webpackContext; -webpackContext.id = ${JSON.stringify(id)};`; - } +const { ConcatSource } = __webpack_require__(53665); +const Template = __webpack_require__(96066); - getWeakSyncSource(dependencies, id) { - const map = this.getUserRequestMap(dependencies); - const fakeMap = this.getFakeMap(dependencies); - const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); +class FunctionModuleTemplatePlugin { + apply(moduleTemplate) { + moduleTemplate.hooks.render.tap( + "FunctionModuleTemplatePlugin", + (moduleSource, module) => { + const source = new ConcatSource(); + const args = [module.moduleArgument]; + // TODO remove HACK checking type for javascript + if (module.type && module.type.startsWith("javascript")) { + args.push(module.exportsArgument); + if (module.hasDependencies(d => d.requireWebpackRequire !== false)) { + args.push("__webpack_require__"); + } + } else if (module.type && module.type.startsWith("json")) { + // no additional arguments needed + } else { + args.push(module.exportsArgument, "__webpack_require__"); + } + source.add("/***/ (function(" + args.join(", ") + ") {\n\n"); + if (module.buildInfo.strict) source.add('"use strict";\n'); + source.add(moduleSource); + source.add("\n\n/***/ })"); + return source; + } + ); - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} + moduleTemplate.hooks.package.tap( + "FunctionModuleTemplatePlugin", + (moduleSource, module) => { + if (moduleTemplate.runtimeTemplate.outputOptions.pathinfo) { + const source = new ConcatSource(); + const req = module.readableIdentifier( + moduleTemplate.runtimeTemplate.requestShortener + ); + const reqStr = req.replace(/\*\//g, "*_/"); + const reqStrStar = "*".repeat(reqStr.length); + source.add("/*!****" + reqStrStar + "****!*\\\n"); + source.add(" !*** " + reqStr + " ***!\n"); + source.add(" \\****" + reqStrStar + "****/\n"); + if ( + Array.isArray(module.buildMeta.providedExports) && + module.buildMeta.providedExports.length === 0 + ) { + source.add(Template.toComment("no exports provided") + "\n"); + } else if (Array.isArray(module.buildMeta.providedExports)) { + source.add( + Template.toComment( + "exports provided: " + + module.buildMeta.providedExports.join(", ") + ) + "\n" + ); + } else if (module.buildMeta.providedExports) { + source.add(Template.toComment("no static exports found") + "\n"); + } + if ( + Array.isArray(module.usedExports) && + module.usedExports.length === 0 + ) { + source.add(Template.toComment("no exports used") + "\n"); + } else if (Array.isArray(module.usedExports)) { + source.add( + Template.toComment( + "exports used: " + module.usedExports.join(", ") + ) + "\n" + ); + } else if (module.usedExports) { + source.add(Template.toComment("all exports used") + "\n"); + } + if (module.optimizationBailout) { + for (const text of module.optimizationBailout) { + let code; + if (typeof text === "function") { + code = text(moduleTemplate.runtimeTemplate.requestShortener); + } else { + code = text; + } + source.add(Template.toComment(`${code}`) + "\n"); + } + } + source.add(moduleSource); + return source; + } + return moduleSource; + } + ); -function webpackContext(req) { - var id = webpackContextResolve(req); - if(!__webpack_require__.m[id]) { - var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - ${returnModuleObject} -} -function webpackContextResolve(req) { - if(!__webpack_require__.o(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; + moduleTemplate.hooks.hash.tap("FunctionModuleTemplatePlugin", hash => { + hash.update("FunctionModuleTemplatePlugin"); + hash.update("2"); + }); } - return map[req]; } -webpackContext.keys = function webpackContextKeys() { - return Object.keys(map); -}; -webpackContext.resolve = webpackContextResolve; -webpackContext.id = ${JSON.stringify(id)}; -module.exports = webpackContext;`; - } +module.exports = FunctionModuleTemplatePlugin; - getAsyncWeakSource(dependencies, id) { - const map = this.getUserRequestMap(dependencies); - const fakeMap = this.getFakeMap(dependencies); - const returnModuleObject = this.getReturnModuleObjectSource(fakeMap); - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} +/***/ }), -function webpackAsyncContext(req) { - return webpackAsyncContextResolve(req).then(function(id) { - if(!__webpack_require__.m[id]) { - var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - ${returnModuleObject} - }); -} -function webpackAsyncContextResolve(req) { - // Here Promise.resolve().then() is used instead of new Promise() to prevent - // uncaught exception popping up in devtools - return Promise.resolve().then(function() { - if(!__webpack_require__.o(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; - }); -} -webpackAsyncContext.keys = function webpackAsyncContextKeys() { - return Object.keys(map); -}; -webpackAsyncContext.resolve = webpackAsyncContextResolve; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; - } +/***/ 39172: +/***/ (function(module) { - getEagerSource(dependencies, id) { - const map = this.getUserRequestMap(dependencies); - const fakeMap = this.getFakeMap(dependencies); - const thenFunction = - fakeMap !== 9 - ? `function(id) { - ${this.getReturnModuleObjectSource(fakeMap)} - }` - : "__webpack_require__"; - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -function webpackAsyncContext(req) { - return webpackAsyncContextResolve(req).then(${thenFunction}); -} -function webpackAsyncContextResolve(req) { - // Here Promise.resolve().then() is used instead of new Promise() to prevent - // uncaught exception popping up in devtools - return Promise.resolve().then(function() { - if(!__webpack_require__.o(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; - }); -} -webpackAsyncContext.keys = function webpackAsyncContextKeys() { - return Object.keys(map); -}; -webpackAsyncContext.resolve = webpackAsyncContextResolve; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; - } - getLazyOnceSource(block, dependencies, id, runtimeTemplate) { - const promise = runtimeTemplate.blockPromise({ - block, - message: "lazy-once context" - }); - const map = this.getUserRequestMap(dependencies); - const fakeMap = this.getFakeMap(dependencies); - const thenFunction = - fakeMap !== 9 - ? `function(id) { - ${this.getReturnModuleObjectSource(fakeMap)}; - }` - : "__webpack_require__"; +/** @typedef {import("./NormalModule")} NormalModule */ +/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ - return `var map = ${JSON.stringify(map, null, "\t")}; -${this.getFakeMapInitStatement(fakeMap)} +/** + * + */ +class Generator { + static byType(map) { + return new ByTypeGenerator(map); + } -function webpackAsyncContext(req) { - return webpackAsyncContextResolve(req).then(${thenFunction}); + /** + * @abstract + * @param {NormalModule} module module for which the code should be generated + * @param {Map} dependencyTemplates mapping from dependencies to templates + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {string} type which kind of code should be generated + * @returns {Source} generated code + */ + generate(module, dependencyTemplates, runtimeTemplate, type) { + throw new Error("Generator.generate: must be overridden"); + } } -function webpackAsyncContextResolve(req) { - return ${promise}.then(function() { - if(!__webpack_require__.o(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; + +class ByTypeGenerator extends Generator { + constructor(map) { + super(); + this.map = map; + } + + /** + * @param {NormalModule} module module for which the code should be generated + * @param {Map} dependencyTemplates mapping from dependencies to templates + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {string} type which kind of code should be generated + * @returns {Source} generated code + */ + generate(module, dependencyTemplates, runtimeTemplate, type) { + const generator = this.map[type]; + if (!generator) { + throw new Error(`Generator.byType: no generator specified for ${type}`); } - return map[req]; - }); -} -webpackAsyncContext.keys = function webpackAsyncContextKeys() { - return Object.keys(map); -}; -webpackAsyncContext.resolve = webpackAsyncContextResolve; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; + return generator.generate( + module, + dependencyTemplates, + runtimeTemplate, + type + ); } +} - getLazySource(blocks, id) { - let hasMultipleOrNoChunks = false; - let hasNoChunk = true; - const fakeMap = this.getFakeMap(blocks.map(b => b.dependencies[0])); - const hasFakeMap = typeof fakeMap === "object"; - const map = blocks - .filter(block => block.dependencies[0].module) - .map(block => { - const chunks = block.chunkGroup ? block.chunkGroup.chunks : []; - if (chunks.length > 0) { - hasNoChunk = false; - } - if (chunks.length !== 1) { - hasMultipleOrNoChunks = true; - } - return { - dependency: block.dependencies[0], - block: block, - userRequest: block.dependencies[0].userRequest, - chunks - }; - }) - .sort((a, b) => { - if (a.userRequest === b.userRequest) return 0; - return a.userRequest < b.userRequest ? -1 : 1; - }) - .reduce((map, item) => { - const chunks = item.chunks; +module.exports = Generator; - if (hasNoChunk && !hasFakeMap) { - map[item.userRequest] = item.dependency.module.id; - } else { - const arrayStart = [item.dependency.module.id]; - if (typeof fakeMap === "object") { - arrayStart.push(fakeMap[item.dependency.module.id]); - } - map[item.userRequest] = arrayStart.concat( - chunks.map(chunk => chunk.id) - ); - } - return map; - }, Object.create(null)); +/***/ }), - const shortMode = hasNoChunk && !hasFakeMap; - const chunksStartPosition = hasFakeMap ? 2 : 1; - const requestPrefix = hasNoChunk - ? "Promise.resolve()" - : hasMultipleOrNoChunks - ? `Promise.all(ids.slice(${chunksStartPosition}).map(__webpack_require__.e))` - : `__webpack_require__.e(ids[${chunksStartPosition}])`; - const returnModuleObject = this.getReturnModuleObjectSource( - fakeMap, - shortMode ? "invalid" : "ids[1]" - ); +/***/ 32973: +/***/ (function(__unused_webpack_module, exports) { - const webpackAsyncContext = - requestPrefix === "Promise.resolve()" - ? `${shortMode ? "" : ""} -function webpackAsyncContext(req) { - return Promise.resolve().then(function() { - if(!__webpack_require__.o(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ - ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"} - ${returnModuleObject} - }); -}` - : `function webpackAsyncContext(req) { - if(!__webpack_require__.o(map, req)) { - return Promise.resolve().then(function() { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - }); +/** + * @param {ChunkGroup} chunkGroup the ChunkGroup to connect + * @param {Chunk} chunk chunk to tie to ChunkGroup + * @returns {void} + */ +const connectChunkGroupAndChunk = (chunkGroup, chunk) => { + if (chunkGroup.pushChunk(chunk)) { + chunk.addGroup(chunkGroup); } - - var ids = map[req], id = ids[0]; - return ${requestPrefix}.then(function() { - ${returnModuleObject} - }); -}`; - - return `var map = ${JSON.stringify(map, null, "\t")}; -${webpackAsyncContext} -webpackAsyncContext.keys = function webpackAsyncContextKeys() { - return Object.keys(map); }; -webpackAsyncContext.id = ${JSON.stringify(id)}; -module.exports = webpackAsyncContext;`; - } - getSourceForEmptyContext(id) { - return `function webpackEmptyContext(req) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; -} -webpackEmptyContext.keys = function() { return []; }; -webpackEmptyContext.resolve = webpackEmptyContext; -module.exports = webpackEmptyContext; -webpackEmptyContext.id = ${JSON.stringify(id)};`; +/** + * @param {ChunkGroup} parent parent ChunkGroup to connect + * @param {ChunkGroup} child child ChunkGroup to connect + * @returns {void} + */ +const connectChunkGroupParentAndChild = (parent, child) => { + if (parent.addChild(child)) { + child.addParent(parent); } +}; - getSourceForEmptyAsyncContext(id) { - return `function webpackEmptyAsyncContext(req) { - // Here Promise.resolve().then() is used instead of new Promise() to prevent - // uncaught exception popping up in devtools - return Promise.resolve().then(function() { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - }); -} -webpackEmptyAsyncContext.keys = function() { return []; }; -webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; -module.exports = webpackEmptyAsyncContext; -webpackEmptyAsyncContext.id = ${JSON.stringify(id)};`; +/** + * @param {Chunk} chunk Chunk to connect to Module + * @param {Module} module Module to connect to Chunk + * @returns {void} + */ +const connectChunkAndModule = (chunk, module) => { + if (module.addChunk(chunk)) { + chunk.addModule(module); } +}; - getSourceString(asyncMode, runtimeTemplate) { - if (asyncMode === "lazy") { - if (this.blocks && this.blocks.length > 0) { - return this.getLazySource(this.blocks, this.id); - } - return this.getSourceForEmptyAsyncContext(this.id); - } - if (asyncMode === "eager") { - if (this.dependencies && this.dependencies.length > 0) { - return this.getEagerSource(this.dependencies, this.id); - } - return this.getSourceForEmptyAsyncContext(this.id); - } - if (asyncMode === "lazy-once") { - const block = this.blocks[0]; - if (block) { - return this.getLazyOnceSource( - block, - block.dependencies, - this.id, - runtimeTemplate - ); - } - return this.getSourceForEmptyAsyncContext(this.id); - } - if (asyncMode === "async-weak") { - if (this.dependencies && this.dependencies.length > 0) { - return this.getAsyncWeakSource(this.dependencies, this.id); - } - return this.getSourceForEmptyAsyncContext(this.id); - } - if (asyncMode === "weak") { - if (this.dependencies && this.dependencies.length > 0) { - return this.getWeakSyncSource(this.dependencies, this.id); - } - } - if (this.dependencies && this.dependencies.length > 0) { - return this.getSyncSource(this.dependencies, this.id); - } - return this.getSourceForEmptyContext(this.id); - } +/** + * @param {Chunk} chunk Chunk being disconnected + * @param {Module} module Module being disconnected + * @returns {void} + */ +const disconnectChunkAndModule = (chunk, module) => { + chunk.removeModule(module); + module.removeChunk(chunk); +}; - getSource(sourceString) { - if (this.useSourceMap) { - return new OriginalSource(sourceString, this.identifier()); - } - return new RawSource(sourceString); +/** + * @param {AsyncDependenciesBlock} depBlock DepBlock being tied to ChunkGroup + * @param {ChunkGroup} chunkGroup ChunkGroup being tied to DepBlock + * @returns {void} + */ +const connectDependenciesBlockAndChunkGroup = (depBlock, chunkGroup) => { + if (chunkGroup.addBlock(depBlock)) { + depBlock.chunkGroup = chunkGroup; } +}; - source(dependencyTemplates, runtimeTemplate) { - return this.getSource( - this.getSourceString(this.options.mode, runtimeTemplate) - ); - } +exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk; +exports.connectChunkGroupParentAndChild = connectChunkGroupParentAndChild; +exports.connectChunkAndModule = connectChunkAndModule; +exports.disconnectChunkAndModule = disconnectChunkAndModule; +exports.connectDependenciesBlockAndChunkGroup = connectDependenciesBlockAndChunkGroup; - size() { - // base penalty - const initialSize = 160; - // if we dont have dependencies we stop here. - return this.dependencies.reduce((size, dependency) => { - const element = /** @type {ContextElementDependency} */ (dependency); - return size + 5 + element.userRequest.length; - }, initialSize); - } -} +/***/ }), -// TODO remove in webpack 5 -Object.defineProperty(ContextModule.prototype, "recursive", { - configurable: false, - get: util.deprecate( - /** - * @deprecated - * @this {ContextModule} - * @returns {boolean} is recursive - */ - function() { - return this.options.recursive; - }, - "ContextModule.recursive has been moved to ContextModule.options.recursive" - ), - set: util.deprecate( - /** - * @deprecated - * @this {ContextModule} - * @param {boolean} value is recursive - * @returns {void} - */ - function(value) { - this.options.recursive = value; - }, - "ContextModule.recursive has been moved to ContextModule.options.recursive" - ) -}); +/***/ 30327: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -// TODO remove in webpack 5 -Object.defineProperty(ContextModule.prototype, "regExp", { - configurable: false, - get: util.deprecate( - /** - * @deprecated - * @this {ContextModule} - * @returns {RegExp} regular expression - */ - function() { - return this.options.regExp; - }, - "ContextModule.regExp has been moved to ContextModule.options.regExp" - ), - set: util.deprecate( - /** - * @deprecated - * @this {ContextModule} - * @param {RegExp} value Regular expression - * @returns {void} - */ - function(value) { - this.options.regExp = value; - }, - "ContextModule.regExp has been moved to ContextModule.options.regExp" - ) -}); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ -// TODO remove in webpack 5 -Object.defineProperty(ContextModule.prototype, "addon", { - configurable: false, - get: util.deprecate( - /** - * @deprecated - * @this {ContextModule} - * @returns {string} addon - */ - function() { - return this.options.addon; - }, - "ContextModule.addon has been moved to ContextModule.options.addon" - ), - set: util.deprecate( - /** - * @deprecated - * @this {ContextModule} - * @param {string} value addon - * @returns {void} - */ - function(value) { - this.options.addon = value; - }, - "ContextModule.addon has been moved to ContextModule.options.addon" - ) -}); -// TODO remove in webpack 5 -Object.defineProperty(ContextModule.prototype, "async", { - configurable: false, - get: util.deprecate( - /** - * @deprecated - * @this {ContextModule} - * @returns {boolean} is async - */ - function() { - return this.options.mode; - }, - "ContextModule.async has been moved to ContextModule.options.mode" - ), - set: util.deprecate( - /** - * @deprecated - * @this {ContextModule} - * @param {ContextMode} value Context mode - * @returns {void} - */ - function(value) { - this.options.mode = value; - }, - "ContextModule.async has been moved to ContextModule.options.mode" - ) -}); +const WebpackError = __webpack_require__(97391); -// TODO remove in webpack 5 -Object.defineProperty(ContextModule.prototype, "chunkName", { - configurable: false, - get: util.deprecate( - /** - * @deprecated - * @this {ContextModule} - * @returns {string} chunk name - */ - function() { - return this.options.chunkName; - }, - "ContextModule.chunkName has been moved to ContextModule.options.chunkName" - ), - set: util.deprecate( - /** - * @deprecated - * @this {ContextModule} - * @param {string} value chunk name - * @returns {void} - */ - function(value) { - this.options.chunkName = value; - }, - "ContextModule.chunkName has been moved to ContextModule.options.chunkName" - ) -}); +module.exports = class HarmonyLinkingError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "HarmonyLinkingError"; + this.hideStack = true; -module.exports = ContextModule; + Error.captureStackTrace(this, this.constructor); + } +}; /***/ }), -/***/ 88239: +/***/ 50268: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -76208,828 +75924,797 @@ module.exports = ContextModule; Author Tobias Koppers @sokra */ +const createHash = __webpack_require__(15660); -const asyncLib = __webpack_require__(36386); -const path = __webpack_require__(85622); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(45843); -const { - Tapable, - AsyncSeriesWaterfallHook, - SyncWaterfallHook -} = __webpack_require__(56758); -const ContextModule = __webpack_require__(20090); -const ContextElementDependency = __webpack_require__(89079); +/** @typedef {import("../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */ -/** @typedef {import("./Module")} Module */ +class HashedModuleIdsPlugin { + /** + * @param {HashedModuleIdsPluginOptions=} options options object + */ + constructor(options) { + if (!options) options = {}; -const EMPTY_RESOLVE_OPTIONS = {}; + validateOptions(schema, options, "Hashed Module Ids Plugin"); -module.exports = class ContextModuleFactory extends Tapable { - constructor(resolverFactory) { - super(); - this.hooks = { - /** @type {AsyncSeriesWaterfallHook} */ - beforeResolve: new AsyncSeriesWaterfallHook(["data"]), - /** @type {AsyncSeriesWaterfallHook} */ - afterResolve: new AsyncSeriesWaterfallHook(["data"]), - /** @type {SyncWaterfallHook} */ - contextModuleFiles: new SyncWaterfallHook(["files"]), - /** @type {SyncWaterfallHook} */ - alternatives: new AsyncSeriesWaterfallHook(["modules"]) - }; - this._pluginCompat.tap("ContextModuleFactory", options => { - switch (options.name) { - case "before-resolve": - case "after-resolve": - case "alternatives": - options.async = true; - break; - } - }); - this.resolverFactory = resolverFactory; + /** @type {HashedModuleIdsPluginOptions} */ + this.options = Object.assign( + { + context: null, + hashFunction: "md4", + hashDigest: "base64", + hashDigestLength: 4 + }, + options + ); } - create(data, callback) { - const context = data.context; - const dependencies = data.dependencies; - const resolveOptions = data.resolveOptions; - const dependency = dependencies[0]; - this.hooks.beforeResolve.callAsync( - Object.assign( - { - context: context, - dependencies: dependencies, - resolveOptions - }, - dependency.options - ), - (err, beforeResolveResult) => { - if (err) return callback(err); - - // Ignored - if (!beforeResolveResult) return callback(); - - const context = beforeResolveResult.context; - const request = beforeResolveResult.request; - const resolveOptions = beforeResolveResult.resolveOptions; - - let loaders, - resource, - loadersPrefix = ""; - const idx = request.lastIndexOf("!"); - if (idx >= 0) { - let loadersRequest = request.substr(0, idx + 1); - let i; - for ( - i = 0; - i < loadersRequest.length && loadersRequest[i] === "!"; - i++ - ) { - loadersPrefix += "!"; - } - loadersRequest = loadersRequest - .substr(i) - .replace(/!+$/, "") - .replace(/!!+/g, "!"); - if (loadersRequest === "") { - loaders = []; - } else { - loaders = loadersRequest.split("!"); + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("HashedModuleIdsPlugin", compilation => { + const usedIds = new Set(); + compilation.hooks.beforeModuleIds.tap( + "HashedModuleIdsPlugin", + modules => { + for (const module of modules) { + if (module.id === null && module.libIdent) { + const id = module.libIdent({ + context: this.options.context || compiler.options.context + }); + const hash = createHash(options.hashFunction); + hash.update(id); + const hashId = /** @type {string} */ (hash.digest( + options.hashDigest + )); + let len = options.hashDigestLength; + while (usedIds.has(hashId.substr(0, len))) len++; + module.id = hashId.substr(0, len); + usedIds.add(module.id); + } } - resource = request.substr(idx + 1); - } else { - loaders = []; - resource = request; } + ); + }); + } +} - const contextResolver = this.resolverFactory.get( - "context", - resolveOptions || EMPTY_RESOLVE_OPTIONS - ); - const loaderResolver = this.resolverFactory.get( - "loader", - EMPTY_RESOLVE_OPTIONS - ); +module.exports = HashedModuleIdsPlugin; - asyncLib.parallel( - [ - callback => { - contextResolver.resolve( - {}, - context, - resource, - {}, - (err, result) => { - if (err) return callback(err); - callback(null, result); - } - ); - }, - callback => { - asyncLib.map( - loaders, - (loader, callback) => { - loaderResolver.resolve( - {}, - context, - loader, - {}, - (err, result) => { - if (err) return callback(err); - callback(null, result); - } - ); - }, - callback - ); - } - ], - (err, result) => { - if (err) return callback(err); - this.hooks.afterResolve.callAsync( - Object.assign( - { - addon: - loadersPrefix + - result[1].join("!") + - (result[1].length > 0 ? "!" : ""), - resource: result[0], - resolveDependencies: this.resolveDependencies.bind(this) - }, - beforeResolveResult - ), - (err, result) => { - if (err) return callback(err); +/***/ }), - // Ignored - if (!result) return callback(); +/***/ 65217: +/***/ (function(module) { - return callback( - null, - new ContextModule(result.resolveDependencies, result) - ); - } - ); +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +// eslint-disable no-unused-vars +var $hash$ = undefined; +var $requestTimeout$ = undefined; +var installedModules = undefined; +var $require$ = undefined; +var hotDownloadManifest = undefined; +var hotDownloadUpdateChunk = undefined; +var hotDisposeChunk = undefined; +var modules = undefined; +var chunkId = undefined; + +module.exports = function() { + var hotApplyOnUpdate = true; + // eslint-disable-next-line no-unused-vars + var hotCurrentHash = $hash$; + var hotRequestTimeout = $requestTimeout$; + var hotCurrentModuleData = {}; + var hotCurrentChildModule; + // eslint-disable-next-line no-unused-vars + var hotCurrentParents = []; + // eslint-disable-next-line no-unused-vars + var hotCurrentParentsTemp = []; + + // eslint-disable-next-line no-unused-vars + function hotCreateRequire(moduleId) { + var me = installedModules[moduleId]; + if (!me) return $require$; + var fn = function(request) { + if (me.hot.active) { + if (installedModules[request]) { + if (installedModules[request].parents.indexOf(moduleId) === -1) { + installedModules[request].parents.push(moduleId); } + } else { + hotCurrentParents = [moduleId]; + hotCurrentChildModule = request; + } + if (me.children.indexOf(request) === -1) { + me.children.push(request); + } + } else { + console.warn( + "[HMR] unexpected require(" + + request + + ") from disposed module " + + moduleId ); + hotCurrentParents = []; } - ); - } - - resolveDependencies(fs, options, callback) { - const cmf = this; - let resource = options.resource; - let resourceQuery = options.resourceQuery; - let recursive = options.recursive; - let regExp = options.regExp; - let include = options.include; - let exclude = options.exclude; - if (!regExp || !resource) return callback(null, []); - - const addDirectory = (directory, callback) => { - fs.readdir(directory, (err, files) => { - if (err) return callback(err); - files = cmf.hooks.contextModuleFiles.call(files); - if (!files || files.length === 0) return callback(null, []); - asyncLib.map( - files.filter(p => p.indexOf(".") !== 0), - (segment, callback) => { - const subResource = path.join(directory, segment); - - if (!exclude || !subResource.match(exclude)) { - fs.stat(subResource, (err, stat) => { - if (err) { - if (err.code === "ENOENT") { - // ENOENT is ok here because the file may have been deleted between - // the readdir and stat calls. - return callback(); - } else { - return callback(err); - } - } - - if (stat.isDirectory()) { - if (!recursive) return callback(); - addDirectory.call(this, subResource, callback); - } else if ( - stat.isFile() && - (!include || subResource.match(include)) - ) { - const obj = { - context: resource, - request: - "." + - subResource.substr(resource.length).replace(/\\/g, "/") - }; - - this.hooks.alternatives.callAsync( - [obj], - (err, alternatives) => { - if (err) return callback(err); - alternatives = alternatives - .filter(obj => regExp.test(obj.request)) - .map(obj => { - const dep = new ContextElementDependency( - obj.request + resourceQuery, - obj.request - ); - dep.optional = true; - return dep; - }); - callback(null, alternatives); - } - ); - } else { - callback(); - } - }); - } else { - callback(); - } - }, - (err, result) => { - if (err) return callback(err); - - if (!result) return callback(null, []); - - callback( - null, - result.filter(Boolean).reduce((a, i) => a.concat(i), []) - ); - } - ); - }); + return $require$(request); }; - - addDirectory(resource, callback); - } -}; - - -/***/ }), - -/***/ 27295: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const path = __webpack_require__(85622); -const ContextElementDependency = __webpack_require__(89079); - -class ContextReplacementPlugin { - constructor( - resourceRegExp, - newContentResource, - newContentRecursive, - newContentRegExp - ) { - this.resourceRegExp = resourceRegExp; - - if (typeof newContentResource === "function") { - this.newContentCallback = newContentResource; - } else if ( - typeof newContentResource === "string" && - typeof newContentRecursive === "object" - ) { - this.newContentResource = newContentResource; - this.newContentCreateContextMap = (fs, callback) => { - callback(null, newContentRecursive); + var ObjectFactory = function ObjectFactory(name) { + return { + configurable: true, + enumerable: true, + get: function() { + return $require$[name]; + }, + set: function(value) { + $require$[name] = value; + } }; - } else if ( - typeof newContentResource === "string" && - typeof newContentRecursive === "function" - ) { - this.newContentResource = newContentResource; - this.newContentCreateContextMap = newContentRecursive; - } else { - if (typeof newContentResource !== "string") { - newContentRegExp = newContentRecursive; - newContentRecursive = newContentResource; - newContentResource = undefined; - } - if (typeof newContentRecursive !== "boolean") { - newContentRegExp = newContentRecursive; - newContentRecursive = undefined; + }; + for (var name in $require$) { + if ( + Object.prototype.hasOwnProperty.call($require$, name) && + name !== "e" && + name !== "t" + ) { + Object.defineProperty(fn, name, ObjectFactory(name)); } - this.newContentResource = newContentResource; - this.newContentRecursive = newContentRecursive; - this.newContentRegExp = newContentRegExp; } - } - - apply(compiler) { - const resourceRegExp = this.resourceRegExp; - const newContentCallback = this.newContentCallback; - const newContentResource = this.newContentResource; - const newContentRecursive = this.newContentRecursive; - const newContentRegExp = this.newContentRegExp; - const newContentCreateContextMap = this.newContentCreateContextMap; - - compiler.hooks.contextModuleFactory.tap("ContextReplacementPlugin", cmf => { - cmf.hooks.beforeResolve.tap("ContextReplacementPlugin", result => { - if (!result) return; - if (resourceRegExp.test(result.request)) { - if (newContentResource !== undefined) { - result.request = newContentResource; - } - if (newContentRecursive !== undefined) { - result.recursive = newContentRecursive; - } - if (newContentRegExp !== undefined) { - result.regExp = newContentRegExp; - } - if (typeof newContentCallback === "function") { - newContentCallback(result); - } else { - for (const d of result.dependencies) { - if (d.critical) d.critical = false; - } - } - } - return result; + fn.e = function(chunkId) { + if (hotStatus === "ready") hotSetStatus("prepare"); + hotChunksLoading++; + return $require$.e(chunkId).then(finishChunkLoading, function(err) { + finishChunkLoading(); + throw err; }); - cmf.hooks.afterResolve.tap("ContextReplacementPlugin", result => { - if (!result) return; - if (resourceRegExp.test(result.resource)) { - if (newContentResource !== undefined) { - result.resource = path.resolve(result.resource, newContentResource); - } - if (newContentRecursive !== undefined) { - result.recursive = newContentRecursive; - } - if (newContentRegExp !== undefined) { - result.regExp = newContentRegExp; - } - if (typeof newContentCreateContextMap === "function") { - result.resolveDependencies = createResolveDependenciesFromContextMap( - newContentCreateContextMap - ); + + function finishChunkLoading() { + hotChunksLoading--; + if (hotStatus === "prepare") { + if (!hotWaitingFilesMap[chunkId]) { + hotEnsureUpdateChunk(chunkId); } - if (typeof newContentCallback === "function") { - const origResource = result.resource; - newContentCallback(result); - if (result.resource !== origResource) { - result.resource = path.resolve(origResource, result.resource); - } - } else { - for (const d of result.dependencies) { - if (d.critical) d.critical = false; - } + if (hotChunksLoading === 0 && hotWaitingFiles === 0) { + hotUpdateDownloaded(); } } - return result; - }); - }); + } + }; + fn.t = function(value, mode) { + if (mode & 1) value = fn(value); + return $require$.t(value, mode & ~1); + }; + return fn; } -} - -const createResolveDependenciesFromContextMap = createContextMap => { - const resolveDependenciesFromContextMap = (fs, options, callback) => { - createContextMap(fs, (err, map) => { - if (err) return callback(err); - const dependencies = Object.keys(map).map(key => { - return new ContextElementDependency( - map[key] + options.resourceQuery, - key - ); - }); - callback(null, dependencies); - }); - }; - return resolveDependenciesFromContextMap; -}; -module.exports = ContextReplacementPlugin; + // eslint-disable-next-line no-unused-vars + function hotCreateModule(moduleId) { + var hot = { + // private stuff + _acceptedDependencies: {}, + _declinedDependencies: {}, + _selfAccepted: false, + _selfDeclined: false, + _selfInvalidated: false, + _disposeHandlers: [], + _main: hotCurrentChildModule !== moduleId, + // Module API + active: true, + accept: function(dep, callback) { + if (dep === undefined) hot._selfAccepted = true; + else if (typeof dep === "function") hot._selfAccepted = dep; + else if (typeof dep === "object") + for (var i = 0; i < dep.length; i++) + hot._acceptedDependencies[dep[i]] = callback || function() {}; + else hot._acceptedDependencies[dep] = callback || function() {}; + }, + decline: function(dep) { + if (dep === undefined) hot._selfDeclined = true; + else if (typeof dep === "object") + for (var i = 0; i < dep.length; i++) + hot._declinedDependencies[dep[i]] = true; + else hot._declinedDependencies[dep] = true; + }, + dispose: function(callback) { + hot._disposeHandlers.push(callback); + }, + addDisposeHandler: function(callback) { + hot._disposeHandlers.push(callback); + }, + removeDisposeHandler: function(callback) { + var idx = hot._disposeHandlers.indexOf(callback); + if (idx >= 0) hot._disposeHandlers.splice(idx, 1); + }, + invalidate: function() { + this._selfInvalidated = true; + switch (hotStatus) { + case "idle": + hotUpdate = {}; + hotUpdate[moduleId] = modules[moduleId]; + hotSetStatus("ready"); + break; + case "ready": + hotApplyInvalidatedModule(moduleId); + break; + case "prepare": + case "check": + case "dispose": + case "apply": + (hotQueuedInvalidatedModules = + hotQueuedInvalidatedModules || []).push(moduleId); + break; + default: + // ignore requests in error states + break; + } + }, -/***/ }), + // Management API + check: hotCheck, + apply: hotApply, + status: function(l) { + if (!l) return hotStatus; + hotStatusHandlers.push(l); + }, + addStatusHandler: function(l) { + hotStatusHandlers.push(l); + }, + removeStatusHandler: function(l) { + var idx = hotStatusHandlers.indexOf(l); + if (idx >= 0) hotStatusHandlers.splice(idx, 1); + }, -/***/ 97374: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + //inherit from previous dispose call + data: hotCurrentModuleData[moduleId] + }; + hotCurrentChildModule = undefined; + return hot; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + var hotStatusHandlers = []; + var hotStatus = "idle"; + function hotSetStatus(newStatus) { + hotStatus = newStatus; + for (var i = 0; i < hotStatusHandlers.length; i++) + hotStatusHandlers[i].call(null, newStatus); + } -const ConstDependency = __webpack_require__(71101); -const BasicEvaluatedExpression = __webpack_require__(96770); -const ParserHelpers = __webpack_require__(23999); -const NullFactory = __webpack_require__(40438); + // while downloading + var hotWaitingFiles = 0; + var hotChunksLoading = 0; + var hotWaitingFilesMap = {}; + var hotRequestedFilesMap = {}; + var hotAvailableFilesMap = {}; + var hotDeferred; -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Parser")} Parser */ -/** @typedef {null|undefined|RegExp|Function|string|number} CodeValuePrimitive */ -/** @typedef {CodeValuePrimitive|Record|RuntimeValue} CodeValue */ + // The update info + var hotUpdate, hotUpdateNewHash, hotQueuedInvalidatedModules; -class RuntimeValue { - constructor(fn, fileDependencies) { - this.fn = fn; - this.fileDependencies = fileDependencies || []; + function toModuleId(id) { + var isNumber = +id + "" === id; + return isNumber ? +id : id; } - exec(parser) { - if (this.fileDependencies === true) { - parser.state.module.buildInfo.cacheable = false; - } else { - for (const fileDependency of this.fileDependencies) { - parser.state.module.buildInfo.fileDependencies.add(fileDependency); - } + function hotCheck(apply) { + if (hotStatus !== "idle") { + throw new Error("check() is only allowed in idle status"); } + hotApplyOnUpdate = apply; + hotSetStatus("check"); + return hotDownloadManifest(hotRequestTimeout).then(function(update) { + if (!update) { + hotSetStatus(hotApplyInvalidatedModules() ? "ready" : "idle"); + return null; + } + hotRequestedFilesMap = {}; + hotWaitingFilesMap = {}; + hotAvailableFilesMap = update.c; + hotUpdateNewHash = update.h; - return this.fn({ module: parser.state.module }); + hotSetStatus("prepare"); + var promise = new Promise(function(resolve, reject) { + hotDeferred = { + resolve: resolve, + reject: reject + }; + }); + hotUpdate = {}; + /*foreachInstalledChunks*/ + // eslint-disable-next-line no-lone-blocks + { + hotEnsureUpdateChunk(chunkId); + } + if ( + hotStatus === "prepare" && + hotChunksLoading === 0 && + hotWaitingFiles === 0 + ) { + hotUpdateDownloaded(); + } + return promise; + }); } -} - -const stringifyObj = (obj, parser) => { - return ( - "Object({" + - Object.keys(obj) - .map(key => { - const code = obj[key]; - return JSON.stringify(key) + ":" + toCode(code, parser); - }) - .join(",") + - "})" - ); -}; -/** - * Convert code to a string that evaluates - * @param {CodeValue} code Code to evaluate - * @param {Parser} parser Parser - * @returns {string} code converted to string that evaluates - */ -const toCode = (code, parser) => { - if (code === null) { - return "null"; - } - if (code === undefined) { - return "undefined"; - } - if (code instanceof RuntimeValue) { - return toCode(code.exec(parser), parser); - } - if (code instanceof RegExp && code.toString) { - return code.toString(); - } - if (typeof code === "function" && code.toString) { - return "(" + code.toString() + ")"; + // eslint-disable-next-line no-unused-vars + function hotAddUpdateChunk(chunkId, moreModules) { + if (!hotAvailableFilesMap[chunkId] || !hotRequestedFilesMap[chunkId]) + return; + hotRequestedFilesMap[chunkId] = false; + for (var moduleId in moreModules) { + if (Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { + hotUpdate[moduleId] = moreModules[moduleId]; + } + } + if (--hotWaitingFiles === 0 && hotChunksLoading === 0) { + hotUpdateDownloaded(); + } } - if (typeof code === "object") { - return stringifyObj(code, parser); + + function hotEnsureUpdateChunk(chunkId) { + if (!hotAvailableFilesMap[chunkId]) { + hotWaitingFilesMap[chunkId] = true; + } else { + hotRequestedFilesMap[chunkId] = true; + hotWaitingFiles++; + hotDownloadUpdateChunk(chunkId); + } } - return code + ""; -}; -class DefinePlugin { - /** - * Create a new define plugin - * @param {Record} definitions A map of global object definitions - */ - constructor(definitions) { - this.definitions = definitions; + function hotUpdateDownloaded() { + hotSetStatus("ready"); + var deferred = hotDeferred; + hotDeferred = null; + if (!deferred) return; + if (hotApplyOnUpdate) { + // Wrap deferred object in Promise to mark it as a well-handled Promise to + // avoid triggering uncaught exception warning in Chrome. + // See https://bugs.chromium.org/p/chromium/issues/detail?id=465666 + Promise.resolve() + .then(function() { + return hotApply(hotApplyOnUpdate); + }) + .then( + function(result) { + deferred.resolve(result); + }, + function(err) { + deferred.reject(err); + } + ); + } else { + var outdatedModules = []; + for (var id in hotUpdate) { + if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { + outdatedModules.push(toModuleId(id)); + } + } + deferred.resolve(outdatedModules); + } } - static runtimeValue(fn, fileDependencies) { - return new RuntimeValue(fn, fileDependencies); + function hotApply(options) { + if (hotStatus !== "ready") + throw new Error("apply() is only allowed in ready status"); + options = options || {}; + return hotApplyInternal(options); } - /** - * Apply the plugin - * @param {Compiler} compiler Webpack compiler - * @returns {void} - */ - apply(compiler) { - const definitions = this.definitions; - compiler.hooks.compilation.tap( - "DefinePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set(ConstDependency, new NullFactory()); - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); + function hotApplyInternal(options) { + hotApplyInvalidatedModules(); - /** - * Handler - * @param {Parser} parser Parser - * @returns {void} - */ - const handler = parser => { - /** - * Walk definitions - * @param {Object} definitions Definitions map - * @param {string} prefix Prefix string - * @returns {void} - */ - const walkDefinitions = (definitions, prefix) => { - Object.keys(definitions).forEach(key => { - const code = definitions[key]; - if ( - code && - typeof code === "object" && - !(code instanceof RuntimeValue) && - !(code instanceof RegExp) - ) { - walkDefinitions(code, prefix + key + "."); - applyObjectDefine(prefix + key, code); - return; - } - applyDefineKey(prefix, key); - applyDefine(prefix + key, code); - }); - }; + var cb; + var i; + var j; + var module; + var moduleId; - /** - * Apply define key - * @param {string} prefix Prefix - * @param {string} key Key - * @returns {void} - */ - const applyDefineKey = (prefix, key) => { - const splittedKey = key.split("."); - splittedKey.slice(1).forEach((_, i) => { - const fullKey = prefix + splittedKey.slice(0, i + 1).join("."); - parser.hooks.canRename - .for(fullKey) - .tap("DefinePlugin", ParserHelpers.approve); - }); - }; + function getAffectedStuff(updateModuleId) { + var outdatedModules = [updateModuleId]; + var outdatedDependencies = {}; - /** - * Apply Code - * @param {string} key Key - * @param {CodeValue} code Code - * @returns {void} - */ - const applyDefine = (key, code) => { - const isTypeof = /^typeof\s+/.test(key); - if (isTypeof) key = key.replace(/^typeof\s+/, ""); - let recurse = false; - let recurseTypeof = false; - if (!isTypeof) { - parser.hooks.canRename - .for(key) - .tap("DefinePlugin", ParserHelpers.approve); - parser.hooks.evaluateIdentifier - .for(key) - .tap("DefinePlugin", expr => { - /** - * this is needed in case there is a recursion in the DefinePlugin - * to prevent an endless recursion - * e.g.: new DefinePlugin({ - * "a": "b", - * "b": "a" - * }); - */ - if (recurse) return; - recurse = true; - const res = parser.evaluate(toCode(code, parser)); - recurse = false; - res.setRange(expr.range); - return res; - }); - parser.hooks.expression.for(key).tap("DefinePlugin", expr => { - const strCode = toCode(code, parser); - if (/__webpack_require__/.test(strCode)) { - return ParserHelpers.toConstantDependencyWithWebpackRequire( - parser, - strCode - )(expr); - } else { - return ParserHelpers.toConstantDependency( - parser, - strCode - )(expr); - } - }); - } - parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => { - /** - * this is needed in case there is a recursion in the DefinePlugin - * to prevent an endless recursion - * e.g.: new DefinePlugin({ - * "typeof a": "typeof b", - * "typeof b": "typeof a" - * }); - */ - if (recurseTypeof) return; - recurseTypeof = true; - const typeofCode = isTypeof - ? toCode(code, parser) - : "typeof (" + toCode(code, parser) + ")"; - const res = parser.evaluate(typeofCode); - recurseTypeof = false; - res.setRange(expr.range); - return res; - }); - parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { - const typeofCode = isTypeof - ? toCode(code, parser) - : "typeof (" + toCode(code, parser) + ")"; - const res = parser.evaluate(typeofCode); - if (!res.isString()) return; - return ParserHelpers.toConstantDependency( - parser, - JSON.stringify(res.string) - ).bind(parser)(expr); - }); + var queue = outdatedModules.map(function(id) { + return { + chain: [id], + id: id + }; + }); + while (queue.length > 0) { + var queueItem = queue.pop(); + var moduleId = queueItem.id; + var chain = queueItem.chain; + module = installedModules[moduleId]; + if ( + !module || + (module.hot._selfAccepted && !module.hot._selfInvalidated) + ) + continue; + if (module.hot._selfDeclined) { + return { + type: "self-declined", + chain: chain, + moduleId: moduleId }; - - /** - * Apply Object - * @param {string} key Key - * @param {Object} obj Object - * @returns {void} - */ - const applyObjectDefine = (key, obj) => { - parser.hooks.canRename - .for(key) - .tap("DefinePlugin", ParserHelpers.approve); - parser.hooks.evaluateIdentifier - .for(key) - .tap("DefinePlugin", expr => - new BasicEvaluatedExpression().setTruthy().setRange(expr.range) - ); - parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => { - return ParserHelpers.evaluateToString("object")(expr); - }); - parser.hooks.expression.for(key).tap("DefinePlugin", expr => { - const strCode = stringifyObj(obj, parser); - - if (/__webpack_require__/.test(strCode)) { - return ParserHelpers.toConstantDependencyWithWebpackRequire( - parser, - strCode - )(expr); - } else { - return ParserHelpers.toConstantDependency( - parser, - strCode - )(expr); - } - }); - parser.hooks.typeof.for(key).tap("DefinePlugin", expr => { - return ParserHelpers.toConstantDependency( - parser, - JSON.stringify("object") - )(expr); - }); + } + if (module.hot._main) { + return { + type: "unaccepted", + chain: chain, + moduleId: moduleId }; + } + for (var i = 0; i < module.parents.length; i++) { + var parentId = module.parents[i]; + var parent = installedModules[parentId]; + if (!parent) continue; + if (parent.hot._declinedDependencies[moduleId]) { + return { + type: "declined", + chain: chain.concat([parentId]), + moduleId: moduleId, + parentId: parentId + }; + } + if (outdatedModules.indexOf(parentId) !== -1) continue; + if (parent.hot._acceptedDependencies[moduleId]) { + if (!outdatedDependencies[parentId]) + outdatedDependencies[parentId] = []; + addAllToSet(outdatedDependencies[parentId], [moduleId]); + continue; + } + delete outdatedDependencies[parentId]; + outdatedModules.push(parentId); + queue.push({ + chain: chain.concat([parentId]), + id: parentId + }); + } + } - walkDefinitions(definitions, ""); - }; + return { + type: "accepted", + moduleId: updateModuleId, + outdatedModules: outdatedModules, + outdatedDependencies: outdatedDependencies + }; + } - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("DefinePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("DefinePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("DefinePlugin", handler); + function addAllToSet(a, b) { + for (var i = 0; i < b.length; i++) { + var item = b[i]; + if (a.indexOf(item) === -1) a.push(item); } - ); - } -} -module.exports = DefinePlugin; - + } -/***/ }), + // at begin all updates modules are outdated + // the "outdated" status can propagate to parents if they don't accept the children + var outdatedDependencies = {}; + var outdatedModules = []; + var appliedUpdate = {}; -/***/ 42173: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + var warnUnexpectedRequire = function warnUnexpectedRequire() { + console.warn( + "[HMR] unexpected require(" + result.moduleId + ") to disposed module" + ); + }; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + for (var id in hotUpdate) { + if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { + moduleId = toModuleId(id); + /** @type {TODO} */ + var result; + if (hotUpdate[id]) { + result = getAffectedStuff(moduleId); + } else { + result = { + type: "disposed", + moduleId: id + }; + } + /** @type {Error|false} */ + var abortError = false; + var doApply = false; + var doDispose = false; + var chainInfo = ""; + if (result.chain) { + chainInfo = "\nUpdate propagation: " + result.chain.join(" -> "); + } + switch (result.type) { + case "self-declined": + if (options.onDeclined) options.onDeclined(result); + if (!options.ignoreDeclined) + abortError = new Error( + "Aborted because of self decline: " + + result.moduleId + + chainInfo + ); + break; + case "declined": + if (options.onDeclined) options.onDeclined(result); + if (!options.ignoreDeclined) + abortError = new Error( + "Aborted because of declined dependency: " + + result.moduleId + + " in " + + result.parentId + + chainInfo + ); + break; + case "unaccepted": + if (options.onUnaccepted) options.onUnaccepted(result); + if (!options.ignoreUnaccepted) + abortError = new Error( + "Aborted because " + moduleId + " is not accepted" + chainInfo + ); + break; + case "accepted": + if (options.onAccepted) options.onAccepted(result); + doApply = true; + break; + case "disposed": + if (options.onDisposed) options.onDisposed(result); + doDispose = true; + break; + default: + throw new Error("Unexception type " + result.type); + } + if (abortError) { + hotSetStatus("abort"); + return Promise.reject(abortError); + } + if (doApply) { + appliedUpdate[moduleId] = hotUpdate[moduleId]; + addAllToSet(outdatedModules, result.outdatedModules); + for (moduleId in result.outdatedDependencies) { + if ( + Object.prototype.hasOwnProperty.call( + result.outdatedDependencies, + moduleId + ) + ) { + if (!outdatedDependencies[moduleId]) + outdatedDependencies[moduleId] = []; + addAllToSet( + outdatedDependencies[moduleId], + result.outdatedDependencies[moduleId] + ); + } + } + } + if (doDispose) { + addAllToSet(outdatedModules, [result.moduleId]); + appliedUpdate[moduleId] = warnUnexpectedRequire; + } + } + } + // Store self accepted outdated modules to require them later by the module system + var outdatedSelfAcceptedModules = []; + for (i = 0; i < outdatedModules.length; i++) { + moduleId = outdatedModules[i]; + if ( + installedModules[moduleId] && + installedModules[moduleId].hot._selfAccepted && + // removed self-accepted modules should not be required + appliedUpdate[moduleId] !== warnUnexpectedRequire && + // when called invalidate self-accepting is not possible + !installedModules[moduleId].hot._selfInvalidated + ) { + outdatedSelfAcceptedModules.push({ + module: moduleId, + parents: installedModules[moduleId].parents.slice(), + errorHandler: installedModules[moduleId].hot._selfAccepted + }); + } + } -const { OriginalSource, RawSource } = __webpack_require__(53665); + // Now in "dispose" phase + hotSetStatus("dispose"); + Object.keys(hotAvailableFilesMap).forEach(function(chunkId) { + if (hotAvailableFilesMap[chunkId] === false) { + hotDisposeChunk(chunkId); + } + }); -const Module = __webpack_require__(75993); -const WebpackMissingModule = __webpack_require__(75386); -const DelegatedSourceDependency = __webpack_require__(25930); -const DelegatedExportsDependency = __webpack_require__(53104); + var idx; + var queue = outdatedModules.slice(); + while (queue.length > 0) { + moduleId = queue.pop(); + module = installedModules[moduleId]; + if (!module) continue; -/** @typedef {import("./dependencies/ModuleDependency")} ModuleDependency */ -/** @typedef {import("./util/createHash").Hash} Hash */ + var data = {}; -class DelegatedModule extends Module { - constructor(sourceRequest, data, type, userRequest, originalRequest) { - super("javascript/dynamic", null); + // Call dispose handlers + var disposeHandlers = module.hot._disposeHandlers; + for (j = 0; j < disposeHandlers.length; j++) { + cb = disposeHandlers[j]; + cb(data); + } + hotCurrentModuleData[moduleId] = data; - // Info from Factory - this.sourceRequest = sourceRequest; - this.request = data.id; - this.type = type; - this.userRequest = userRequest; - this.originalRequest = originalRequest; - this.delegateData = data; + // disable module (this disables requires from this module) + module.hot.active = false; - // Build info - this.delegatedSourceDependency = undefined; - } + // remove module from cache + delete installedModules[moduleId]; - libIdent(options) { - return typeof this.originalRequest === "string" - ? this.originalRequest - : this.originalRequest.libIdent(options); - } + // when disposing there is no need to call dispose handler + delete outdatedDependencies[moduleId]; - identifier() { - return `delegated ${JSON.stringify(this.request)} from ${ - this.sourceRequest - }`; - } + // remove "parents" references from all children + for (j = 0; j < module.children.length; j++) { + var child = installedModules[module.children[j]]; + if (!child) continue; + idx = child.parents.indexOf(moduleId); + if (idx >= 0) { + child.parents.splice(idx, 1); + } + } + } - readableIdentifier() { - return `delegated ${this.userRequest} from ${this.sourceRequest}`; - } + // remove outdated dependency from module children + var dependency; + var moduleOutdatedDependencies; + for (moduleId in outdatedDependencies) { + if ( + Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) + ) { + module = installedModules[moduleId]; + if (module) { + moduleOutdatedDependencies = outdatedDependencies[moduleId]; + for (j = 0; j < moduleOutdatedDependencies.length; j++) { + dependency = moduleOutdatedDependencies[j]; + idx = module.children.indexOf(dependency); + if (idx >= 0) module.children.splice(idx, 1); + } + } + } + } - needRebuild() { - return false; - } + // Now in "apply" phase + hotSetStatus("apply"); - build(options, compilation, resolver, fs, callback) { - this.built = true; - this.buildMeta = Object.assign({}, this.delegateData.buildMeta); - this.buildInfo = {}; - this.delegatedSourceDependency = new DelegatedSourceDependency( - this.sourceRequest - ); - this.addDependency(this.delegatedSourceDependency); - this.addDependency( - new DelegatedExportsDependency(this, this.delegateData.exports || true) - ); - callback(); - } + if (hotUpdateNewHash !== undefined) { + hotCurrentHash = hotUpdateNewHash; + hotUpdateNewHash = undefined; + } + hotUpdate = undefined; - source(depTemplates, runtime) { - const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]); - const sourceModule = dep.module; - let str; + // insert new code + for (moduleId in appliedUpdate) { + if (Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) { + modules[moduleId] = appliedUpdate[moduleId]; + } + } - if (!sourceModule) { - str = WebpackMissingModule.moduleCode(this.sourceRequest); - } else { - str = `module.exports = (${runtime.moduleExports({ - module: sourceModule, - request: dep.request - })})`; + // call accept handlers + var error = null; + for (moduleId in outdatedDependencies) { + if ( + Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) + ) { + module = installedModules[moduleId]; + if (module) { + moduleOutdatedDependencies = outdatedDependencies[moduleId]; + var callbacks = []; + for (i = 0; i < moduleOutdatedDependencies.length; i++) { + dependency = moduleOutdatedDependencies[i]; + cb = module.hot._acceptedDependencies[dependency]; + if (cb) { + if (callbacks.indexOf(cb) !== -1) continue; + callbacks.push(cb); + } + } + for (i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + try { + cb(moduleOutdatedDependencies); + } catch (err) { + if (options.onErrored) { + options.onErrored({ + type: "accept-errored", + moduleId: moduleId, + dependencyId: moduleOutdatedDependencies[i], + error: err + }); + } + if (!options.ignoreErrored) { + if (!error) error = err; + } + } + } + } + } + } - switch (this.type) { - case "require": - str += `(${JSON.stringify(this.request)})`; - break; - case "object": - str += `[${JSON.stringify(this.request)}]`; - break; + // Load self accepted modules + for (i = 0; i < outdatedSelfAcceptedModules.length; i++) { + var item = outdatedSelfAcceptedModules[i]; + moduleId = item.module; + hotCurrentParents = item.parents; + hotCurrentChildModule = moduleId; + try { + $require$(moduleId); + } catch (err) { + if (typeof item.errorHandler === "function") { + try { + item.errorHandler(err); + } catch (err2) { + if (options.onErrored) { + options.onErrored({ + type: "self-accept-error-handler-errored", + moduleId: moduleId, + error: err2, + originalError: err + }); + } + if (!options.ignoreErrored) { + if (!error) error = err2; + } + if (!error) error = err; + } + } else { + if (options.onErrored) { + options.onErrored({ + type: "self-accept-errored", + moduleId: moduleId, + error: err + }); + } + if (!options.ignoreErrored) { + if (!error) error = err; + } + } } + } - str += ";"; + // handle errors in accept handlers and self accepted module load + if (error) { + hotSetStatus("fail"); + return Promise.reject(error); } - if (this.useSourceMap) { - return new OriginalSource(str, this.identifier()); - } else { - return new RawSource(str); + if (hotQueuedInvalidatedModules) { + return hotApplyInternal(options).then(function(list) { + outdatedModules.forEach(function(moduleId) { + if (list.indexOf(moduleId) < 0) list.push(moduleId); + }); + return list; + }); } - } - size() { - return 42; + hotSetStatus("idle"); + return new Promise(function(resolve) { + resolve(outdatedModules); + }); } - /** - * @param {Hash} hash the hash used to track dependencies - * @returns {void} - */ - updateHash(hash) { - hash.update(this.type); - hash.update(JSON.stringify(this.request)); - super.updateHash(hash); + function hotApplyInvalidatedModules() { + if (hotQueuedInvalidatedModules) { + if (!hotUpdate) hotUpdate = {}; + hotQueuedInvalidatedModules.forEach(hotApplyInvalidatedModule); + hotQueuedInvalidatedModules = undefined; + return true; + } } -} -module.exports = DelegatedModule; + function hotApplyInvalidatedModule(moduleId) { + if (!Object.prototype.hasOwnProperty.call(hotUpdate, moduleId)) + hotUpdate[moduleId] = modules[moduleId]; + } +}; /***/ }), -/***/ 81002: +/***/ 69575: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -77039,312 +76724,430 @@ module.exports = DelegatedModule; */ -const DelegatedModule = __webpack_require__(42173); +const { SyncBailHook } = __webpack_require__(56758); +const { RawSource } = __webpack_require__(53665); +const Template = __webpack_require__(96066); +const ModuleHotAcceptDependency = __webpack_require__(29018); +const ModuleHotDeclineDependency = __webpack_require__(60482); +const ConstDependency = __webpack_require__(71101); +const NullFactory = __webpack_require__(40438); +const ParserHelpers = __webpack_require__(23999); -// options.source -// options.type -// options.context -// options.scope -// options.content -class DelegatedModuleFactoryPlugin { +module.exports = class HotModuleReplacementPlugin { constructor(options) { - this.options = options; - options.type = options.type || "require"; - options.extensions = options.extensions || [ - "", - ".wasm", - ".mjs", - ".js", - ".json" - ]; + this.options = options || {}; + this.multiStep = this.options.multiStep; + this.fullBuildTimeout = this.options.fullBuildTimeout || 200; + this.requestTimeout = this.options.requestTimeout || 10000; } - apply(normalModuleFactory) { - const scope = this.options.scope; - if (scope) { - normalModuleFactory.hooks.factory.tap( - "DelegatedModuleFactoryPlugin", - factory => (data, callback) => { - const dependency = data.dependencies[0]; - const request = dependency.request; - if (request && request.indexOf(scope + "/") === 0) { - const innerRequest = "." + request.substr(scope.length); - let resolved; - if (innerRequest in this.options.content) { - resolved = this.options.content[innerRequest]; - return callback( - null, - new DelegatedModule( - this.options.source, - resolved, - this.options.type, - innerRequest, - request - ) - ); + apply(compiler) { + const multiStep = this.multiStep; + const fullBuildTimeout = this.fullBuildTimeout; + const requestTimeout = this.requestTimeout; + const hotUpdateChunkFilename = + compiler.options.output.hotUpdateChunkFilename; + const hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename; + compiler.hooks.additionalPass.tapAsync( + "HotModuleReplacementPlugin", + callback => { + if (multiStep) return setTimeout(callback, fullBuildTimeout); + return callback(); + } + ); + + const addParserPlugins = (parser, parserOptions) => { + parser.hooks.expression + .for("__webpack_hash__") + .tap( + "HotModuleReplacementPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.h()" + ) + ); + parser.hooks.evaluateTypeof + .for("__webpack_hash__") + .tap( + "HotModuleReplacementPlugin", + ParserHelpers.evaluateToString("string") + ); + parser.hooks.evaluateIdentifier.for("module.hot").tap( + { + name: "HotModuleReplacementPlugin", + before: "NodeStuffPlugin" + }, + expr => { + return ParserHelpers.evaluateToIdentifier( + "module.hot", + !!parser.state.compilation.hotUpdateChunkTemplate + )(expr); + } + ); + // TODO webpack 5: refactor this, no custom hooks + if (!parser.hooks.hotAcceptCallback) { + parser.hooks.hotAcceptCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + if (!parser.hooks.hotAcceptWithoutCallback) { + parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + parser.hooks.call + .for("module.hot.accept") + .tap("HotModuleReplacementPlugin", expr => { + if (!parser.state.compilation.hotUpdateChunkTemplate) { + return false; + } + if (expr.arguments.length >= 1) { + const arg = parser.evaluateExpression(expr.arguments[0]); + let params = []; + let requests = []; + if (arg.isString()) { + params = [arg]; + } else if (arg.isArray()) { + params = arg.items.filter(param => param.isString()); } - for (let i = 0; i < this.options.extensions.length; i++) { - const extension = this.options.extensions[i]; - const requestPlusExt = innerRequest + extension; - if (requestPlusExt in this.options.content) { - resolved = this.options.content[requestPlusExt]; - return callback( - null, - new DelegatedModule( - this.options.source, - resolved, - this.options.type, - requestPlusExt, - request + extension - ) + if (params.length > 0) { + params.forEach((param, idx) => { + const request = param.string; + const dep = new ModuleHotAcceptDependency(request, param.range); + dep.optional = true; + dep.loc = Object.create(expr.loc); + dep.loc.index = idx; + parser.state.module.addDependency(dep); + requests.push(request); + }); + if (expr.arguments.length > 1) { + parser.hooks.hotAcceptCallback.call( + expr.arguments[1], + requests ); + parser.walkExpression(expr.arguments[1]); // other args are ignored + return true; + } else { + parser.hooks.hotAcceptWithoutCallback.call(expr, requests); + return true; } } } - return factory(data, callback); - } - ); - } else { - normalModuleFactory.hooks.module.tap( - "DelegatedModuleFactoryPlugin", - module => { - if (module.libIdent) { - const request = module.libIdent(this.options); - if (request && request in this.options.content) { - const resolved = this.options.content[request]; - return new DelegatedModule( - this.options.source, - resolved, - this.options.type, - request, - module - ); + }); + parser.hooks.call + .for("module.hot.decline") + .tap("HotModuleReplacementPlugin", expr => { + if (!parser.state.compilation.hotUpdateChunkTemplate) { + return false; + } + if (expr.arguments.length === 1) { + const arg = parser.evaluateExpression(expr.arguments[0]); + let params = []; + if (arg.isString()) { + params = [arg]; + } else if (arg.isArray()) { + params = arg.items.filter(param => param.isString()); } + params.forEach((param, idx) => { + const dep = new ModuleHotDeclineDependency( + param.string, + param.range + ); + dep.optional = true; + dep.loc = Object.create(expr.loc); + dep.loc.index = idx; + parser.state.module.addDependency(dep); + }); } - return module; - } - ); - } - } -} -module.exports = DelegatedModuleFactoryPlugin; - - -/***/ }), - -/***/ 16071: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ - - -const DependenciesBlockVariable = __webpack_require__(82904); - -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./DependenciesBlockVariable")} DependenciesBlockVariable */ -/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */ -/** @typedef {import("./util/createHash").Hash} Hash */ - -class DependenciesBlock { - constructor() { - /** @type {Dependency[]} */ - this.dependencies = []; - /** @type {AsyncDependenciesBlock[]} */ - this.blocks = []; - /** @type {DependenciesBlockVariable[]} */ - this.variables = []; - } - - /** - * Adds a DependencyBlock to DependencyBlock relationship. - * This is used for when a Module has a AsyncDependencyBlock tie (for code-splitting) - * - * @param {AsyncDependenciesBlock} block block being added - * @returns {void} - */ - addBlock(block) { - this.blocks.push(block); - block.parent = this; - } - - /** - * @param {string} name name of dependency - * @param {string} expression expression string for variable - * @param {Dependency[]} dependencies dependency instances tied to variable - * @returns {void} - */ - addVariable(name, expression, dependencies) { - for (let v of this.variables) { - if (v.name === name && v.expression === expression) { - return; - } - } - this.variables.push( - new DependenciesBlockVariable(name, expression, dependencies) - ); - } - - /** - * @param {Dependency} dependency dependency being tied to block. - * This is an "edge" pointing to another "node" on module graph. - * @returns {void} - */ - addDependency(dependency) { - this.dependencies.push(dependency); - } - - /** - * @param {Dependency} dependency dependency being removed - * @returns {void} - */ - removeDependency(dependency) { - const idx = this.dependencies.indexOf(dependency); - if (idx >= 0) { - this.dependencies.splice(idx, 1); - } - } - - /** - * @param {Hash} hash the hash used to track dependencies - * @returns {void} - */ - updateHash(hash) { - for (const dep of this.dependencies) dep.updateHash(hash); - for (const block of this.blocks) block.updateHash(hash); - for (const variable of this.variables) variable.updateHash(hash); - } - - disconnect() { - for (const dep of this.dependencies) dep.disconnect(); - for (const block of this.blocks) block.disconnect(); - for (const variable of this.variables) variable.disconnect(); - } - - unseal() { - for (const block of this.blocks) block.unseal(); - } - - /** - * @param {DependencyFilterFunction} filter filter function for dependencies, gets passed all dependency ties from current instance - * @returns {boolean} returns boolean for filter - */ - hasDependencies(filter) { - if (filter) { - for (const dep of this.dependencies) { - if (filter(dep)) return true; - } - } else { - if (this.dependencies.length > 0) { - return true; - } - } - - for (const block of this.blocks) { - if (block.hasDependencies(filter)) return true; - } - for (const variable of this.variables) { - if (variable.hasDependencies(filter)) return true; - } - return false; - } - - sortItems() { - for (const block of this.blocks) block.sortItems(); - } -} - -module.exports = DependenciesBlock; + }); + parser.hooks.expression + .for("module.hot") + .tap("HotModuleReplacementPlugin", ParserHelpers.skipTraversal); + }; + compiler.hooks.compilation.tap( + "HotModuleReplacementPlugin", + (compilation, { normalModuleFactory }) => { + // This applies the HMR plugin only to the targeted compiler + // It should not affect child compilations + if (compilation.compiler !== compiler) return; -/***/ }), + const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate; + if (!hotUpdateChunkTemplate) return; -/***/ 82904: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + compilation.dependencyFactories.set( + ModuleHotAcceptDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ModuleHotAcceptDependency, + new ModuleHotAcceptDependency.Template() + ); + compilation.dependencyFactories.set( + ModuleHotDeclineDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ModuleHotDeclineDependency, + new ModuleHotDeclineDependency.Template() + ); -const { RawSource, ReplaceSource } = __webpack_require__(53665); + compilation.hooks.record.tap( + "HotModuleReplacementPlugin", + (compilation, records) => { + if (records.hash === compilation.hash) return; + records.hash = compilation.hash; + records.moduleHashs = {}; + for (const module of compilation.modules) { + const identifier = module.identifier(); + records.moduleHashs[identifier] = module.hash; + } + records.chunkHashs = {}; + for (const chunk of compilation.chunks) { + records.chunkHashs[chunk.id] = chunk.hash; + } + records.chunkModuleIds = {}; + for (const chunk of compilation.chunks) { + records.chunkModuleIds[chunk.id] = Array.from( + chunk.modulesIterable, + m => m.id + ); + } + } + ); + let initialPass = false; + let recompilation = false; + compilation.hooks.afterHash.tap("HotModuleReplacementPlugin", () => { + let records = compilation.records; + if (!records) { + initialPass = true; + return; + } + if (!records.hash) initialPass = true; + const preHash = records.preHash || "x"; + const prepreHash = records.prepreHash || "x"; + if (preHash === compilation.hash) { + recompilation = true; + compilation.modifyHash(prepreHash); + return; + } + records.prepreHash = records.hash || "x"; + records.preHash = compilation.hash; + compilation.modifyHash(records.prepreHash); + }); + compilation.hooks.shouldGenerateChunkAssets.tap( + "HotModuleReplacementPlugin", + () => { + if (multiStep && !recompilation && !initialPass) return false; + } + ); + compilation.hooks.needAdditionalPass.tap( + "HotModuleReplacementPlugin", + () => { + if (multiStep && !recompilation && !initialPass) return true; + } + ); + compilation.hooks.additionalChunkAssets.tap( + "HotModuleReplacementPlugin", + () => { + const records = compilation.records; + if (records.hash === compilation.hash) return; + if ( + !records.moduleHashs || + !records.chunkHashs || + !records.chunkModuleIds + ) + return; + for (const module of compilation.modules) { + const identifier = module.identifier(); + let hash = module.hash; + module.hotUpdate = records.moduleHashs[identifier] !== hash; + } + const hotUpdateMainContent = { + h: compilation.hash, + c: {} + }; + for (const key of Object.keys(records.chunkHashs)) { + const chunkId = isNaN(+key) ? key : +key; + const currentChunk = compilation.chunks.find( + chunk => `${chunk.id}` === key + ); + if (currentChunk) { + const newModules = currentChunk + .getModules() + .filter(module => module.hotUpdate); + const allModules = new Set(); + for (const module of currentChunk.modulesIterable) { + allModules.add(module.id); + } + const removedModules = records.chunkModuleIds[chunkId].filter( + id => !allModules.has(id) + ); + if (newModules.length > 0 || removedModules.length > 0) { + const source = hotUpdateChunkTemplate.render( + chunkId, + newModules, + removedModules, + compilation.hash, + compilation.moduleTemplates.javascript, + compilation.dependencyTemplates + ); + const { + path: filename, + info: assetInfo + } = compilation.getPathWithInfo(hotUpdateChunkFilename, { + hash: records.hash, + chunk: currentChunk + }); + compilation.additionalChunkAssets.push(filename); + compilation.emitAsset( + filename, + source, + Object.assign({ hotModuleReplacement: true }, assetInfo) + ); + hotUpdateMainContent.c[chunkId] = true; + currentChunk.files.push(filename); + compilation.hooks.chunkAsset.call(currentChunk, filename); + } + } else { + hotUpdateMainContent.c[chunkId] = false; + } + } + const source = new RawSource(JSON.stringify(hotUpdateMainContent)); + const { + path: filename, + info: assetInfo + } = compilation.getPathWithInfo(hotUpdateMainFilename, { + hash: records.hash + }); + compilation.emitAsset( + filename, + source, + Object.assign({ hotModuleReplacement: true }, assetInfo) + ); + } + ); -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("./util/createHash").Hash} Hash */ -/** @typedef {(d: Dependency) => boolean} DependencyFilterFunction */ -/** @typedef {Map} DependencyTemplates */ + const mainTemplate = compilation.mainTemplate; -class DependenciesBlockVariable { - /** - * Creates an instance of DependenciesBlockVariable. - * @param {string} name name of DependenciesBlockVariable - * @param {string} expression expression string - * @param {Dependency[]=} dependencies dependencies tied to this varaiable - */ - constructor(name, expression, dependencies) { - this.name = name; - this.expression = expression; - this.dependencies = dependencies || []; - } + mainTemplate.hooks.hash.tap("HotModuleReplacementPlugin", hash => { + hash.update("HotMainTemplateDecorator"); + }); - /** - * @param {Hash} hash hash for instance to update - * @returns {void} - */ - updateHash(hash) { - hash.update(this.name); - hash.update(this.expression); - for (const d of this.dependencies) { - d.updateHash(hash); - } - } + mainTemplate.hooks.moduleRequire.tap( + "HotModuleReplacementPlugin", + (_, chunk, hash, varModuleId) => { + return `hotCreateRequire(${varModuleId})`; + } + ); - /** - * @param {DependencyTemplates} dependencyTemplates Dependency constructors and templates Map. - * @param {RuntimeTemplate} runtimeTemplate runtimeTemplate to generate expression souce - * @returns {ReplaceSource} returns constructed source for expression via templates - */ - expressionSource(dependencyTemplates, runtimeTemplate) { - const source = new ReplaceSource(new RawSource(this.expression)); - for (const dep of this.dependencies) { - const template = dependencyTemplates.get(dep.constructor); - if (!template) { - throw new Error(`No template for dependency: ${dep.constructor.name}`); - } - template.apply(dep, source, runtimeTemplate, dependencyTemplates); - } - return source; - } + mainTemplate.hooks.requireExtensions.tap( + "HotModuleReplacementPlugin", + source => { + const buf = [source]; + buf.push(""); + buf.push("// __webpack_hash__"); + buf.push( + mainTemplate.requireFn + + ".h = function() { return hotCurrentHash; };" + ); + return Template.asString(buf); + } + ); - disconnect() { - for (const d of this.dependencies) { - d.disconnect(); - } - } + const needChunkLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.chunks.length > 1) return true; + if (chunkGroup.getNumberOfChildren() > 0) return true; + } + return false; + }; - hasDependencies(filter) { - if (filter) { - return this.dependencies.some(filter); - } - return this.dependencies.length > 0; + mainTemplate.hooks.bootstrap.tap( + "HotModuleReplacementPlugin", + (source, chunk, hash) => { + source = mainTemplate.hooks.hotBootstrap.call(source, chunk, hash); + return Template.asString([ + source, + "", + hotInitCode + .replace(/\$require\$/g, mainTemplate.requireFn) + .replace(/\$hash\$/g, JSON.stringify(hash)) + .replace(/\$requestTimeout\$/g, requestTimeout) + .replace( + /\/\*foreachInstalledChunks\*\//g, + needChunkLoadingCode(chunk) + ? "for(var chunkId in installedChunks)" + : `var chunkId = ${JSON.stringify(chunk.id)};` + ) + ]); + } + ); + + mainTemplate.hooks.globalHash.tap( + "HotModuleReplacementPlugin", + () => true + ); + + mainTemplate.hooks.currentHash.tap( + "HotModuleReplacementPlugin", + (_, length) => { + if (isFinite(length)) { + return `hotCurrentHash.substr(0, ${length})`; + } else { + return "hotCurrentHash"; + } + } + ); + + mainTemplate.hooks.moduleObj.tap( + "HotModuleReplacementPlugin", + (source, chunk, hash, varModuleId) => { + return Template.asString([ + `${source},`, + `hot: hotCreateModule(${varModuleId}),`, + "parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),", + "children: []" + ]); + } + ); + + // TODO add HMR support for javascript/esm + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("HotModuleReplacementPlugin", addParserPlugins); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("HotModuleReplacementPlugin", addParserPlugins); + + compilation.hooks.normalModuleLoader.tap( + "HotModuleReplacementPlugin", + context => { + context.hot = true; + } + ); + } + ); } -} +}; -module.exports = DependenciesBlockVariable; +const hotInitCode = Template.getFunctionContent( + __webpack_require__(65217) +); /***/ }), -/***/ 57282: +/***/ 26782: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -77354,94 +77157,22 @@ module.exports = DependenciesBlockVariable; */ -const util = __webpack_require__(31669); -const compareLocations = __webpack_require__(22562); -const DependencyReference = __webpack_require__(71722); - -/** @typedef {import("./Module")} Module */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ - -/** - * @typedef {Object} DependencyTemplate - * @property {function(Dependency, Source, RuntimeTemplate, Map): void} apply - */ - -/** @typedef {Object} SourcePosition - * @property {number} line - * @property {number=} column - */ - -/** @typedef {Object} RealDependencyLocation - * @property {SourcePosition} start - * @property {SourcePosition=} end - * @property {number=} index - */ - -/** @typedef {Object} SynteticDependencyLocation - * @property {string} name - * @property {number=} index - */ - -/** @typedef {SynteticDependencyLocation|RealDependencyLocation} DependencyLocation */ +const Chunk = __webpack_require__(2919); -class Dependency { +class HotUpdateChunk extends Chunk { constructor() { - /** @type {Module|null} */ - this.module = null; - // TODO remove in webpack 5 - /** @type {boolean} */ - this.weak = false; - /** @type {boolean} */ - this.optional = false; - /** @type {DependencyLocation} */ - this.loc = undefined; - } - - getResourceIdentifier() { - return null; - } - - // Returns the referenced module and export - getReference() { - if (!this.module) return null; - return new DependencyReference(this.module, true, this.weak); - } - - // Returns the exported names - getExports() { - return null; - } - - getWarnings() { - return null; - } - - getErrors() { - return null; - } - - updateHash(hash) { - hash.update((this.module && this.module.id) + ""); - } - - disconnect() { - this.module = null; + super(); + /** @type {(string|number)[]} */ + this.removedModules = undefined; } } -// TODO remove in webpack 5 -Dependency.compare = util.deprecate( - (a, b) => compareLocations(a.loc, b.loc), - "Dependency.compare is deprecated and will be removed in the next major version" -); - -module.exports = Dependency; +module.exports = HotUpdateChunk; /***/ }), -/***/ 6659: +/***/ 66062: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -77451,127 +77182,182 @@ module.exports = Dependency; */ -const DllEntryDependency = __webpack_require__(66279); -const SingleEntryDependency = __webpack_require__(84828); -const DllModuleFactory = __webpack_require__(62468); +const Template = __webpack_require__(96066); +const HotUpdateChunk = __webpack_require__(26782); +const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(56758); -class DllEntryPlugin { - constructor(context, entries, name) { - this.context = context; - this.entries = entries; - this.name = name; +module.exports = class HotUpdateChunkTemplate extends Tapable { + constructor(outputOptions) { + super(); + this.outputOptions = outputOptions || {}; + this.hooks = { + modules: new SyncWaterfallHook([ + "source", + "modules", + "removedModules", + "moduleTemplate", + "dependencyTemplates" + ]), + render: new SyncWaterfallHook([ + "source", + "modules", + "removedModules", + "hash", + "id", + "moduleTemplate", + "dependencyTemplates" + ]), + hash: new SyncHook(["hash"]) + }; } - apply(compiler) { - compiler.hooks.compilation.tap( - "DllEntryPlugin", - (compilation, { normalModuleFactory }) => { - const dllModuleFactory = new DllModuleFactory(); - compilation.dependencyFactories.set( - DllEntryDependency, - dllModuleFactory - ); - compilation.dependencyFactories.set( - SingleEntryDependency, - normalModuleFactory - ); - } + render( + id, + modules, + removedModules, + hash, + moduleTemplate, + dependencyTemplates + ) { + const hotUpdateChunk = new HotUpdateChunk(); + hotUpdateChunk.id = id; + hotUpdateChunk.setModules(modules); + hotUpdateChunk.removedModules = removedModules; + const modulesSource = Template.renderChunkModules( + hotUpdateChunk, + m => typeof m.source === "function", + moduleTemplate, + dependencyTemplates ); - compiler.hooks.make.tapAsync("DllEntryPlugin", (compilation, callback) => { - compilation.addEntry( - this.context, - new DllEntryDependency( - this.entries.map((e, idx) => { - const dep = new SingleEntryDependency(e); - dep.loc = { - name: this.name, - index: idx - }; - return dep; - }), - this.name - ), - this.name, - callback - ); - }); + const core = this.hooks.modules.call( + modulesSource, + modules, + removedModules, + moduleTemplate, + dependencyTemplates + ); + const source = this.hooks.render.call( + core, + modules, + removedModules, + hash, + id, + moduleTemplate, + dependencyTemplates + ); + return source; } -} -module.exports = DllEntryPlugin; + updateHash(hash) { + hash.update("HotUpdateChunkTemplate"); + hash.update("1"); + this.hooks.hash.call(hash); + } +}; /***/ }), -/***/ 24803: +/***/ 41364: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra - */ - - -const { RawSource } = __webpack_require__(53665); -const Module = __webpack_require__(75993); - -/** @typedef {import("./util/createHash").Hash} Hash */ +*/ -class DllModule extends Module { - constructor(context, dependencies, name, type) { - super("javascript/dynamic", context); - // Info from Factory - this.dependencies = dependencies; - this.name = name; - this.type = type; - } +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(69667); - identifier() { - return `dll ${this.name}`; - } +/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */ +/** @typedef {import("./Compiler")} Compiler */ - readableIdentifier() { - return `dll ${this.name}`; - } +class IgnorePlugin { + /** + * @param {IgnorePluginOptions} options IgnorePlugin options + */ + constructor(options) { + // TODO webpack 5 remove this compat-layer + if (arguments.length > 1 || options instanceof RegExp) { + options = { + resourceRegExp: arguments[0], + contextRegExp: arguments[1] + }; + } - build(options, compilation, resolver, fs, callback) { - this.built = true; - this.buildMeta = {}; - this.buildInfo = {}; - return callback(); - } + validateOptions(schema, options, "IgnorePlugin"); + this.options = options; - source() { - return new RawSource("module.exports = __webpack_require__;"); + /** @private @type {Function} */ + this.checkIgnore = this.checkIgnore.bind(this); } - needRebuild() { - return false; - } + /** + * Note that if "contextRegExp" is given, both the "resourceRegExp" + * and "contextRegExp" have to match. + * + * @param {TODO} result result + * @returns {TODO|null} returns result or null if result should be ignored + */ + checkIgnore(result) { + if (!result) return result; - size() { - return 12; + if ( + "checkResource" in this.options && + this.options.checkResource && + this.options.checkResource(result.request, result.context) + ) { + // TODO webpack 5 remove checkContext, as checkResource already gets context + if ("checkContext" in this.options && this.options.checkContext) { + if (this.options.checkContext(result.context)) { + return null; + } + } else { + return null; + } + } + + if ( + "resourceRegExp" in this.options && + this.options.resourceRegExp && + this.options.resourceRegExp.test(result.request) + ) { + if ("contextRegExp" in this.options && this.options.contextRegExp) { + // if "contextRegExp" is given, + // both the "resourceRegExp" and "contextRegExp" have to match. + if (this.options.contextRegExp.test(result.context)) { + return null; + } + } else { + return null; + } + } + + return result; } /** - * @param {Hash} hash the hash used to track dependencies + * @param {Compiler} compiler Webpack Compiler * @returns {void} */ - updateHash(hash) { - hash.update("dll module"); - hash.update(this.name || ""); - super.updateHash(hash); + apply(compiler) { + compiler.hooks.normalModuleFactory.tap("IgnorePlugin", nmf => { + nmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore); + }); + compiler.hooks.contextModuleFactory.tap("IgnorePlugin", cmf => { + cmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore); + }); } } -module.exports = DllModule; +module.exports = IgnorePlugin; /***/ }), -/***/ 62468: +/***/ 98509: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -77581,357 +77367,427 @@ module.exports = DllModule; */ -const { Tapable } = __webpack_require__(56758); -const DllModule = __webpack_require__(24803); +const { RawSource, ReplaceSource } = __webpack_require__(53665); -class DllModuleFactory extends Tapable { - constructor() { - super(); - this.hooks = {}; - } - create(data, callback) { - const dependency = data.dependencies[0]; - callback( - null, - new DllModule( - data.context, - dependency.dependencies, - dependency.name, - dependency.type - ) - ); - } -} +// TODO: clean up this file +// replace with newer constructs -module.exports = DllModuleFactory; +// TODO: remove DependencyVariables and replace them with something better +class JavascriptGenerator { + generate(module, dependencyTemplates, runtimeTemplate) { + const originalSource = module.originalSource(); + if (!originalSource) { + return new RawSource("throw new Error('No source available');"); + } -/***/ }), + const source = new ReplaceSource(originalSource); -/***/ 45255: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + this.sourceBlock( + module, + module, + [], + dependencyTemplates, + source, + runtimeTemplate + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ + return source; + } + sourceBlock( + module, + block, + availableVars, + dependencyTemplates, + source, + runtimeTemplate + ) { + for (const dependency of block.dependencies) { + this.sourceDependency( + dependency, + dependencyTemplates, + source, + runtimeTemplate + ); + } -const DllEntryPlugin = __webpack_require__(6659); -const FlagAllModulesAsUsedPlugin = __webpack_require__(47163); -const LibManifestPlugin = __webpack_require__(30735); + /** + * Get the variables of all blocks that we need to inject. + * These will contain the variable name and its expression. + * The name will be added as a parameter in a IIFE the expression as its value. + */ + const vars = block.variables.reduce((result, value) => { + const variable = this.sourceVariables( + value, + availableVars, + dependencyTemplates, + runtimeTemplate + ); -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(7303); + if (variable) { + result.push(variable); + } -/** @typedef {import("../declarations/plugins/DllPlugin").DllPluginOptions} DllPluginOptions */ + return result; + }, []); -class DllPlugin { - /** - * @param {DllPluginOptions} options options object - */ - constructor(options) { - validateOptions(schema, options, "Dll Plugin"); - this.options = options; - } + /** + * if we actually have variables + * this is important as how #splitVariablesInUniqueNamedChunks works + * it will always return an array in an array which would lead to a IIFE wrapper around + * a module if we do this with an empty vars array. + */ + if (vars.length > 0) { + /** + * Split all variables up into chunks of unique names. + * e.g. imagine you have the following variable names that need to be injected: + * [foo, bar, baz, foo, some, more] + * we can not inject "foo" twice, therefore we just make two IIFEs like so: + * (function(foo, bar, baz){ + * (function(foo, some, more){ + * … + * }(…)); + * }(…)); + * + * "splitVariablesInUniqueNamedChunks" splits the variables shown above up to this: + * [[foo, bar, baz], [foo, some, more]] + */ + const injectionVariableChunks = this.splitVariablesInUniqueNamedChunks( + vars + ); - apply(compiler) { - compiler.hooks.entryOption.tap("DllPlugin", (context, entry) => { - const itemToPlugin = (item, name) => { - if (Array.isArray(item)) { - return new DllEntryPlugin(context, item, name); + // create all the beginnings of IIFEs + const functionWrapperStarts = injectionVariableChunks.map( + variableChunk => { + return this.variableInjectionFunctionWrapperStartCode( + variableChunk.map(variable => variable.name) + ); } - throw new Error("DllPlugin: supply an Array as entry"); - }; - if (typeof entry === "object" && !Array.isArray(entry)) { - Object.keys(entry).forEach(name => { - itemToPlugin(entry[name], name).apply(compiler); - }); - } else { - itemToPlugin(entry, "main").apply(compiler); - } - return true; - }); - new LibManifestPlugin(this.options).apply(compiler); - if (!this.options.entryOnly) { - new FlagAllModulesAsUsedPlugin("DllPlugin").apply(compiler); - } - } -} - -module.exports = DllPlugin; + ); + // and all the ends + const functionWrapperEnds = injectionVariableChunks.map(variableChunk => { + return this.variableInjectionFunctionWrapperEndCode( + module, + variableChunk.map(variable => variable.expression), + block + ); + }); -/***/ }), + // join them to one big string + const varStartCode = functionWrapperStarts.join(""); -/***/ 86231: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // reverse the ends first before joining them, as the last added must be the inner most + const varEndCode = functionWrapperEnds.reverse().join(""); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // if we have anything, add it to the source + if (varStartCode && varEndCode) { + const start = block.range ? block.range[0] : -10; + const end = block.range + ? block.range[1] + : module.originalSource().size() + 1; + source.insert(start + 0.5, varStartCode); + source.insert(end + 0.5, "\n/* WEBPACK VAR INJECTION */" + varEndCode); + } + } + for (const childBlock of block.blocks) { + this.sourceBlock( + module, + childBlock, + availableVars.concat(vars), + dependencyTemplates, + source, + runtimeTemplate + ); + } + } -const parseJson = __webpack_require__(48335); -const DelegatedSourceDependency = __webpack_require__(25930); -const DelegatedModuleFactoryPlugin = __webpack_require__(81002); -const ExternalModuleFactoryPlugin = __webpack_require__(67876); -const DelegatedExportsDependency = __webpack_require__(53104); -const NullFactory = __webpack_require__(40438); -const makePathsRelative = __webpack_require__(94658).makePathsRelative; -const WebpackError = __webpack_require__(97391); + sourceDependency(dependency, dependencyTemplates, source, runtimeTemplate) { + const template = dependencyTemplates.get(dependency.constructor); + if (!template) { + throw new Error( + "No template for dependency: " + dependency.constructor.name + ); + } + template.apply(dependency, source, runtimeTemplate, dependencyTemplates); + } -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(61112); + sourceVariables( + variable, + availableVars, + dependencyTemplates, + runtimeTemplate + ) { + const name = variable.name; + const expr = variable.expressionSource( + dependencyTemplates, + runtimeTemplate + ); -/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */ -/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptionsManifest} DllReferencePluginOptionsManifest */ + if ( + availableVars.some( + v => v.name === name && v.expression.source() === expr.source() + ) + ) { + return; + } + return { + name: name, + expression: expr + }; + } -class DllReferencePlugin { - /** - * @param {DllReferencePluginOptions} options options object + /* + * creates the start part of a IIFE around the module to inject a variable name + * (function(…){ <- this part + * }.call(…)) */ - constructor(options) { - validateOptions(schema, options, "Dll Reference Plugin"); - this.options = options; + variableInjectionFunctionWrapperStartCode(varNames) { + const args = varNames.join(", "); + return `/* WEBPACK VAR INJECTION */(function(${args}) {`; } - apply(compiler) { - compiler.hooks.compilation.tap( - "DllReferencePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - DelegatedSourceDependency, - normalModuleFactory - ); - compilation.dependencyFactories.set( - DelegatedExportsDependency, - new NullFactory() - ); - } - ); + contextArgument(module, block) { + if (this === block) { + return module.exportsArgument; + } + return "this"; + } - compiler.hooks.beforeCompile.tapAsync( - "DllReferencePlugin", - (params, callback) => { - if ("manifest" in this.options) { - const manifest = this.options.manifest; - if (typeof manifest === "string") { - params.compilationDependencies.add(manifest); - compiler.inputFileSystem.readFile(manifest, (err, result) => { - if (err) return callback(err); - // Catch errors parsing the manifest so that blank - // or malformed manifest files don't kill the process. - try { - params["dll reference " + manifest] = parseJson( - result.toString("utf-8") - ); - } catch (e) { - // Store the error in the params so that it can - // be added as a compilation error later on. - const manifestPath = makePathsRelative( - compiler.options.context, - manifest - ); - params[ - "dll reference parse error " + manifest - ] = new DllManifestError(manifestPath, e.message); - } - return callback(); - }); - return; - } - } - return callback(); - } - ); + /* + * creates the end part of a IIFE around the module to inject a variable name + * (function(…){ + * }.call(…)) <- this part + */ + variableInjectionFunctionWrapperEndCode(module, varExpressions, block) { + const firstParam = this.contextArgument(module, block); + const furtherParams = varExpressions.map(e => e.source()).join(", "); + return `}.call(${firstParam}, ${furtherParams}))`; + } - compiler.hooks.compile.tap("DllReferencePlugin", params => { - let name = this.options.name; - let sourceType = this.options.sourceType; - let content = - "content" in this.options ? this.options.content : undefined; - if ("manifest" in this.options) { - let manifestParameter = this.options.manifest; - let manifest; - if (typeof manifestParameter === "string") { - // If there was an error parsing the manifest - // file, exit now because the error will be added - // as a compilation error in the "compilation" hook. - if (params["dll reference parse error " + manifestParameter]) { - return; - } - manifest = - /** @type {DllReferencePluginOptionsManifest} */ (params[ - "dll reference " + manifestParameter - ]); - } else { - manifest = manifestParameter; - } - if (manifest) { - if (!name) name = manifest.name; - if (!sourceType) sourceType = manifest.type; - if (!content) content = manifest.content; - } - } - const externals = {}; - const source = "dll-reference " + name; - externals[source] = name; - const normalModuleFactory = params.normalModuleFactory; - new ExternalModuleFactoryPlugin(sourceType || "var", externals).apply( - normalModuleFactory + splitVariablesInUniqueNamedChunks(vars) { + const startState = [[]]; + return vars.reduce((chunks, variable) => { + const current = chunks[chunks.length - 1]; + // check if variable with same name exists already + // if so create a new chunk of variables. + const variableNameAlreadyExists = current.some( + v => v.name === variable.name ); - new DelegatedModuleFactoryPlugin({ - source: source, - type: this.options.type, - scope: this.options.scope, - context: this.options.context || compiler.options.context, - content, - extensions: this.options.extensions - }).apply(normalModuleFactory); - }); - compiler.hooks.compilation.tap( - "DllReferencePlugin", - (compilation, params) => { - if ("manifest" in this.options) { - let manifest = this.options.manifest; - if (typeof manifest === "string") { - // If there was an error parsing the manifest file, add the - // error as a compilation error to make the compilation fail. - let e = params["dll reference parse error " + manifest]; - if (e) { - compilation.errors.push(e); - } - } - } + if (variableNameAlreadyExists) { + // start new chunk with current variable + chunks.push([variable]); + } else { + // else add it to current chunk + current.push(variable); } - ); - } -} - -class DllManifestError extends WebpackError { - constructor(filename, message) { - super(); - - this.name = "DllManifestError"; - this.message = `Dll manifest ${filename}\n${message}`; - - Error.captureStackTrace(this, this.constructor); + return chunks; + }, startState); } } -module.exports = DllReferencePlugin; +module.exports = JavascriptGenerator; /***/ }), -/***/ 49784: +/***/ 10339: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Naoyuki Kanezawa @nkzawa + Author Tobias Koppers @sokra */ -const MultiEntryDependency = __webpack_require__(7791); -const SingleEntryDependency = __webpack_require__(84828); -const MultiModuleFactory = __webpack_require__(24005); -const MultiEntryPlugin = __webpack_require__(98046); -const SingleEntryPlugin = __webpack_require__(19070); - -/** @typedef {import("../declarations/WebpackOptions").EntryDynamic} EntryDynamic */ -/** @typedef {import("../declarations/WebpackOptions").EntryStatic} EntryStatic */ -/** @typedef {import("./Compiler")} Compiler */ +const Parser = __webpack_require__(70558); +const Template = __webpack_require__(96066); +const { ConcatSource } = __webpack_require__(53665); +const JavascriptGenerator = __webpack_require__(98509); +const createHash = __webpack_require__(15660); -class DynamicEntryPlugin { - /** - * @param {string} context the context path - * @param {EntryDynamic} entry the entry value - */ - constructor(context, entry) { - this.context = context; - this.entry = entry; - } - - /** - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ +class JavascriptModulesPlugin { apply(compiler) { compiler.hooks.compilation.tap( - "DynamicEntryPlugin", + "JavascriptModulesPlugin", (compilation, { normalModuleFactory }) => { - const multiModuleFactory = new MultiModuleFactory(); + normalModuleFactory.hooks.createParser + .for("javascript/auto") + .tap("JavascriptModulesPlugin", options => { + return new Parser(options, "auto"); + }); + normalModuleFactory.hooks.createParser + .for("javascript/dynamic") + .tap("JavascriptModulesPlugin", options => { + return new Parser(options, "script"); + }); + normalModuleFactory.hooks.createParser + .for("javascript/esm") + .tap("JavascriptModulesPlugin", options => { + return new Parser(options, "module"); + }); + normalModuleFactory.hooks.createGenerator + .for("javascript/auto") + .tap("JavascriptModulesPlugin", () => { + return new JavascriptGenerator(); + }); + normalModuleFactory.hooks.createGenerator + .for("javascript/dynamic") + .tap("JavascriptModulesPlugin", () => { + return new JavascriptGenerator(); + }); + normalModuleFactory.hooks.createGenerator + .for("javascript/esm") + .tap("JavascriptModulesPlugin", () => { + return new JavascriptGenerator(); + }); + compilation.mainTemplate.hooks.renderManifest.tap( + "JavascriptModulesPlugin", + (result, options) => { + const chunk = options.chunk; + const hash = options.hash; + const fullHash = options.fullHash; + const outputOptions = options.outputOptions; + const moduleTemplates = options.moduleTemplates; + const dependencyTemplates = options.dependencyTemplates; - compilation.dependencyFactories.set( - MultiEntryDependency, - multiModuleFactory + const filenameTemplate = + chunk.filenameTemplate || outputOptions.filename; + + const useChunkHash = compilation.mainTemplate.useChunkHash(chunk); + + result.push({ + render: () => + compilation.mainTemplate.render( + hash, + chunk, + moduleTemplates.javascript, + dependencyTemplates + ), + filenameTemplate, + pathOptions: { + noChunkHash: !useChunkHash, + contentHashType: "javascript", + chunk + }, + identifier: `chunk${chunk.id}`, + hash: useChunkHash ? chunk.hash : fullHash + }); + return result; + } ); - compilation.dependencyFactories.set( - SingleEntryDependency, - normalModuleFactory + compilation.mainTemplate.hooks.modules.tap( + "JavascriptModulesPlugin", + (source, chunk, hash, moduleTemplate, dependencyTemplates) => { + return Template.renderChunkModules( + chunk, + m => typeof m.source === "function", + moduleTemplate, + dependencyTemplates, + "/******/ " + ); + } ); - } - ); + compilation.chunkTemplate.hooks.renderManifest.tap( + "JavascriptModulesPlugin", + (result, options) => { + const chunk = options.chunk; + const outputOptions = options.outputOptions; + const moduleTemplates = options.moduleTemplates; + const dependencyTemplates = options.dependencyTemplates; + const filenameTemplate = + chunk.filenameTemplate || outputOptions.chunkFilename; - compiler.hooks.make.tapAsync( - "DynamicEntryPlugin", - (compilation, callback) => { - /** - * @param {string|string[]} entry entry value or array of entry values - * @param {string} name name of entry - * @returns {Promise} returns the promise resolving the Compilation#addEntry function - */ - const addEntry = (entry, name) => { - const dep = DynamicEntryPlugin.createDependency(entry, name); - return new Promise((resolve, reject) => { - compilation.addEntry(this.context, dep, name, err => { - if (err) return reject(err); - resolve(); + result.push({ + render: () => + this.renderJavascript( + compilation.chunkTemplate, + chunk, + moduleTemplates.javascript, + dependencyTemplates + ), + filenameTemplate, + pathOptions: { + chunk, + contentHashType: "javascript" + }, + identifier: `chunk${chunk.id}`, + hash: chunk.hash }); - }); - }; - Promise.resolve(this.entry()).then(entry => { - if (typeof entry === "string" || Array.isArray(entry)) { - addEntry(entry, "main").then(() => callback(), callback); - } else if (typeof entry === "object") { - Promise.all( - Object.keys(entry).map(name => { - return addEntry(entry[name], name); - }) - ).then(() => callback(), callback); + return result; + } + ); + compilation.hooks.contentHash.tap("JavascriptModulesPlugin", chunk => { + const outputOptions = compilation.outputOptions; + const { + hashSalt, + hashDigest, + hashDigestLength, + hashFunction + } = outputOptions; + const hash = createHash(hashFunction); + if (hashSalt) hash.update(hashSalt); + const template = chunk.hasRuntime() + ? compilation.mainTemplate + : compilation.chunkTemplate; + hash.update(`${chunk.id} `); + hash.update(chunk.ids ? chunk.ids.join(",") : ""); + template.updateHashForChunk( + hash, + chunk, + compilation.moduleTemplates.javascript, + compilation.dependencyTemplates + ); + for (const m of chunk.modulesIterable) { + if (typeof m.source === "function") { + hash.update(m.hash); + } } + const digest = /** @type {string} */ (hash.digest(hashDigest)); + chunk.contentHash.javascript = digest.substr(0, hashDigestLength); }); } ); } -} -module.exports = DynamicEntryPlugin; -/** - * @param {string|string[]} entry entry value or array of entry paths - * @param {string} name name of entry - * @returns {SingleEntryDependency|MultiEntryDependency} returns dep - */ -DynamicEntryPlugin.createDependency = (entry, name) => { - if (Array.isArray(entry)) { - return MultiEntryPlugin.createDependency(entry, name); - } else { - return SingleEntryPlugin.createDependency(entry, name); + renderJavascript(chunkTemplate, chunk, moduleTemplate, dependencyTemplates) { + const moduleSources = Template.renderChunkModules( + chunk, + m => typeof m.source === "function", + moduleTemplate, + dependencyTemplates + ); + const core = chunkTemplate.hooks.modules.call( + moduleSources, + chunk, + moduleTemplate, + dependencyTemplates + ); + let source = chunkTemplate.hooks.render.call( + core, + chunk, + moduleTemplate, + dependencyTemplates + ); + if (chunk.hasEntryModule()) { + source = chunkTemplate.hooks.renderWithEntry.call(source, chunk); + } + chunk.rendered = true; + return new ConcatSource(source, ";"); } -}; +} + +module.exports = JavascriptModulesPlugin; /***/ }), -/***/ 99531: +/***/ 72806: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -77941,26 +77797,62 @@ DynamicEntryPlugin.createDependency = (entry, name) => { */ -const WebpackError = __webpack_require__(97391); +const { ConcatSource, RawSource } = __webpack_require__(53665); -class EntryModuleNotFoundError extends WebpackError { - constructor(err) { - super("Entry module not found: " + err); +const stringifySafe = data => { + const stringified = JSON.stringify(data); + if (!stringified) { + return undefined; // Invalid JSON + } - this.name = "EntryModuleNotFoundError"; - this.details = err.details; - this.error = err; + return stringified.replace(/\u2028|\u2029/g, str => + str === "\u2029" ? "\\u2029" : "\\u2028" + ); // invalid in JavaScript but valid JSON +}; - Error.captureStackTrace(this, this.constructor); +class JsonGenerator { + generate(module, dependencyTemplates, runtimeTemplate) { + const source = new ConcatSource(); + const data = module.buildInfo.jsonData; + if (data === undefined) { + return new RawSource( + runtimeTemplate.missingModuleStatement({ + request: module.rawRequest + }) + ); + } + let finalJson; + if ( + Array.isArray(module.buildMeta.providedExports) && + !module.isUsed("default") + ) { + // Only some exports are used: We can optimize here, by only generating a part of the JSON + const reducedJson = {}; + for (const exportName of module.buildMeta.providedExports) { + if (exportName === "default") continue; + const used = module.isUsed(exportName); + if (used) { + reducedJson[used] = data[exportName]; + } + } + finalJson = reducedJson; + } else { + finalJson = data; + } + // Use JSON because JSON.parse() is much faster than JavaScript evaluation + const jsonSource = JSON.stringify(stringifySafe(finalJson)); + const jsonExpr = `JSON.parse(${jsonSource})`; + source.add(`${module.moduleArgument}.exports = ${jsonExpr};`); + return source; } } -module.exports = EntryModuleNotFoundError; +module.exports = JsonGenerator; /***/ }), -/***/ 14604: +/***/ 2859: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -77970,51 +77862,35 @@ module.exports = EntryModuleNotFoundError; */ -const SingleEntryPlugin = __webpack_require__(19070); -const MultiEntryPlugin = __webpack_require__(98046); -const DynamicEntryPlugin = __webpack_require__(49784); - -/** @typedef {import("../declarations/WebpackOptions").EntryItem} EntryItem */ -/** @typedef {import("./Compiler")} Compiler */ - -/** - * @param {string} context context path - * @param {EntryItem} item entry array or single path - * @param {string} name entry key name - * @returns {SingleEntryPlugin | MultiEntryPlugin} returns either a single or multi entry plugin - */ -const itemToPlugin = (context, item, name) => { - if (Array.isArray(item)) { - return new MultiEntryPlugin(context, item, name); - } - return new SingleEntryPlugin(context, item, name); -}; +const JsonParser = __webpack_require__(5807); +const JsonGenerator = __webpack_require__(72806); -module.exports = class EntryOptionPlugin { - /** - * @param {Compiler} compiler the compiler instance one is tapping into - * @returns {void} - */ +class JsonModulesPlugin { apply(compiler) { - compiler.hooks.entryOption.tap("EntryOptionPlugin", (context, entry) => { - if (typeof entry === "string" || Array.isArray(entry)) { - itemToPlugin(context, entry, "main").apply(compiler); - } else if (typeof entry === "object") { - for (const name of Object.keys(entry)) { - itemToPlugin(context, entry[name], name).apply(compiler); - } - } else if (typeof entry === "function") { - new DynamicEntryPlugin(context, entry).apply(compiler); + compiler.hooks.compilation.tap( + "JsonModulesPlugin", + (compilation, { normalModuleFactory }) => { + normalModuleFactory.hooks.createParser + .for("json") + .tap("JsonModulesPlugin", () => { + return new JsonParser(); + }); + normalModuleFactory.hooks.createGenerator + .for("json") + .tap("JsonModulesPlugin", () => { + return new JsonGenerator(); + }); } - return true; - }); + ); } -}; +} + +module.exports = JsonModulesPlugin; /***/ }), -/***/ 71931: +/***/ 5807: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -78024,150 +77900,325 @@ module.exports = class EntryOptionPlugin { */ -const ChunkGroup = __webpack_require__(52911); - -/** @typedef {import("./Chunk")} Chunk */ +const parseJson = __webpack_require__(48335); +const JsonExportsDependency = __webpack_require__(54396); -/** - * Entrypoint serves as an encapsulation primitive for chunks that are - * a part of a single ChunkGroup. They represent all bundles that need to be loaded for a - * single instance of a page. Multi-page application architectures will typically yield multiple Entrypoint objects - * inside of the compilation, whereas a Single Page App may only contain one with many lazy-loaded chunks. - */ -class Entrypoint extends ChunkGroup { - /** - * Creates an instance of Entrypoint. - * @param {string} name the name of the entrypoint - */ - constructor(name) { - super(name); - /** @type {Chunk=} */ - this.runtimeChunk = undefined; +class JsonParser { + constructor(options) { + this.options = options; } - /** - * isInitial will always return true for Entrypoint ChunkGroup. - * @returns {true} returns true as all entrypoints are initial ChunkGroups - */ - isInitial() { - return true; + parse(source, state) { + const data = parseJson(source[0] === "\ufeff" ? source.slice(1) : source); + state.module.buildInfo.jsonData = data; + state.module.buildMeta.exportsType = "named"; + if (typeof data === "object" && data) { + state.module.addDependency(new JsonExportsDependency(Object.keys(data))); + } + state.module.addDependency(new JsonExportsDependency(["default"])); + return state; } +} - /** - * Sets the runtimeChunk for an entrypoint. - * @param {Chunk} chunk the chunk being set as the runtime chunk. - * @returns {void} - */ - setRuntimeChunk(chunk) { - this.runtimeChunk = chunk; - } +module.exports = JsonParser; - /** - * Fetches the chunk reference containing the webpack bootstrap code - * @returns {Chunk} returns the runtime chunk or first chunk in `this.chunks` - */ - getRuntimeChunk() { - return this.runtimeChunk || this.chunks[0]; + +/***/ }), + +/***/ 30735: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const path = __webpack_require__(85622); +const asyncLib = __webpack_require__(36386); +const SingleEntryDependency = __webpack_require__(84828); + +class LibManifestPlugin { + constructor(options) { + this.options = options; } - /** - * @param {Chunk} oldChunk chunk to be replaced - * @param {Chunk} newChunk New chunk that will be replaced with - * @returns {boolean} returns true if the replacement was successful - */ - replaceChunk(oldChunk, newChunk) { - if (this.runtimeChunk === oldChunk) this.runtimeChunk = newChunk; - return super.replaceChunk(oldChunk, newChunk); + apply(compiler) { + compiler.hooks.emit.tapAsync( + "LibManifestPlugin", + (compilation, callback) => { + asyncLib.forEach( + compilation.chunks, + (chunk, callback) => { + if (!chunk.isOnlyInitial()) { + callback(); + return; + } + const targetPath = compilation.getPath(this.options.path, { + hash: compilation.hash, + chunk + }); + const name = + this.options.name && + compilation.getPath(this.options.name, { + hash: compilation.hash, + chunk + }); + const manifest = { + name, + type: this.options.type, + content: Array.from(chunk.modulesIterable, module => { + if ( + this.options.entryOnly && + !module.reasons.some( + r => r.dependency instanceof SingleEntryDependency + ) + ) { + return; + } + if (module.libIdent) { + const ident = module.libIdent({ + context: this.options.context || compiler.options.context + }); + if (ident) { + return { + ident, + data: { + id: module.id, + buildMeta: module.buildMeta + } + }; + } + } + }) + .filter(Boolean) + .reduce((obj, item) => { + obj[item.ident] = item.data; + return obj; + }, Object.create(null)) + }; + // Apply formatting to content if format flag is true; + const manifestContent = this.options.format + ? JSON.stringify(manifest, null, 2) + : JSON.stringify(manifest); + const content = Buffer.from(manifestContent, "utf8"); + compiler.outputFileSystem.mkdirp(path.dirname(targetPath), err => { + if (err) return callback(err); + compiler.outputFileSystem.writeFile( + targetPath, + content, + callback + ); + }); + }, + callback + ); + } + ); } } - -module.exports = Entrypoint; +module.exports = LibManifestPlugin; /***/ }), -/***/ 6098: +/***/ 65237: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Authors Simen Brekken @simenbrekken, Einar Löve @einarlove + Author Tobias Koppers @sokra */ +const SetVarMainTemplatePlugin = __webpack_require__(37098); +/** @typedef {import("../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ /** @typedef {import("./Compiler")} Compiler */ -const WebpackError = __webpack_require__(97391); -const DefinePlugin = __webpack_require__(97374); - -const needsEnvVarFix = - ["8", "9"].indexOf(process.versions.node.split(".")[0]) >= 0 && - process.platform === "win32"; +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); +}; -class EnvironmentPlugin { - constructor(...keys) { - if (keys.length === 1 && Array.isArray(keys[0])) { - this.keys = keys[0]; - this.defaultValues = {}; - } else if (keys.length === 1 && keys[0] && typeof keys[0] === "object") { - this.keys = Object.keys(keys[0]); - this.defaultValues = keys[0]; - } else { - this.keys = keys; - this.defaultValues = {}; - } +/** + * @param {string=} base the path prefix + * @param {string|string[]|LibraryCustomUmdObject} accessor the accessor + * @param {"amd" | "commonjs" | "root"} umdProperty property used when a custom umd object is provided + * @param {string=} joinWith the element separator + * @returns {string} the path + */ +const accessorAccess = (base, accessor, umdProperty, joinWith = "; ") => { + const normalizedAccessor = + typeof accessor === "object" && !Array.isArray(accessor) + ? accessor[umdProperty] + : accessor; + const accessors = Array.isArray(normalizedAccessor) + ? normalizedAccessor + : [normalizedAccessor]; + return accessors + .map((_, idx) => { + const a = base + ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) + : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); + if (idx === accessors.length - 1) return a; + if (idx === 0 && base === undefined) { + return `${a} = typeof ${a} === "object" ? ${a} : {}`; + } + return `${a} = ${a} || {}`; + }) + .join(joinWith); +}; + +class LibraryTemplatePlugin { + /** + * @param {string|string[]|LibraryCustomUmdObject} name name of library + * @param {string} target type of library + * @param {boolean} umdNamedDefine setting this to true will name the UMD module + * @param {string|TODO} auxiliaryComment comment in the UMD wrapper + * @param {string|string[]} exportProperty which export should be exposed as library + */ + constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) { + this.name = name; + this.target = target; + this.umdNamedDefine = umdNamedDefine; + this.auxiliaryComment = auxiliaryComment; + this.exportProperty = exportProperty; } /** - * @param {Compiler} compiler webpack compiler instance + * @param {Compiler} compiler the compiler instance * @returns {void} */ apply(compiler) { - const definitions = this.keys.reduce((defs, key) => { - // TODO remove once the fix has made its way into Node 8. - // Work around https://github.com/nodejs/node/pull/18463, - // affecting Node 8 & 9 by performing an OS-level - // operation that always succeeds before reading - // environment variables: - if (needsEnvVarFix) __webpack_require__(12087).cpus(); - - const value = - process.env[key] !== undefined - ? process.env[key] - : this.defaultValues[key]; - - if (value === undefined) { - compiler.hooks.thisCompilation.tap("EnvironmentPlugin", compilation => { - const error = new WebpackError( - `EnvironmentPlugin - ${key} environment variable is undefined.\n\n` + - "You can pass an object with default values to suppress this warning.\n" + - "See https://webpack.js.org/plugins/environment-plugin for example." + compiler.hooks.thisCompilation.tap("LibraryTemplatePlugin", compilation => { + if (this.exportProperty) { + const ExportPropertyMainTemplatePlugin = __webpack_require__(50471); + new ExportPropertyMainTemplatePlugin(this.exportProperty).apply( + compilation + ); + } + switch (this.target) { + case "var": + if ( + !this.name || + (typeof this.name === "object" && !Array.isArray(this.name)) + ) { + throw new Error( + "library name must be set and not an UMD custom object for non-UMD target" + ); + } + new SetVarMainTemplatePlugin( + `var ${accessorAccess(undefined, this.name, "root")}`, + false + ).apply(compilation); + break; + case "assign": + new SetVarMainTemplatePlugin( + accessorAccess(undefined, this.name, "root"), + false + ).apply(compilation); + break; + case "this": + case "self": + case "window": + if (this.name) { + new SetVarMainTemplatePlugin( + accessorAccess(this.target, this.name, "root"), + false + ).apply(compilation); + } else { + new SetVarMainTemplatePlugin(this.target, true).apply(compilation); + } + break; + case "global": + if (this.name) { + new SetVarMainTemplatePlugin( + accessorAccess( + compilation.runtimeTemplate.outputOptions.globalObject, + this.name, + "root" + ), + false + ).apply(compilation); + } else { + new SetVarMainTemplatePlugin( + compilation.runtimeTemplate.outputOptions.globalObject, + true + ).apply(compilation); + } + break; + case "commonjs": + if (this.name) { + new SetVarMainTemplatePlugin( + accessorAccess("exports", this.name, "commonjs"), + false + ).apply(compilation); + } else { + new SetVarMainTemplatePlugin("exports", true).apply(compilation); + } + break; + case "commonjs2": + case "commonjs-module": + new SetVarMainTemplatePlugin("module.exports", false).apply( + compilation ); - - error.name = "EnvVariableNotDefinedError"; - compilation.warnings.push(error); - }); + break; + case "amd": + case "amd-require": { + const AmdMainTemplatePlugin = __webpack_require__(9701); + if (this.name && typeof this.name !== "string") { + throw new Error("library name must be a string for amd target"); + } + new AmdMainTemplatePlugin({ + name: this.name, + requireAsWrapper: this.target === "amd-require" + }).apply(compilation); + break; + } + case "umd": + case "umd2": { + const UmdMainTemplatePlugin = __webpack_require__(75374); + new UmdMainTemplatePlugin(this.name, { + optionalAmdExternalAsGlobal: this.target === "umd2", + namedDefine: this.umdNamedDefine, + auxiliaryComment: this.auxiliaryComment + }).apply(compilation); + break; + } + case "jsonp": { + const JsonpExportMainTemplatePlugin = __webpack_require__(13732); + if (typeof this.name !== "string") + throw new Error("library name must be a string for jsonp target"); + new JsonpExportMainTemplatePlugin(this.name).apply(compilation); + break; + } + case "system": { + const SystemMainTemplatePlugin = __webpack_require__(97365); + new SystemMainTemplatePlugin({ + name: this.name + }).apply(compilation); + break; + } + default: + throw new Error(`${this.target} is not a valid Library target`); } - - defs[`process.env.${key}`] = - value === undefined ? "undefined" : JSON.stringify(value); - - return defs; - }, {}); - - new DefinePlugin(definitions).apply(compiler); + }); } } -module.exports = EnvironmentPlugin; +module.exports = LibraryTemplatePlugin; /***/ }), -/***/ 80140: -/***/ (function(__unused_webpack_module, exports) { +/***/ 48775: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -78176,101 +78227,64 @@ module.exports = EnvironmentPlugin; */ -const loaderFlag = "LOADER_EXECUTION"; - -const webpackOptionsFlag = "WEBPACK_OPTIONS"; - -exports.cutOffByFlag = (stack, flag) => { - stack = stack.split("\n"); - for (let i = 0; i < stack.length; i++) { - if (stack[i].includes(flag)) { - stack.length = i; - } - } - return stack.join("\n"); -}; - -exports.cutOffLoaderExecution = stack => - exports.cutOffByFlag(stack, loaderFlag); - -exports.cutOffWebpackOptions = stack => - exports.cutOffByFlag(stack, webpackOptionsFlag); - -exports.cutOffMultilineMessage = (stack, message) => { - stack = stack.split("\n"); - message = message.split("\n"); - - return stack - .reduce( - (acc, line, idx) => - line.includes(message[idx]) ? acc : acc.concat(line), - [] - ) - .join("\n"); -}; - -exports.cutOffMessage = (stack, message) => { - const nextLine = stack.indexOf("\n"); - if (nextLine === -1) { - return stack === message ? "" : stack; - } else { - const firstLine = stack.substr(0, nextLine); - return firstLine === message ? stack.substr(nextLine + 1) : stack; - } -}; - -exports.cleanUp = (stack, message) => { - stack = exports.cutOffLoaderExecution(stack); - stack = exports.cutOffMessage(stack, message); - return stack; -}; - -exports.cleanUpWebpackOptions = (stack, message) => { - stack = exports.cutOffWebpackOptions(stack); - stack = exports.cutOffMultilineMessage(stack, message); - return stack; -}; - - -/***/ }), - -/***/ 65200: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const ModuleFilenameHelpers = __webpack_require__(71474); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(4994); -const EvalDevToolModuleTemplatePlugin = __webpack_require__(24157); +/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */ -class EvalDevToolModulePlugin { +class LoaderOptionsPlugin { + /** + * @param {LoaderOptionsPluginOptions} options options object + */ constructor(options) { - this.sourceUrlComment = options.sourceUrlComment; - this.moduleFilenameTemplate = options.moduleFilenameTemplate; - this.namespace = options.namespace; + validateOptions(schema, options || {}, "Loader Options Plugin"); + + if (typeof options !== "object") options = {}; + if (!options.test) { + options.test = { + test: () => true + }; + } + this.options = options; } apply(compiler) { - compiler.hooks.compilation.tap("EvalDevToolModulePlugin", compilation => { - new EvalDevToolModuleTemplatePlugin({ - sourceUrlComment: this.sourceUrlComment, - moduleFilenameTemplate: this.moduleFilenameTemplate, - namespace: this.namespace - }).apply(compilation.moduleTemplates.javascript); + const options = this.options; + compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => { + compilation.hooks.normalModuleLoader.tap( + "LoaderOptionsPlugin", + (context, module) => { + const resource = module.resource; + if (!resource) return; + const i = resource.indexOf("?"); + if ( + ModuleFilenameHelpers.matchObject( + options, + i < 0 ? resource : resource.substr(0, i) + ) + ) { + for (const key of Object.keys(options)) { + if (key === "include" || key === "exclude" || key === "test") { + continue; + } + context[key] = options[key]; + } + } + } + ); }); } } -module.exports = EvalDevToolModulePlugin; +module.exports = LoaderOptionsPlugin; /***/ }), -/***/ 24157: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 95154: +/***/ (function(module) { "use strict"; /* @@ -78279,66 +78293,29 @@ module.exports = EvalDevToolModulePlugin; */ -const { RawSource } = __webpack_require__(53665); -const ModuleFilenameHelpers = __webpack_require__(71474); - -const cache = new WeakMap(); - -class EvalDevToolModuleTemplatePlugin { - constructor(options) { - this.sourceUrlComment = options.sourceUrlComment || "\n//# sourceURL=[url]"; - this.moduleFilenameTemplate = - options.moduleFilenameTemplate || - "webpack://[namespace]/[resourcePath]?[loaders]"; - this.namespace = options.namespace || ""; +class LoaderTargetPlugin { + constructor(target) { + this.target = target; } - apply(moduleTemplate) { - moduleTemplate.hooks.module.tap( - "EvalDevToolModuleTemplatePlugin", - (source, module) => { - const cacheEntry = cache.get(source); - if (cacheEntry !== undefined) return cacheEntry; - const content = source.source(); - const str = ModuleFilenameHelpers.createFilename( - module, - { - moduleFilenameTemplate: this.moduleFilenameTemplate, - namespace: this.namespace - }, - moduleTemplate.runtimeTemplate.requestShortener - ); - const footer = - "\n" + - this.sourceUrlComment.replace( - /\[url\]/g, - encodeURI(str) - .replace(/%2F/g, "/") - .replace(/%20/g, "_") - .replace(/%5E/g, "^") - .replace(/%5C/g, "\\") - .replace(/^\//, "") - ); - const result = new RawSource( - `eval(${JSON.stringify(content + footer)});` - ); - cache.set(source, result); - return result; - } - ); - moduleTemplate.hooks.hash.tap("EvalDevToolModuleTemplatePlugin", hash => { - hash.update("EvalDevToolModuleTemplatePlugin"); - hash.update("2"); + apply(compiler) { + compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => { + compilation.hooks.normalModuleLoader.tap( + "LoaderTargetPlugin", + loaderContext => { + loaderContext.target = this.target; + } + ); }); } } -module.exports = EvalDevToolModuleTemplatePlugin; +module.exports = LoaderTargetPlugin; /***/ }), -/***/ 51352: +/***/ 43626: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -78348,331 +78325,585 @@ module.exports = EvalDevToolModuleTemplatePlugin; */ -const { RawSource } = __webpack_require__(53665); -const ModuleFilenameHelpers = __webpack_require__(71474); -const { absolutify } = __webpack_require__(94658); - -const cache = new WeakMap(); - -class EvalSourceMapDevToolModuleTemplatePlugin { - constructor(compilation, options) { - this.compilation = compilation; - this.sourceMapComment = - options.append || "//# sourceURL=[module]\n//# sourceMappingURL=[url]"; - this.moduleFilenameTemplate = - options.moduleFilenameTemplate || - "webpack://[namespace]/[resource-path]?[hash]"; - this.namespace = options.namespace || ""; - this.options = options; - } +const { + ConcatSource, + OriginalSource, + PrefixSource, + RawSource +} = __webpack_require__(53665); +const { + Tapable, + SyncWaterfallHook, + SyncHook, + SyncBailHook +} = __webpack_require__(56758); +const Template = __webpack_require__(96066); - apply(moduleTemplate) { - const self = this; - const options = this.options; - const matchModule = ModuleFilenameHelpers.matchObject.bind( - ModuleFilenameHelpers, - options - ); - moduleTemplate.hooks.module.tap( - "EvalSourceMapDevToolModuleTemplatePlugin", - (source, module) => { - const cachedSource = cache.get(source); - if (cachedSource !== undefined) { - return cachedSource; - } +/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Module")} Module} */ +/** @typedef {import("./util/createHash").Hash} Hash} */ +/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate} */ - if (!matchModule(module.resource)) { - return source; - } +/** + * @typedef {Object} RenderManifestOptions + * @property {Chunk} chunk the chunk used to render + * @property {string} hash + * @property {string} fullHash + * @property {TODO} outputOptions + * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates + * @property {Map} dependencyTemplates + */ - /** @type {{ [key: string]: TODO; }} */ - let sourceMap; - let content; - if (source.sourceAndMap) { - const sourceAndMap = source.sourceAndMap(options); - sourceMap = sourceAndMap.map; - content = sourceAndMap.source; - } else { - sourceMap = source.map(options); - content = source.source(); - } - if (!sourceMap) { - return source; - } +// require function shortcuts: +// __webpack_require__.s = the module id of the entry point +// __webpack_require__.c = the module cache +// __webpack_require__.m = the module functions +// __webpack_require__.p = the bundle public path +// __webpack_require__.i = the identity function used for harmony imports +// __webpack_require__.e = the chunk ensure function +// __webpack_require__.d = the exported property define getter function +// __webpack_require__.o = Object.prototype.hasOwnProperty.call +// __webpack_require__.r = define compatibility on export +// __webpack_require__.t = create a fake namespace object +// __webpack_require__.n = compatibility get default export +// __webpack_require__.h = the webpack hash +// __webpack_require__.w = an object containing all installed WebAssembly.Instance export objects keyed by module id +// __webpack_require__.oe = the uncaught error handler for the webpack runtime +// __webpack_require__.nc = the script nonce - // Clone (flat) the sourcemap to ensure that the mutations below do not persist. - sourceMap = Object.keys(sourceMap).reduce((obj, key) => { - obj[key] = sourceMap[key]; - return obj; - }, {}); - const context = this.compilation.compiler.options.context; - const modules = sourceMap.sources.map(source => { - if (source.startsWith("webpack://")) { - source = absolutify(context, source.slice(10)); - } - const module = self.compilation.findModule(source); - return module || source; - }); - let moduleFilenames = modules.map(module => { - return ModuleFilenameHelpers.createFilename( - module, - { - moduleFilenameTemplate: self.moduleFilenameTemplate, - namespace: self.namespace - }, - moduleTemplate.runtimeTemplate.requestShortener - ); - }); - moduleFilenames = ModuleFilenameHelpers.replaceDuplicates( - moduleFilenames, - (filename, i, n) => { - for (let j = 0; j < n; j++) filename += "*"; - return filename; - } - ); - sourceMap.sources = moduleFilenames; - sourceMap.sourceRoot = options.sourceRoot || ""; - sourceMap.file = `${module.id}.js`; - - const footer = - self.sourceMapComment.replace( - /\[url\]/g, - `data:application/json;charset=utf-8;base64,${Buffer.from( - JSON.stringify(sourceMap), - "utf8" - ).toString("base64")}` - ) + `\n//# sourceURL=webpack-internal:///${module.id}\n`; // workaround for chrome bug +module.exports = class MainTemplate extends Tapable { + /** + * + * @param {TODO=} outputOptions output options for the MainTemplate + */ + constructor(outputOptions) { + super(); + /** @type {TODO?} */ + this.outputOptions = outputOptions || {}; + this.hooks = { + /** @type {SyncWaterfallHook} */ + renderManifest: new SyncWaterfallHook(["result", "options"]), + modules: new SyncWaterfallHook([ + "modules", + "chunk", + "hash", + "moduleTemplate", + "dependencyTemplates" + ]), + moduleObj: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleIdExpression" + ]), + requireEnsure: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "chunkIdExpression" + ]), + bootstrap: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleTemplate", + "dependencyTemplates" + ]), + localVars: new SyncWaterfallHook(["source", "chunk", "hash"]), + require: new SyncWaterfallHook(["source", "chunk", "hash"]), + requireExtensions: new SyncWaterfallHook(["source", "chunk", "hash"]), + /** @type {SyncWaterfallHook} */ + beforeStartup: new SyncWaterfallHook(["source", "chunk", "hash"]), + /** @type {SyncWaterfallHook} */ + startup: new SyncWaterfallHook(["source", "chunk", "hash"]), + /** @type {SyncWaterfallHook} */ + afterStartup: new SyncWaterfallHook(["source", "chunk", "hash"]), + render: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleTemplate", + "dependencyTemplates" + ]), + renderWithEntry: new SyncWaterfallHook(["source", "chunk", "hash"]), + moduleRequire: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleIdExpression" + ]), + addModule: new SyncWaterfallHook([ + "source", + "chunk", + "hash", + "moduleIdExpression", + "moduleExpression" + ]), + currentHash: new SyncWaterfallHook(["source", "requestedLength"]), + assetPath: new SyncWaterfallHook(["path", "options", "assetInfo"]), + hash: new SyncHook(["hash"]), + hashForChunk: new SyncHook(["hash", "chunk"]), + globalHashPaths: new SyncWaterfallHook(["paths"]), + globalHash: new SyncBailHook(["chunk", "paths"]), - const evalSource = new RawSource( - `eval(${JSON.stringify(content + footer)});` + // TODO this should be moved somewhere else + // It's weird here + hotBootstrap: new SyncWaterfallHook(["source", "chunk", "hash"]) + }; + this.hooks.startup.tap("MainTemplate", (source, chunk, hash) => { + /** @type {string[]} */ + const buf = []; + if (chunk.entryModule) { + buf.push("// Load entry module and return exports"); + buf.push( + `return ${this.renderRequireFunctionForModule( + hash, + chunk, + JSON.stringify(chunk.entryModule.id) + )}(${this.requireFn}.s = ${JSON.stringify(chunk.entryModule.id)});` ); - - cache.set(source, evalSource); - - return evalSource; + } + return Template.asString(buf); + }); + this.hooks.render.tap( + "MainTemplate", + (bootstrapSource, chunk, hash, moduleTemplate, dependencyTemplates) => { + const source = new ConcatSource(); + source.add("/******/ (function(modules) { // webpackBootstrap\n"); + source.add(new PrefixSource("/******/", bootstrapSource)); + source.add("/******/ })\n"); + source.add( + "/************************************************************************/\n" + ); + source.add("/******/ ("); + source.add( + this.hooks.modules.call( + new RawSource(""), + chunk, + hash, + moduleTemplate, + dependencyTemplates + ) + ); + source.add(")"); + return source; } ); - moduleTemplate.hooks.hash.tap( - "EvalSourceMapDevToolModuleTemplatePlugin", - hash => { - hash.update("eval-source-map"); - hash.update("2"); + this.hooks.localVars.tap("MainTemplate", (source, chunk, hash) => { + return Template.asString([ + source, + "// The module cache", + "var installedModules = {};" + ]); + }); + this.hooks.require.tap("MainTemplate", (source, chunk, hash) => { + return Template.asString([ + source, + "// Check if module is in cache", + "if(installedModules[moduleId]) {", + Template.indent("return installedModules[moduleId].exports;"), + "}", + "// Create a new module (and put it into the cache)", + "var module = installedModules[moduleId] = {", + Template.indent(this.hooks.moduleObj.call("", chunk, hash, "moduleId")), + "};", + "", + Template.asString( + outputOptions.strictModuleExceptionHandling + ? [ + "// Execute the module function", + "var threw = true;", + "try {", + Template.indent([ + `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule( + hash, + chunk, + "moduleId" + )});`, + "threw = false;" + ]), + "} finally {", + Template.indent([ + "if(threw) delete installedModules[moduleId];" + ]), + "}" + ] + : [ + "// Execute the module function", + `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule( + hash, + chunk, + "moduleId" + )});` + ] + ), + "", + "// Flag the module as loaded", + "module.l = true;", + "", + "// Return the exports of the module", + "return module.exports;" + ]); + }); + this.hooks.moduleObj.tap( + "MainTemplate", + (source, chunk, hash, varModuleId) => { + return Template.asString(["i: moduleId,", "l: false,", "exports: {}"]); } ); - } -} -module.exports = EvalSourceMapDevToolModuleTemplatePlugin; - - -/***/ }), - -/***/ 99994: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + this.hooks.requireExtensions.tap("MainTemplate", (source, chunk, hash) => { + const buf = []; + const chunkMaps = chunk.getChunkMaps(); + // Check if there are non initial chunks which need to be imported using require-ensure + if (Object.keys(chunkMaps.hash).length) { + buf.push("// This file contains only the entry chunk."); + buf.push("// The chunk loading function for additional chunks"); + buf.push(`${this.requireFn}.e = function requireEnsure(chunkId) {`); + buf.push(Template.indent("var promises = [];")); + buf.push( + Template.indent( + this.hooks.requireEnsure.call("", chunk, hash, "chunkId") + ) + ); + buf.push(Template.indent("return Promise.all(promises);")); + buf.push("};"); + } else if ( + chunk.hasModuleInGraph(m => + m.blocks.some(b => b.chunkGroup && b.chunkGroup.chunks.length > 0) + ) + ) { + // There async blocks in the graph, so we need to add an empty requireEnsure + // function anyway. This can happen with multiple entrypoints. + buf.push("// The chunk loading function for additional chunks"); + buf.push("// Since all referenced chunks are already included"); + buf.push("// in this file, this function is empty here."); + buf.push(`${this.requireFn}.e = function requireEnsure() {`); + buf.push(Template.indent("return Promise.resolve();")); + buf.push("};"); + } + buf.push(""); + buf.push("// expose the modules object (__webpack_modules__)"); + buf.push(`${this.requireFn}.m = modules;`); -const EvalSourceMapDevToolModuleTemplatePlugin = __webpack_require__(51352); -const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(24113); + buf.push(""); + buf.push("// expose the module cache"); + buf.push(`${this.requireFn}.c = installedModules;`); -class EvalSourceMapDevToolPlugin { - constructor(options) { - if (arguments.length > 1) { - throw new Error( - "EvalSourceMapDevToolPlugin only takes one argument (pass an options object)" + buf.push(""); + buf.push("// define getter function for harmony exports"); + buf.push(`${this.requireFn}.d = function(exports, name, getter) {`); + buf.push( + Template.indent([ + `if(!${this.requireFn}.o(exports, name)) {`, + Template.indent([ + "Object.defineProperty(exports, name, { enumerable: true, get: getter });" + ]), + "}" + ]) ); - } - if (typeof options === "string") { - options = { - append: options - }; - } - if (!options) options = {}; - this.options = options; - } - - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap( - "EvalSourceMapDevToolPlugin", - compilation => { - new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); - new EvalSourceMapDevToolModuleTemplatePlugin( - compilation, - options - ).apply(compilation.moduleTemplates.javascript); - } - ); - } -} + buf.push("};"); -module.exports = EvalSourceMapDevToolPlugin; + buf.push(""); + buf.push("// define __esModule on exports"); + buf.push(`${this.requireFn}.r = function(exports) {`); + buf.push( + Template.indent([ + "if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {", + Template.indent([ + "Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });" + ]), + "}", + "Object.defineProperty(exports, '__esModule', { value: true });" + ]) + ); + buf.push("};"); + buf.push(""); + buf.push("// create a fake namespace object"); + buf.push("// mode & 1: value is a module id, require it"); + buf.push("// mode & 2: merge all properties of value into the ns"); + buf.push("// mode & 4: return value when already ns object"); + buf.push("// mode & 8|1: behave like require"); + buf.push(`${this.requireFn}.t = function(value, mode) {`); + buf.push( + Template.indent([ + `if(mode & 1) value = ${this.requireFn}(value);`, + `if(mode & 8) return value;`, + "if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;", + "var ns = Object.create(null);", + `${this.requireFn}.r(ns);`, + "Object.defineProperty(ns, 'default', { enumerable: true, value: value });", + "if(mode & 2 && typeof value != 'string') for(var key in value) " + + `${this.requireFn}.d(ns, key, function(key) { ` + + "return value[key]; " + + "}.bind(null, key));", + "return ns;" + ]) + ); + buf.push("};"); -/***/ }), + buf.push(""); + buf.push( + "// getDefaultExport function for compatibility with non-harmony modules" + ); + buf.push(this.requireFn + ".n = function(module) {"); + buf.push( + Template.indent([ + "var getter = module && module.__esModule ?", + Template.indent([ + "function getDefault() { return module['default']; } :", + "function getModuleExports() { return module; };" + ]), + `${this.requireFn}.d(getter, 'a', getter);`, + "return getter;" + ]) + ); + buf.push("};"); -/***/ 50471: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + buf.push(""); + buf.push("// Object.prototype.hasOwnProperty.call"); + buf.push( + `${this.requireFn}.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };` + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const publicPath = this.getPublicPath({ + hash: hash + }); + buf.push(""); + buf.push("// __webpack_public_path__"); + buf.push(`${this.requireFn}.p = ${JSON.stringify(publicPath)};`); + return Template.asString(buf); + }); + this.requireFn = "__webpack_require__"; + } -const { ConcatSource } = __webpack_require__(53665); + /** + * + * @param {RenderManifestOptions} options render manifest options + * @returns {TODO[]} returns render manifest + */ + getRenderManifest(options) { + const result = []; -/** @typedef {import("./Compilation")} Compilation */ + this.hooks.renderManifest.call(result, options); -/** - * @param {string[]} accessor the accessor to convert to path - * @returns {string} the path - */ -const accessorToObjectAccess = accessor => { - return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); -}; + return result; + } -class ExportPropertyMainTemplatePlugin { /** - * @param {string|string[]} property the name of the property to export + * TODO webpack 5: remove moduleTemplate and dependencyTemplates + * @param {string} hash hash to be used for render call + * @param {Chunk} chunk Chunk instance + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map} dependencyTemplates dependency templates + * @returns {string[]} the generated source of the bootstrap code */ - constructor(property) { - this.property = property; + renderBootstrap(hash, chunk, moduleTemplate, dependencyTemplates) { + const buf = []; + buf.push( + this.hooks.bootstrap.call( + "", + chunk, + hash, + moduleTemplate, + dependencyTemplates + ) + ); + buf.push(this.hooks.localVars.call("", chunk, hash)); + buf.push(""); + buf.push("// The require function"); + buf.push(`function ${this.requireFn}(moduleId) {`); + buf.push(Template.indent(this.hooks.require.call("", chunk, hash))); + buf.push("}"); + buf.push(""); + buf.push( + Template.asString(this.hooks.requireExtensions.call("", chunk, hash)) + ); + buf.push(""); + buf.push(Template.asString(this.hooks.beforeStartup.call("", chunk, hash))); + const afterStartupCode = Template.asString( + this.hooks.afterStartup.call("", chunk, hash) + ); + if (afterStartupCode) { + // TODO webpack 5: this is a bit hacky to avoid a breaking change + // change it to a better way + buf.push("var startupResult = (function() {"); + } + buf.push(Template.asString(this.hooks.startup.call("", chunk, hash))); + if (afterStartupCode) { + buf.push("})();"); + buf.push(afterStartupCode); + buf.push("return startupResult;"); + } + return buf; } /** - * @param {Compilation} compilation the compilation instance - * @returns {void} + * @param {string} hash hash to be used for render call + * @param {Chunk} chunk Chunk instance + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map} dependencyTemplates dependency templates + * @returns {ConcatSource} the newly generated source from rendering */ - apply(compilation) { - const { mainTemplate, chunkTemplate } = compilation; - - const onRenderWithEntry = (source, chunk, hash) => { - const postfix = `${accessorToObjectAccess([].concat(this.property))}`; - return new ConcatSource(source, postfix); - }; - - for (const template of [mainTemplate, chunkTemplate]) { - template.hooks.renderWithEntry.tap( - "ExportPropertyMainTemplatePlugin", - onRenderWithEntry + render(hash, chunk, moduleTemplate, dependencyTemplates) { + const buf = this.renderBootstrap( + hash, + chunk, + moduleTemplate, + dependencyTemplates + ); + let source = this.hooks.render.call( + new OriginalSource( + Template.prefix(buf, " \t") + "\n", + "webpack/bootstrap" + ), + chunk, + hash, + moduleTemplate, + dependencyTemplates + ); + if (chunk.hasEntryModule()) { + source = this.hooks.renderWithEntry.call(source, chunk, hash); + } + if (!source) { + throw new Error( + "Compiler error: MainTemplate plugin 'render' should return something" ); } - - mainTemplate.hooks.hash.tap("ExportPropertyMainTemplatePlugin", hash => { - hash.update("export property"); - hash.update(`${this.property}`); - }); + chunk.rendered = true; + return new ConcatSource(source, ";"); } -} - -module.exports = ExportPropertyMainTemplatePlugin; - -/***/ }), - -/***/ 17270: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * + * @param {string} hash hash for render fn + * @param {Chunk} chunk Chunk instance for require + * @param {(number|string)=} varModuleId module id + * @returns {TODO} the moduleRequire hook call return signature + */ + renderRequireFunctionForModule(hash, chunk, varModuleId) { + return this.hooks.moduleRequire.call( + this.requireFn, + chunk, + hash, + varModuleId + ); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * + * @param {string} hash hash for render add fn + * @param {Chunk} chunk Chunk instance for require add fn + * @param {(string|number)=} varModuleId module id + * @param {Module} varModule Module instance + * @returns {TODO} renderAddModule call + */ + renderAddModule(hash, chunk, varModuleId, varModule) { + return this.hooks.addModule.call( + `modules[${varModuleId}] = ${varModule};`, + chunk, + hash, + varModuleId, + varModule + ); + } + /** + * + * @param {string} hash string hash + * @param {number=} length length + * @returns {string} call hook return + */ + renderCurrentHashCode(hash, length) { + length = length || Infinity; + return this.hooks.currentHash.call( + JSON.stringify(hash.substr(0, length)), + length + ); + } -const Template = __webpack_require__(96066); -const ConstDependency = __webpack_require__(71101); -const ParserHelpers = __webpack_require__(23999); -const NullFactory = __webpack_require__(40438); + /** + * + * @param {object} options get public path options + * @returns {string} hook call + */ + getPublicPath(options) { + return this.hooks.assetPath.call( + this.outputOptions.publicPath || "", + options + ); + } -const REPLACEMENTS = { - // eslint-disable-next-line camelcase - __webpack_hash__: "__webpack_require__.h", - // eslint-disable-next-line camelcase - __webpack_chunkname__: "__webpack_require__.cn" -}; -const REPLACEMENT_TYPES = { - // eslint-disable-next-line camelcase - __webpack_hash__: "string", - // eslint-disable-next-line camelcase - __webpack_chunkname__: "string" -}; + getAssetPath(path, options) { + return this.hooks.assetPath.call(path, options); + } -class ExtendedAPIPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "ExtendedAPIPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set(ConstDependency, new NullFactory()); - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); + getAssetPathWithInfo(path, options) { + const assetInfo = {}; + // TODO webpack 5: refactor assetPath hook to receive { path, info } object + const newPath = this.hooks.assetPath.call(path, options, assetInfo); + return { path: newPath, info: assetInfo }; + } - const mainTemplate = compilation.mainTemplate; - mainTemplate.hooks.requireExtensions.tap( - "ExtendedAPIPlugin", - (source, chunk, hash) => { - const buf = [source]; - buf.push(""); - buf.push("// __webpack_hash__"); - buf.push(`${mainTemplate.requireFn}.h = ${JSON.stringify(hash)};`); - buf.push(""); - buf.push("// __webpack_chunkname__"); - buf.push( - `${mainTemplate.requireFn}.cn = ${JSON.stringify(chunk.name)};` - ); - return Template.asString(buf); - } - ); - mainTemplate.hooks.globalHash.tap("ExtendedAPIPlugin", () => true); + /** + * Updates hash with information from this template + * @param {Hash} hash the hash to update + * @returns {void} + */ + updateHash(hash) { + hash.update("maintemplate"); + hash.update("3"); + this.hooks.hash.call(hash); + } - const handler = (parser, parserOptions) => { - Object.keys(REPLACEMENTS).forEach(key => { - parser.hooks.expression - .for(key) - .tap( - "ExtendedAPIPlugin", - ParserHelpers.toConstantDependencyWithWebpackRequire( - parser, - REPLACEMENTS[key] - ) - ); - parser.hooks.evaluateTypeof - .for(key) - .tap( - "ExtendedAPIPlugin", - ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]) - ); - }); - }; + /** + * TODO webpack 5: remove moduleTemplate and dependencyTemplates + * Updates hash with chunk-specific information from this template + * @param {Hash} hash the hash to update + * @param {Chunk} chunk the chunk + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render + * @param {Map} dependencyTemplates dependency templates + * @returns {void} + */ + updateHashForChunk(hash, chunk, moduleTemplate, dependencyTemplates) { + this.updateHash(hash); + this.hooks.hashForChunk.call(hash, chunk); + for (const line of this.renderBootstrap( + "0000", + chunk, + moduleTemplate, + dependencyTemplates + )) { + hash.update(line); + } + } - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("ExtendedAPIPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("ExtendedAPIPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("ExtendedAPIPlugin", handler); - } - ); + useChunkHash(chunk) { + const paths = this.hooks.globalHashPaths.call([]); + return !this.hooks.globalHash.call(chunk, paths); } -} +}; -module.exports = ExtendedAPIPlugin; + +/***/ }), + +/***/ 50332: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +module.exports = __webpack_require__(32327); /***/ }), -/***/ 17204: +/***/ 75993: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -78682,302 +78913,440 @@ module.exports = ExtendedAPIPlugin; */ -const { OriginalSource, RawSource } = __webpack_require__(53665); -const Module = __webpack_require__(75993); -const WebpackMissingModule = __webpack_require__(75386); +const util = __webpack_require__(31669); + +const DependenciesBlock = __webpack_require__(16071); +const ModuleReason = __webpack_require__(44576); +const SortableSet = __webpack_require__(50071); const Template = __webpack_require__(96066); +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./RequestShortener")} RequestShortener */ +/** @typedef {import("./WebpackError")} WebpackError */ /** @typedef {import("./util/createHash").Hash} Hash */ -class ExternalModule extends Module { - constructor(request, type, userRequest) { - super("javascript/dynamic", null); +const EMPTY_RESOLVE_OPTIONS = {}; + +let debugId = 1000; + +const sortById = (a, b) => { + return a.id - b.id; +}; + +const sortByDebugId = (a, b) => { + return a.debugId - b.debugId; +}; + +/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ + +class Module extends DependenciesBlock { + constructor(type, context = null) { + super(); + /** @type {string} */ + this.type = type; + /** @type {string} */ + this.context = context; + + // Unique Id + /** @type {number} */ + this.debugId = debugId++; + + // Hash + /** @type {string} */ + this.hash = undefined; + /** @type {string} */ + this.renderedHash = undefined; // Info from Factory - this.request = request; - this.externalType = type; - this.userRequest = userRequest; - this.external = true; + /** @type {TODO} */ + this.resolveOptions = EMPTY_RESOLVE_OPTIONS; + /** @type {object} */ + this.factoryMeta = {}; + + // Info from Build + /** @type {WebpackError[]} */ + this.warnings = []; + /** @type {WebpackError[]} */ + this.errors = []; + /** @type {object} */ + this.buildMeta = undefined; + /** @type {object} */ + this.buildInfo = undefined; + + // Graph (per Compilation) + /** @type {ModuleReason[]} */ + this.reasons = []; + /** @type {SortableSet} */ + this._chunks = new SortableSet(undefined, sortById); + + // Info from Compilation (per Compilation) + /** @type {number|string} */ + this.id = null; + /** @type {number} */ + this.index = null; + /** @type {number} */ + this.index2 = null; + /** @type {number} */ + this.depth = null; + /** @type {Module} */ + this.issuer = null; + /** @type {undefined | object} */ + this.profile = undefined; + /** @type {boolean} */ + this.prefetched = false; + /** @type {boolean} */ + this.built = false; + + // Info from Optimization (per Compilation) + /** @type {null | boolean} */ + this.used = null; + /** @type {false | true | string[]} */ + this.usedExports = null; + /** @type {(string | OptimizationBailoutFunction)[]} */ + this.optimizationBailout = []; + + // delayed operations + /** @type {undefined | {oldChunk: Chunk, newChunks: Chunk[]}[] } */ + this._rewriteChunkInReasons = undefined; + + /** @type {boolean} */ + this.useSourceMap = false; + + // info from build + this._source = null; } - libIdent() { - return this.userRequest; + get exportsArgument() { + return (this.buildInfo && this.buildInfo.exportsArgument) || "exports"; } - chunkCondition(chunk) { - return chunk.hasEntryModule(); + get moduleArgument() { + return (this.buildInfo && this.buildInfo.moduleArgument) || "module"; } - identifier() { - return "external " + JSON.stringify(this.request); + disconnect() { + this.hash = undefined; + this.renderedHash = undefined; + + this.reasons.length = 0; + this._rewriteChunkInReasons = undefined; + this._chunks.clear(); + + this.id = null; + this.index = null; + this.index2 = null; + this.depth = null; + this.issuer = null; + this.profile = undefined; + this.prefetched = false; + this.built = false; + + this.used = null; + this.usedExports = null; + this.optimizationBailout.length = 0; + super.disconnect(); } - readableIdentifier() { - return "external " + JSON.stringify(this.request); + unseal() { + this.id = null; + this.index = null; + this.index2 = null; + this.depth = null; + this._chunks.clear(); + super.unseal(); } - needRebuild() { - return false; + setChunks(chunks) { + this._chunks = new SortableSet(chunks, sortById); } - build(options, compilation, resolver, fs, callback) { - this.built = true; - this.buildMeta = {}; - this.buildInfo = {}; - callback(); + addChunk(chunk) { + if (this._chunks.has(chunk)) return false; + this._chunks.add(chunk); + return true; } - getSourceForGlobalVariableExternal(variableName, type) { - if (!Array.isArray(variableName)) { - // make it an array as the look up works the same basically - variableName = [variableName]; + removeChunk(chunk) { + if (this._chunks.delete(chunk)) { + chunk.removeModule(this); + return true; } + return false; + } - // needed for e.g. window["some"]["thing"] - const objectLookup = variableName - .map(r => `[${JSON.stringify(r)}]`) - .join(""); - return `(function() { module.exports = ${type}${objectLookup}; }());`; + isInChunk(chunk) { + return this._chunks.has(chunk); } - getSourceForCommonJsExternal(moduleAndSpecifiers) { - if (!Array.isArray(moduleAndSpecifiers)) { - return `module.exports = require(${JSON.stringify( - moduleAndSpecifiers - )});`; + isEntryModule() { + for (const chunk of this._chunks) { + if (chunk.entryModule === this) return true; } + return false; + } - const moduleName = moduleAndSpecifiers[0]; - const objectLookup = moduleAndSpecifiers - .slice(1) - .map(r => `[${JSON.stringify(r)}]`) - .join(""); - return `module.exports = require(${JSON.stringify( - moduleName - )})${objectLookup};`; + get optional() { + return ( + this.reasons.length > 0 && + this.reasons.every(r => r.dependency && r.dependency.optional) + ); } - checkExternalVariable(variableToCheck, request) { - return `if(typeof ${variableToCheck} === 'undefined') {${WebpackMissingModule.moduleCode( - request - )}}\n`; + /** + * @returns {Chunk[]} all chunks which contain the module + */ + getChunks() { + return Array.from(this._chunks); } - getSourceForAmdOrUmdExternal(id, optional, request) { - const externalVariable = `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier( - `${id}` - )}__`; - const missingModuleError = optional - ? this.checkExternalVariable(externalVariable, request) - : ""; - return `${missingModuleError}module.exports = ${externalVariable};`; + getNumberOfChunks() { + return this._chunks.size; } - getSourceForDefaultCase(optional, request) { - if (!Array.isArray(request)) { - // make it an array as the look up works the same basically - request = [request]; + get chunksIterable() { + return this._chunks; + } + + hasEqualsChunks(otherModule) { + if (this._chunks.size !== otherModule._chunks.size) return false; + this._chunks.sortWith(sortByDebugId); + otherModule._chunks.sortWith(sortByDebugId); + const a = this._chunks[Symbol.iterator](); + const b = otherModule._chunks[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = a.next(); + const bItem = b.next(); + if (aItem.done) return true; + if (aItem.value !== bItem.value) return false; } + } - const variableName = request[0]; - const missingModuleError = optional - ? this.checkExternalVariable(variableName, request.join(".")) - : ""; - const objectLookup = request - .slice(1) - .map(r => `[${JSON.stringify(r)}]`) - .join(""); - return `${missingModuleError}module.exports = ${variableName}${objectLookup};`; + addReason(module, dependency, explanation) { + this.reasons.push(new ModuleReason(module, dependency, explanation)); } - getSourceString(runtime) { - const request = - typeof this.request === "object" && !Array.isArray(this.request) - ? this.request[this.externalType] - : this.request; - switch (this.externalType) { - case "this": - case "window": - case "self": - return this.getSourceForGlobalVariableExternal( - request, - this.externalType - ); - case "global": - return this.getSourceForGlobalVariableExternal( - request, - runtime.outputOptions.globalObject - ); - case "commonjs": - case "commonjs2": - return this.getSourceForCommonJsExternal(request); - case "amd": - case "amd-require": - case "umd": - case "umd2": - case "system": - return this.getSourceForAmdOrUmdExternal( - this.id, - this.optional, - request - ); - default: - return this.getSourceForDefaultCase(this.optional, request); + removeReason(module, dependency) { + for (let i = 0; i < this.reasons.length; i++) { + let r = this.reasons[i]; + if (r.module === module && r.dependency === dependency) { + this.reasons.splice(i, 1); + return true; + } } + return false; } - getSource(sourceString) { - if (this.useSourceMap) { - return new OriginalSource(sourceString, this.identifier()); + hasReasonForChunk(chunk) { + if (this._rewriteChunkInReasons) { + for (const operation of this._rewriteChunkInReasons) { + this._doRewriteChunkInReasons(operation.oldChunk, operation.newChunks); + } + this._rewriteChunkInReasons = undefined; } + for (let i = 0; i < this.reasons.length; i++) { + if (this.reasons[i].hasChunk(chunk)) return true; + } + return false; + } - return new RawSource(sourceString); + hasReasons() { + return this.reasons.length > 0; } - source(dependencyTemplates, runtime) { - return this.getSource(this.getSourceString(runtime)); + rewriteChunkInReasons(oldChunk, newChunks) { + // This is expensive. Delay operation until we really need the data + if (this._rewriteChunkInReasons === undefined) { + this._rewriteChunkInReasons = []; + } + this._rewriteChunkInReasons.push({ + oldChunk, + newChunks + }); } - size() { - return 42; + _doRewriteChunkInReasons(oldChunk, newChunks) { + for (let i = 0; i < this.reasons.length; i++) { + this.reasons[i].rewriteChunks(oldChunk, newChunks); + } } /** - * @param {Hash} hash the hash used to track dependencies - * @returns {void} + * @param {string=} exportName the name of the export + * @returns {boolean|string} false if the export isn't used, true if no exportName is provided and the module is used, or the name to access it if the export is used */ - updateHash(hash) { - hash.update(this.externalType); - hash.update(JSON.stringify(this.request)); - hash.update(JSON.stringify(Boolean(this.optional))); - super.updateHash(hash); - } -} - -module.exports = ExternalModule; - - -/***/ }), + isUsed(exportName) { + if (!exportName) return this.used !== false; + if (this.used === null || this.usedExports === null) return exportName; + if (!this.used) return false; + if (!this.usedExports) return false; + if (this.usedExports === true) return exportName; + let idx = this.usedExports.indexOf(exportName); + if (idx < 0) return false; -/***/ 67876: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Mangle export name if possible + if (this.isProvided(exportName)) { + if (this.buildMeta.exportsType === "namespace") { + return Template.numberToIdentifer(idx); + } + if ( + this.buildMeta.exportsType === "named" && + !this.usedExports.includes("default") + ) { + return Template.numberToIdentifer(idx); + } + } + return exportName; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + isProvided(exportName) { + if (!Array.isArray(this.buildMeta.providedExports)) return null; + return this.buildMeta.providedExports.includes(exportName); + } + toString() { + return `Module[${this.id || this.debugId}]`; + } -const ExternalModule = __webpack_require__(17204); + needRebuild(fileTimestamps, contextTimestamps) { + return true; + } -class ExternalModuleFactoryPlugin { - constructor(type, externals) { - this.type = type; - this.externals = externals; + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update(`${this.id}`); + hash.update(JSON.stringify(this.usedExports)); + super.updateHash(hash); } - apply(normalModuleFactory) { - const globalType = this.type; - normalModuleFactory.hooks.factory.tap( - "ExternalModuleFactoryPlugin", - factory => (data, callback) => { - const context = data.context; - const dependency = data.dependencies[0]; + sortItems(sortChunks) { + super.sortItems(); + if (sortChunks) this._chunks.sort(); + this.reasons.sort((a, b) => { + if (a.module === b.module) return 0; + if (!a.module) return -1; + if (!b.module) return 1; + return sortById(a.module, b.module); + }); + if (Array.isArray(this.usedExports)) { + this.usedExports.sort(); + } + } - const handleExternal = (value, type, callback) => { - if (typeof type === "function") { - callback = type; - type = undefined; - } - if (value === false) return factory(data, callback); - if (value === true) value = dependency.request; - if (type === undefined && /^[a-z0-9]+ /.test(value)) { - const idx = value.indexOf(" "); - type = value.substr(0, idx); - value = value.substr(idx + 1); - } - callback( - null, - new ExternalModule(value, type || globalType, dependency.request) - ); - return true; - }; + unbuild() { + this.dependencies.length = 0; + this.blocks.length = 0; + this.variables.length = 0; + this.buildMeta = undefined; + this.buildInfo = undefined; + this.disconnect(); + } - const handleExternals = (externals, callback) => { - if (typeof externals === "string") { - if (externals === dependency.request) { - return handleExternal(dependency.request, callback); - } - } else if (Array.isArray(externals)) { - let i = 0; - const next = () => { - let asyncFlag; - const handleExternalsAndCallback = (err, module) => { - if (err) return callback(err); - if (!module) { - if (asyncFlag) { - asyncFlag = false; - return; - } - return next(); - } - callback(null, module); - }; + get arguments() { + throw new Error("Module.arguments was removed, there is no replacement."); + } - do { - asyncFlag = true; - if (i >= externals.length) return callback(); - handleExternals(externals[i++], handleExternalsAndCallback); - } while (!asyncFlag); - asyncFlag = false; - }; + set arguments(value) { + throw new Error("Module.arguments was removed, there is no replacement."); + } +} - next(); - return; - } else if (externals instanceof RegExp) { - if (externals.test(dependency.request)) { - return handleExternal(dependency.request, callback); - } - } else if (typeof externals === "function") { - externals.call( - null, - context, - dependency.request, - (err, value, type) => { - if (err) return callback(err); - if (value !== undefined) { - handleExternal(value, type, callback); - } else { - callback(); - } - } - ); - return; - } else if ( - typeof externals === "object" && - Object.prototype.hasOwnProperty.call(externals, dependency.request) - ) { - return handleExternal(externals[dependency.request], callback); - } - callback(); - }; +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "forEachChunk", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @param {function(any, any, Set): void} fn callback function + * @returns {void} + * @this {Module} + */ + function(fn) { + this._chunks.forEach(fn); + }, + "Module.forEachChunk: Use for(const chunk of module.chunksIterable) instead" + ) +}); - handleExternals(this.externals, (err, module) => { - if (err) return callback(err); - if (!module) return handleExternal(false, callback); - return callback(null, module); - }); - } - ); +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "mapChunks", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @param {function(any, any): void} fn Mapper function + * @returns {Array} Array of chunks mapped + * @this {Module} + */ + function(fn) { + return Array.from(this._chunks, fn); + }, + "Module.mapChunks: Use Array.from(module.chunksIterable, fn) instead" + ) +}); + +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "entry", { + configurable: false, + get() { + throw new Error("Module.entry was removed. Use Chunk.entryModule"); + }, + set() { + throw new Error("Module.entry was removed. Use Chunk.entryModule"); } -} -module.exports = ExternalModuleFactoryPlugin; +}); + +// TODO remove in webpack 5 +Object.defineProperty(Module.prototype, "meta", { + configurable: false, + get: util.deprecate( + /** + * @deprecated + * @returns {void} + * @this {Module} + */ + function() { + return this.buildMeta; + }, + "Module.meta was renamed to Module.buildMeta" + ), + set: util.deprecate( + /** + * @deprecated + * @param {TODO} value Value + * @returns {void} + * @this {Module} + */ + function(value) { + this.buildMeta = value; + }, + "Module.meta was renamed to Module.buildMeta" + ) +}); + +/** @type {function(): string} */ +Module.prototype.identifier = null; + +/** @type {function(RequestShortener): string} */ +Module.prototype.readableIdentifier = null; + +Module.prototype.build = null; +Module.prototype.source = null; +Module.prototype.size = null; +Module.prototype.nameForCondition = null; +/** @type {null | function(Chunk): boolean} */ +Module.prototype.chunkCondition = null; +Module.prototype.updateCacheModule = null; + +module.exports = Module; /***/ }), -/***/ 75705: +/***/ 12072: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -78987,29 +79356,58 @@ module.exports = ExternalModuleFactoryPlugin; */ -const ExternalModuleFactoryPlugin = __webpack_require__(67876); +const WebpackError = __webpack_require__(97391); +const { cutOffLoaderExecution } = __webpack_require__(80140); -class ExternalsPlugin { - constructor(type, externals) { - this.type = type; - this.externals = externals; - } - apply(compiler) { - compiler.hooks.compile.tap("ExternalsPlugin", ({ normalModuleFactory }) => { - new ExternalModuleFactoryPlugin(this.type, this.externals).apply( - normalModuleFactory - ); - }); +class ModuleBuildError extends WebpackError { + constructor(module, err, { from = null } = {}) { + let message = "Module build failed"; + let details = undefined; + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } + if (err !== null && typeof err === "object") { + if (typeof err.stack === "string" && err.stack) { + const stack = cutOffLoaderExecution(err.stack); + if (!err.hideStack) { + message += stack; + } else { + details = stack; + if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += err; + } + } + } else if (typeof err.message === "string" && err.message) { + message += err.message; + } else { + message += err; + } + } else { + message = err; + } + + super(message); + + this.name = "ModuleBuildError"; + this.details = details; + this.module = module; + this.error = err; + + Error.captureStackTrace(this, this.constructor); } } -module.exports = ExternalsPlugin; +module.exports = ModuleBuildError; /***/ }), -/***/ 47163: -/***/ (function(module) { +/***/ 14953: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -79018,43 +79416,40 @@ module.exports = ExternalsPlugin; */ +const WebpackError = __webpack_require__(97391); -/** @typedef {import("./Compiler")} Compiler */ - -class FlagAllModulesAsUsedPlugin { - constructor(explanation) { - this.explanation = explanation; - } +/** @typedef {import("./Module")} Module */ +class ModuleDependencyError extends WebpackError { /** - * @param {Compiler} compiler webpack compiler - * @returns {void} + * Creates an instance of ModuleDependencyError. + * @param {Module} module module tied to dependency + * @param {Error} err error thrown + * @param {TODO} loc location of dependency */ - apply(compiler) { - compiler.hooks.compilation.tap( - "FlagAllModulesAsUsedPlugin", - compilation => { - compilation.hooks.optimizeDependencies.tap( - "FlagAllModulesAsUsedPlugin", - modules => { - for (const module of modules) { - module.used = true; - module.usedExports = true; - module.addReason(null, null, this.explanation); - } - } - ); - } - ); + constructor(module, err, loc) { + super(err.message); + + this.name = "ModuleDependencyError"; + this.details = err.stack + .split("\n") + .slice(1) + .join("\n"); + this.module = module; + this.loc = loc; + this.error = err; + this.origin = module.issuer; + + Error.captureStackTrace(this, this.constructor); } } -module.exports = FlagAllModulesAsUsedPlugin; +module.exports = ModuleDependencyError; /***/ }), -/***/ 73599: +/***/ 59136: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -79064,180 +79459,75 @@ module.exports = FlagAllModulesAsUsedPlugin; */ -const Queue = __webpack_require__(38637); +const WebpackError = __webpack_require__(97391); -const addToSet = (a, b) => { - for (const item of b) { - a.add(item); +module.exports = class ModuleDependencyWarning extends WebpackError { + constructor(module, err, loc) { + super(err.message); + + this.name = "ModuleDependencyWarning"; + this.details = err.stack + .split("\n") + .slice(1) + .join("\n"); + this.module = module; + this.loc = loc; + this.error = err; + this.origin = module.issuer; + + Error.captureStackTrace(this, this.constructor); } }; -class FlagDependencyExportsPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "FlagDependencyExportsPlugin", - compilation => { - compilation.hooks.finishModules.tap( - "FlagDependencyExportsPlugin", - modules => { - const dependencies = new Map(); - const queue = new Queue(); +/***/ }), - let module; - let moduleWithExports; - let moduleProvidedExports; - let providedExportsAreTemporary; +/***/ 82528: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const processDependenciesBlock = depBlock => { - for (const dep of depBlock.dependencies) { - if (processDependency(dep)) return true; - } - for (const variable of depBlock.variables) { - for (const dep of variable.dependencies) { - if (processDependency(dep)) return true; - } - } - for (const block of depBlock.blocks) { - if (processDependenciesBlock(block)) return true; - } - return false; - }; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const processDependency = dep => { - const exportDesc = dep.getExports && dep.getExports(); - if (!exportDesc) return; - moduleWithExports = true; - const exports = exportDesc.exports; - // break early if it's only in the worst state - if (module.buildMeta.providedExports === true) { - return true; - } - // break if it should move to the worst state - if (exports === true) { - module.buildMeta.providedExports = true; - return true; - } - // merge in new exports - if (Array.isArray(exports)) { - addToSet(moduleProvidedExports, exports); - } - // store dependencies - const exportDeps = exportDesc.dependencies; - if (exportDeps) { - providedExportsAreTemporary = true; - for (const exportDependency of exportDeps) { - // add dependency for this module - const set = dependencies.get(exportDependency); - if (set === undefined) { - dependencies.set(exportDependency, new Set([module])); - } else { - set.add(module); - } - } - } - return false; - }; - const notifyDependencies = () => { - const deps = dependencies.get(module); - if (deps !== undefined) { - for (const dep of deps) { - queue.enqueue(dep); - } - } - }; +const WebpackError = __webpack_require__(97391); +const { cleanUp } = __webpack_require__(80140); - const notifyDependenciesIfDifferent = (set, array) => { - const deps = dependencies.get(module); - if (deps !== undefined) { - if (set.size === array.length) { - let i = 0; - let different = false; - for (const item of set) { - if (item !== array[i++]) { - different = true; - break; - } - } - if (!different) return; - } - for (const dep of deps) { - queue.enqueue(dep); - } - } - }; +class ModuleError extends WebpackError { + constructor(module, err, { from = null } = {}) { + let message = "Module Error"; + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } + if (err && typeof err === "object" && err.message) { + message += err.message; + } else if (err) { + message += err; + } + super(message); + this.name = "ModuleError"; + this.module = module; + this.error = err; + this.details = + err && typeof err === "object" && err.stack + ? cleanUp(err.stack, this.message) + : undefined; - // Start with all modules without provided exports - for (const module of modules) { - if (module.buildInfo.temporaryProvidedExports) { - // Clear exports when they are temporary - // and recreate them - module.buildMeta.providedExports = null; - queue.enqueue(module); - } else if (!module.buildMeta.providedExports) { - queue.enqueue(module); - } - } - - while (queue.length > 0) { - module = queue.dequeue(); - - if (module.buildMeta.providedExports !== true) { - moduleWithExports = - module.buildMeta && module.buildMeta.exportsType; - moduleProvidedExports = new Set(); - providedExportsAreTemporary = false; - processDependenciesBlock(module); - module.buildInfo.temporaryProvidedExports = providedExportsAreTemporary; - if (!moduleWithExports) { - notifyDependencies(); - module.buildMeta.providedExports = true; - } else if (module.buildMeta.providedExports === true) { - notifyDependencies(); - } else if (!module.buildMeta.providedExports) { - notifyDependencies(); - module.buildMeta.providedExports = Array.from( - moduleProvidedExports - ); - } else { - notifyDependenciesIfDifferent( - moduleProvidedExports, - module.buildMeta.providedExports - ); - module.buildMeta.providedExports = Array.from( - moduleProvidedExports - ); - } - } - } - } - ); - const providedExportsCache = new WeakMap(); - compilation.hooks.rebuildModule.tap( - "FlagDependencyExportsPlugin", - module => { - providedExportsCache.set(module, module.buildMeta.providedExports); - } - ); - compilation.hooks.finishRebuildingModule.tap( - "FlagDependencyExportsPlugin", - module => { - module.buildMeta.providedExports = providedExportsCache.get(module); - } - ); - } - ); + Error.captureStackTrace(this, this.constructor); } } -module.exports = FlagDependencyExportsPlugin; +module.exports = ModuleError; /***/ }), -/***/ 33632: -/***/ (function(module) { +/***/ 71474: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -79246,121 +79536,184 @@ module.exports = FlagDependencyExportsPlugin; */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +const createHash = __webpack_require__(15660); -/** @typedef {false | true | string[]} UsedExports */ +const ModuleFilenameHelpers = exports; -const addToSet = (a, b) => { - for (const item of b) { - if (!a.includes(item)) a.push(item); - } - return a; -}; +ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]"; +ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE = /\[all-?loaders\]\[resource\]/gi; +ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]"; +ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi; +ModuleFilenameHelpers.RESOURCE = "[resource]"; +ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi; +ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]"; +ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH = /\[abs(olute)?-?resource-?path\]/gi; +ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]"; +ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi; +ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]"; +ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi; +ModuleFilenameHelpers.LOADERS = "[loaders]"; +ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi; +ModuleFilenameHelpers.QUERY = "[query]"; +ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi; +ModuleFilenameHelpers.ID = "[id]"; +ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi; +ModuleFilenameHelpers.HASH = "[hash]"; +ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi; +ModuleFilenameHelpers.NAMESPACE = "[namespace]"; +ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi; -const isSubset = (biggerSet, subset) => { - if (biggerSet === true) return true; - if (subset === true) return false; - return subset.every(item => biggerSet.indexOf(item) >= 0); +const getAfter = (str, token) => { + const idx = str.indexOf(token); + return idx < 0 ? "" : str.substr(idx); }; -class FlagDependencyUsagePlugin { - apply(compiler) { - compiler.hooks.compilation.tap("FlagDependencyUsagePlugin", compilation => { - compilation.hooks.optimizeDependencies.tap( - "FlagDependencyUsagePlugin", - modules => { - const processModule = (module, usedExports) => { - module.used = true; - if (module.usedExports === true) return; - if (usedExports === true) { - module.usedExports = true; - } else if (Array.isArray(usedExports)) { - const old = module.usedExports ? module.usedExports.length : -1; - module.usedExports = addToSet( - module.usedExports || [], - usedExports - ); - if (module.usedExports.length === old) { - return; - } - } else if (Array.isArray(module.usedExports)) { - return; - } else { - module.usedExports = false; - } +const getBefore = (str, token) => { + const idx = str.lastIndexOf(token); + return idx < 0 ? "" : str.substr(0, idx); +}; - // for a module without side effects we stop tracking usage here when no export is used - // This module won't be evaluated in this case - if (module.factoryMeta.sideEffectFree) { - if (module.usedExports === false) return; - if ( - Array.isArray(module.usedExports) && - module.usedExports.length === 0 - ) - return; - } +const getHash = str => { + const hash = createHash("md4"); + hash.update(str); + const digest = /** @type {string} */ (hash.digest("hex")); + return digest.substr(0, 4); +}; - queue.push([module, module, module.usedExports]); - }; +const asRegExp = test => { + if (typeof test === "string") { + test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); + } + return test; +}; - const processDependenciesBlock = (module, depBlock, usedExports) => { - for (const dep of depBlock.dependencies) { - processDependency(module, dep); - } - for (const variable of depBlock.variables) { - for (const dep of variable.dependencies) { - processDependency(module, dep); - } - } - for (const block of depBlock.blocks) { - queue.push([module, block, usedExports]); - } - }; +ModuleFilenameHelpers.createFilename = (module, options, requestShortener) => { + const opts = Object.assign( + { + namespace: "", + moduleFilenameTemplate: "" + }, + typeof options === "object" + ? options + : { + moduleFilenameTemplate: options + } + ); - const processDependency = (module, dep) => { - const reference = compilation.getDependencyReference(module, dep); - if (!reference) return; - const referenceModule = reference.module; - const importedNames = reference.importedNames; - const oldUsed = referenceModule.used; - const oldUsedExports = referenceModule.usedExports; - if ( - !oldUsed || - (importedNames && - (!oldUsedExports || !isSubset(oldUsedExports, importedNames))) - ) { - processModule(referenceModule, importedNames); - } - }; + let absoluteResourcePath; + let hash; + let identifier; + let moduleId; + let shortIdentifier; + if (module === undefined) module = ""; + if (typeof module === "string") { + shortIdentifier = requestShortener.shorten(module); + identifier = shortIdentifier; + moduleId = ""; + absoluteResourcePath = module.split("!").pop(); + hash = getHash(identifier); + } else { + shortIdentifier = module.readableIdentifier(requestShortener); + identifier = requestShortener.shorten(module.identifier()); + moduleId = module.id; + absoluteResourcePath = module + .identifier() + .split("!") + .pop(); + hash = getHash(identifier); + } + const resource = shortIdentifier.split("!").pop(); + const loaders = getBefore(shortIdentifier, "!"); + const allLoaders = getBefore(identifier, "!"); + const query = getAfter(resource, "?"); + const resourcePath = resource.substr(0, resource.length - query.length); + if (typeof opts.moduleFilenameTemplate === "function") { + return opts.moduleFilenameTemplate({ + identifier: identifier, + shortIdentifier: shortIdentifier, + resource: resource, + resourcePath: resourcePath, + absoluteResourcePath: absoluteResourcePath, + allLoaders: allLoaders, + query: query, + moduleId: moduleId, + hash: hash, + namespace: opts.namespace + }); + } + return opts.moduleFilenameTemplate + .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, identifier) + .replace(ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE, shortIdentifier) + .replace(ModuleFilenameHelpers.REGEXP_RESOURCE, resource) + .replace(ModuleFilenameHelpers.REGEXP_RESOURCE_PATH, resourcePath) + .replace( + ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH, + absoluteResourcePath + ) + .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS, allLoaders) + .replace(ModuleFilenameHelpers.REGEXP_LOADERS, loaders) + .replace(ModuleFilenameHelpers.REGEXP_QUERY, query) + .replace(ModuleFilenameHelpers.REGEXP_ID, moduleId) + .replace(ModuleFilenameHelpers.REGEXP_HASH, hash) + .replace(ModuleFilenameHelpers.REGEXP_NAMESPACE, opts.namespace); +}; - for (const module of modules) { - if (!module.used) module.used = false; - } +ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => { + const countMap = Object.create(null); + const posMap = Object.create(null); + array.forEach((item, idx) => { + countMap[item] = countMap[item] || []; + countMap[item].push(idx); + posMap[item] = 0; + }); + if (comparator) { + Object.keys(countMap).forEach(item => { + countMap[item].sort(comparator); + }); + } + return array.map((item, i) => { + if (countMap[item].length > 1) { + if (comparator && countMap[item][0] === i) return item; + return fn(item, i, posMap[item]++); + } else { + return item; + } + }); +}; - /** @type {[Module, DependenciesBlock, UsedExports][]} */ - const queue = []; - for (const preparedEntrypoint of compilation._preparedEntrypoints) { - if (preparedEntrypoint.module) { - processModule(preparedEntrypoint.module, true); - } - } +ModuleFilenameHelpers.matchPart = (str, test) => { + if (!test) return true; + test = asRegExp(test); + if (Array.isArray(test)) { + return test.map(asRegExp).some(regExp => regExp.test(str)); + } else { + return test.test(str); + } +}; - while (queue.length) { - const queueItem = queue.pop(); - processDependenciesBlock(queueItem[0], queueItem[1], queueItem[2]); - } - } - ); - }); +ModuleFilenameHelpers.matchObject = (obj, str) => { + if (obj.test) { + if (!ModuleFilenameHelpers.matchPart(str, obj.test)) { + return false; + } } -} -module.exports = FlagDependencyUsagePlugin; + if (obj.include) { + if (!ModuleFilenameHelpers.matchPart(str, obj.include)) { + return false; + } + } + if (obj.exclude) { + if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) { + return false; + } + } + return true; +}; /***/ }), -/***/ 31221: +/***/ 71638: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -79370,24 +79723,28 @@ module.exports = FlagDependencyUsagePlugin; */ -const FunctionModuleTemplatePlugin = __webpack_require__(18864); +const WebpackError = __webpack_require__(97391); -class FunctionModulePlugin { - apply(compiler) { - compiler.hooks.compilation.tap("FunctionModulePlugin", compilation => { - new FunctionModuleTemplatePlugin().apply( - compilation.moduleTemplates.javascript - ); - }); +class ModuleNotFoundError extends WebpackError { + constructor(module, err) { + super("Module not found: " + err); + + this.name = "ModuleNotFoundError"; + this.details = err.details; + this.missing = err.missing; + this.module = module; + this.error = err; + + Error.captureStackTrace(this, this.constructor); } } -module.exports = FunctionModulePlugin; +module.exports = ModuleNotFoundError; /***/ }), -/***/ 18864: +/***/ 62500: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -79397,107 +79754,72 @@ module.exports = FunctionModulePlugin; */ -const { ConcatSource } = __webpack_require__(53665); -const Template = __webpack_require__(96066); +const WebpackError = __webpack_require__(97391); -class FunctionModuleTemplatePlugin { - apply(moduleTemplate) { - moduleTemplate.hooks.render.tap( - "FunctionModuleTemplatePlugin", - (moduleSource, module) => { - const source = new ConcatSource(); - const args = [module.moduleArgument]; - // TODO remove HACK checking type for javascript - if (module.type && module.type.startsWith("javascript")) { - args.push(module.exportsArgument); - if (module.hasDependencies(d => d.requireWebpackRequire !== false)) { - args.push("__webpack_require__"); - } - } else if (module.type && module.type.startsWith("json")) { - // no additional arguments needed - } else { - args.push(module.exportsArgument, "__webpack_require__"); - } - source.add("/***/ (function(" + args.join(", ") + ") {\n\n"); - if (module.buildInfo.strict) source.add('"use strict";\n'); - source.add(moduleSource); - source.add("\n\n/***/ })"); - return source; - } - ); +/** @typedef {import("./Module")} Module */ - moduleTemplate.hooks.package.tap( - "FunctionModuleTemplatePlugin", - (moduleSource, module) => { - if (moduleTemplate.runtimeTemplate.outputOptions.pathinfo) { - const source = new ConcatSource(); - const req = module.readableIdentifier( - moduleTemplate.runtimeTemplate.requestShortener - ); - const reqStr = req.replace(/\*\//g, "*_/"); - const reqStrStar = "*".repeat(reqStr.length); - source.add("/*!****" + reqStrStar + "****!*\\\n"); - source.add(" !*** " + reqStr + " ***!\n"); - source.add(" \\****" + reqStrStar + "****/\n"); - if ( - Array.isArray(module.buildMeta.providedExports) && - module.buildMeta.providedExports.length === 0 - ) { - source.add(Template.toComment("no exports provided") + "\n"); - } else if (Array.isArray(module.buildMeta.providedExports)) { - source.add( - Template.toComment( - "exports provided: " + - module.buildMeta.providedExports.join(", ") - ) + "\n" - ); - } else if (module.buildMeta.providedExports) { - source.add(Template.toComment("no static exports found") + "\n"); - } - if ( - Array.isArray(module.usedExports) && - module.usedExports.length === 0 - ) { - source.add(Template.toComment("no exports used") + "\n"); - } else if (Array.isArray(module.usedExports)) { - source.add( - Template.toComment( - "exports used: " + module.usedExports.join(", ") - ) + "\n" - ); - } else if (module.usedExports) { - source.add(Template.toComment("all exports used") + "\n"); - } - if (module.optimizationBailout) { - for (const text of module.optimizationBailout) { - let code; - if (typeof text === "function") { - code = text(moduleTemplate.runtimeTemplate.requestShortener); - } else { - code = text; - } - source.add(Template.toComment(`${code}`) + "\n"); - } - } - source.add(moduleSource); - return source; - } - return moduleSource; +class ModuleParseError extends WebpackError { + /** + * @param {Module} module the errored module + * @param {string} source source code + * @param {Error&any} err the parse error + * @param {string[]} loaders the loaders used + */ + constructor(module, source, err, loaders) { + let message = "Module parse failed: " + err.message; + let loc = undefined; + if (loaders.length >= 1) { + message += `\nFile was processed with these loaders:${loaders + .map(loader => `\n * ${loader}`) + .join("")}`; + message += + "\nYou may need an additional loader to handle the result of these loaders."; + } else { + message += + "\nYou may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders"; + } + if ( + err.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" + ) { + var lineNumber = err.loc.line; + if (/[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source)) { + // binary file + message += "\n(Source code omitted for this binary file)"; + } else { + const sourceLines = source.split(/\r?\n/); + const start = Math.max(0, lineNumber - 3); + const linesBefore = sourceLines.slice(start, lineNumber - 1); + const theLine = sourceLines[lineNumber - 1]; + const linesAfter = sourceLines.slice(lineNumber, lineNumber + 2); + message += + linesBefore.map(l => `\n| ${l}`).join("") + + `\n> ${theLine}` + + linesAfter.map(l => `\n| ${l}`).join(""); } - ); + loc = err.loc; + } else { + message += "\n" + err.stack; + } - moduleTemplate.hooks.hash.tap("FunctionModuleTemplatePlugin", hash => { - hash.update("FunctionModuleTemplatePlugin"); - hash.update("2"); - }); + super(message); + + this.name = "ModuleParseError"; + this.module = module; + this.loc = loc; + this.error = err; + + Error.captureStackTrace(this, this.constructor); } } -module.exports = FunctionModuleTemplatePlugin; + +module.exports = ModuleParseError; /***/ }), -/***/ 39172: +/***/ 44576: /***/ (function(module) { "use strict"; @@ -79507,162 +79829,198 @@ module.exports = FunctionModuleTemplatePlugin; */ -/** @typedef {import("./NormalModule")} NormalModule */ -/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate */ - -/** - * - */ -class Generator { - static byType(map) { - return new ByTypeGenerator(map); - } +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Dependency")} Dependency */ +class ModuleReason { /** - * @abstract - * @param {NormalModule} module module for which the code should be generated - * @param {Map} dependencyTemplates mapping from dependencies to templates - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {string} type which kind of code should be generated - * @returns {Source} generated code + * @param {Module} module the referencing module + * @param {Dependency} dependency the referencing dependency + * @param {string=} explanation some extra detail */ - generate(module, dependencyTemplates, runtimeTemplate, type) { - throw new Error("Generator.generate: must be overridden"); + constructor(module, dependency, explanation) { + this.module = module; + this.dependency = dependency; + this.explanation = explanation; + this._chunks = null; } -} -class ByTypeGenerator extends Generator { - constructor(map) { - super(); - this.map = map; + hasChunk(chunk) { + if (this._chunks) { + if (this._chunks.has(chunk)) return true; + } else if (this.module && this.module._chunks.has(chunk)) return true; + return false; } - /** - * @param {NormalModule} module module for which the code should be generated - * @param {Map} dependencyTemplates mapping from dependencies to templates - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {string} type which kind of code should be generated - * @returns {Source} generated code - */ - generate(module, dependencyTemplates, runtimeTemplate, type) { - const generator = this.map[type]; - if (!generator) { - throw new Error(`Generator.byType: no generator specified for ${type}`); + rewriteChunks(oldChunk, newChunks) { + if (!this._chunks) { + if (this.module) { + if (!this.module._chunks.has(oldChunk)) return; + this._chunks = new Set(this.module._chunks); + } else { + this._chunks = new Set(); + } + } + if (this._chunks.has(oldChunk)) { + this._chunks.delete(oldChunk); + for (let i = 0; i < newChunks.length; i++) { + this._chunks.add(newChunks[i]); + } } - return generator.generate( - module, - dependencyTemplates, - runtimeTemplate, - type - ); } } -module.exports = Generator; +module.exports = ModuleReason; /***/ }), -/***/ 32973: -/***/ (function(__unused_webpack_module, exports) { +/***/ 75100: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * @param {ChunkGroup} chunkGroup the ChunkGroup to connect - * @param {Chunk} chunk chunk to tie to ChunkGroup - * @returns {void} - */ -const connectChunkGroupAndChunk = (chunkGroup, chunk) => { - if (chunkGroup.pushChunk(chunk)) { - chunk.addGroup(chunkGroup); - } -}; -/** - * @param {ChunkGroup} parent parent ChunkGroup to connect - * @param {ChunkGroup} child child ChunkGroup to connect - * @returns {void} - */ -const connectChunkGroupParentAndChild = (parent, child) => { - if (parent.addChild(child)) { - child.addParent(parent); - } -}; +const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(56758); -/** - * @param {Chunk} chunk Chunk to connect to Module - * @param {Module} module Module to connect to Chunk - * @returns {void} - */ -const connectChunkAndModule = (chunk, module) => { - if (module.addChunk(chunk)) { - chunk.addModule(module); +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Module")} Module */ + +module.exports = class ModuleTemplate extends Tapable { + constructor(runtimeTemplate, type) { + super(); + this.runtimeTemplate = runtimeTemplate; + this.type = type; + this.hooks = { + content: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + module: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + render: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + package: new SyncWaterfallHook([ + "source", + "module", + "options", + "dependencyTemplates" + ]), + hash: new SyncHook(["hash"]) + }; } -}; -/** - * @param {Chunk} chunk Chunk being disconnected - * @param {Module} module Module being disconnected - * @returns {void} - */ -const disconnectChunkAndModule = (chunk, module) => { - chunk.removeModule(module); - module.removeChunk(chunk); -}; + /** + * @param {Module} module the module + * @param {TODO} dependencyTemplates templates for dependencies + * @param {TODO} options render options + * @returns {Source} the source + */ + render(module, dependencyTemplates, options) { + try { + const moduleSource = module.source( + dependencyTemplates, + this.runtimeTemplate, + this.type + ); + const moduleSourcePostContent = this.hooks.content.call( + moduleSource, + module, + options, + dependencyTemplates + ); + const moduleSourcePostModule = this.hooks.module.call( + moduleSourcePostContent, + module, + options, + dependencyTemplates + ); + const moduleSourcePostRender = this.hooks.render.call( + moduleSourcePostModule, + module, + options, + dependencyTemplates + ); + return this.hooks.package.call( + moduleSourcePostRender, + module, + options, + dependencyTemplates + ); + } catch (e) { + e.message = `${module.identifier()}\n${e.message}`; + throw e; + } + } -/** - * @param {AsyncDependenciesBlock} depBlock DepBlock being tied to ChunkGroup - * @param {ChunkGroup} chunkGroup ChunkGroup being tied to DepBlock - * @returns {void} - */ -const connectDependenciesBlockAndChunkGroup = (depBlock, chunkGroup) => { - if (chunkGroup.addBlock(depBlock)) { - depBlock.chunkGroup = chunkGroup; + updateHash(hash) { + hash.update("1"); + this.hooks.hash.call(hash); } }; -exports.connectChunkGroupAndChunk = connectChunkGroupAndChunk; -exports.connectChunkGroupParentAndChild = connectChunkGroupParentAndChild; -exports.connectChunkAndModule = connectChunkAndModule; -exports.disconnectChunkAndModule = disconnectChunkAndModule; -exports.connectDependenciesBlockAndChunkGroup = connectDependenciesBlockAndChunkGroup; - /***/ }), -/***/ 30327: +/***/ 6372: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ const WebpackError = __webpack_require__(97391); +const { cleanUp } = __webpack_require__(80140); -module.exports = class HarmonyLinkingError extends WebpackError { - /** @param {string} message Error message */ - constructor(message) { +class ModuleWarning extends WebpackError { + constructor(module, warning, { from = null } = {}) { + let message = "Module Warning"; + if (from) { + message += ` (from ${from}):\n`; + } else { + message += ": "; + } + if (warning && typeof warning === "object" && warning.message) { + message += warning.message; + } else if (warning) { + message += warning; + } super(message); - this.name = "HarmonyLinkingError"; - this.hideStack = true; + this.name = "ModuleWarning"; + this.module = module; + this.warning = warning; + this.details = + warning && typeof warning === "object" && warning.stack + ? cleanUp(warning.stack, this.message) + : undefined; Error.captureStackTrace(this, this.constructor); } -}; +} + +module.exports = ModuleWarning; /***/ }), -/***/ 50268: +/***/ 10238: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -79671,798 +80029,669 @@ module.exports = class HarmonyLinkingError extends WebpackError { Author Tobias Koppers @sokra */ -const createHash = __webpack_require__(15660); - -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(45843); -/** @typedef {import("../declarations/plugins/HashedModuleIdsPlugin").HashedModuleIdsPluginOptions} HashedModuleIdsPluginOptions */ +const { Tapable, SyncHook, MultiHook } = __webpack_require__(56758); +const asyncLib = __webpack_require__(36386); +const MultiWatching = __webpack_require__(66624); +const MultiStats = __webpack_require__(55144); +const ConcurrentCompilationError = __webpack_require__(18933); -class HashedModuleIdsPlugin { - /** - * @param {HashedModuleIdsPluginOptions=} options options object - */ - constructor(options) { - if (!options) options = {}; +module.exports = class MultiCompiler extends Tapable { + constructor(compilers) { + super(); + this.hooks = { + done: new SyncHook(["stats"]), + invalid: new MultiHook(compilers.map(c => c.hooks.invalid)), + run: new MultiHook(compilers.map(c => c.hooks.run)), + watchClose: new SyncHook([]), + watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)), + infrastructureLog: new MultiHook( + compilers.map(c => c.hooks.infrastructureLog) + ) + }; + if (!Array.isArray(compilers)) { + compilers = Object.keys(compilers).map(name => { + compilers[name].name = name; + return compilers[name]; + }); + } + this.compilers = compilers; + let doneCompilers = 0; + let compilerStats = []; + let index = 0; + for (const compiler of this.compilers) { + let compilerDone = false; + const compilerIndex = index++; + // eslint-disable-next-line no-loop-func + compiler.hooks.done.tap("MultiCompiler", stats => { + if (!compilerDone) { + compilerDone = true; + doneCompilers++; + } + compilerStats[compilerIndex] = stats; + if (doneCompilers === this.compilers.length) { + this.hooks.done.call(new MultiStats(compilerStats)); + } + }); + // eslint-disable-next-line no-loop-func + compiler.hooks.invalid.tap("MultiCompiler", () => { + if (compilerDone) { + compilerDone = false; + doneCompilers--; + } + }); + } + this.running = false; + } - validateOptions(schema, options, "Hashed Module Ids Plugin"); + get outputPath() { + let commonPath = this.compilers[0].outputPath; + for (const compiler of this.compilers) { + while ( + compiler.outputPath.indexOf(commonPath) !== 0 && + /[/\\]/.test(commonPath) + ) { + commonPath = commonPath.replace(/[/\\][^/\\]*$/, ""); + } + } - /** @type {HashedModuleIdsPluginOptions} */ - this.options = Object.assign( - { - context: null, - hashFunction: "md4", - hashDigest: "base64", - hashDigestLength: 4 - }, - options - ); + if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/"; + return commonPath; } - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap("HashedModuleIdsPlugin", compilation => { - const usedIds = new Set(); - compilation.hooks.beforeModuleIds.tap( - "HashedModuleIdsPlugin", - modules => { - for (const module of modules) { - if (module.id === null && module.libIdent) { - const id = module.libIdent({ - context: this.options.context || compiler.options.context - }); - const hash = createHash(options.hashFunction); - hash.update(id); - const hashId = /** @type {string} */ (hash.digest( - options.hashDigest - )); - let len = options.hashDigestLength; - while (usedIds.has(hashId.substr(0, len))) len++; - module.id = hashId.substr(0, len); - usedIds.add(module.id); - } - } - } - ); - }); + get inputFileSystem() { + throw new Error("Cannot read inputFileSystem of a MultiCompiler"); } -} - -module.exports = HashedModuleIdsPlugin; - -/***/ }), + get outputFileSystem() { + throw new Error("Cannot read outputFileSystem of a MultiCompiler"); + } -/***/ 65217: -/***/ (function(module) { + set inputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.inputFileSystem = value; + } + } -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -// eslint-disable no-unused-vars -var $hash$ = undefined; -var $requestTimeout$ = undefined; -var installedModules = undefined; -var $require$ = undefined; -var hotDownloadManifest = undefined; -var hotDownloadUpdateChunk = undefined; -var hotDisposeChunk = undefined; -var modules = undefined; -var chunkId = undefined; + set outputFileSystem(value) { + for (const compiler of this.compilers) { + compiler.outputFileSystem = value; + } + } -module.exports = function() { - var hotApplyOnUpdate = true; - // eslint-disable-next-line no-unused-vars - var hotCurrentHash = $hash$; - var hotRequestTimeout = $requestTimeout$; - var hotCurrentModuleData = {}; - var hotCurrentChildModule; - // eslint-disable-next-line no-unused-vars - var hotCurrentParents = []; - // eslint-disable-next-line no-unused-vars - var hotCurrentParentsTemp = []; + getInfrastructureLogger(name) { + return this.compilers[0].getInfrastructureLogger(name); + } - // eslint-disable-next-line no-unused-vars - function hotCreateRequire(moduleId) { - var me = installedModules[moduleId]; - if (!me) return $require$; - var fn = function(request) { - if (me.hot.active) { - if (installedModules[request]) { - if (installedModules[request].parents.indexOf(moduleId) === -1) { - installedModules[request].parents.push(moduleId); - } - } else { - hotCurrentParents = [moduleId]; - hotCurrentChildModule = request; - } - if (me.children.indexOf(request) === -1) { - me.children.push(request); + validateDependencies(callback) { + const edges = new Set(); + const missing = []; + const targetFound = compiler => { + for (const edge of edges) { + if (edge.target === compiler) { + return true; } - } else { - console.warn( - "[HMR] unexpected require(" + - request + - ") from disposed module " + - moduleId - ); - hotCurrentParents = []; } - return $require$(request); + return false; }; - var ObjectFactory = function ObjectFactory(name) { - return { - configurable: true, - enumerable: true, - get: function() { - return $require$[name]; - }, - set: function(value) { - $require$[name] = value; - } - }; + const sortEdges = (e1, e2) => { + return ( + e1.source.name.localeCompare(e2.source.name) || + e1.target.name.localeCompare(e2.target.name) + ); }; - for (var name in $require$) { - if ( - Object.prototype.hasOwnProperty.call($require$, name) && - name !== "e" && - name !== "t" - ) { - Object.defineProperty(fn, name, ObjectFactory(name)); + for (const source of this.compilers) { + if (source.dependencies) { + for (const dep of source.dependencies) { + const target = this.compilers.find(c => c.name === dep); + if (!target) { + missing.push(dep); + } else { + edges.add({ + source, + target + }); + } + } } } - fn.e = function(chunkId) { - if (hotStatus === "ready") hotSetStatus("prepare"); - hotChunksLoading++; - return $require$.e(chunkId).then(finishChunkLoading, function(err) { - finishChunkLoading(); - throw err; - }); - - function finishChunkLoading() { - hotChunksLoading--; - if (hotStatus === "prepare") { - if (!hotWaitingFilesMap[chunkId]) { - hotEnsureUpdateChunk(chunkId); - } - if (hotChunksLoading === 0 && hotWaitingFiles === 0) { - hotUpdateDownloaded(); + const errors = missing.map(m => `Compiler dependency \`${m}\` not found.`); + const stack = this.compilers.filter(c => !targetFound(c)); + while (stack.length > 0) { + const current = stack.pop(); + for (const edge of edges) { + if (edge.source === current) { + edges.delete(edge); + const target = edge.target; + if (!targetFound(target)) { + stack.push(target); } } } - }; - fn.t = function(value, mode) { - if (mode & 1) value = fn(value); - return $require$.t(value, mode & ~1); - }; - return fn; - } - - // eslint-disable-next-line no-unused-vars - function hotCreateModule(moduleId) { - var hot = { - // private stuff - _acceptedDependencies: {}, - _declinedDependencies: {}, - _selfAccepted: false, - _selfDeclined: false, - _selfInvalidated: false, - _disposeHandlers: [], - _main: hotCurrentChildModule !== moduleId, + } + if (edges.size > 0) { + const lines = Array.from(edges) + .sort(sortEdges) + .map(edge => `${edge.source.name} -> ${edge.target.name}`); + lines.unshift("Circular dependency found in compiler dependencies."); + errors.unshift(lines.join("\n")); + } + if (errors.length > 0) { + const message = errors.join("\n"); + callback(new Error(message)); + return false; + } + return true; + } - // Module API - active: true, - accept: function(dep, callback) { - if (dep === undefined) hot._selfAccepted = true; - else if (typeof dep === "function") hot._selfAccepted = dep; - else if (typeof dep === "object") - for (var i = 0; i < dep.length; i++) - hot._acceptedDependencies[dep[i]] = callback || function() {}; - else hot._acceptedDependencies[dep] = callback || function() {}; - }, - decline: function(dep) { - if (dep === undefined) hot._selfDeclined = true; - else if (typeof dep === "object") - for (var i = 0; i < dep.length; i++) - hot._declinedDependencies[dep[i]] = true; - else hot._declinedDependencies[dep] = true; - }, - dispose: function(callback) { - hot._disposeHandlers.push(callback); - }, - addDisposeHandler: function(callback) { - hot._disposeHandlers.push(callback); - }, - removeDisposeHandler: function(callback) { - var idx = hot._disposeHandlers.indexOf(callback); - if (idx >= 0) hot._disposeHandlers.splice(idx, 1); - }, - invalidate: function() { - this._selfInvalidated = true; - switch (hotStatus) { - case "idle": - hotUpdate = {}; - hotUpdate[moduleId] = modules[moduleId]; - hotSetStatus("ready"); - break; - case "ready": - hotApplyInvalidatedModule(moduleId); - break; - case "prepare": - case "check": - case "dispose": - case "apply": - (hotQueuedInvalidatedModules = - hotQueuedInvalidatedModules || []).push(moduleId); - break; - default: - // ignore requests in error states - break; + runWithDependencies(compilers, fn, callback) { + const fulfilledNames = new Set(); + let remainingCompilers = compilers; + const isDependencyFulfilled = d => fulfilledNames.has(d); + const getReadyCompilers = () => { + let readyCompilers = []; + let list = remainingCompilers; + remainingCompilers = []; + for (const c of list) { + const ready = + !c.dependencies || c.dependencies.every(isDependencyFulfilled); + if (ready) { + readyCompilers.push(c); + } else { + remainingCompilers.push(c); } - }, - - // Management API - check: hotCheck, - apply: hotApply, - status: function(l) { - if (!l) return hotStatus; - hotStatusHandlers.push(l); - }, - addStatusHandler: function(l) { - hotStatusHandlers.push(l); - }, - removeStatusHandler: function(l) { - var idx = hotStatusHandlers.indexOf(l); - if (idx >= 0) hotStatusHandlers.splice(idx, 1); - }, - - //inherit from previous dispose call - data: hotCurrentModuleData[moduleId] + } + return readyCompilers; }; - hotCurrentChildModule = undefined; - return hot; - } - - var hotStatusHandlers = []; - var hotStatus = "idle"; - - function hotSetStatus(newStatus) { - hotStatus = newStatus; - for (var i = 0; i < hotStatusHandlers.length; i++) - hotStatusHandlers[i].call(null, newStatus); + const runCompilers = callback => { + if (remainingCompilers.length === 0) return callback(); + asyncLib.map( + getReadyCompilers(), + (compiler, callback) => { + fn(compiler, err => { + if (err) return callback(err); + fulfilledNames.add(compiler.name); + runCompilers(callback); + }); + }, + callback + ); + }; + runCompilers(callback); } - // while downloading - var hotWaitingFiles = 0; - var hotChunksLoading = 0; - var hotWaitingFilesMap = {}; - var hotRequestedFilesMap = {}; - var hotAvailableFilesMap = {}; - var hotDeferred; + watch(watchOptions, handler) { + if (this.running) return handler(new ConcurrentCompilationError()); - // The update info - var hotUpdate, hotUpdateNewHash, hotQueuedInvalidatedModules; + let watchings = []; + let allStats = this.compilers.map(() => null); + let compilerStatus = this.compilers.map(() => false); + if (this.validateDependencies(handler)) { + this.running = true; + this.runWithDependencies( + this.compilers, + (compiler, callback) => { + const compilerIdx = this.compilers.indexOf(compiler); + let firstRun = true; + let watching = compiler.watch( + Array.isArray(watchOptions) + ? watchOptions[compilerIdx] + : watchOptions, + (err, stats) => { + if (err) handler(err); + if (stats) { + allStats[compilerIdx] = stats; + compilerStatus[compilerIdx] = "new"; + if (compilerStatus.every(Boolean)) { + const freshStats = allStats.filter((s, idx) => { + return compilerStatus[idx] === "new"; + }); + compilerStatus.fill(true); + const multiStats = new MultiStats(freshStats); + handler(null, multiStats); + } + } + if (firstRun && !err) { + firstRun = false; + callback(); + } + } + ); + watchings.push(watching); + }, + () => { + // ignore + } + ); + } - function toModuleId(id) { - var isNumber = +id + "" === id; - return isNumber ? +id : id; + return new MultiWatching(watchings, this); } - function hotCheck(apply) { - if (hotStatus !== "idle") { - throw new Error("check() is only allowed in idle status"); + run(callback) { + if (this.running) { + return callback(new ConcurrentCompilationError()); } - hotApplyOnUpdate = apply; - hotSetStatus("check"); - return hotDownloadManifest(hotRequestTimeout).then(function(update) { - if (!update) { - hotSetStatus(hotApplyInvalidatedModules() ? "ready" : "idle"); - return null; - } - hotRequestedFilesMap = {}; - hotWaitingFilesMap = {}; - hotAvailableFilesMap = update.c; - hotUpdateNewHash = update.h; - hotSetStatus("prepare"); - var promise = new Promise(function(resolve, reject) { - hotDeferred = { - resolve: resolve, - reject: reject - }; - }); - hotUpdate = {}; - /*foreachInstalledChunks*/ - // eslint-disable-next-line no-lone-blocks - { - hotEnsureUpdateChunk(chunkId); - } - if ( - hotStatus === "prepare" && - hotChunksLoading === 0 && - hotWaitingFiles === 0 - ) { - hotUpdateDownloaded(); + const finalCallback = (err, stats) => { + this.running = false; + + if (callback !== undefined) { + return callback(err, stats); } - return promise; - }); + }; + + const allStats = this.compilers.map(() => null); + if (this.validateDependencies(callback)) { + this.running = true; + this.runWithDependencies( + this.compilers, + (compiler, callback) => { + const compilerIdx = this.compilers.indexOf(compiler); + compiler.run((err, stats) => { + if (err) { + return callback(err); + } + allStats[compilerIdx] = stats; + callback(); + }); + }, + err => { + if (err) { + return finalCallback(err); + } + finalCallback(null, new MultiStats(allStats)); + } + ); + } } - // eslint-disable-next-line no-unused-vars - function hotAddUpdateChunk(chunkId, moreModules) { - if (!hotAvailableFilesMap[chunkId] || !hotRequestedFilesMap[chunkId]) - return; - hotRequestedFilesMap[chunkId] = false; - for (var moduleId in moreModules) { - if (Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { - hotUpdate[moduleId] = moreModules[moduleId]; + purgeInputFileSystem() { + for (const compiler of this.compilers) { + if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { + compiler.inputFileSystem.purge(); } } - if (--hotWaitingFiles === 0 && hotChunksLoading === 0) { - hotUpdateDownloaded(); - } } +}; - function hotEnsureUpdateChunk(chunkId) { - if (!hotAvailableFilesMap[chunkId]) { - hotWaitingFilesMap[chunkId] = true; - } else { - hotRequestedFilesMap[chunkId] = true; - hotWaitingFiles++; - hotDownloadUpdateChunk(chunkId); - } + +/***/ }), + +/***/ 98046: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const MultiEntryDependency = __webpack_require__(7791); +const SingleEntryDependency = __webpack_require__(84828); +const MultiModuleFactory = __webpack_require__(24005); + +/** @typedef {import("./Compiler")} Compiler */ + +class MultiEntryPlugin { + /** + * The MultiEntryPlugin is invoked whenever this.options.entry value is an array of paths + * @param {string} context context path + * @param {string[]} entries array of entry paths + * @param {string} name entry key name + */ + constructor(context, entries, name) { + this.context = context; + this.entries = entries; + this.name = name; } - function hotUpdateDownloaded() { - hotSetStatus("ready"); - var deferred = hotDeferred; - hotDeferred = null; - if (!deferred) return; - if (hotApplyOnUpdate) { - // Wrap deferred object in Promise to mark it as a well-handled Promise to - // avoid triggering uncaught exception warning in Chrome. - // See https://bugs.chromium.org/p/chromium/issues/detail?id=465666 - Promise.resolve() - .then(function() { - return hotApply(hotApplyOnUpdate); - }) - .then( - function(result) { - deferred.resolve(result); - }, - function(err) { - deferred.reject(err); - } + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "MultiEntryPlugin", + (compilation, { normalModuleFactory }) => { + const multiModuleFactory = new MultiModuleFactory(); + + compilation.dependencyFactories.set( + MultiEntryDependency, + multiModuleFactory + ); + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory ); - } else { - var outdatedModules = []; - for (var id in hotUpdate) { - if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { - outdatedModules.push(toModuleId(id)); - } } - deferred.resolve(outdatedModules); - } + ); + + compiler.hooks.make.tapAsync( + "MultiEntryPlugin", + (compilation, callback) => { + const { context, entries, name } = this; + + const dep = MultiEntryPlugin.createDependency(entries, name); + compilation.addEntry(context, dep, name, callback); + } + ); } - function hotApply(options) { - if (hotStatus !== "ready") - throw new Error("apply() is only allowed in ready status"); - options = options || {}; - return hotApplyInternal(options); + /** + * @param {string[]} entries each entry path string + * @param {string} name name of the entry + * @returns {MultiEntryDependency} returns a constructed Dependency + */ + static createDependency(entries, name) { + return new MultiEntryDependency( + entries.map((e, idx) => { + const dep = new SingleEntryDependency(e); + // Because entrypoints are not dependencies found in an + // existing module, we give it a synthetic id + dep.loc = { + name, + index: idx + }; + return dep; + }), + name + ); } +} - function hotApplyInternal(options) { - hotApplyInvalidatedModules(); +module.exports = MultiEntryPlugin; - var cb; - var i; - var j; - var module; - var moduleId; - function getAffectedStuff(updateModuleId) { - var outdatedModules = [updateModuleId]; - var outdatedDependencies = {}; +/***/ }), - var queue = outdatedModules.map(function(id) { - return { - chain: [id], - id: id - }; - }); - while (queue.length > 0) { - var queueItem = queue.pop(); - var moduleId = queueItem.id; - var chain = queueItem.chain; - module = installedModules[moduleId]; - if ( - !module || - (module.hot._selfAccepted && !module.hot._selfInvalidated) - ) - continue; - if (module.hot._selfDeclined) { - return { - type: "self-declined", - chain: chain, - moduleId: moduleId - }; - } - if (module.hot._main) { - return { - type: "unaccepted", - chain: chain, - moduleId: moduleId - }; - } - for (var i = 0; i < module.parents.length; i++) { - var parentId = module.parents[i]; - var parent = installedModules[parentId]; - if (!parent) continue; - if (parent.hot._declinedDependencies[moduleId]) { - return { - type: "declined", - chain: chain.concat([parentId]), - moduleId: moduleId, - parentId: parentId - }; - } - if (outdatedModules.indexOf(parentId) !== -1) continue; - if (parent.hot._acceptedDependencies[moduleId]) { - if (!outdatedDependencies[parentId]) - outdatedDependencies[parentId] = []; - addAllToSet(outdatedDependencies[parentId], [moduleId]); - continue; - } - delete outdatedDependencies[parentId]; - outdatedModules.push(parentId); - queue.push({ - chain: chain.concat([parentId]), - id: parentId - }); - } - } +/***/ 4198: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return { - type: "accepted", - moduleId: updateModuleId, - outdatedModules: outdatedModules, - outdatedDependencies: outdatedDependencies - }; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - function addAllToSet(a, b) { - for (var i = 0; i < b.length; i++) { - var item = b[i]; - if (a.indexOf(item) === -1) a.push(item); - } - } - // at begin all updates modules are outdated - // the "outdated" status can propagate to parents if they don't accept the children - var outdatedDependencies = {}; - var outdatedModules = []; - var appliedUpdate = {}; +const Module = __webpack_require__(75993); +const Template = __webpack_require__(96066); +const { RawSource } = __webpack_require__(53665); - var warnUnexpectedRequire = function warnUnexpectedRequire() { - console.warn( - "[HMR] unexpected require(" + result.moduleId + ") to disposed module" - ); - }; +/** @typedef {import("./util/createHash").Hash} Hash */ - for (var id in hotUpdate) { - if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { - moduleId = toModuleId(id); - /** @type {TODO} */ - var result; - if (hotUpdate[id]) { - result = getAffectedStuff(moduleId); - } else { - result = { - type: "disposed", - moduleId: id - }; - } - /** @type {Error|false} */ - var abortError = false; - var doApply = false; - var doDispose = false; - var chainInfo = ""; - if (result.chain) { - chainInfo = "\nUpdate propagation: " + result.chain.join(" -> "); - } - switch (result.type) { - case "self-declined": - if (options.onDeclined) options.onDeclined(result); - if (!options.ignoreDeclined) - abortError = new Error( - "Aborted because of self decline: " + - result.moduleId + - chainInfo - ); - break; - case "declined": - if (options.onDeclined) options.onDeclined(result); - if (!options.ignoreDeclined) - abortError = new Error( - "Aborted because of declined dependency: " + - result.moduleId + - " in " + - result.parentId + - chainInfo - ); - break; - case "unaccepted": - if (options.onUnaccepted) options.onUnaccepted(result); - if (!options.ignoreUnaccepted) - abortError = new Error( - "Aborted because " + moduleId + " is not accepted" + chainInfo - ); - break; - case "accepted": - if (options.onAccepted) options.onAccepted(result); - doApply = true; - break; - case "disposed": - if (options.onDisposed) options.onDisposed(result); - doDispose = true; - break; - default: - throw new Error("Unexception type " + result.type); - } - if (abortError) { - hotSetStatus("abort"); - return Promise.reject(abortError); - } - if (doApply) { - appliedUpdate[moduleId] = hotUpdate[moduleId]; - addAllToSet(outdatedModules, result.outdatedModules); - for (moduleId in result.outdatedDependencies) { - if ( - Object.prototype.hasOwnProperty.call( - result.outdatedDependencies, - moduleId - ) - ) { - if (!outdatedDependencies[moduleId]) - outdatedDependencies[moduleId] = []; - addAllToSet( - outdatedDependencies[moduleId], - result.outdatedDependencies[moduleId] - ); - } - } +class MultiModule extends Module { + constructor(context, dependencies, name) { + super("javascript/dynamic", context); + + // Info from Factory + this.dependencies = dependencies; + this.name = name; + this._identifier = `multi ${this.dependencies + .map(d => d.request) + .join(" ")}`; + } + + identifier() { + return this._identifier; + } + + readableIdentifier(requestShortener) { + return `multi ${this.dependencies + .map(d => requestShortener.shorten(d.request)) + .join(" ")}`; + } + + build(options, compilation, resolver, fs, callback) { + this.built = true; + this.buildMeta = {}; + this.buildInfo = {}; + return callback(); + } + + needRebuild() { + return false; + } + + size() { + return 16 + this.dependencies.length * 12; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update("multi module"); + hash.update(this.name || ""); + super.updateHash(hash); + } + + source(dependencyTemplates, runtimeTemplate) { + const str = []; + let idx = 0; + for (const dep of this.dependencies) { + if (dep.module) { + if (idx === this.dependencies.length - 1) { + str.push("module.exports = "); } - if (doDispose) { - addAllToSet(outdatedModules, [result.moduleId]); - appliedUpdate[moduleId] = warnUnexpectedRequire; + str.push("__webpack_require__("); + if (runtimeTemplate.outputOptions.pathinfo) { + str.push(Template.toComment(dep.request)); } + str.push(`${JSON.stringify(dep.module.id)}`); + str.push(")"); + } else { + const content = __webpack_require__(75386).module( + dep.request + ); + str.push(content); } + str.push(";\n"); + idx++; } + return new RawSource(str.join("")); + } +} - // Store self accepted outdated modules to require them later by the module system - var outdatedSelfAcceptedModules = []; - for (i = 0; i < outdatedModules.length; i++) { - moduleId = outdatedModules[i]; - if ( - installedModules[moduleId] && - installedModules[moduleId].hot._selfAccepted && - // removed self-accepted modules should not be required - appliedUpdate[moduleId] !== warnUnexpectedRequire && - // when called invalidate self-accepting is not possible - !installedModules[moduleId].hot._selfInvalidated - ) { - outdatedSelfAcceptedModules.push({ - module: moduleId, - parents: installedModules[moduleId].parents.slice(), - errorHandler: installedModules[moduleId].hot._selfAccepted - }); - } - } +module.exports = MultiModule; - // Now in "dispose" phase - hotSetStatus("dispose"); - Object.keys(hotAvailableFilesMap).forEach(function(chunkId) { - if (hotAvailableFilesMap[chunkId] === false) { - hotDisposeChunk(chunkId); - } - }); - var idx; - var queue = outdatedModules.slice(); - while (queue.length > 0) { - moduleId = queue.pop(); - module = installedModules[moduleId]; - if (!module) continue; +/***/ }), - var data = {}; +/***/ 24005: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Call dispose handlers - var disposeHandlers = module.hot._disposeHandlers; - for (j = 0; j < disposeHandlers.length; j++) { - cb = disposeHandlers[j]; - cb(data); - } - hotCurrentModuleData[moduleId] = data; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // disable module (this disables requires from this module) - module.hot.active = false; - // remove module from cache - delete installedModules[moduleId]; +const { Tapable } = __webpack_require__(56758); +const MultiModule = __webpack_require__(4198); - // when disposing there is no need to call dispose handler - delete outdatedDependencies[moduleId]; +module.exports = class MultiModuleFactory extends Tapable { + constructor() { + super(); + this.hooks = {}; + } - // remove "parents" references from all children - for (j = 0; j < module.children.length; j++) { - var child = installedModules[module.children[j]]; - if (!child) continue; - idx = child.parents.indexOf(moduleId); - if (idx >= 0) { - child.parents.splice(idx, 1); - } - } - } + create(data, callback) { + const dependency = data.dependencies[0]; + callback( + null, + new MultiModule(data.context, dependency.dependencies, dependency.name) + ); + } +}; - // remove outdated dependency from module children - var dependency; - var moduleOutdatedDependencies; - for (moduleId in outdatedDependencies) { - if ( - Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) - ) { - module = installedModules[moduleId]; - if (module) { - moduleOutdatedDependencies = outdatedDependencies[moduleId]; - for (j = 0; j < moduleOutdatedDependencies.length; j++) { - dependency = moduleOutdatedDependencies[j]; - idx = module.children.indexOf(dependency); - if (idx >= 0) module.children.splice(idx, 1); - } - } - } - } - // Now in "apply" phase - hotSetStatus("apply"); +/***/ }), - if (hotUpdateNewHash !== undefined) { - hotCurrentHash = hotUpdateNewHash; - hotUpdateNewHash = undefined; - } - hotUpdate = undefined; +/***/ 55144: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // insert new code - for (moduleId in appliedUpdate) { - if (Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) { - modules[moduleId] = appliedUpdate[moduleId]; - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // call accept handlers - var error = null; - for (moduleId in outdatedDependencies) { - if ( - Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) - ) { - module = installedModules[moduleId]; - if (module) { - moduleOutdatedDependencies = outdatedDependencies[moduleId]; - var callbacks = []; - for (i = 0; i < moduleOutdatedDependencies.length; i++) { - dependency = moduleOutdatedDependencies[i]; - cb = module.hot._acceptedDependencies[dependency]; - if (cb) { - if (callbacks.indexOf(cb) !== -1) continue; - callbacks.push(cb); - } - } - for (i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - try { - cb(moduleOutdatedDependencies); - } catch (err) { - if (options.onErrored) { - options.onErrored({ - type: "accept-errored", - moduleId: moduleId, - dependencyId: moduleOutdatedDependencies[i], - error: err - }); - } - if (!options.ignoreErrored) { - if (!error) error = err; - } - } - } - } - } - } - // Load self accepted modules - for (i = 0; i < outdatedSelfAcceptedModules.length; i++) { - var item = outdatedSelfAcceptedModules[i]; - moduleId = item.module; - hotCurrentParents = item.parents; - hotCurrentChildModule = moduleId; - try { - $require$(moduleId); - } catch (err) { - if (typeof item.errorHandler === "function") { - try { - item.errorHandler(err); - } catch (err2) { - if (options.onErrored) { - options.onErrored({ - type: "self-accept-error-handler-errored", - moduleId: moduleId, - error: err2, - originalError: err - }); - } - if (!options.ignoreErrored) { - if (!error) error = err2; - } - if (!error) error = err; - } - } else { - if (options.onErrored) { - options.onErrored({ - type: "self-accept-errored", - moduleId: moduleId, - error: err - }); - } - if (!options.ignoreErrored) { - if (!error) error = err; - } - } +const Stats = __webpack_require__(99977); + +const optionOrFallback = (optionValue, fallbackValue) => + optionValue !== undefined ? optionValue : fallbackValue; + +class MultiStats { + constructor(stats) { + this.stats = stats; + this.hash = stats.map(stat => stat.hash).join(""); + } + + hasErrors() { + return this.stats + .map(stat => stat.hasErrors()) + .reduce((a, b) => a || b, false); + } + + hasWarnings() { + return this.stats + .map(stat => stat.hasWarnings()) + .reduce((a, b) => a || b, false); + } + + toJson(options, forToString) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } + const jsons = this.stats.map((stat, idx) => { + const childOptions = Stats.getChildOptions(options, idx); + const obj = stat.toJson(childOptions, forToString); + obj.name = stat.compilation && stat.compilation.name; + return obj; + }); + const showVersion = + options.version === undefined + ? jsons.every(j => j.version) + : options.version !== false; + const showHash = + options.hash === undefined + ? jsons.every(j => j.hash) + : options.hash !== false; + if (showVersion) { + for (const j of jsons) { + delete j.version; } } + const obj = { + errors: jsons.reduce((arr, j) => { + return arr.concat( + j.errors.map(msg => { + return `(${j.name}) ${msg}`; + }) + ); + }, []), + warnings: jsons.reduce((arr, j) => { + return arr.concat( + j.warnings.map(msg => { + return `(${j.name}) ${msg}`; + }) + ); + }, []) + }; + if (showVersion) obj.version = __webpack_require__(71618)/* .version */ .i8; + if (showHash) obj.hash = this.hash; + if (options.children !== false) obj.children = jsons; + return obj; + } - // handle errors in accept handlers and self accepted module load - if (error) { - hotSetStatus("fail"); - return Promise.reject(error); + toString(options) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; } - if (hotQueuedInvalidatedModules) { - return hotApplyInternal(options).then(function(list) { - outdatedModules.forEach(function(moduleId) { - if (list.indexOf(moduleId) < 0) list.push(moduleId); - }); - return list; - }); + const useColors = optionOrFallback(options.colors, false); + + const obj = this.toJson(options, true); + + return Stats.jsonToString(obj, useColors); + } +} + +module.exports = MultiStats; + + +/***/ }), + +/***/ 66624: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const asyncLib = __webpack_require__(36386); + +class MultiWatching { + constructor(watchings, compiler) { + this.watchings = watchings; + this.compiler = compiler; + } + + invalidate() { + for (const watching of this.watchings) { + watching.invalidate(); } + } - hotSetStatus("idle"); - return new Promise(function(resolve) { - resolve(outdatedModules); - }); + suspend() { + for (const watching of this.watchings) { + watching.suspend(); + } } - function hotApplyInvalidatedModules() { - if (hotQueuedInvalidatedModules) { - if (!hotUpdate) hotUpdate = {}; - hotQueuedInvalidatedModules.forEach(hotApplyInvalidatedModule); - hotQueuedInvalidatedModules = undefined; - return true; + resume() { + for (const watching of this.watchings) { + watching.resume(); } } - function hotApplyInvalidatedModule(moduleId) { - if (!Object.prototype.hasOwnProperty.call(hotUpdate, moduleId)) - hotUpdate[moduleId] = modules[moduleId]; + close(callback) { + asyncLib.forEach( + this.watchings, + (watching, finishedCallback) => { + watching.close(finishedCallback); + }, + err => { + this.compiler.hooks.watchClose.call(); + if (typeof callback === "function") { + this.compiler.running = false; + callback(err); + } + } + ); } -}; +} + +module.exports = MultiWatching; /***/ }), -/***/ 69575: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 70419: +/***/ (function(module) { "use strict"; /* @@ -80471,430 +80700,128 @@ module.exports = function() { */ -const { SyncBailHook } = __webpack_require__(56758); -const { RawSource } = __webpack_require__(53665); -const Template = __webpack_require__(96066); -const ModuleHotAcceptDependency = __webpack_require__(29018); -const ModuleHotDeclineDependency = __webpack_require__(60482); -const ConstDependency = __webpack_require__(71101); -const NullFactory = __webpack_require__(40438); -const ParserHelpers = __webpack_require__(23999); +class NamedChunksPlugin { + static defaultNameResolver(chunk) { + return chunk.name || null; + } -module.exports = class HotModuleReplacementPlugin { - constructor(options) { - this.options = options || {}; - this.multiStep = this.options.multiStep; - this.fullBuildTimeout = this.options.fullBuildTimeout || 200; - this.requestTimeout = this.options.requestTimeout || 10000; + constructor(nameResolver) { + this.nameResolver = nameResolver || NamedChunksPlugin.defaultNameResolver; } apply(compiler) { - const multiStep = this.multiStep; - const fullBuildTimeout = this.fullBuildTimeout; - const requestTimeout = this.requestTimeout; - const hotUpdateChunkFilename = - compiler.options.output.hotUpdateChunkFilename; - const hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename; - compiler.hooks.additionalPass.tapAsync( - "HotModuleReplacementPlugin", - callback => { - if (multiStep) return setTimeout(callback, fullBuildTimeout); - return callback(); - } - ); - - const addParserPlugins = (parser, parserOptions) => { - parser.hooks.expression - .for("__webpack_hash__") - .tap( - "HotModuleReplacementPlugin", - ParserHelpers.toConstantDependencyWithWebpackRequire( - parser, - "__webpack_require__.h()" - ) - ); - parser.hooks.evaluateTypeof - .for("__webpack_hash__") - .tap( - "HotModuleReplacementPlugin", - ParserHelpers.evaluateToString("string") - ); - parser.hooks.evaluateIdentifier.for("module.hot").tap( - { - name: "HotModuleReplacementPlugin", - before: "NodeStuffPlugin" - }, - expr => { - return ParserHelpers.evaluateToIdentifier( - "module.hot", - !!parser.state.compilation.hotUpdateChunkTemplate - )(expr); - } - ); - // TODO webpack 5: refactor this, no custom hooks - if (!parser.hooks.hotAcceptCallback) { - parser.hooks.hotAcceptCallback = new SyncBailHook([ - "expression", - "requests" - ]); - } - if (!parser.hooks.hotAcceptWithoutCallback) { - parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ - "expression", - "requests" - ]); - } - parser.hooks.call - .for("module.hot.accept") - .tap("HotModuleReplacementPlugin", expr => { - if (!parser.state.compilation.hotUpdateChunkTemplate) { - return false; - } - if (expr.arguments.length >= 1) { - const arg = parser.evaluateExpression(expr.arguments[0]); - let params = []; - let requests = []; - if (arg.isString()) { - params = [arg]; - } else if (arg.isArray()) { - params = arg.items.filter(param => param.isString()); - } - if (params.length > 0) { - params.forEach((param, idx) => { - const request = param.string; - const dep = new ModuleHotAcceptDependency(request, param.range); - dep.optional = true; - dep.loc = Object.create(expr.loc); - dep.loc.index = idx; - parser.state.module.addDependency(dep); - requests.push(request); - }); - if (expr.arguments.length > 1) { - parser.hooks.hotAcceptCallback.call( - expr.arguments[1], - requests - ); - parser.walkExpression(expr.arguments[1]); // other args are ignored - return true; - } else { - parser.hooks.hotAcceptWithoutCallback.call(expr, requests); - return true; - } - } - } - }); - parser.hooks.call - .for("module.hot.decline") - .tap("HotModuleReplacementPlugin", expr => { - if (!parser.state.compilation.hotUpdateChunkTemplate) { - return false; - } - if (expr.arguments.length === 1) { - const arg = parser.evaluateExpression(expr.arguments[0]); - let params = []; - if (arg.isString()) { - params = [arg]; - } else if (arg.isArray()) { - params = arg.items.filter(param => param.isString()); - } - params.forEach((param, idx) => { - const dep = new ModuleHotDeclineDependency( - param.string, - param.range - ); - dep.optional = true; - dep.loc = Object.create(expr.loc); - dep.loc.index = idx; - parser.state.module.addDependency(dep); - }); + compiler.hooks.compilation.tap("NamedChunksPlugin", compilation => { + compilation.hooks.beforeChunkIds.tap("NamedChunksPlugin", chunks => { + for (const chunk of chunks) { + if (chunk.id === null) { + chunk.id = this.nameResolver(chunk); } - }); - parser.hooks.expression - .for("module.hot") - .tap("HotModuleReplacementPlugin", ParserHelpers.skipTraversal); - }; - - compiler.hooks.compilation.tap( - "HotModuleReplacementPlugin", - (compilation, { normalModuleFactory }) => { - // This applies the HMR plugin only to the targeted compiler - // It should not affect child compilations - if (compilation.compiler !== compiler) return; + } + }); + }); + } +} - const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate; - if (!hotUpdateChunkTemplate) return; +module.exports = NamedChunksPlugin; - compilation.dependencyFactories.set(ConstDependency, new NullFactory()); - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); - compilation.dependencyFactories.set( - ModuleHotAcceptDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ModuleHotAcceptDependency, - new ModuleHotAcceptDependency.Template() - ); +/***/ }), - compilation.dependencyFactories.set( - ModuleHotDeclineDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ModuleHotDeclineDependency, - new ModuleHotDeclineDependency.Template() - ); +/***/ 86707: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - compilation.hooks.record.tap( - "HotModuleReplacementPlugin", - (compilation, records) => { - if (records.hash === compilation.hash) return; - records.hash = compilation.hash; - records.moduleHashs = {}; - for (const module of compilation.modules) { - const identifier = module.identifier(); - records.moduleHashs[identifier] = module.hash; - } - records.chunkHashs = {}; - for (const chunk of compilation.chunks) { - records.chunkHashs[chunk.id] = chunk.hash; - } - records.chunkModuleIds = {}; - for (const chunk of compilation.chunks) { - records.chunkModuleIds[chunk.id] = Array.from( - chunk.modulesIterable, - m => m.id - ); - } - } - ); - let initialPass = false; - let recompilation = false; - compilation.hooks.afterHash.tap("HotModuleReplacementPlugin", () => { - let records = compilation.records; - if (!records) { - initialPass = true; - return; - } - if (!records.hash) initialPass = true; - const preHash = records.preHash || "x"; - const prepreHash = records.prepreHash || "x"; - if (preHash === compilation.hash) { - recompilation = true; - compilation.modifyHash(prepreHash); - return; - } - records.prepreHash = records.hash || "x"; - records.preHash = compilation.hash; - compilation.modifyHash(records.prepreHash); - }); - compilation.hooks.shouldGenerateChunkAssets.tap( - "HotModuleReplacementPlugin", - () => { - if (multiStep && !recompilation && !initialPass) return false; - } - ); - compilation.hooks.needAdditionalPass.tap( - "HotModuleReplacementPlugin", - () => { - if (multiStep && !recompilation && !initialPass) return true; - } - ); - compilation.hooks.additionalChunkAssets.tap( - "HotModuleReplacementPlugin", - () => { - const records = compilation.records; - if (records.hash === compilation.hash) return; - if ( - !records.moduleHashs || - !records.chunkHashs || - !records.chunkModuleIds - ) - return; - for (const module of compilation.modules) { - const identifier = module.identifier(); - let hash = module.hash; - module.hotUpdate = records.moduleHashs[identifier] !== hash; - } - const hotUpdateMainContent = { - h: compilation.hash, - c: {} - }; - for (const key of Object.keys(records.chunkHashs)) { - const chunkId = isNaN(+key) ? key : +key; - const currentChunk = compilation.chunks.find( - chunk => `${chunk.id}` === key - ); - if (currentChunk) { - const newModules = currentChunk - .getModules() - .filter(module => module.hotUpdate); - const allModules = new Set(); - for (const module of currentChunk.modulesIterable) { - allModules.add(module.id); - } - const removedModules = records.chunkModuleIds[chunkId].filter( - id => !allModules.has(id) - ); - if (newModules.length > 0 || removedModules.length > 0) { - const source = hotUpdateChunkTemplate.render( - chunkId, - newModules, - removedModules, - compilation.hash, - compilation.moduleTemplates.javascript, - compilation.dependencyTemplates - ); - const { - path: filename, - info: assetInfo - } = compilation.getPathWithInfo(hotUpdateChunkFilename, { - hash: records.hash, - chunk: currentChunk - }); - compilation.additionalChunkAssets.push(filename); - compilation.emitAsset( - filename, - source, - Object.assign({ hotModuleReplacement: true }, assetInfo) - ); - hotUpdateMainContent.c[chunkId] = true; - currentChunk.files.push(filename); - compilation.hooks.chunkAsset.call(currentChunk, filename); - } - } else { - hotUpdateMainContent.c[chunkId] = false; - } - } - const source = new RawSource(JSON.stringify(hotUpdateMainContent)); - const { - path: filename, - info: assetInfo - } = compilation.getPathWithInfo(hotUpdateMainFilename, { - hash: records.hash - }); - compilation.emitAsset( - filename, - source, - Object.assign({ hotModuleReplacement: true }, assetInfo) - ); - } - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const mainTemplate = compilation.mainTemplate; - mainTemplate.hooks.hash.tap("HotModuleReplacementPlugin", hash => { - hash.update("HotMainTemplateDecorator"); - }); +const createHash = __webpack_require__(15660); +const RequestShortener = __webpack_require__(54254); - mainTemplate.hooks.moduleRequire.tap( - "HotModuleReplacementPlugin", - (_, chunk, hash, varModuleId) => { - return `hotCreateRequire(${varModuleId})`; - } - ); +const getHash = str => { + const hash = createHash("md4"); + hash.update(str); + const digest = /** @type {string} */ (hash.digest("hex")); + return digest.substr(0, 4); +}; - mainTemplate.hooks.requireExtensions.tap( - "HotModuleReplacementPlugin", - source => { - const buf = [source]; - buf.push(""); - buf.push("// __webpack_hash__"); - buf.push( - mainTemplate.requireFn + - ".h = function() { return hotCurrentHash; };" - ); - return Template.asString(buf); - } - ); +class NamedModulesPlugin { + constructor(options) { + this.options = options || {}; + } - const needChunkLoadingCode = chunk => { - for (const chunkGroup of chunk.groupsIterable) { - if (chunkGroup.chunks.length > 1) return true; - if (chunkGroup.getNumberOfChildren() > 0) return true; - } - return false; - }; + apply(compiler) { + compiler.hooks.compilation.tap("NamedModulesPlugin", compilation => { + compilation.hooks.beforeModuleIds.tap("NamedModulesPlugin", modules => { + const namedModules = new Map(); + const context = this.options.context || compiler.options.context; - mainTemplate.hooks.bootstrap.tap( - "HotModuleReplacementPlugin", - (source, chunk, hash) => { - source = mainTemplate.hooks.hotBootstrap.call(source, chunk, hash); - return Template.asString([ - source, - "", - hotInitCode - .replace(/\$require\$/g, mainTemplate.requireFn) - .replace(/\$hash\$/g, JSON.stringify(hash)) - .replace(/\$requestTimeout\$/g, requestTimeout) - .replace( - /\/\*foreachInstalledChunks\*\//g, - needChunkLoadingCode(chunk) - ? "for(var chunkId in installedChunks)" - : `var chunkId = ${JSON.stringify(chunk.id)};` - ) - ]); + for (const module of modules) { + if (module.id === null && module.libIdent) { + module.id = module.libIdent({ context }); } - ); - - mainTemplate.hooks.globalHash.tap( - "HotModuleReplacementPlugin", - () => true - ); - mainTemplate.hooks.currentHash.tap( - "HotModuleReplacementPlugin", - (_, length) => { - if (isFinite(length)) { - return `hotCurrentHash.substr(0, ${length})`; + if (module.id !== null) { + const namedModule = namedModules.get(module.id); + if (namedModule !== undefined) { + namedModule.push(module); } else { - return "hotCurrentHash"; + namedModules.set(module.id, [module]); } } - ); + } - mainTemplate.hooks.moduleObj.tap( - "HotModuleReplacementPlugin", - (source, chunk, hash, varModuleId) => { - return Template.asString([ - `${source},`, - `hot: hotCreateModule(${varModuleId}),`, - "parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),", - "children: []" - ]); + for (const namedModule of namedModules.values()) { + if (namedModule.length > 1) { + for (const module of namedModule) { + const requestShortener = new RequestShortener(context); + module.id = `${module.id}?${getHash( + requestShortener.shorten(module.identifier()) + )}`; + } } - ); + } + }); + }); + } +} - // TODO add HMR support for javascript/esm - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("HotModuleReplacementPlugin", addParserPlugins); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("HotModuleReplacementPlugin", addParserPlugins); +module.exports = NamedModulesPlugin; - compilation.hooks.normalModuleLoader.tap( - "HotModuleReplacementPlugin", - context => { - context.hot = true; - } - ); - } - ); + +/***/ }), + +/***/ 22615: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class NoEmitOnErrorsPlugin { + apply(compiler) { + compiler.hooks.shouldEmit.tap("NoEmitOnErrorsPlugin", compilation => { + if (compilation.getStats().hasErrors()) return false; + }); + compiler.hooks.compilation.tap("NoEmitOnErrorsPlugin", compilation => { + compilation.hooks.shouldRecord.tap("NoEmitOnErrorsPlugin", () => { + if (compilation.getStats().hasErrors()) return false; + }); + }); } -}; +} -const hotInitCode = Template.getFunctionContent( - __webpack_require__(65217) -); +module.exports = NoEmitOnErrorsPlugin; /***/ }), -/***/ 26782: +/***/ 45759: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -80904,22 +80831,28 @@ const hotInitCode = Template.getFunctionContent( */ -const Chunk = __webpack_require__(2919); +const WebpackError = __webpack_require__(97391); -class HotUpdateChunk extends Chunk { - constructor() { +module.exports = class NoModeWarning extends WebpackError { + constructor(modules) { super(); - /** @type {(string|number)[]} */ - this.removedModules = undefined; - } -} -module.exports = HotUpdateChunk; + this.name = "NoModeWarning"; + this.message = + "configuration\n" + + "The 'mode' option has not been set, webpack will fallback to 'production' for this value. " + + "Set 'mode' option to 'development' or 'production' to enable defaults for each environment.\n" + + "You can also set it to 'none' to disable any default behavior. " + + "Learn more: https://webpack.js.org/configuration/mode/"; + + Error.captureStackTrace(this, this.constructor); + } +}; /***/ }), -/***/ 66062: +/***/ 28386: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -80929,182 +80862,123 @@ module.exports = HotUpdateChunk; */ -const Template = __webpack_require__(96066); -const HotUpdateChunk = __webpack_require__(26782); -const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(56758); +const path = __webpack_require__(85622); +const ParserHelpers = __webpack_require__(23999); +const ConstDependency = __webpack_require__(71101); -module.exports = class HotUpdateChunkTemplate extends Tapable { - constructor(outputOptions) { - super(); - this.outputOptions = outputOptions || {}; - this.hooks = { - modules: new SyncWaterfallHook([ - "source", - "modules", - "removedModules", - "moduleTemplate", - "dependencyTemplates" - ]), - render: new SyncWaterfallHook([ - "source", - "modules", - "removedModules", - "hash", - "id", - "moduleTemplate", - "dependencyTemplates" - ]), - hash: new SyncHook(["hash"]) - }; - } +const NullFactory = __webpack_require__(40438); - render( - id, - modules, - removedModules, - hash, - moduleTemplate, - dependencyTemplates - ) { - const hotUpdateChunk = new HotUpdateChunk(); - hotUpdateChunk.id = id; - hotUpdateChunk.setModules(modules); - hotUpdateChunk.removedModules = removedModules; - const modulesSource = Template.renderChunkModules( - hotUpdateChunk, - m => typeof m.source === "function", - moduleTemplate, - dependencyTemplates - ); - const core = this.hooks.modules.call( - modulesSource, - modules, - removedModules, - moduleTemplate, - dependencyTemplates - ); - const source = this.hooks.render.call( - core, - modules, - removedModules, - hash, - id, - moduleTemplate, - dependencyTemplates - ); - return source; - } - - updateHash(hash) { - hash.update("HotUpdateChunkTemplate"); - hash.update("1"); - this.hooks.hash.call(hash); - } -}; - - -/***/ }), - -/***/ 41364: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(69667); - -/** @typedef {import("../declarations/plugins/IgnorePlugin").IgnorePluginOptions} IgnorePluginOptions */ -/** @typedef {import("./Compiler")} Compiler */ - -class IgnorePlugin { - /** - * @param {IgnorePluginOptions} options IgnorePlugin options - */ +class NodeStuffPlugin { constructor(options) { - // TODO webpack 5 remove this compat-layer - if (arguments.length > 1 || options instanceof RegExp) { - options = { - resourceRegExp: arguments[0], - contextRegExp: arguments[1] - }; - } - - validateOptions(schema, options, "IgnorePlugin"); this.options = options; - - /** @private @type {Function} */ - this.checkIgnore = this.checkIgnore.bind(this); } - /** - * Note that if "contextRegExp" is given, both the "resourceRegExp" - * and "contextRegExp" have to match. - * - * @param {TODO} result result - * @returns {TODO|null} returns result or null if result should be ignored - */ - checkIgnore(result) { - if (!result) return result; + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "NodeStuffPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); - if ( - "checkResource" in this.options && - this.options.checkResource && - this.options.checkResource(result.request, result.context) - ) { - // TODO webpack 5 remove checkContext, as checkResource already gets context - if ("checkContext" in this.options && this.options.checkContext) { - if (this.options.checkContext(result.context)) { - return null; - } - } else { - return null; - } - } + const handler = (parser, parserOptions) => { + if (parserOptions.node === false) return; - if ( - "resourceRegExp" in this.options && - this.options.resourceRegExp && - this.options.resourceRegExp.test(result.request) - ) { - if ("contextRegExp" in this.options && this.options.contextRegExp) { - // if "contextRegExp" is given, - // both the "resourceRegExp" and "contextRegExp" have to match. - if (this.options.contextRegExp.test(result.context)) { - return null; - } - } else { - return null; - } - } + let localOptions = options; + if (parserOptions.node) { + localOptions = Object.assign({}, localOptions, parserOptions.node); + } - return result; - } + const setConstant = (expressionName, value) => { + parser.hooks.expression + .for(expressionName) + .tap("NodeStuffPlugin", () => { + parser.state.current.addVariable( + expressionName, + JSON.stringify(value) + ); + return true; + }); + }; - /** - * @param {Compiler} compiler Webpack Compiler - * @returns {void} - */ - apply(compiler) { - compiler.hooks.normalModuleFactory.tap("IgnorePlugin", nmf => { - nmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore); - }); - compiler.hooks.contextModuleFactory.tap("IgnorePlugin", cmf => { - cmf.hooks.beforeResolve.tap("IgnorePlugin", this.checkIgnore); - }); + const setModuleConstant = (expressionName, fn) => { + parser.hooks.expression + .for(expressionName) + .tap("NodeStuffPlugin", () => { + parser.state.current.addVariable( + expressionName, + JSON.stringify(fn(parser.state.module)) + ); + return true; + }); + }; + const context = compiler.context; + if (localOptions.__filename) { + if (localOptions.__filename === "mock") { + setConstant("__filename", "/index.js"); + } else { + setModuleConstant("__filename", module => + path.relative(context, module.resource) + ); + } + parser.hooks.evaluateIdentifier + .for("__filename") + .tap("NodeStuffPlugin", expr => { + if (!parser.state.module) return; + const resource = parser.state.module.resource; + const i = resource.indexOf("?"); + return ParserHelpers.evaluateToString( + i < 0 ? resource : resource.substr(0, i) + )(expr); + }); + } + if (localOptions.__dirname) { + if (localOptions.__dirname === "mock") { + setConstant("__dirname", "/"); + } else { + setModuleConstant("__dirname", module => + path.relative(context, module.context) + ); + } + parser.hooks.evaluateIdentifier + .for("__dirname") + .tap("NodeStuffPlugin", expr => { + if (!parser.state.module) return; + return ParserHelpers.evaluateToString( + parser.state.module.context + )(expr); + }); + } + parser.hooks.expression + .for("require.extensions") + .tap( + "NodeStuffPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + "require.extensions is not supported by webpack. Use a loader instead." + ) + ); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("NodeStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("NodeStuffPlugin", handler); + } + ); } } - -module.exports = IgnorePlugin; +module.exports = NodeStuffPlugin; /***/ }), -/***/ 98509: +/***/ 25963: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -81114,924 +80988,1124 @@ module.exports = IgnorePlugin; */ -const { RawSource, ReplaceSource } = __webpack_require__(53665); - -// TODO: clean up this file -// replace with newer constructs - -// TODO: remove DependencyVariables and replace them with something better +const NativeModule = __webpack_require__(32282); -class JavascriptGenerator { - generate(module, dependencyTemplates, runtimeTemplate) { - const originalSource = module.originalSource(); - if (!originalSource) { - return new RawSource("throw new Error('No source available');"); - } +const { + CachedSource, + LineToLineMappedSource, + OriginalSource, + RawSource, + SourceMapSource +} = __webpack_require__(53665); +const { getContext, runLoaders } = __webpack_require__(73278); - const source = new ReplaceSource(originalSource); +const WebpackError = __webpack_require__(97391); +const Module = __webpack_require__(75993); +const ModuleParseError = __webpack_require__(62500); +const ModuleBuildError = __webpack_require__(12072); +const ModuleError = __webpack_require__(82528); +const ModuleWarning = __webpack_require__(6372); +const createHash = __webpack_require__(15660); +const contextify = __webpack_require__(94658).contextify; - this.sourceBlock( - module, - module, - [], - dependencyTemplates, - source, - runtimeTemplate - ); +/** @typedef {import("./util/createHash").Hash} Hash */ - return source; +const asString = buf => { + if (Buffer.isBuffer(buf)) { + return buf.toString("utf-8"); } + return buf; +}; - sourceBlock( - module, - block, - availableVars, - dependencyTemplates, - source, - runtimeTemplate - ) { - for (const dependency of block.dependencies) { - this.sourceDependency( - dependency, - dependencyTemplates, - source, - runtimeTemplate - ); - } +const asBuffer = str => { + if (!Buffer.isBuffer(str)) { + return Buffer.from(str, "utf-8"); + } + return str; +}; - /** - * Get the variables of all blocks that we need to inject. - * These will contain the variable name and its expression. - * The name will be added as a parameter in a IIFE the expression as its value. - */ - const vars = block.variables.reduce((result, value) => { - const variable = this.sourceVariables( - value, - availableVars, - dependencyTemplates, - runtimeTemplate - ); +class NonErrorEmittedError extends WebpackError { + constructor(error) { + super(); - if (variable) { - result.push(variable); - } + this.name = "NonErrorEmittedError"; + this.message = "(Emitted value instead of an instance of Error) " + error; - return result; - }, []); + Error.captureStackTrace(this, this.constructor); + } +} - /** - * if we actually have variables - * this is important as how #splitVariablesInUniqueNamedChunks works - * it will always return an array in an array which would lead to a IIFE wrapper around - * a module if we do this with an empty vars array. - */ - if (vars.length > 0) { - /** - * Split all variables up into chunks of unique names. - * e.g. imagine you have the following variable names that need to be injected: - * [foo, bar, baz, foo, some, more] - * we can not inject "foo" twice, therefore we just make two IIFEs like so: - * (function(foo, bar, baz){ - * (function(foo, some, more){ - * … - * }(…)); - * }(…)); - * - * "splitVariablesInUniqueNamedChunks" splits the variables shown above up to this: - * [[foo, bar, baz], [foo, some, more]] - */ - const injectionVariableChunks = this.splitVariablesInUniqueNamedChunks( - vars - ); +/** + * @typedef {Object} CachedSourceEntry + * @property {TODO} source the generated source + * @property {string} hash the hash value + */ - // create all the beginnings of IIFEs - const functionWrapperStarts = injectionVariableChunks.map( - variableChunk => { - return this.variableInjectionFunctionWrapperStartCode( - variableChunk.map(variable => variable.name) - ); - } - ); +class NormalModule extends Module { + constructor({ + type, + request, + userRequest, + rawRequest, + loaders, + resource, + matchResource, + parser, + generator, + resolveOptions + }) { + super(type, getContext(resource)); - // and all the ends - const functionWrapperEnds = injectionVariableChunks.map(variableChunk => { - return this.variableInjectionFunctionWrapperEndCode( - module, - variableChunk.map(variable => variable.expression), - block - ); - }); + // Info from Factory + this.request = request; + this.userRequest = userRequest; + this.rawRequest = rawRequest; + this.binary = type.startsWith("webassembly"); + this.parser = parser; + this.generator = generator; + this.resource = resource; + this.matchResource = matchResource; + this.loaders = loaders; + if (resolveOptions !== undefined) this.resolveOptions = resolveOptions; - // join them to one big string - const varStartCode = functionWrapperStarts.join(""); + // Info from Build + this.error = null; + this._source = null; + this._sourceSize = null; + this._buildHash = ""; + this.buildTimestamp = undefined; + /** @private @type {Map} */ + this._cachedSources = new Map(); - // reverse the ends first before joining them, as the last added must be the inner most - const varEndCode = functionWrapperEnds.reverse().join(""); + // Options for the NormalModule set by plugins + // TODO refactor this -> options object filled from Factory + this.useSourceMap = false; + this.lineToLine = false; - // if we have anything, add it to the source - if (varStartCode && varEndCode) { - const start = block.range ? block.range[0] : -10; - const end = block.range - ? block.range[1] - : module.originalSource().size() + 1; - source.insert(start + 0.5, varStartCode); - source.insert(end + 0.5, "\n/* WEBPACK VAR INJECTION */" + varEndCode); - } - } + // Cache + this._lastSuccessfulBuildMeta = {}; + } - for (const childBlock of block.blocks) { - this.sourceBlock( - module, - childBlock, - availableVars.concat(vars), - dependencyTemplates, - source, - runtimeTemplate - ); - } + identifier() { + return this.request; } - sourceDependency(dependency, dependencyTemplates, source, runtimeTemplate) { - const template = dependencyTemplates.get(dependency.constructor); - if (!template) { - throw new Error( - "No template for dependency: " + dependency.constructor.name - ); - } - template.apply(dependency, source, runtimeTemplate, dependencyTemplates); + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.userRequest); } - sourceVariables( - variable, - availableVars, - dependencyTemplates, - runtimeTemplate - ) { - const name = variable.name; - const expr = variable.expressionSource( - dependencyTemplates, - runtimeTemplate - ); + libIdent(options) { + return contextify(options.context, this.userRequest); + } - if ( - availableVars.some( - v => v.name === name && v.expression.source() === expr.source() - ) - ) { - return; - } - return { - name: name, - expression: expr - }; + nameForCondition() { + const resource = this.matchResource || this.resource; + const idx = resource.indexOf("?"); + if (idx >= 0) return resource.substr(0, idx); + return resource; } - /* - * creates the start part of a IIFE around the module to inject a variable name - * (function(…){ <- this part - * }.call(…)) - */ - variableInjectionFunctionWrapperStartCode(varNames) { - const args = varNames.join(", "); - return `/* WEBPACK VAR INJECTION */(function(${args}) {`; + updateCacheModule(module) { + this.type = module.type; + this.request = module.request; + this.userRequest = module.userRequest; + this.rawRequest = module.rawRequest; + this.parser = module.parser; + this.generator = module.generator; + this.resource = module.resource; + this.matchResource = module.matchResource; + this.loaders = module.loaders; + this.resolveOptions = module.resolveOptions; } - contextArgument(module, block) { - if (this === block) { - return module.exportsArgument; + createSourceForAsset(name, content, sourceMap) { + if (!sourceMap) { + return new RawSource(content); } - return "this"; + + if (typeof sourceMap === "string") { + return new OriginalSource(content, sourceMap); + } + + return new SourceMapSource(content, name, sourceMap); } - /* - * creates the end part of a IIFE around the module to inject a variable name - * (function(…){ - * }.call(…)) <- this part - */ - variableInjectionFunctionWrapperEndCode(module, varExpressions, block) { - const firstParam = this.contextArgument(module, block); - const furtherParams = varExpressions.map(e => e.source()).join(", "); - return `}.call(${firstParam}, ${furtherParams}))`; - } + createLoaderContext(resolver, options, compilation, fs) { + const requestShortener = compilation.runtimeTemplate.requestShortener; + const getCurrentLoaderName = () => { + const currentLoader = this.getCurrentLoader(loaderContext); + if (!currentLoader) return "(not in loader scope)"; + return requestShortener.shorten(currentLoader.loader); + }; + const loaderContext = { + version: 2, + emitWarning: warning => { + if (!(warning instanceof Error)) { + warning = new NonErrorEmittedError(warning); + } + this.warnings.push( + new ModuleWarning(this, warning, { + from: getCurrentLoaderName() + }) + ); + }, + emitError: error => { + if (!(error instanceof Error)) { + error = new NonErrorEmittedError(error); + } + this.errors.push( + new ModuleError(this, error, { + from: getCurrentLoaderName() + }) + ); + }, + getLogger: name => { + const currentLoader = this.getCurrentLoader(loaderContext); + return compilation.getLogger(() => + [currentLoader && currentLoader.loader, name, this.identifier()] + .filter(Boolean) + .join("|") + ); + }, + // TODO remove in webpack 5 + exec: (code, filename) => { + // @ts-ignore Argument of type 'this' is not assignable to parameter of type 'Module'. + const module = new NativeModule(filename, this); + // @ts-ignore _nodeModulePaths is deprecated and undocumented Node.js API + module.paths = NativeModule._nodeModulePaths(this.context); + module.filename = filename; + module._compile(code, filename); + return module.exports; + }, + resolve(context, request, callback) { + resolver.resolve({}, context, request, {}, callback); + }, + getResolve(options) { + const child = options ? resolver.withOptions(options) : resolver; + return (context, request, callback) => { + if (callback) { + child.resolve({}, context, request, {}, callback); + } else { + return new Promise((resolve, reject) => { + child.resolve({}, context, request, {}, (err, result) => { + if (err) reject(err); + else resolve(result); + }); + }); + } + }; + }, + emitFile: (name, content, sourceMap, assetInfo) => { + if (!this.buildInfo.assets) { + this.buildInfo.assets = Object.create(null); + this.buildInfo.assetsInfo = new Map(); + } + this.buildInfo.assets[name] = this.createSourceForAsset( + name, + content, + sourceMap + ); + this.buildInfo.assetsInfo.set(name, assetInfo); + }, + rootContext: options.context, + webpack: true, + sourceMap: !!this.useSourceMap, + mode: options.mode || "production", + _module: this, + _compilation: compilation, + _compiler: compilation.compiler, + fs: fs + }; - splitVariablesInUniqueNamedChunks(vars) { - const startState = [[]]; - return vars.reduce((chunks, variable) => { - const current = chunks[chunks.length - 1]; - // check if variable with same name exists already - // if so create a new chunk of variables. - const variableNameAlreadyExists = current.some( - v => v.name === variable.name - ); + compilation.hooks.normalModuleLoader.call(loaderContext, this); + if (options.loader) { + Object.assign(loaderContext, options.loader); + } - if (variableNameAlreadyExists) { - // start new chunk with current variable - chunks.push([variable]); - } else { - // else add it to current chunk - current.push(variable); - } - return chunks; - }, startState); + return loaderContext; } -} - -module.exports = JavascriptGenerator; + getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) { + if ( + this.loaders && + this.loaders.length && + index < this.loaders.length && + index >= 0 && + this.loaders[index] + ) { + return this.loaders[index]; + } + return null; + } -/***/ }), + createSource(source, resourceBuffer, sourceMap) { + // if there is no identifier return raw source + if (!this.identifier) { + return new RawSource(source); + } -/***/ 10339: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // from here on we assume we have an identifier + const identifier = this.identifier(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (this.lineToLine && resourceBuffer) { + return new LineToLineMappedSource( + source, + identifier, + asString(resourceBuffer) + ); + } + if (this.useSourceMap && sourceMap) { + return new SourceMapSource(source, identifier, sourceMap); + } -const Parser = __webpack_require__(70558); -const Template = __webpack_require__(96066); -const { ConcatSource } = __webpack_require__(53665); -const JavascriptGenerator = __webpack_require__(98509); -const createHash = __webpack_require__(15660); + if (Buffer.isBuffer(source)) { + // @ts-ignore + // TODO We need to fix @types/webpack-sources to allow RawSource to take a Buffer | string + return new RawSource(source); + } -class JavascriptModulesPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "JavascriptModulesPlugin", - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.createParser - .for("javascript/auto") - .tap("JavascriptModulesPlugin", options => { - return new Parser(options, "auto"); - }); - normalModuleFactory.hooks.createParser - .for("javascript/dynamic") - .tap("JavascriptModulesPlugin", options => { - return new Parser(options, "script"); - }); - normalModuleFactory.hooks.createParser - .for("javascript/esm") - .tap("JavascriptModulesPlugin", options => { - return new Parser(options, "module"); - }); - normalModuleFactory.hooks.createGenerator - .for("javascript/auto") - .tap("JavascriptModulesPlugin", () => { - return new JavascriptGenerator(); - }); - normalModuleFactory.hooks.createGenerator - .for("javascript/dynamic") - .tap("JavascriptModulesPlugin", () => { - return new JavascriptGenerator(); - }); - normalModuleFactory.hooks.createGenerator - .for("javascript/esm") - .tap("JavascriptModulesPlugin", () => { - return new JavascriptGenerator(); - }); - compilation.mainTemplate.hooks.renderManifest.tap( - "JavascriptModulesPlugin", - (result, options) => { - const chunk = options.chunk; - const hash = options.hash; - const fullHash = options.fullHash; - const outputOptions = options.outputOptions; - const moduleTemplates = options.moduleTemplates; - const dependencyTemplates = options.dependencyTemplates; + return new OriginalSource(source, identifier); + } - const filenameTemplate = - chunk.filenameTemplate || outputOptions.filename; + doBuild(options, compilation, resolver, fs, callback) { + const loaderContext = this.createLoaderContext( + resolver, + options, + compilation, + fs + ); - const useChunkHash = compilation.mainTemplate.useChunkHash(chunk); + runLoaders( + { + resource: this.resource, + loaders: this.loaders, + context: loaderContext, + readResource: fs.readFile.bind(fs) + }, + (err, result) => { + if (result) { + this.buildInfo.cacheable = result.cacheable; + this.buildInfo.fileDependencies = new Set(result.fileDependencies); + this.buildInfo.contextDependencies = new Set( + result.contextDependencies + ); + } - result.push({ - render: () => - compilation.mainTemplate.render( - hash, - chunk, - moduleTemplates.javascript, - dependencyTemplates - ), - filenameTemplate, - pathOptions: { - noChunkHash: !useChunkHash, - contentHashType: "javascript", - chunk - }, - identifier: `chunk${chunk.id}`, - hash: useChunkHash ? chunk.hash : fullHash - }); - return result; - } - ); - compilation.mainTemplate.hooks.modules.tap( - "JavascriptModulesPlugin", - (source, chunk, hash, moduleTemplate, dependencyTemplates) => { - return Template.renderChunkModules( - chunk, - m => typeof m.source === "function", - moduleTemplate, - dependencyTemplates, - "/******/ " - ); + if (err) { + if (!(err instanceof Error)) { + err = new NonErrorEmittedError(err); } - ); - compilation.chunkTemplate.hooks.renderManifest.tap( - "JavascriptModulesPlugin", - (result, options) => { - const chunk = options.chunk; - const outputOptions = options.outputOptions; - const moduleTemplates = options.moduleTemplates; - const dependencyTemplates = options.dependencyTemplates; - const filenameTemplate = - chunk.filenameTemplate || outputOptions.chunkFilename; + const currentLoader = this.getCurrentLoader(loaderContext); + const error = new ModuleBuildError(this, err, { + from: + currentLoader && + compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader + ) + }); + return callback(error); + } - result.push({ - render: () => - this.renderJavascript( - compilation.chunkTemplate, - chunk, - moduleTemplates.javascript, - dependencyTemplates - ), - filenameTemplate, - pathOptions: { - chunk, - contentHashType: "javascript" - }, - identifier: `chunk${chunk.id}`, - hash: chunk.hash - }); + const resourceBuffer = result.resourceBuffer; + const source = result.result[0]; + const sourceMap = result.result.length >= 1 ? result.result[1] : null; + const extraInfo = result.result.length >= 2 ? result.result[2] : null; - return result; - } - ); - compilation.hooks.contentHash.tap("JavascriptModulesPlugin", chunk => { - const outputOptions = compilation.outputOptions; - const { - hashSalt, - hashDigest, - hashDigestLength, - hashFunction - } = outputOptions; - const hash = createHash(hashFunction); - if (hashSalt) hash.update(hashSalt); - const template = chunk.hasRuntime() - ? compilation.mainTemplate - : compilation.chunkTemplate; - hash.update(`${chunk.id} `); - hash.update(chunk.ids ? chunk.ids.join(",") : ""); - template.updateHashForChunk( - hash, - chunk, - compilation.moduleTemplates.javascript, - compilation.dependencyTemplates + if (!Buffer.isBuffer(source) && typeof source !== "string") { + const currentLoader = this.getCurrentLoader(loaderContext, 0); + const err = new Error( + `Final loader (${ + currentLoader + ? compilation.runtimeTemplate.requestShortener.shorten( + currentLoader.loader + ) + : "unknown" + }) didn't return a Buffer or String` ); - for (const m of chunk.modulesIterable) { - if (typeof m.source === "function") { - hash.update(m.hash); - } - } - const digest = /** @type {string} */ (hash.digest(hashDigest)); - chunk.contentHash.javascript = digest.substr(0, hashDigestLength); - }); + const error = new ModuleBuildError(this, err); + return callback(error); + } + + this._source = this.createSource( + this.binary ? asBuffer(source) : asString(source), + resourceBuffer, + sourceMap + ); + this._sourceSize = null; + this._ast = + typeof extraInfo === "object" && + extraInfo !== null && + extraInfo.webpackAST !== undefined + ? extraInfo.webpackAST + : null; + return callback(); } ); } - renderJavascript(chunkTemplate, chunk, moduleTemplate, dependencyTemplates) { - const moduleSources = Template.renderChunkModules( - chunk, - m => typeof m.source === "function", - moduleTemplate, - dependencyTemplates - ); - const core = chunkTemplate.hooks.modules.call( - moduleSources, - chunk, - moduleTemplate, - dependencyTemplates - ); - let source = chunkTemplate.hooks.render.call( - core, - chunk, - moduleTemplate, - dependencyTemplates + markModuleAsErrored(error) { + // Restore build meta from successful build to keep importing state + this.buildMeta = Object.assign({}, this._lastSuccessfulBuildMeta); + this.error = error; + this.errors.push(this.error); + this._source = new RawSource( + "throw new Error(" + JSON.stringify(this.error.message) + ");" ); - if (chunk.hasEntryModule()) { - source = chunkTemplate.hooks.renderWithEntry.call(source, chunk); - } - chunk.rendered = true; - return new ConcatSource(source, ";"); + this._sourceSize = null; + this._ast = null; } -} - -module.exports = JavascriptModulesPlugin; - -/***/ }), - -/***/ 72806: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const { ConcatSource, RawSource } = __webpack_require__(53665); + applyNoParseRule(rule, content) { + // must start with "rule" if rule is a string + if (typeof rule === "string") { + return content.indexOf(rule) === 0; + } -const stringifySafe = data => { - const stringified = JSON.stringify(data); - if (!stringified) { - return undefined; // Invalid JSON + if (typeof rule === "function") { + return rule(content); + } + // we assume rule is a regexp + return rule.test(content); } - return stringified.replace(/\u2028|\u2029/g, str => - str === "\u2029" ? "\\u2029" : "\\u2028" - ); // invalid in JavaScript but valid JSON -}; + // check if module should not be parsed + // returns "true" if the module should !not! be parsed + // returns "false" if the module !must! be parsed + shouldPreventParsing(noParseRule, request) { + // if no noParseRule exists, return false + // the module !must! be parsed. + if (!noParseRule) { + return false; + } -class JsonGenerator { - generate(module, dependencyTemplates, runtimeTemplate) { - const source = new ConcatSource(); - const data = module.buildInfo.jsonData; - if (data === undefined) { - return new RawSource( - runtimeTemplate.missingModuleStatement({ - request: module.rawRequest - }) - ); + // we only have one rule to check + if (!Array.isArray(noParseRule)) { + // returns "true" if the module is !not! to be parsed + return this.applyNoParseRule(noParseRule, request); } - let finalJson; - if ( - Array.isArray(module.buildMeta.providedExports) && - !module.isUsed("default") - ) { - // Only some exports are used: We can optimize here, by only generating a part of the JSON - const reducedJson = {}; - for (const exportName of module.buildMeta.providedExports) { - if (exportName === "default") continue; - const used = module.isUsed(exportName); - if (used) { - reducedJson[used] = data[exportName]; - } + + for (let i = 0; i < noParseRule.length; i++) { + const rule = noParseRule[i]; + // early exit on first truthy match + // this module is !not! to be parsed + if (this.applyNoParseRule(rule, request)) { + return true; } - finalJson = reducedJson; - } else { - finalJson = data; } - // Use JSON because JSON.parse() is much faster than JavaScript evaluation - const jsonSource = JSON.stringify(stringifySafe(finalJson)); - const jsonExpr = `JSON.parse(${jsonSource})`; - source.add(`${module.moduleArgument}.exports = ${jsonExpr};`); - return source; + // no match found, so this module !should! be parsed + return false; } -} - -module.exports = JsonGenerator; - - -/***/ }), - -/***/ 2859: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const JsonParser = __webpack_require__(5807); -const JsonGenerator = __webpack_require__(72806); + _initBuildHash(compilation) { + const hash = createHash(compilation.outputOptions.hashFunction); + if (this._source) { + hash.update("source"); + this._source.updateHash(hash); + } + hash.update("meta"); + hash.update(JSON.stringify(this.buildMeta)); + this._buildHash = /** @type {string} */ (hash.digest("hex")); + } -class JsonModulesPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "JsonModulesPlugin", - (compilation, { normalModuleFactory }) => { - normalModuleFactory.hooks.createParser - .for("json") - .tap("JsonModulesPlugin", () => { - return new JsonParser(); - }); - normalModuleFactory.hooks.createGenerator - .for("json") - .tap("JsonModulesPlugin", () => { - return new JsonGenerator(); - }); + build(options, compilation, resolver, fs, callback) { + this.buildTimestamp = Date.now(); + this.built = true; + this._source = null; + this._sourceSize = null; + this._ast = null; + this._buildHash = ""; + this.error = null; + this.errors.length = 0; + this.warnings.length = 0; + this.buildMeta = {}; + this.buildInfo = { + cacheable: false, + fileDependencies: new Set(), + contextDependencies: new Set(), + assets: undefined, + assetsInfo: undefined + }; + + return this.doBuild(options, compilation, resolver, fs, err => { + this._cachedSources.clear(); + + // if we have an error mark module as failed and exit + if (err) { + this.markModuleAsErrored(err); + this._initBuildHash(compilation); + return callback(); } - ); + + // check if this module should !not! be parsed. + // if so, exit here; + const noParseRule = options.module && options.module.noParse; + if (this.shouldPreventParsing(noParseRule, this.request)) { + this._initBuildHash(compilation); + return callback(); + } + + const handleParseError = e => { + const source = this._source.source(); + const loaders = this.loaders.map(item => + contextify(options.context, item.loader) + ); + const error = new ModuleParseError(this, source, e, loaders); + this.markModuleAsErrored(error); + this._initBuildHash(compilation); + return callback(); + }; + + const handleParseResult = result => { + this._lastSuccessfulBuildMeta = this.buildMeta; + this._initBuildHash(compilation); + return callback(); + }; + + try { + const result = this.parser.parse( + this._ast || this._source.source(), + { + current: this, + module: this, + compilation: compilation, + options: options + }, + (err, result) => { + if (err) { + handleParseError(err); + } else { + handleParseResult(result); + } + } + ); + if (result !== undefined) { + // parse is sync + handleParseResult(result); + } + } catch (e) { + handleParseError(e); + } + }); } -} -module.exports = JsonModulesPlugin; + getHashDigest(dependencyTemplates) { + // TODO webpack 5 refactor + let dtHash = dependencyTemplates.get("hash"); + return `${this.hash}-${dtHash}`; + } + source(dependencyTemplates, runtimeTemplate, type = "javascript") { + const hashDigest = this.getHashDigest(dependencyTemplates); + const cacheEntry = this._cachedSources.get(type); + if (cacheEntry !== undefined && cacheEntry.hash === hashDigest) { + // We can reuse the cached source + return cacheEntry.source; + } -/***/ }), + const source = this.generator.generate( + this, + dependencyTemplates, + runtimeTemplate, + type + ); -/***/ 5807: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const cachedSource = new CachedSource(source); + this._cachedSources.set(type, { + source: cachedSource, + hash: hashDigest + }); + return cachedSource; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + originalSource() { + return this._source; + } + needRebuild(fileTimestamps, contextTimestamps) { + // always try to rebuild in case of an error + if (this.error) return true; -const parseJson = __webpack_require__(48335); -const JsonExportsDependency = __webpack_require__(54396); + // always rebuild when module is not cacheable + if (!this.buildInfo.cacheable) return true; -class JsonParser { - constructor(options) { - this.options = options; + // Check timestamps of all dependencies + // Missing timestamp -> need rebuild + // Timestamp bigger than buildTimestamp -> need rebuild + for (const file of this.buildInfo.fileDependencies) { + const timestamp = fileTimestamps.get(file); + if (!timestamp) return true; + if (timestamp >= this.buildTimestamp) return true; + } + for (const file of this.buildInfo.contextDependencies) { + const timestamp = contextTimestamps.get(file); + if (!timestamp) return true; + if (timestamp >= this.buildTimestamp) return true; + } + // elsewise -> no rebuild needed + return false; } - parse(source, state) { - const data = parseJson(source[0] === "\ufeff" ? source.slice(1) : source); - state.module.buildInfo.jsonData = data; - state.module.buildMeta.exportsType = "named"; - if (typeof data === "object" && data) { - state.module.addDependency(new JsonExportsDependency(Object.keys(data))); + size() { + if (this._sourceSize === null) { + this._sourceSize = this._source ? this._source.size() : -1; } - state.module.addDependency(new JsonExportsDependency(["default"])); - return state; + return this._sourceSize; + } + + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + hash.update(this._buildHash); + super.updateHash(hash); } } -module.exports = JsonParser; +module.exports = NormalModule; /***/ }), -/***/ 30735: +/***/ 22298: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ const path = __webpack_require__(85622); const asyncLib = __webpack_require__(36386); -const SingleEntryDependency = __webpack_require__(84828); +const { + Tapable, + AsyncSeriesWaterfallHook, + SyncWaterfallHook, + SyncBailHook, + SyncHook, + HookMap +} = __webpack_require__(56758); +const NormalModule = __webpack_require__(25963); +const RawModule = __webpack_require__(82353); +const RuleSet = __webpack_require__(84247); +const { cachedCleverMerge } = __webpack_require__(67916); -class LibManifestPlugin { - constructor(options) { - this.options = options; +const EMPTY_RESOLVE_OPTIONS = {}; + +const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; + +const loaderToIdent = data => { + if (!data.options) { + return data.loader; + } + if (typeof data.options === "string") { + return data.loader + "?" + data.options; + } + if (typeof data.options !== "object") { + throw new Error("loader options must be string or object"); + } + if (data.ident) { + return data.loader + "??" + data.ident; } + return data.loader + "?" + JSON.stringify(data.options); +}; - apply(compiler) { - compiler.hooks.emit.tapAsync( - "LibManifestPlugin", - (compilation, callback) => { - asyncLib.forEach( - compilation.chunks, - (chunk, callback) => { - if (!chunk.isOnlyInitial()) { - callback(); - return; - } - const targetPath = compilation.getPath(this.options.path, { - hash: compilation.hash, - chunk - }); - const name = - this.options.name && - compilation.getPath(this.options.name, { - hash: compilation.hash, - chunk - }); - const manifest = { - name, - type: this.options.type, - content: Array.from(chunk.modulesIterable, module => { - if ( - this.options.entryOnly && - !module.reasons.some( - r => r.dependency instanceof SingleEntryDependency - ) - ) { - return; - } - if (module.libIdent) { - const ident = module.libIdent({ - context: this.options.context || compiler.options.context - }); - if (ident) { - return { - ident, - data: { - id: module.id, - buildMeta: module.buildMeta - } - }; - } - } - }) - .filter(Boolean) - .reduce((obj, item) => { - obj[item.ident] = item.data; - return obj; - }, Object.create(null)) - }; - // Apply formatting to content if format flag is true; - const manifestContent = this.options.format - ? JSON.stringify(manifest, null, 2) - : JSON.stringify(manifest); - const content = Buffer.from(manifestContent, "utf8"); - compiler.outputFileSystem.mkdirp(path.dirname(targetPath), err => { - if (err) return callback(err); - compiler.outputFileSystem.writeFile( - targetPath, - content, - callback - ); - }); - }, - callback - ); - } - ); +const identToLoaderRequest = resultString => { + const idx = resultString.indexOf("?"); + if (idx >= 0) { + const loader = resultString.substr(0, idx); + const options = resultString.substr(idx + 1); + return { + loader, + options + }; + } else { + return { + loader: resultString, + options: undefined + }; } -} -module.exports = LibManifestPlugin; +}; +const dependencyCache = new WeakMap(); -/***/ }), +class NormalModuleFactory extends Tapable { + constructor(context, resolverFactory, options) { + super(); + this.hooks = { + resolver: new SyncWaterfallHook(["resolver"]), + factory: new SyncWaterfallHook(["factory"]), + beforeResolve: new AsyncSeriesWaterfallHook(["data"]), + afterResolve: new AsyncSeriesWaterfallHook(["data"]), + createModule: new SyncBailHook(["data"]), + module: new SyncWaterfallHook(["module", "data"]), + createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), + parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), + createGenerator: new HookMap( + () => new SyncBailHook(["generatorOptions"]) + ), + generator: new HookMap( + () => new SyncHook(["generator", "generatorOptions"]) + ) + }; + this._pluginCompat.tap("NormalModuleFactory", options => { + switch (options.name) { + case "before-resolve": + case "after-resolve": + options.async = true; + break; + case "parser": + this.hooks.parser + .for("javascript/auto") + .tap(options.fn.name || "unnamed compat plugin", options.fn); + return true; + } + let match; + match = /^parser (.+)$/.exec(options.name); + if (match) { + this.hooks.parser + .for(match[1]) + .tap( + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + return true; + } + match = /^create-parser (.+)$/.exec(options.name); + if (match) { + this.hooks.createParser + .for(match[1]) + .tap( + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + return true; + } + }); + this.resolverFactory = resolverFactory; + this.ruleSet = new RuleSet(options.defaultRules.concat(options.rules)); + this.cachePredicate = + typeof options.unsafeCache === "function" + ? options.unsafeCache + : Boolean.bind(null, options.unsafeCache); + this.context = context || ""; + this.parserCache = Object.create(null); + this.generatorCache = Object.create(null); + this.hooks.factory.tap("NormalModuleFactory", () => (result, callback) => { + let resolver = this.hooks.resolver.call(null); -/***/ 65237: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Ignored + if (!resolver) return callback(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + resolver(result, (err, data) => { + if (err) return callback(err); + // Ignored + if (!data) return callback(); -const SetVarMainTemplatePlugin = __webpack_require__(37098); + // direct module + if (typeof data.source === "function") return callback(null, data); -/** @typedef {import("../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ -/** @typedef {import("./Compiler")} Compiler */ + this.hooks.afterResolve.callAsync(data, (err, result) => { + if (err) return callback(err); -/** - * @param {string[]} accessor the accessor to convert to path - * @returns {string} the path - */ -const accessorToObjectAccess = accessor => { - return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); -}; + // Ignored + if (!result) return callback(); -/** - * @param {string=} base the path prefix - * @param {string|string[]|LibraryCustomUmdObject} accessor the accessor - * @param {"amd" | "commonjs" | "root"} umdProperty property used when a custom umd object is provided - * @param {string=} joinWith the element separator - * @returns {string} the path - */ -const accessorAccess = (base, accessor, umdProperty, joinWith = "; ") => { - const normalizedAccessor = - typeof accessor === "object" && !Array.isArray(accessor) - ? accessor[umdProperty] - : accessor; - const accessors = Array.isArray(normalizedAccessor) - ? normalizedAccessor - : [normalizedAccessor]; - return accessors - .map((_, idx) => { - const a = base - ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) - : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); - if (idx === accessors.length - 1) return a; - if (idx === 0 && base === undefined) { - return `${a} = typeof ${a} === "object" ? ${a} : {}`; - } - return `${a} = ${a} || {}`; - }) - .join(joinWith); -}; + let createdModule = this.hooks.createModule.call(result); + if (!createdModule) { + if (!result.request) { + return callback(new Error("Empty dependency (no request)")); + } -class LibraryTemplatePlugin { - /** - * @param {string|string[]|LibraryCustomUmdObject} name name of library - * @param {string} target type of library - * @param {boolean} umdNamedDefine setting this to true will name the UMD module - * @param {string|TODO} auxiliaryComment comment in the UMD wrapper - * @param {string|string[]} exportProperty which export should be exposed as library - */ - constructor(name, target, umdNamedDefine, auxiliaryComment, exportProperty) { - this.name = name; - this.target = target; - this.umdNamedDefine = umdNamedDefine; - this.auxiliaryComment = auxiliaryComment; - this.exportProperty = exportProperty; - } + createdModule = new NormalModule(result); + } - /** - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap("LibraryTemplatePlugin", compilation => { - if (this.exportProperty) { - const ExportPropertyMainTemplatePlugin = __webpack_require__(50471); - new ExportPropertyMainTemplatePlugin(this.exportProperty).apply( - compilation + createdModule = this.hooks.module.call(createdModule, result); + + return callback(null, createdModule); + }); + }); + }); + this.hooks.resolver.tap("NormalModuleFactory", () => (data, callback) => { + const contextInfo = data.contextInfo; + const context = data.context; + const request = data.request; + + const loaderResolver = this.getResolver("loader"); + const normalResolver = this.getResolver("normal", data.resolveOptions); + + let matchResource = undefined; + let requestWithoutMatchResource = request; + const matchResourceMatch = MATCH_RESOURCE_REGEX.exec(request); + if (matchResourceMatch) { + matchResource = matchResourceMatch[1]; + if (/^\.\.?\//.test(matchResource)) { + matchResource = path.join(context, matchResource); + } + requestWithoutMatchResource = request.substr( + matchResourceMatch[0].length ); } - switch (this.target) { - case "var": - if ( - !this.name || - (typeof this.name === "object" && !Array.isArray(this.name)) - ) { - throw new Error( - "library name must be set and not an UMD custom object for non-UMD target" - ); - } - new SetVarMainTemplatePlugin( - `var ${accessorAccess(undefined, this.name, "root")}`, - false - ).apply(compilation); - break; - case "assign": - new SetVarMainTemplatePlugin( - accessorAccess(undefined, this.name, "root"), - false - ).apply(compilation); - break; - case "this": - case "self": - case "window": - if (this.name) { - new SetVarMainTemplatePlugin( - accessorAccess(this.target, this.name, "root"), - false - ).apply(compilation); - } else { - new SetVarMainTemplatePlugin(this.target, true).apply(compilation); + + const noPreAutoLoaders = requestWithoutMatchResource.startsWith("-!"); + const noAutoLoaders = + noPreAutoLoaders || requestWithoutMatchResource.startsWith("!"); + const noPrePostAutoLoaders = requestWithoutMatchResource.startsWith("!!"); + let elements = requestWithoutMatchResource + .replace(/^-?!+/, "") + .replace(/!!+/g, "!") + .split("!"); + let resource = elements.pop(); + elements = elements.map(identToLoaderRequest); + + asyncLib.parallel( + [ + callback => + this.resolveRequestArray( + contextInfo, + context, + elements, + loaderResolver, + callback + ), + callback => { + if (resource === "" || resource[0] === "?") { + return callback(null, { + resource + }); + } + + normalResolver.resolve( + contextInfo, + context, + resource, + {}, + (err, resource, resourceResolveData) => { + if (err) return callback(err); + callback(null, { + resourceResolveData, + resource + }); + } + ); } - break; - case "global": - if (this.name) { - new SetVarMainTemplatePlugin( - accessorAccess( - compilation.runtimeTemplate.outputOptions.globalObject, - this.name, - "root" - ), - false - ).apply(compilation); - } else { - new SetVarMainTemplatePlugin( - compilation.runtimeTemplate.outputOptions.globalObject, - true - ).apply(compilation); + ], + (err, results) => { + if (err) return callback(err); + let loaders = results[0]; + const resourceResolveData = results[1].resourceResolveData; + resource = results[1].resource; + + // translate option idents + try { + for (const item of loaders) { + if (typeof item.options === "string" && item.options[0] === "?") { + const ident = item.options.substr(1); + item.options = this.ruleSet.findOptionsByIdent(ident); + item.ident = ident; + } + } + } catch (e) { + return callback(e); } - break; - case "commonjs": - if (this.name) { - new SetVarMainTemplatePlugin( - accessorAccess("exports", this.name, "commonjs"), - false - ).apply(compilation); - } else { - new SetVarMainTemplatePlugin("exports", true).apply(compilation); + + if (resource === false) { + // ignored + return callback( + null, + new RawModule( + "/* (ignored) */", + `ignored ${context} ${request}`, + `${request} (ignored)` + ) + ); } - break; - case "commonjs2": - case "commonjs-module": - new SetVarMainTemplatePlugin("module.exports", false).apply( - compilation - ); - break; - case "amd": - case "amd-require": { - const AmdMainTemplatePlugin = __webpack_require__(9701); - if (this.name && typeof this.name !== "string") { - throw new Error("library name must be a string for amd target"); + + const userRequest = + (matchResource !== undefined ? `${matchResource}!=!` : "") + + loaders + .map(loaderToIdent) + .concat([resource]) + .join("!"); + + let resourcePath = + matchResource !== undefined ? matchResource : resource; + let resourceQuery = ""; + const queryIndex = resourcePath.indexOf("?"); + if (queryIndex >= 0) { + resourceQuery = resourcePath.substr(queryIndex); + resourcePath = resourcePath.substr(0, queryIndex); } - new AmdMainTemplatePlugin({ - name: this.name, - requireAsWrapper: this.target === "amd-require" - }).apply(compilation); - break; - } - case "umd": - case "umd2": { - const UmdMainTemplatePlugin = __webpack_require__(75374); - new UmdMainTemplatePlugin(this.name, { - optionalAmdExternalAsGlobal: this.target === "umd2", - namedDefine: this.umdNamedDefine, - auxiliaryComment: this.auxiliaryComment - }).apply(compilation); - break; - } - case "jsonp": { - const JsonpExportMainTemplatePlugin = __webpack_require__(13732); - if (typeof this.name !== "string") - throw new Error("library name must be a string for jsonp target"); - new JsonpExportMainTemplatePlugin(this.name).apply(compilation); - break; - } - case "system": { - const SystemMainTemplatePlugin = __webpack_require__(97365); - new SystemMainTemplatePlugin({ - name: this.name - }).apply(compilation); - break; + + const result = this.ruleSet.exec({ + resource: resourcePath, + realResource: + matchResource !== undefined + ? resource.replace(/\?.*/, "") + : resourcePath, + resourceQuery, + issuer: contextInfo.issuer, + compiler: contextInfo.compiler + }); + const settings = {}; + const useLoadersPost = []; + const useLoaders = []; + const useLoadersPre = []; + for (const r of result) { + if (r.type === "use") { + if (r.enforce === "post" && !noPrePostAutoLoaders) { + useLoadersPost.push(r.value); + } else if ( + r.enforce === "pre" && + !noPreAutoLoaders && + !noPrePostAutoLoaders + ) { + useLoadersPre.push(r.value); + } else if ( + !r.enforce && + !noAutoLoaders && + !noPrePostAutoLoaders + ) { + useLoaders.push(r.value); + } + } else if ( + typeof r.value === "object" && + r.value !== null && + typeof settings[r.type] === "object" && + settings[r.type] !== null + ) { + settings[r.type] = cachedCleverMerge(settings[r.type], r.value); + } else { + settings[r.type] = r.value; + } + } + asyncLib.parallel( + [ + this.resolveRequestArray.bind( + this, + contextInfo, + this.context, + useLoadersPost, + loaderResolver + ), + this.resolveRequestArray.bind( + this, + contextInfo, + this.context, + useLoaders, + loaderResolver + ), + this.resolveRequestArray.bind( + this, + contextInfo, + this.context, + useLoadersPre, + loaderResolver + ) + ], + (err, results) => { + if (err) return callback(err); + if (matchResource === undefined) { + loaders = results[0].concat(loaders, results[1], results[2]); + } else { + loaders = results[0].concat(results[1], loaders, results[2]); + } + process.nextTick(() => { + const type = settings.type; + const resolveOptions = settings.resolve; + callback(null, { + context: context, + request: loaders + .map(loaderToIdent) + .concat([resource]) + .join("!"), + dependencies: data.dependencies, + userRequest, + rawRequest: request, + loaders, + resource, + matchResource, + resourceResolveData, + settings, + type, + parser: this.getParser(type, settings.parser), + generator: this.getGenerator(type, settings.generator), + resolveOptions + }); + }); + } + ); } - default: - throw new Error(`${this.target} is not a valid Library target`); - } + ); }); } -} -module.exports = LibraryTemplatePlugin; + create(data, callback) { + const dependencies = data.dependencies; + const cacheEntry = dependencyCache.get(dependencies[0]); + if (cacheEntry) return callback(null, cacheEntry); + const context = data.context || this.context; + const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS; + const request = dependencies[0].request; + const contextInfo = data.contextInfo || {}; + this.hooks.beforeResolve.callAsync( + { + contextInfo, + resolveOptions, + context, + request, + dependencies + }, + (err, result) => { + if (err) return callback(err); + // Ignored + if (!result) return callback(); -/***/ }), + const factory = this.hooks.factory.call(null); -/***/ 48775: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Ignored + if (!factory) return callback(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + factory(result, (err, module) => { + if (err) return callback(err); + if (module && this.cachePredicate(module)) { + for (const d of dependencies) { + dependencyCache.set(d, module); + } + } -const ModuleFilenameHelpers = __webpack_require__(71474); + callback(null, module); + }); + } + ); + } -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(4994); + resolveRequestArray(contextInfo, context, array, resolver, callback) { + if (array.length === 0) return callback(null, []); + asyncLib.map( + array, + (item, callback) => { + resolver.resolve( + contextInfo, + context, + item.loader, + {}, + (err, result) => { + if ( + err && + /^[^/]*$/.test(item.loader) && + !/-loader$/.test(item.loader) + ) { + return resolver.resolve( + contextInfo, + context, + item.loader + "-loader", + {}, + err2 => { + if (!err2) { + err.message = + err.message + + "\n" + + "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" + + ` You need to specify '${item.loader}-loader' instead of '${item.loader}',\n` + + " see https://webpack.js.org/migrate/3/#automatic-loader-module-name-extension-removed"; + } + callback(err); + } + ); + } + if (err) return callback(err); -/** @typedef {import("../declarations/plugins/LoaderOptionsPlugin").LoaderOptionsPluginOptions} LoaderOptionsPluginOptions */ + const optionsOnly = item.options + ? { + options: item.options + } + : undefined; + return callback( + null, + Object.assign({}, item, identToLoaderRequest(result), optionsOnly) + ); + } + ); + }, + callback + ); + } -class LoaderOptionsPlugin { - /** - * @param {LoaderOptionsPluginOptions} options options object - */ - constructor(options) { - validateOptions(schema, options || {}, "Loader Options Plugin"); + getParser(type, parserOptions) { + let ident = type; + if (parserOptions) { + if (parserOptions.ident) { + ident = `${type}|${parserOptions.ident}`; + } else { + ident = JSON.stringify([type, parserOptions]); + } + } + if (ident in this.parserCache) { + return this.parserCache[ident]; + } + return (this.parserCache[ident] = this.createParser(type, parserOptions)); + } - if (typeof options !== "object") options = {}; - if (!options.test) { - options.test = { - test: () => true - }; + createParser(type, parserOptions = {}) { + const parser = this.hooks.createParser.for(type).call(parserOptions); + if (!parser) { + throw new Error(`No parser registered for ${type}`); } - this.options = options; + this.hooks.parser.for(type).call(parser, parserOptions); + return parser; } - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap("LoaderOptionsPlugin", compilation => { - compilation.hooks.normalModuleLoader.tap( - "LoaderOptionsPlugin", - (context, module) => { - const resource = module.resource; - if (!resource) return; - const i = resource.indexOf("?"); - if ( - ModuleFilenameHelpers.matchObject( - options, - i < 0 ? resource : resource.substr(0, i) - ) - ) { - for (const key of Object.keys(options)) { - if (key === "include" || key === "exclude" || key === "test") { - continue; - } - context[key] = options[key]; - } - } - } - ); - }); + getGenerator(type, generatorOptions) { + let ident = type; + if (generatorOptions) { + if (generatorOptions.ident) { + ident = `${type}|${generatorOptions.ident}`; + } else { + ident = JSON.stringify([type, generatorOptions]); + } + } + if (ident in this.generatorCache) { + return this.generatorCache[ident]; + } + return (this.generatorCache[ident] = this.createGenerator( + type, + generatorOptions + )); + } + + createGenerator(type, generatorOptions = {}) { + const generator = this.hooks.createGenerator + .for(type) + .call(generatorOptions); + if (!generator) { + throw new Error(`No generator registered for ${type}`); + } + this.hooks.generator.for(type).call(generator, generatorOptions); + return generator; + } + + getResolver(type, resolveOptions) { + return this.resolverFactory.get( + type, + resolveOptions || EMPTY_RESOLVE_OPTIONS + ); } } -module.exports = LoaderOptionsPlugin; +module.exports = NormalModuleFactory; /***/ }), -/***/ 95154: -/***/ (function(module) { +/***/ 73253: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -82040,30 +82114,57 @@ module.exports = LoaderOptionsPlugin; */ -class LoaderTargetPlugin { - constructor(target) { - this.target = target; +const path = __webpack_require__(85622); + +class NormalModuleReplacementPlugin { + constructor(resourceRegExp, newResource) { + this.resourceRegExp = resourceRegExp; + this.newResource = newResource; } apply(compiler) { - compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => { - compilation.hooks.normalModuleLoader.tap( - "LoaderTargetPlugin", - loaderContext => { - loaderContext.target = this.target; - } - ); - }); + const resourceRegExp = this.resourceRegExp; + const newResource = this.newResource; + compiler.hooks.normalModuleFactory.tap( + "NormalModuleReplacementPlugin", + nmf => { + nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => { + if (!result) return; + if (resourceRegExp.test(result.request)) { + if (typeof newResource === "function") { + newResource(result); + } else { + result.request = newResource; + } + } + return result; + }); + nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => { + if (!result) return; + if (resourceRegExp.test(result.resource)) { + if (typeof newResource === "function") { + newResource(result); + } else { + result.resource = path.resolve( + path.dirname(result.resource), + newResource + ); + } + } + return result; + }); + } + ); } } -module.exports = LoaderTargetPlugin; +module.exports = NormalModuleReplacementPlugin; /***/ }), -/***/ 43626: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 40438: +/***/ (function(module) { "use strict"; /* @@ -82072,585 +82173,184 @@ module.exports = LoaderTargetPlugin; */ -const { - ConcatSource, - OriginalSource, - PrefixSource, - RawSource -} = __webpack_require__(53665); -const { - Tapable, - SyncWaterfallHook, - SyncHook, - SyncBailHook -} = __webpack_require__(56758); -const Template = __webpack_require__(96066); +class NullFactory { + create(data, callback) { + return callback(); + } +} +module.exports = NullFactory; -/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Module")} Module} */ -/** @typedef {import("./util/createHash").Hash} Hash} */ -/** @typedef {import("./Dependency").DependencyTemplate} DependencyTemplate} */ -/** - * @typedef {Object} RenderManifestOptions - * @property {Chunk} chunk the chunk used to render - * @property {string} hash - * @property {string} fullHash - * @property {TODO} outputOptions - * @property {{javascript: ModuleTemplate, webassembly: ModuleTemplate}} moduleTemplates - * @property {Map} dependencyTemplates - */ +/***/ }), -// require function shortcuts: -// __webpack_require__.s = the module id of the entry point -// __webpack_require__.c = the module cache -// __webpack_require__.m = the module functions -// __webpack_require__.p = the bundle public path -// __webpack_require__.i = the identity function used for harmony imports -// __webpack_require__.e = the chunk ensure function -// __webpack_require__.d = the exported property define getter function -// __webpack_require__.o = Object.prototype.hasOwnProperty.call -// __webpack_require__.r = define compatibility on export -// __webpack_require__.t = create a fake namespace object -// __webpack_require__.n = compatibility get default export -// __webpack_require__.h = the webpack hash -// __webpack_require__.w = an object containing all installed WebAssembly.Instance export objects keyed by module id -// __webpack_require__.oe = the uncaught error handler for the webpack runtime -// __webpack_require__.nc = the script nonce +/***/ 4428: +/***/ (function(module) { -module.exports = class MainTemplate extends Tapable { - /** - * - * @param {TODO=} outputOptions output options for the MainTemplate - */ - constructor(outputOptions) { - super(); - /** @type {TODO?} */ - this.outputOptions = outputOptions || {}; - this.hooks = { - /** @type {SyncWaterfallHook} */ - renderManifest: new SyncWaterfallHook(["result", "options"]), - modules: new SyncWaterfallHook([ - "modules", - "chunk", - "hash", - "moduleTemplate", - "dependencyTemplates" - ]), - moduleObj: new SyncWaterfallHook([ - "source", - "chunk", - "hash", - "moduleIdExpression" - ]), - requireEnsure: new SyncWaterfallHook([ - "source", - "chunk", - "hash", - "chunkIdExpression" - ]), - bootstrap: new SyncWaterfallHook([ - "source", - "chunk", - "hash", - "moduleTemplate", - "dependencyTemplates" - ]), - localVars: new SyncWaterfallHook(["source", "chunk", "hash"]), - require: new SyncWaterfallHook(["source", "chunk", "hash"]), - requireExtensions: new SyncWaterfallHook(["source", "chunk", "hash"]), - /** @type {SyncWaterfallHook} */ - beforeStartup: new SyncWaterfallHook(["source", "chunk", "hash"]), - /** @type {SyncWaterfallHook} */ - startup: new SyncWaterfallHook(["source", "chunk", "hash"]), - /** @type {SyncWaterfallHook} */ - afterStartup: new SyncWaterfallHook(["source", "chunk", "hash"]), - render: new SyncWaterfallHook([ - "source", - "chunk", - "hash", - "moduleTemplate", - "dependencyTemplates" - ]), - renderWithEntry: new SyncWaterfallHook(["source", "chunk", "hash"]), - moduleRequire: new SyncWaterfallHook([ - "source", - "chunk", - "hash", - "moduleIdExpression" - ]), - addModule: new SyncWaterfallHook([ - "source", - "chunk", - "hash", - "moduleIdExpression", - "moduleExpression" - ]), - currentHash: new SyncWaterfallHook(["source", "requestedLength"]), - assetPath: new SyncWaterfallHook(["path", "options", "assetInfo"]), - hash: new SyncHook(["hash"]), - hashForChunk: new SyncHook(["hash", "chunk"]), - globalHashPaths: new SyncWaterfallHook(["paths"]), - globalHash: new SyncBailHook(["chunk", "paths"]), +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // TODO this should be moved somewhere else - // It's weird here - hotBootstrap: new SyncWaterfallHook(["source", "chunk", "hash"]) - }; - this.hooks.startup.tap("MainTemplate", (source, chunk, hash) => { - /** @type {string[]} */ - const buf = []; - if (chunk.entryModule) { - buf.push("// Load entry module and return exports"); - buf.push( - `return ${this.renderRequireFunctionForModule( - hash, - chunk, - JSON.stringify(chunk.entryModule.id) - )}(${this.requireFn}.s = ${JSON.stringify(chunk.entryModule.id)});` - ); - } - return Template.asString(buf); - }); - this.hooks.render.tap( - "MainTemplate", - (bootstrapSource, chunk, hash, moduleTemplate, dependencyTemplates) => { - const source = new ConcatSource(); - source.add("/******/ (function(modules) { // webpackBootstrap\n"); - source.add(new PrefixSource("/******/", bootstrapSource)); - source.add("/******/ })\n"); - source.add( - "/************************************************************************/\n" - ); - source.add("/******/ ("); - source.add( - this.hooks.modules.call( - new RawSource(""), - chunk, - hash, - moduleTemplate, - dependencyTemplates - ) - ); - source.add(")"); - return source; - } - ); - this.hooks.localVars.tap("MainTemplate", (source, chunk, hash) => { - return Template.asString([ - source, - "// The module cache", - "var installedModules = {};" - ]); - }); - this.hooks.require.tap("MainTemplate", (source, chunk, hash) => { - return Template.asString([ - source, - "// Check if module is in cache", - "if(installedModules[moduleId]) {", - Template.indent("return installedModules[moduleId].exports;"), - "}", - "// Create a new module (and put it into the cache)", - "var module = installedModules[moduleId] = {", - Template.indent(this.hooks.moduleObj.call("", chunk, hash, "moduleId")), - "};", - "", - Template.asString( - outputOptions.strictModuleExceptionHandling - ? [ - "// Execute the module function", - "var threw = true;", - "try {", - Template.indent([ - `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule( - hash, - chunk, - "moduleId" - )});`, - "threw = false;" - ]), - "} finally {", - Template.indent([ - "if(threw) delete installedModules[moduleId];" - ]), - "}" - ] - : [ - "// Execute the module function", - `modules[moduleId].call(module.exports, module, module.exports, ${this.renderRequireFunctionForModule( - hash, - chunk, - "moduleId" - )});` - ] - ), - "", - "// Flag the module as loaded", - "module.l = true;", - "", - "// Return the exports of the module", - "return module.exports;" - ]); - }); - this.hooks.moduleObj.tap( - "MainTemplate", - (source, chunk, hash, varModuleId) => { - return Template.asString(["i: moduleId,", "l: false,", "exports: {}"]); - } - ); - this.hooks.requireExtensions.tap("MainTemplate", (source, chunk, hash) => { - const buf = []; - const chunkMaps = chunk.getChunkMaps(); - // Check if there are non initial chunks which need to be imported using require-ensure - if (Object.keys(chunkMaps.hash).length) { - buf.push("// This file contains only the entry chunk."); - buf.push("// The chunk loading function for additional chunks"); - buf.push(`${this.requireFn}.e = function requireEnsure(chunkId) {`); - buf.push(Template.indent("var promises = [];")); - buf.push( - Template.indent( - this.hooks.requireEnsure.call("", chunk, hash, "chunkId") - ) - ); - buf.push(Template.indent("return Promise.all(promises);")); - buf.push("};"); - } else if ( - chunk.hasModuleInGraph(m => - m.blocks.some(b => b.chunkGroup && b.chunkGroup.chunks.length > 0) - ) - ) { - // There async blocks in the graph, so we need to add an empty requireEnsure - // function anyway. This can happen with multiple entrypoints. - buf.push("// The chunk loading function for additional chunks"); - buf.push("// Since all referenced chunks are already included"); - buf.push("// in this file, this function is empty here."); - buf.push(`${this.requireFn}.e = function requireEnsure() {`); - buf.push(Template.indent("return Promise.resolve();")); - buf.push("};"); - } - buf.push(""); - buf.push("// expose the modules object (__webpack_modules__)"); - buf.push(`${this.requireFn}.m = modules;`); - buf.push(""); - buf.push("// expose the module cache"); - buf.push(`${this.requireFn}.c = installedModules;`); +class OptionsApply { + process(options, compiler) {} +} +module.exports = OptionsApply; - buf.push(""); - buf.push("// define getter function for harmony exports"); - buf.push(`${this.requireFn}.d = function(exports, name, getter) {`); - buf.push( - Template.indent([ - `if(!${this.requireFn}.o(exports, name)) {`, - Template.indent([ - "Object.defineProperty(exports, name, { enumerable: true, get: getter });" - ]), - "}" - ]) - ); - buf.push("};"); - buf.push(""); - buf.push("// define __esModule on exports"); - buf.push(`${this.requireFn}.r = function(exports) {`); - buf.push( - Template.indent([ - "if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {", - Template.indent([ - "Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });" - ]), - "}", - "Object.defineProperty(exports, '__esModule', { value: true });" - ]) - ); - buf.push("};"); +/***/ }), - buf.push(""); - buf.push("// create a fake namespace object"); - buf.push("// mode & 1: value is a module id, require it"); - buf.push("// mode & 2: merge all properties of value into the ns"); - buf.push("// mode & 4: return value when already ns object"); - buf.push("// mode & 8|1: behave like require"); - buf.push(`${this.requireFn}.t = function(value, mode) {`); - buf.push( - Template.indent([ - `if(mode & 1) value = ${this.requireFn}(value);`, - `if(mode & 8) return value;`, - "if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;", - "var ns = Object.create(null);", - `${this.requireFn}.r(ns);`, - "Object.defineProperty(ns, 'default', { enumerable: true, value: value });", - "if(mode & 2 && typeof value != 'string') for(var key in value) " + - `${this.requireFn}.d(ns, key, function(key) { ` + - "return value[key]; " + - "}.bind(null, key));", - "return ns;" - ]) - ); - buf.push("};"); +/***/ 3414: +/***/ (function(module) { - buf.push(""); - buf.push( - "// getDefaultExport function for compatibility with non-harmony modules" - ); - buf.push(this.requireFn + ".n = function(module) {"); - buf.push( - Template.indent([ - "var getter = module && module.__esModule ?", - Template.indent([ - "function getDefault() { return module['default']; } :", - "function getModuleExports() { return module; };" - ]), - `${this.requireFn}.d(getter, 'a', getter);`, - "return getter;" - ]) - ); - buf.push("};"); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - buf.push(""); - buf.push("// Object.prototype.hasOwnProperty.call"); - buf.push( - `${this.requireFn}.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };` - ); - const publicPath = this.getPublicPath({ - hash: hash - }); - buf.push(""); - buf.push("// __webpack_public_path__"); - buf.push(`${this.requireFn}.p = ${JSON.stringify(publicPath)};`); - return Template.asString(buf); - }); +/** + * Gets the value at path of object + * @param {object} obj object to query + * @param {string} path query path + * @returns {any} - if {@param path} requests element from array, then `undefined` will be returned + */ +const getProperty = (obj, path) => { + let name = path.split("."); + for (let i = 0; i < name.length - 1; i++) { + obj = obj[name[i]]; + if (typeof obj !== "object" || !obj || Array.isArray(obj)) return; + } + return obj[name.pop()]; +}; - this.requireFn = "__webpack_require__"; +/** + * Sets the value at path of object. Stops execution, if {@param path} requests element from array to be set + * @param {object} obj object to query + * @param {string} path query path + * @param {any} value value to be set + * @returns {void} + */ +const setProperty = (obj, path, value) => { + let name = path.split("."); + for (let i = 0; i < name.length - 1; i++) { + if (typeof obj[name[i]] !== "object" && obj[name[i]] !== undefined) return; + if (Array.isArray(obj[name[i]])) return; + if (!obj[name[i]]) obj[name[i]] = {}; + obj = obj[name[i]]; } + obj[name.pop()] = value; +}; - /** - * - * @param {RenderManifestOptions} options render manifest options - * @returns {TODO[]} returns render manifest - */ - getRenderManifest(options) { - const result = []; +/** + * @typedef {'call' | 'make' | 'append'} ConfigType + */ +/** + * @typedef {(options: object) => any} MakeConfigHandler + */ +/** + * @typedef {(value: any, options: object) => any} CallConfigHandler + */ +/** + * @typedef {any[]} AppendConfigValues + */ - this.hooks.renderManifest.call(result, options); +class OptionsDefaulter { + constructor() { + /** + * Stores default options settings or functions for computing them + */ + this.defaults = {}; + /** + * Stores configuration for options + * @type {{[key: string]: ConfigType}} + */ + this.config = {}; + } - return result; + /** + * Enhancing {@param options} with default values + * @param {object} options provided options + * @returns {object} - enhanced options + * @throws {Error} - will throw error, if configuration value is other then `undefined` or {@link ConfigType} + */ + process(options) { + options = Object.assign({}, options); + for (let name in this.defaults) { + switch (this.config[name]) { + /** + * If {@link ConfigType} doesn't specified and current value is `undefined`, then default value will be assigned + */ + case undefined: + if (getProperty(options, name) === undefined) { + setProperty(options, name, this.defaults[name]); + } + break; + /** + * Assign result of {@link CallConfigHandler} + */ + case "call": + setProperty( + options, + name, + this.defaults[name].call(this, getProperty(options, name), options) + ); + break; + /** + * Assign result of {@link MakeConfigHandler}, if current value is `undefined` + */ + case "make": + if (getProperty(options, name) === undefined) { + setProperty(options, name, this.defaults[name].call(this, options)); + } + break; + /** + * Adding {@link AppendConfigValues} at the end of the current array + */ + case "append": { + let oldValue = getProperty(options, name); + if (!Array.isArray(oldValue)) { + oldValue = []; + } + oldValue.push(...this.defaults[name]); + setProperty(options, name, oldValue); + break; + } + default: + throw new Error( + "OptionsDefaulter cannot process " + this.config[name] + ); + } + } + return options; } /** - * TODO webpack 5: remove moduleTemplate and dependencyTemplates - * @param {string} hash hash to be used for render call - * @param {Chunk} chunk Chunk instance - * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render - * @param {Map} dependencyTemplates dependency templates - * @returns {string[]} the generated source of the bootstrap code + * Builds up default values + * @param {string} name option path + * @param {ConfigType | any} config if {@param def} is provided, then only {@link ConfigType} is allowed + * @param {MakeConfigHandler | CallConfigHandler | AppendConfigValues} [def] defaults + * @returns {void} */ - renderBootstrap(hash, chunk, moduleTemplate, dependencyTemplates) { - const buf = []; - buf.push( - this.hooks.bootstrap.call( - "", - chunk, - hash, - moduleTemplate, - dependencyTemplates - ) - ); - buf.push(this.hooks.localVars.call("", chunk, hash)); - buf.push(""); - buf.push("// The require function"); - buf.push(`function ${this.requireFn}(moduleId) {`); - buf.push(Template.indent(this.hooks.require.call("", chunk, hash))); - buf.push("}"); - buf.push(""); - buf.push( - Template.asString(this.hooks.requireExtensions.call("", chunk, hash)) - ); - buf.push(""); - buf.push(Template.asString(this.hooks.beforeStartup.call("", chunk, hash))); - const afterStartupCode = Template.asString( - this.hooks.afterStartup.call("", chunk, hash) - ); - if (afterStartupCode) { - // TODO webpack 5: this is a bit hacky to avoid a breaking change - // change it to a better way - buf.push("var startupResult = (function() {"); - } - buf.push(Template.asString(this.hooks.startup.call("", chunk, hash))); - if (afterStartupCode) { - buf.push("})();"); - buf.push(afterStartupCode); - buf.push("return startupResult;"); - } - return buf; - } - - /** - * @param {string} hash hash to be used for render call - * @param {Chunk} chunk Chunk instance - * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render - * @param {Map} dependencyTemplates dependency templates - * @returns {ConcatSource} the newly generated source from rendering - */ - render(hash, chunk, moduleTemplate, dependencyTemplates) { - const buf = this.renderBootstrap( - hash, - chunk, - moduleTemplate, - dependencyTemplates - ); - let source = this.hooks.render.call( - new OriginalSource( - Template.prefix(buf, " \t") + "\n", - "webpack/bootstrap" - ), - chunk, - hash, - moduleTemplate, - dependencyTemplates - ); - if (chunk.hasEntryModule()) { - source = this.hooks.renderWithEntry.call(source, chunk, hash); - } - if (!source) { - throw new Error( - "Compiler error: MainTemplate plugin 'render' should return something" - ); - } - chunk.rendered = true; - return new ConcatSource(source, ";"); - } - - /** - * - * @param {string} hash hash for render fn - * @param {Chunk} chunk Chunk instance for require - * @param {(number|string)=} varModuleId module id - * @returns {TODO} the moduleRequire hook call return signature - */ - renderRequireFunctionForModule(hash, chunk, varModuleId) { - return this.hooks.moduleRequire.call( - this.requireFn, - chunk, - hash, - varModuleId - ); - } - - /** - * - * @param {string} hash hash for render add fn - * @param {Chunk} chunk Chunk instance for require add fn - * @param {(string|number)=} varModuleId module id - * @param {Module} varModule Module instance - * @returns {TODO} renderAddModule call - */ - renderAddModule(hash, chunk, varModuleId, varModule) { - return this.hooks.addModule.call( - `modules[${varModuleId}] = ${varModule};`, - chunk, - hash, - varModuleId, - varModule - ); - } - - /** - * - * @param {string} hash string hash - * @param {number=} length length - * @returns {string} call hook return - */ - renderCurrentHashCode(hash, length) { - length = length || Infinity; - return this.hooks.currentHash.call( - JSON.stringify(hash.substr(0, length)), - length - ); - } - - /** - * - * @param {object} options get public path options - * @returns {string} hook call - */ - getPublicPath(options) { - return this.hooks.assetPath.call( - this.outputOptions.publicPath || "", - options - ); - } - - getAssetPath(path, options) { - return this.hooks.assetPath.call(path, options); - } - - getAssetPathWithInfo(path, options) { - const assetInfo = {}; - // TODO webpack 5: refactor assetPath hook to receive { path, info } object - const newPath = this.hooks.assetPath.call(path, options, assetInfo); - return { path: newPath, info: assetInfo }; - } - - /** - * Updates hash with information from this template - * @param {Hash} hash the hash to update - * @returns {void} - */ - updateHash(hash) { - hash.update("maintemplate"); - hash.update("3"); - this.hooks.hash.call(hash); - } - - /** - * TODO webpack 5: remove moduleTemplate and dependencyTemplates - * Updates hash with chunk-specific information from this template - * @param {Hash} hash the hash to update - * @param {Chunk} chunk the chunk - * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance for render - * @param {Map} dependencyTemplates dependency templates - * @returns {void} - */ - updateHashForChunk(hash, chunk, moduleTemplate, dependencyTemplates) { - this.updateHash(hash); - this.hooks.hashForChunk.call(hash, chunk); - for (const line of this.renderBootstrap( - "0000", - chunk, - moduleTemplate, - dependencyTemplates - )) { - hash.update(line); + set(name, config, def) { + if (def !== undefined) { + this.defaults[name] = def; + this.config[name] = config; + } else { + this.defaults[name] = config; + delete this.config[name]; } } +} - useChunkHash(chunk) { - const paths = this.hooks.globalHashPaths.call([]); - return !this.hooks.globalHash.call(chunk, paths); - } -}; - - -/***/ }), - -/***/ 50332: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -module.exports = __webpack_require__(32327); +module.exports = OptionsDefaulter; /***/ }), -/***/ 75993: +/***/ 70558: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -82660,1916 +82360,2460 @@ module.exports = __webpack_require__(32327); */ -const util = __webpack_require__(31669); - -const DependenciesBlock = __webpack_require__(16071); -const ModuleReason = __webpack_require__(44576); -const SortableSet = __webpack_require__(50071); -const Template = __webpack_require__(96066); - -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./RequestShortener")} RequestShortener */ -/** @typedef {import("./WebpackError")} WebpackError */ -/** @typedef {import("./util/createHash").Hash} Hash */ +// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API -const EMPTY_RESOLVE_OPTIONS = {}; +const acorn = __webpack_require__(77087); +const { Tapable, SyncBailHook, HookMap } = __webpack_require__(56758); +const util = __webpack_require__(31669); +const vm = __webpack_require__(92184); +const BasicEvaluatedExpression = __webpack_require__(96770); +const StackedSetMap = __webpack_require__(92251); -let debugId = 1000; +const acornParser = acorn.Parser; -const sortById = (a, b) => { - return a.id - b.id; +const joinRanges = (startRange, endRange) => { + if (!endRange) return startRange; + if (!startRange) return endRange; + return [startRange[0], endRange[1]]; }; -const sortByDebugId = (a, b) => { - return a.debugId - b.debugId; +const defaultParserOptions = { + ranges: true, + locations: true, + ecmaVersion: 11, + sourceType: "module", + onComment: null }; -/** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */ - -class Module extends DependenciesBlock { - constructor(type, context = null) { - super(); - /** @type {string} */ - this.type = type; - /** @type {string} */ - this.context = context; - - // Unique Id - /** @type {number} */ - this.debugId = debugId++; - - // Hash - /** @type {string} */ - this.hash = undefined; - /** @type {string} */ - this.renderedHash = undefined; - - // Info from Factory - /** @type {TODO} */ - this.resolveOptions = EMPTY_RESOLVE_OPTIONS; - /** @type {object} */ - this.factoryMeta = {}; - - // Info from Build - /** @type {WebpackError[]} */ - this.warnings = []; - /** @type {WebpackError[]} */ - this.errors = []; - /** @type {object} */ - this.buildMeta = undefined; - /** @type {object} */ - this.buildInfo = undefined; - - // Graph (per Compilation) - /** @type {ModuleReason[]} */ - this.reasons = []; - /** @type {SortableSet} */ - this._chunks = new SortableSet(undefined, sortById); - - // Info from Compilation (per Compilation) - /** @type {number|string} */ - this.id = null; - /** @type {number} */ - this.index = null; - /** @type {number} */ - this.index2 = null; - /** @type {number} */ - this.depth = null; - /** @type {Module} */ - this.issuer = null; - /** @type {undefined | object} */ - this.profile = undefined; - /** @type {boolean} */ - this.prefetched = false; - /** @type {boolean} */ - this.built = false; - - // Info from Optimization (per Compilation) - /** @type {null | boolean} */ - this.used = null; - /** @type {false | true | string[]} */ - this.usedExports = null; - /** @type {(string | OptimizationBailoutFunction)[]} */ - this.optimizationBailout = []; - - // delayed operations - /** @type {undefined | {oldChunk: Chunk, newChunks: Chunk[]}[] } */ - this._rewriteChunkInReasons = undefined; - - /** @type {boolean} */ - this.useSourceMap = false; - - // info from build - this._source = null; - } - - get exportsArgument() { - return (this.buildInfo && this.buildInfo.exportsArgument) || "exports"; - } - - get moduleArgument() { - return (this.buildInfo && this.buildInfo.moduleArgument) || "module"; - } - - disconnect() { - this.hash = undefined; - this.renderedHash = undefined; - - this.reasons.length = 0; - this._rewriteChunkInReasons = undefined; - this._chunks.clear(); - - this.id = null; - this.index = null; - this.index2 = null; - this.depth = null; - this.issuer = null; - this.profile = undefined; - this.prefetched = false; - this.built = false; - - this.used = null; - this.usedExports = null; - this.optimizationBailout.length = 0; - super.disconnect(); - } - - unseal() { - this.id = null; - this.index = null; - this.index2 = null; - this.depth = null; - this._chunks.clear(); - super.unseal(); - } - - setChunks(chunks) { - this._chunks = new SortableSet(chunks, sortById); - } - - addChunk(chunk) { - if (this._chunks.has(chunk)) return false; - this._chunks.add(chunk); - return true; - } - - removeChunk(chunk) { - if (this._chunks.delete(chunk)) { - chunk.removeModule(this); - return true; - } - return false; - } - - isInChunk(chunk) { - return this._chunks.has(chunk); - } - - isEntryModule() { - for (const chunk of this._chunks) { - if (chunk.entryModule === this) return true; - } - return false; - } - - get optional() { - return ( - this.reasons.length > 0 && - this.reasons.every(r => r.dependency && r.dependency.optional) - ); - } - - /** - * @returns {Chunk[]} all chunks which contain the module - */ - getChunks() { - return Array.from(this._chunks); - } +// regexp to match at least one "magic comment" +const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/); - getNumberOfChunks() { - return this._chunks.size; - } +const EMPTY_COMMENT_OPTIONS = { + options: null, + errors: null +}; - get chunksIterable() { - return this._chunks; +class Parser extends Tapable { + constructor(options, sourceType = "auto") { + super(); + this.hooks = { + evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), + evaluate: new HookMap(() => new SyncBailHook(["expression"])), + evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), + evaluateDefinedIdentifier: new HookMap( + () => new SyncBailHook(["expression"]) + ), + evaluateCallExpressionMember: new HookMap( + () => new SyncBailHook(["expression", "param"]) + ), + statement: new SyncBailHook(["statement"]), + statementIf: new SyncBailHook(["statement"]), + label: new HookMap(() => new SyncBailHook(["statement"])), + import: new SyncBailHook(["statement", "source"]), + importSpecifier: new SyncBailHook([ + "statement", + "source", + "exportName", + "identifierName" + ]), + export: new SyncBailHook(["statement"]), + exportImport: new SyncBailHook(["statement", "source"]), + exportDeclaration: new SyncBailHook(["statement", "declaration"]), + exportExpression: new SyncBailHook(["statement", "declaration"]), + exportSpecifier: new SyncBailHook([ + "statement", + "identifierName", + "exportName", + "index" + ]), + exportImportSpecifier: new SyncBailHook([ + "statement", + "source", + "identifierName", + "exportName", + "index" + ]), + varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])), + varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])), + varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])), + varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])), + canRename: new HookMap(() => new SyncBailHook(["initExpression"])), + rename: new HookMap(() => new SyncBailHook(["initExpression"])), + assigned: new HookMap(() => new SyncBailHook(["expression"])), + assign: new HookMap(() => new SyncBailHook(["expression"])), + typeof: new HookMap(() => new SyncBailHook(["expression"])), + importCall: new SyncBailHook(["expression"]), + call: new HookMap(() => new SyncBailHook(["expression"])), + callAnyMember: new HookMap(() => new SyncBailHook(["expression"])), + new: new HookMap(() => new SyncBailHook(["expression"])), + expression: new HookMap(() => new SyncBailHook(["expression"])), + expressionAnyMember: new HookMap(() => new SyncBailHook(["expression"])), + expressionConditionalOperator: new SyncBailHook(["expression"]), + expressionLogicalOperator: new SyncBailHook(["expression"]), + program: new SyncBailHook(["ast", "comments"]) + }; + const HOOK_MAP_COMPAT_CONFIG = { + evaluateTypeof: /^evaluate typeof (.+)$/, + evaluateIdentifier: /^evaluate Identifier (.+)$/, + evaluateDefinedIdentifier: /^evaluate defined Identifier (.+)$/, + evaluateCallExpressionMember: /^evaluate CallExpression .(.+)$/, + evaluate: /^evaluate (.+)$/, + label: /^label (.+)$/, + varDeclarationLet: /^var-let (.+)$/, + varDeclarationConst: /^var-const (.+)$/, + varDeclarationVar: /^var-var (.+)$/, + varDeclaration: /^var (.+)$/, + canRename: /^can-rename (.+)$/, + rename: /^rename (.+)$/, + typeof: /^typeof (.+)$/, + assigned: /^assigned (.+)$/, + assign: /^assign (.+)$/, + callAnyMember: /^call (.+)\.\*$/, + call: /^call (.+)$/, + new: /^new (.+)$/, + expressionConditionalOperator: /^expression \?:$/, + expressionAnyMember: /^expression (.+)\.\*$/, + expression: /^expression (.+)$/ + }; + this._pluginCompat.tap("Parser", options => { + for (const name of Object.keys(HOOK_MAP_COMPAT_CONFIG)) { + const regexp = HOOK_MAP_COMPAT_CONFIG[name]; + const match = regexp.exec(options.name); + if (match) { + if (match[1]) { + this.hooks[name].tap( + match[1], + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + } else { + this.hooks[name].tap( + options.fn.name || "unnamed compat plugin", + options.fn.bind(this) + ); + } + return true; + } + } + }); + this.options = options; + this.sourceType = sourceType; + this.scope = undefined; + this.state = undefined; + this.comments = undefined; + this.initializeEvaluating(); } - hasEqualsChunks(otherModule) { - if (this._chunks.size !== otherModule._chunks.size) return false; - this._chunks.sortWith(sortByDebugId); - otherModule._chunks.sortWith(sortByDebugId); - const a = this._chunks[Symbol.iterator](); - const b = otherModule._chunks[Symbol.iterator](); - // eslint-disable-next-line no-constant-condition - while (true) { - const aItem = a.next(); - const bItem = b.next(); - if (aItem.done) return true; - if (aItem.value !== bItem.value) return false; - } - } - - addReason(module, dependency, explanation) { - this.reasons.push(new ModuleReason(module, dependency, explanation)); - } - - removeReason(module, dependency) { - for (let i = 0; i < this.reasons.length; i++) { - let r = this.reasons[i]; - if (r.module === module && r.dependency === dependency) { - this.reasons.splice(i, 1); - return true; + initializeEvaluating() { + this.hooks.evaluate.for("Literal").tap("Parser", expr => { + switch (typeof expr.value) { + case "number": + return new BasicEvaluatedExpression() + .setNumber(expr.value) + .setRange(expr.range); + case "string": + return new BasicEvaluatedExpression() + .setString(expr.value) + .setRange(expr.range); + case "boolean": + return new BasicEvaluatedExpression() + .setBoolean(expr.value) + .setRange(expr.range); } - } - return false; - } - - hasReasonForChunk(chunk) { - if (this._rewriteChunkInReasons) { - for (const operation of this._rewriteChunkInReasons) { - this._doRewriteChunkInReasons(operation.oldChunk, operation.newChunks); + if (expr.value === null) { + return new BasicEvaluatedExpression().setNull().setRange(expr.range); } - this._rewriteChunkInReasons = undefined; - } - for (let i = 0; i < this.reasons.length; i++) { - if (this.reasons[i].hasChunk(chunk)) return true; - } - return false; - } - - hasReasons() { - return this.reasons.length > 0; - } - - rewriteChunkInReasons(oldChunk, newChunks) { - // This is expensive. Delay operation until we really need the data - if (this._rewriteChunkInReasons === undefined) { - this._rewriteChunkInReasons = []; - } - this._rewriteChunkInReasons.push({ - oldChunk, - newChunks - }); - } - - _doRewriteChunkInReasons(oldChunk, newChunks) { - for (let i = 0; i < this.reasons.length; i++) { - this.reasons[i].rewriteChunks(oldChunk, newChunks); - } - } - - /** - * @param {string=} exportName the name of the export - * @returns {boolean|string} false if the export isn't used, true if no exportName is provided and the module is used, or the name to access it if the export is used - */ - isUsed(exportName) { - if (!exportName) return this.used !== false; - if (this.used === null || this.usedExports === null) return exportName; - if (!this.used) return false; - if (!this.usedExports) return false; - if (this.usedExports === true) return exportName; - let idx = this.usedExports.indexOf(exportName); - if (idx < 0) return false; - - // Mangle export name if possible - if (this.isProvided(exportName)) { - if (this.buildMeta.exportsType === "namespace") { - return Template.numberToIdentifer(idx); + if (expr.value instanceof RegExp) { + return new BasicEvaluatedExpression() + .setRegExp(expr.value) + .setRange(expr.range); } - if ( - this.buildMeta.exportsType === "named" && - !this.usedExports.includes("default") - ) { - return Template.numberToIdentifer(idx); + }); + this.hooks.evaluate.for("LogicalExpression").tap("Parser", expr => { + let left; + let leftAsBool; + let right; + if (expr.operator === "&&") { + left = this.evaluateExpression(expr.left); + leftAsBool = left && left.asBool(); + if (leftAsBool === false) return left.setRange(expr.range); + if (leftAsBool !== true) return; + right = this.evaluateExpression(expr.right); + return right.setRange(expr.range); + } else if (expr.operator === "||") { + left = this.evaluateExpression(expr.left); + leftAsBool = left && left.asBool(); + if (leftAsBool === true) return left.setRange(expr.range); + if (leftAsBool !== false) return; + right = this.evaluateExpression(expr.right); + return right.setRange(expr.range); } - } - return exportName; - } - - isProvided(exportName) { - if (!Array.isArray(this.buildMeta.providedExports)) return null; - return this.buildMeta.providedExports.includes(exportName); - } - - toString() { - return `Module[${this.id || this.debugId}]`; - } - - needRebuild(fileTimestamps, contextTimestamps) { - return true; - } - - /** - * @param {Hash} hash the hash used to track dependencies - * @returns {void} - */ - updateHash(hash) { - hash.update(`${this.id}`); - hash.update(JSON.stringify(this.usedExports)); - super.updateHash(hash); - } - - sortItems(sortChunks) { - super.sortItems(); - if (sortChunks) this._chunks.sort(); - this.reasons.sort((a, b) => { - if (a.module === b.module) return 0; - if (!a.module) return -1; - if (!b.module) return 1; - return sortById(a.module, b.module); }); - if (Array.isArray(this.usedExports)) { - this.usedExports.sort(); - } - } - - unbuild() { - this.dependencies.length = 0; - this.blocks.length = 0; - this.variables.length = 0; - this.buildMeta = undefined; - this.buildInfo = undefined; - this.disconnect(); - } - - get arguments() { - throw new Error("Module.arguments was removed, there is no replacement."); - } - - set arguments(value) { - throw new Error("Module.arguments was removed, there is no replacement."); - } -} - -// TODO remove in webpack 5 -Object.defineProperty(Module.prototype, "forEachChunk", { - configurable: false, - value: util.deprecate( - /** - * @deprecated - * @param {function(any, any, Set): void} fn callback function - * @returns {void} - * @this {Module} - */ - function(fn) { - this._chunks.forEach(fn); - }, - "Module.forEachChunk: Use for(const chunk of module.chunksIterable) instead" - ) -}); - -// TODO remove in webpack 5 -Object.defineProperty(Module.prototype, "mapChunks", { - configurable: false, - value: util.deprecate( - /** - * @deprecated - * @param {function(any, any): void} fn Mapper function - * @returns {Array} Array of chunks mapped - * @this {Module} - */ - function(fn) { - return Array.from(this._chunks, fn); - }, - "Module.mapChunks: Use Array.from(module.chunksIterable, fn) instead" - ) -}); - -// TODO remove in webpack 5 -Object.defineProperty(Module.prototype, "entry", { - configurable: false, - get() { - throw new Error("Module.entry was removed. Use Chunk.entryModule"); - }, - set() { - throw new Error("Module.entry was removed. Use Chunk.entryModule"); - } -}); - -// TODO remove in webpack 5 -Object.defineProperty(Module.prototype, "meta", { - configurable: false, - get: util.deprecate( - /** - * @deprecated - * @returns {void} - * @this {Module} - */ - function() { - return this.buildMeta; - }, - "Module.meta was renamed to Module.buildMeta" - ), - set: util.deprecate( - /** - * @deprecated - * @param {TODO} value Value - * @returns {void} - * @this {Module} - */ - function(value) { - this.buildMeta = value; - }, - "Module.meta was renamed to Module.buildMeta" - ) -}); - -/** @type {function(): string} */ -Module.prototype.identifier = null; - -/** @type {function(RequestShortener): string} */ -Module.prototype.readableIdentifier = null; - -Module.prototype.build = null; -Module.prototype.source = null; -Module.prototype.size = null; -Module.prototype.nameForCondition = null; -/** @type {null | function(Chunk): boolean} */ -Module.prototype.chunkCondition = null; -Module.prototype.updateCacheModule = null; - -module.exports = Module; - - -/***/ }), - -/***/ 12072: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const WebpackError = __webpack_require__(97391); -const { cutOffLoaderExecution } = __webpack_require__(80140); - -class ModuleBuildError extends WebpackError { - constructor(module, err, { from = null } = {}) { - let message = "Module build failed"; - let details = undefined; - if (from) { - message += ` (from ${from}):\n`; - } else { - message += ": "; - } - if (err !== null && typeof err === "object") { - if (typeof err.stack === "string" && err.stack) { - const stack = cutOffLoaderExecution(err.stack); - if (!err.hideStack) { - message += stack; + this.hooks.evaluate.for("BinaryExpression").tap("Parser", expr => { + let left; + let right; + let res; + if (expr.operator === "+") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + res = new BasicEvaluatedExpression(); + if (left.isString()) { + if (right.isString()) { + res.setString(left.string + right.string); + } else if (right.isNumber()) { + res.setString(left.string + right.number); + } else if ( + right.isWrapped() && + right.prefix && + right.prefix.isString() + ) { + // "left" + ("prefix" + inner + "postfix") + // => ("leftprefix" + inner + "postfix") + res.setWrapped( + new BasicEvaluatedExpression() + .setString(left.string + right.prefix.string) + .setRange(joinRanges(left.range, right.prefix.range)), + right.postfix, + right.wrappedInnerExpressions + ); + } else if (right.isWrapped()) { + // "left" + ([null] + inner + "postfix") + // => ("left" + inner + "postfix") + res.setWrapped(left, right.postfix, right.wrappedInnerExpressions); + } else { + // "left" + expr + // => ("left" + expr + "") + res.setWrapped(left, null, [right]); + } + } else if (left.isNumber()) { + if (right.isString()) { + res.setString(left.number + right.string); + } else if (right.isNumber()) { + res.setNumber(left.number + right.number); + } else { + return; + } + } else if (left.isWrapped()) { + if (left.postfix && left.postfix.isString() && right.isString()) { + // ("prefix" + inner + "postfix") + "right" + // => ("prefix" + inner + "postfixright") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(left.postfix.string + right.string) + .setRange(joinRanges(left.postfix.range, right.range)), + left.wrappedInnerExpressions + ); + } else if ( + left.postfix && + left.postfix.isString() && + right.isNumber() + ) { + // ("prefix" + inner + "postfix") + 123 + // => ("prefix" + inner + "postfix123") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(left.postfix.string + right.number) + .setRange(joinRanges(left.postfix.range, right.range)), + left.wrappedInnerExpressions + ); + } else if (right.isString()) { + // ("prefix" + inner + [null]) + "right" + // => ("prefix" + inner + "right") + res.setWrapped(left.prefix, right, left.wrappedInnerExpressions); + } else if (right.isNumber()) { + // ("prefix" + inner + [null]) + 123 + // => ("prefix" + inner + "123") + res.setWrapped( + left.prefix, + new BasicEvaluatedExpression() + .setString(right.number + "") + .setRange(right.range), + left.wrappedInnerExpressions + ); + } else if (right.isWrapped()) { + // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2") + // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2") + res.setWrapped( + left.prefix, + right.postfix, + left.wrappedInnerExpressions && + right.wrappedInnerExpressions && + left.wrappedInnerExpressions + .concat(left.postfix ? [left.postfix] : []) + .concat(right.prefix ? [right.prefix] : []) + .concat(right.wrappedInnerExpressions) + ); + } else { + // ("prefix" + inner + postfix) + expr + // => ("prefix" + inner + postfix + expr + [null]) + res.setWrapped( + left.prefix, + null, + left.wrappedInnerExpressions && + left.wrappedInnerExpressions.concat( + left.postfix ? [left.postfix, right] : [right] + ) + ); + } } else { - details = stack; - if (typeof err.message === "string" && err.message) { - message += err.message; + if (right.isString()) { + // left + "right" + // => ([null] + left + "right") + res.setWrapped(null, right, [left]); + } else if (right.isWrapped()) { + // left + (prefix + inner + "postfix") + // => ([null] + left + prefix + inner + "postfix") + res.setWrapped( + null, + right.postfix, + right.wrappedInnerExpressions && + (right.prefix ? [left, right.prefix] : [left]).concat( + right.wrappedInnerExpressions + ) + ); } else { - message += err; + return; } } - } else if (typeof err.message === "string" && err.message) { - message += err.message; - } else { - message += err; - } - } else { - message = err; - } - - super(message); - - this.name = "ModuleBuildError"; - this.details = details; - this.module = module; - this.error = err; - - Error.captureStackTrace(this, this.constructor); - } -} - -module.exports = ModuleBuildError; - - -/***/ }), - -/***/ 14953: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const WebpackError = __webpack_require__(97391); - -/** @typedef {import("./Module")} Module */ - -class ModuleDependencyError extends WebpackError { - /** - * Creates an instance of ModuleDependencyError. - * @param {Module} module module tied to dependency - * @param {Error} err error thrown - * @param {TODO} loc location of dependency - */ - constructor(module, err, loc) { - super(err.message); - - this.name = "ModuleDependencyError"; - this.details = err.stack - .split("\n") - .slice(1) - .join("\n"); - this.module = module; - this.loc = loc; - this.error = err; - this.origin = module.issuer; - - Error.captureStackTrace(this, this.constructor); - } -} - -module.exports = ModuleDependencyError; - - -/***/ }), - -/***/ 59136: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const WebpackError = __webpack_require__(97391); - -module.exports = class ModuleDependencyWarning extends WebpackError { - constructor(module, err, loc) { - super(err.message); - - this.name = "ModuleDependencyWarning"; - this.details = err.stack - .split("\n") - .slice(1) - .join("\n"); - this.module = module; - this.loc = loc; - this.error = err; - this.origin = module.issuer; - - Error.captureStackTrace(this, this.constructor); - } -}; - - -/***/ }), - -/***/ 82528: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const WebpackError = __webpack_require__(97391); -const { cleanUp } = __webpack_require__(80140); - -class ModuleError extends WebpackError { - constructor(module, err, { from = null } = {}) { - let message = "Module Error"; - if (from) { - message += ` (from ${from}):\n`; - } else { - message += ": "; - } - if (err && typeof err === "object" && err.message) { - message += err.message; - } else if (err) { - message += err; - } - super(message); - this.name = "ModuleError"; - this.module = module; - this.error = err; - this.details = - err && typeof err === "object" && err.stack - ? cleanUp(err.stack, this.message) - : undefined; - - Error.captureStackTrace(this, this.constructor); - } -} - -module.exports = ModuleError; - + res.setRange(expr.range); + return res; + } else if (expr.operator === "-") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number - right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "*") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number * right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "/") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number / right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "**") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(Math.pow(left.number, right.number)); + res.setRange(expr.range); + return res; + } else if (expr.operator === "==" || expr.operator === "===") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + res = new BasicEvaluatedExpression(); + res.setRange(expr.range); + if (left.isString() && right.isString()) { + return res.setBoolean(left.string === right.string); + } else if (left.isNumber() && right.isNumber()) { + return res.setBoolean(left.number === right.number); + } else if (left.isBoolean() && right.isBoolean()) { + return res.setBoolean(left.bool === right.bool); + } + } else if (expr.operator === "!=" || expr.operator === "!==") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + res = new BasicEvaluatedExpression(); + res.setRange(expr.range); + if (left.isString() && right.isString()) { + return res.setBoolean(left.string !== right.string); + } else if (left.isNumber() && right.isNumber()) { + return res.setBoolean(left.number !== right.number); + } else if (left.isBoolean() && right.isBoolean()) { + return res.setBoolean(left.bool !== right.bool); + } + } else if (expr.operator === "&") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number & right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "|") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number | right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "^") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number ^ right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === ">>>") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number >>> right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === ">>") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number >> right.number); + res.setRange(expr.range); + return res; + } else if (expr.operator === "<<") { + left = this.evaluateExpression(expr.left); + right = this.evaluateExpression(expr.right); + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; + res = new BasicEvaluatedExpression(); + res.setNumber(left.number << right.number); + res.setRange(expr.range); + return res; + } + }); + this.hooks.evaluate.for("UnaryExpression").tap("Parser", expr => { + if (expr.operator === "typeof") { + let res; + let name; + if (expr.argument.type === "Identifier") { + name = + this.scope.renames.get(expr.argument.name) || expr.argument.name; + if (!this.scope.definitions.has(name)) { + const hook = this.hooks.evaluateTypeof.get(name); + if (hook !== undefined) { + res = hook.call(expr); + if (res !== undefined) return res; + } + } + } + if (expr.argument.type === "MemberExpression") { + const exprName = this.getNameForExpression(expr.argument); + if (exprName && exprName.free) { + const hook = this.hooks.evaluateTypeof.get(exprName.name); + if (hook !== undefined) { + res = hook.call(expr); + if (res !== undefined) return res; + } + } + } + if (expr.argument.type === "FunctionExpression") { + return new BasicEvaluatedExpression() + .setString("function") + .setRange(expr.range); + } + const arg = this.evaluateExpression(expr.argument); + if (arg.isString() || arg.isWrapped()) { + return new BasicEvaluatedExpression() + .setString("string") + .setRange(expr.range); + } + if (arg.isNumber()) { + return new BasicEvaluatedExpression() + .setString("number") + .setRange(expr.range); + } + if (arg.isBoolean()) { + return new BasicEvaluatedExpression() + .setString("boolean") + .setRange(expr.range); + } + if (arg.isArray() || arg.isConstArray() || arg.isRegExp()) { + return new BasicEvaluatedExpression() + .setString("object") + .setRange(expr.range); + } + } else if (expr.operator === "!") { + const argument = this.evaluateExpression(expr.argument); + if (!argument) return; + if (argument.isBoolean()) { + return new BasicEvaluatedExpression() + .setBoolean(!argument.bool) + .setRange(expr.range); + } + if (argument.isTruthy()) { + return new BasicEvaluatedExpression() + .setBoolean(false) + .setRange(expr.range); + } + if (argument.isFalsy()) { + return new BasicEvaluatedExpression() + .setBoolean(true) + .setRange(expr.range); + } + if (argument.isString()) { + return new BasicEvaluatedExpression() + .setBoolean(!argument.string) + .setRange(expr.range); + } + if (argument.isNumber()) { + return new BasicEvaluatedExpression() + .setBoolean(!argument.number) + .setRange(expr.range); + } + } else if (expr.operator === "~") { + const argument = this.evaluateExpression(expr.argument); + if (!argument) return; + if (!argument.isNumber()) return; + const res = new BasicEvaluatedExpression(); + res.setNumber(~argument.number); + res.setRange(expr.range); + return res; + } + }); + this.hooks.evaluateTypeof.for("undefined").tap("Parser", expr => { + return new BasicEvaluatedExpression() + .setString("undefined") + .setRange(expr.range); + }); + this.hooks.evaluate.for("Identifier").tap("Parser", expr => { + const name = this.scope.renames.get(expr.name) || expr.name; + if (!this.scope.definitions.has(expr.name)) { + const hook = this.hooks.evaluateIdentifier.get(name); + if (hook !== undefined) { + const result = hook.call(expr); + if (result) return result; + } + return new BasicEvaluatedExpression() + .setIdentifier(name) + .setRange(expr.range); + } else { + const hook = this.hooks.evaluateDefinedIdentifier.get(name); + if (hook !== undefined) { + return hook.call(expr); + } + } + }); + this.hooks.evaluate.for("ThisExpression").tap("Parser", expr => { + const name = this.scope.renames.get("this"); + if (name) { + const hook = this.hooks.evaluateIdentifier.get(name); + if (hook !== undefined) { + const result = hook.call(expr); + if (result) return result; + } + return new BasicEvaluatedExpression() + .setIdentifier(name) + .setRange(expr.range); + } + }); + this.hooks.evaluate.for("MemberExpression").tap("Parser", expression => { + let exprName = this.getNameForExpression(expression); + if (exprName) { + if (exprName.free) { + const hook = this.hooks.evaluateIdentifier.get(exprName.name); + if (hook !== undefined) { + const result = hook.call(expression); + if (result) return result; + } + return new BasicEvaluatedExpression() + .setIdentifier(exprName.name) + .setRange(expression.range); + } else { + const hook = this.hooks.evaluateDefinedIdentifier.get(exprName.name); + if (hook !== undefined) { + return hook.call(expression); + } + } + } + }); + this.hooks.evaluate.for("CallExpression").tap("Parser", expr => { + if (expr.callee.type !== "MemberExpression") return; + if ( + expr.callee.property.type !== + (expr.callee.computed ? "Literal" : "Identifier") + ) + return; + const param = this.evaluateExpression(expr.callee.object); + if (!param) return; + const property = expr.callee.property.name || expr.callee.property.value; + const hook = this.hooks.evaluateCallExpressionMember.get(property); + if (hook !== undefined) { + return hook.call(expr, param); + } + }); + this.hooks.evaluateCallExpressionMember + .for("replace") + .tap("Parser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 2) return; + let arg1 = this.evaluateExpression(expr.arguments[0]); + let arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isString() && !arg1.isRegExp()) return; + arg1 = arg1.regExp || arg1.string; + if (!arg2.isString()) return; + arg2 = arg2.string; + return new BasicEvaluatedExpression() + .setString(param.string.replace(arg1, arg2)) + .setRange(expr.range); + }); + ["substr", "substring"].forEach(fn => { + this.hooks.evaluateCallExpressionMember + .for(fn) + .tap("Parser", (expr, param) => { + if (!param.isString()) return; + let arg1; + let result, + str = param.string; + switch (expr.arguments.length) { + case 1: + arg1 = this.evaluateExpression(expr.arguments[0]); + if (!arg1.isNumber()) return; + result = str[fn](arg1.number); + break; + case 2: { + arg1 = this.evaluateExpression(expr.arguments[0]); + const arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isNumber()) return; + if (!arg2.isNumber()) return; + result = str[fn](arg1.number, arg2.number); + break; + } + default: + return; + } + return new BasicEvaluatedExpression() + .setString(result) + .setRange(expr.range); + }); + }); -/***/ }), + /** + * @param {string} kind "cooked" | "raw" + * @param {TODO} templateLiteralExpr TemplateLiteral expr + * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template + */ + const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => { + const quasis = []; + const parts = []; -/***/ 71474: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + for (let i = 0; i < templateLiteralExpr.quasis.length; i++) { + const quasiExpr = templateLiteralExpr.quasis[i]; + const quasi = quasiExpr.value[kind]; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (i > 0) { + const prevExpr = parts[parts.length - 1]; + const expr = this.evaluateExpression( + templateLiteralExpr.expressions[i - 1] + ); + const exprAsString = expr.asString(); + if (typeof exprAsString === "string") { + // We can merge quasi + expr + quasi when expr + // is a const string + prevExpr.setString(prevExpr.string + exprAsString + quasi); + prevExpr.setRange([prevExpr.range[0], quasiExpr.range[1]]); + // We unset the expression as it doesn't match to a single expression + prevExpr.setExpression(undefined); + continue; + } + parts.push(expr); + } -const createHash = __webpack_require__(15660); + const part = new BasicEvaluatedExpression() + .setString(quasi) + .setRange(quasiExpr.range) + .setExpression(quasiExpr); + quasis.push(part); + parts.push(part); + } + return { + quasis, + parts + }; + }; -const ModuleFilenameHelpers = exports; + this.hooks.evaluate.for("TemplateLiteral").tap("Parser", node => { + const { quasis, parts } = getSimplifiedTemplateResult("cooked", node); + if (parts.length === 1) { + return parts[0].setRange(node.range); + } + return new BasicEvaluatedExpression() + .setTemplateString(quasis, parts, "cooked") + .setRange(node.range); + }); + this.hooks.evaluate.for("TaggedTemplateExpression").tap("Parser", node => { + if (this.evaluateExpression(node.tag).identifier !== "String.raw") return; + const { quasis, parts } = getSimplifiedTemplateResult("raw", node.quasi); + if (parts.length === 1) { + return parts[0].setRange(node.range); + } + return new BasicEvaluatedExpression() + .setTemplateString(quasis, parts, "raw") + .setRange(node.range); + }); -ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]"; -ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE = /\[all-?loaders\]\[resource\]/gi; -ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]"; -ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi; -ModuleFilenameHelpers.RESOURCE = "[resource]"; -ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi; -ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]"; -ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH = /\[abs(olute)?-?resource-?path\]/gi; -ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]"; -ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi; -ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]"; -ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi; -ModuleFilenameHelpers.LOADERS = "[loaders]"; -ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi; -ModuleFilenameHelpers.QUERY = "[query]"; -ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi; -ModuleFilenameHelpers.ID = "[id]"; -ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi; -ModuleFilenameHelpers.HASH = "[hash]"; -ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi; -ModuleFilenameHelpers.NAMESPACE = "[namespace]"; -ModuleFilenameHelpers.REGEXP_NAMESPACE = /\[namespace\]/gi; + this.hooks.evaluateCallExpressionMember + .for("concat") + .tap("Parser", (expr, param) => { + if (!param.isString() && !param.isWrapped()) return; -const getAfter = (str, token) => { - const idx = str.indexOf(token); - return idx < 0 ? "" : str.substr(idx); -}; + let stringSuffix = null; + let hasUnknownParams = false; + for (let i = expr.arguments.length - 1; i >= 0; i--) { + const argExpr = this.evaluateExpression(expr.arguments[i]); + if (!argExpr.isString() && !argExpr.isNumber()) { + hasUnknownParams = true; + break; + } -const getBefore = (str, token) => { - const idx = str.lastIndexOf(token); - return idx < 0 ? "" : str.substr(0, idx); -}; + const value = argExpr.isString() + ? argExpr.string + : "" + argExpr.number; -const getHash = str => { - const hash = createHash("md4"); - hash.update(str); - const digest = /** @type {string} */ (hash.digest("hex")); - return digest.substr(0, 4); -}; + const newString = value + (stringSuffix ? stringSuffix.string : ""); + const newRange = [ + argExpr.range[0], + (stringSuffix || argExpr).range[1] + ]; + stringSuffix = new BasicEvaluatedExpression() + .setString(newString) + .setRange(newRange); + } -const asRegExp = test => { - if (typeof test === "string") { - test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); + if (hasUnknownParams) { + const prefix = param.isString() ? param : param.prefix; + return new BasicEvaluatedExpression() + .setWrapped(prefix, stringSuffix) + .setRange(expr.range); + } else if (param.isWrapped()) { + const postfix = stringSuffix || param.postfix; + return new BasicEvaluatedExpression() + .setWrapped(param.prefix, postfix) + .setRange(expr.range); + } else { + const newString = + param.string + (stringSuffix ? stringSuffix.string : ""); + return new BasicEvaluatedExpression() + .setString(newString) + .setRange(expr.range); + } + }); + this.hooks.evaluateCallExpressionMember + .for("split") + .tap("Parser", (expr, param) => { + if (!param.isString()) return; + if (expr.arguments.length !== 1) return; + let result; + const arg = this.evaluateExpression(expr.arguments[0]); + if (arg.isString()) { + result = param.string.split(arg.string); + } else if (arg.isRegExp()) { + result = param.string.split(arg.regExp); + } else { + return; + } + return new BasicEvaluatedExpression() + .setArray(result) + .setRange(expr.range); + }); + this.hooks.evaluate.for("ConditionalExpression").tap("Parser", expr => { + const condition = this.evaluateExpression(expr.test); + const conditionValue = condition.asBool(); + let res; + if (conditionValue === undefined) { + const consequent = this.evaluateExpression(expr.consequent); + const alternate = this.evaluateExpression(expr.alternate); + if (!consequent || !alternate) return; + res = new BasicEvaluatedExpression(); + if (consequent.isConditional()) { + res.setOptions(consequent.options); + } else { + res.setOptions([consequent]); + } + if (alternate.isConditional()) { + res.addOptions(alternate.options); + } else { + res.addOptions([alternate]); + } + } else { + res = this.evaluateExpression( + conditionValue ? expr.consequent : expr.alternate + ); + } + res.setRange(expr.range); + return res; + }); + this.hooks.evaluate.for("ArrayExpression").tap("Parser", expr => { + const items = expr.elements.map(element => { + return element !== null && this.evaluateExpression(element); + }); + if (!items.every(Boolean)) return; + return new BasicEvaluatedExpression() + .setItems(items) + .setRange(expr.range); + }); } - return test; -}; - -ModuleFilenameHelpers.createFilename = (module, options, requestShortener) => { - const opts = Object.assign( - { - namespace: "", - moduleFilenameTemplate: "" - }, - typeof options === "object" - ? options - : { - moduleFilenameTemplate: options - } - ); - let absoluteResourcePath; - let hash; - let identifier; - let moduleId; - let shortIdentifier; - if (module === undefined) module = ""; - if (typeof module === "string") { - shortIdentifier = requestShortener.shorten(module); - identifier = shortIdentifier; - moduleId = ""; - absoluteResourcePath = module.split("!").pop(); - hash = getHash(identifier); - } else { - shortIdentifier = module.readableIdentifier(requestShortener); - identifier = requestShortener.shorten(module.identifier()); - moduleId = module.id; - absoluteResourcePath = module - .identifier() - .split("!") - .pop(); - hash = getHash(identifier); - } - const resource = shortIdentifier.split("!").pop(); - const loaders = getBefore(shortIdentifier, "!"); - const allLoaders = getBefore(identifier, "!"); - const query = getAfter(resource, "?"); - const resourcePath = resource.substr(0, resource.length - query.length); - if (typeof opts.moduleFilenameTemplate === "function") { - return opts.moduleFilenameTemplate({ - identifier: identifier, - shortIdentifier: shortIdentifier, - resource: resource, - resourcePath: resourcePath, - absoluteResourcePath: absoluteResourcePath, - allLoaders: allLoaders, - query: query, - moduleId: moduleId, - hash: hash, - namespace: opts.namespace - }); + getRenameIdentifier(expr) { + const result = this.evaluateExpression(expr); + if (result && result.isIdentifier()) { + return result.identifier; + } } - return opts.moduleFilenameTemplate - .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, identifier) - .replace(ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE, shortIdentifier) - .replace(ModuleFilenameHelpers.REGEXP_RESOURCE, resource) - .replace(ModuleFilenameHelpers.REGEXP_RESOURCE_PATH, resourcePath) - .replace( - ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH, - absoluteResourcePath - ) - .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS, allLoaders) - .replace(ModuleFilenameHelpers.REGEXP_LOADERS, loaders) - .replace(ModuleFilenameHelpers.REGEXP_QUERY, query) - .replace(ModuleFilenameHelpers.REGEXP_ID, moduleId) - .replace(ModuleFilenameHelpers.REGEXP_HASH, hash) - .replace(ModuleFilenameHelpers.REGEXP_NAMESPACE, opts.namespace); -}; -ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => { - const countMap = Object.create(null); - const posMap = Object.create(null); - array.forEach((item, idx) => { - countMap[item] = countMap[item] || []; - countMap[item].push(idx); - posMap[item] = 0; - }); - if (comparator) { - Object.keys(countMap).forEach(item => { - countMap[item].sort(comparator); - }); + walkClass(classy) { + if (classy.superClass) this.walkExpression(classy.superClass); + if (classy.body && classy.body.type === "ClassBody") { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + for (const methodDefinition of classy.body.body) { + if (methodDefinition.type === "MethodDefinition") { + this.walkMethodDefinition(methodDefinition); + } + } + this.scope.topLevelScope = wasTopLevel; + } } - return array.map((item, i) => { - if (countMap[item].length > 1) { - if (comparator && countMap[item][0] === i) return item; - return fn(item, i, posMap[item]++); - } else { - return item; + + walkMethodDefinition(methodDefinition) { + if (methodDefinition.computed && methodDefinition.key) { + this.walkExpression(methodDefinition.key); } - }); -}; + if (methodDefinition.value) { + this.walkExpression(methodDefinition.value); + } + } -ModuleFilenameHelpers.matchPart = (str, test) => { - if (!test) return true; - test = asRegExp(test); - if (Array.isArray(test)) { - return test.map(asRegExp).some(regExp => regExp.test(str)); - } else { - return test.test(str); + // Prewalking iterates the scope for variable declarations + prewalkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.prewalkStatement(statement); + } } -}; -ModuleFilenameHelpers.matchObject = (obj, str) => { - if (obj.test) { - if (!ModuleFilenameHelpers.matchPart(str, obj.test)) { - return false; + // Block-Prewalking iterates the scope for block variable declarations + blockPrewalkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.blockPrewalkStatement(statement); } } - if (obj.include) { - if (!ModuleFilenameHelpers.matchPart(str, obj.include)) { - return false; + + // Walking iterates the statements and expressions and processes them + walkStatements(statements) { + for (let index = 0, len = statements.length; index < len; index++) { + const statement = statements[index]; + this.walkStatement(statement); } } - if (obj.exclude) { - if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) { - return false; + + prewalkStatement(statement) { + switch (statement.type) { + case "BlockStatement": + this.prewalkBlockStatement(statement); + break; + case "DoWhileStatement": + this.prewalkDoWhileStatement(statement); + break; + case "ExportAllDeclaration": + this.prewalkExportAllDeclaration(statement); + break; + case "ExportDefaultDeclaration": + this.prewalkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.prewalkExportNamedDeclaration(statement); + break; + case "ForInStatement": + this.prewalkForInStatement(statement); + break; + case "ForOfStatement": + this.prewalkForOfStatement(statement); + break; + case "ForStatement": + this.prewalkForStatement(statement); + break; + case "FunctionDeclaration": + this.prewalkFunctionDeclaration(statement); + break; + case "IfStatement": + this.prewalkIfStatement(statement); + break; + case "ImportDeclaration": + this.prewalkImportDeclaration(statement); + break; + case "LabeledStatement": + this.prewalkLabeledStatement(statement); + break; + case "SwitchStatement": + this.prewalkSwitchStatement(statement); + break; + case "TryStatement": + this.prewalkTryStatement(statement); + break; + case "VariableDeclaration": + this.prewalkVariableDeclaration(statement); + break; + case "WhileStatement": + this.prewalkWhileStatement(statement); + break; + case "WithStatement": + this.prewalkWithStatement(statement); + break; } } - return true; -}; + blockPrewalkStatement(statement) { + switch (statement.type) { + case "VariableDeclaration": + this.blockPrewalkVariableDeclaration(statement); + break; + case "ExportDefaultDeclaration": + this.blockPrewalkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.blockPrewalkExportNamedDeclaration(statement); + break; + case "ClassDeclaration": + this.blockPrewalkClassDeclaration(statement); + break; + } + } -/***/ }), + walkStatement(statement) { + if (this.hooks.statement.call(statement) !== undefined) return; + switch (statement.type) { + case "BlockStatement": + this.walkBlockStatement(statement); + break; + case "ClassDeclaration": + this.walkClassDeclaration(statement); + break; + case "DoWhileStatement": + this.walkDoWhileStatement(statement); + break; + case "ExportDefaultDeclaration": + this.walkExportDefaultDeclaration(statement); + break; + case "ExportNamedDeclaration": + this.walkExportNamedDeclaration(statement); + break; + case "ExpressionStatement": + this.walkExpressionStatement(statement); + break; + case "ForInStatement": + this.walkForInStatement(statement); + break; + case "ForOfStatement": + this.walkForOfStatement(statement); + break; + case "ForStatement": + this.walkForStatement(statement); + break; + case "FunctionDeclaration": + this.walkFunctionDeclaration(statement); + break; + case "IfStatement": + this.walkIfStatement(statement); + break; + case "LabeledStatement": + this.walkLabeledStatement(statement); + break; + case "ReturnStatement": + this.walkReturnStatement(statement); + break; + case "SwitchStatement": + this.walkSwitchStatement(statement); + break; + case "ThrowStatement": + this.walkThrowStatement(statement); + break; + case "TryStatement": + this.walkTryStatement(statement); + break; + case "VariableDeclaration": + this.walkVariableDeclaration(statement); + break; + case "WhileStatement": + this.walkWhileStatement(statement); + break; + case "WithStatement": + this.walkWithStatement(statement); + break; + } + } -/***/ 71638: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Real Statements + prewalkBlockStatement(statement) { + this.prewalkStatements(statement.body); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + walkBlockStatement(statement) { + this.inBlockScope(() => { + const body = statement.body; + this.blockPrewalkStatements(body); + this.walkStatements(body); + }); + } + walkExpressionStatement(statement) { + this.walkExpression(statement.expression); + } -const WebpackError = __webpack_require__(97391); + prewalkIfStatement(statement) { + this.prewalkStatement(statement.consequent); + if (statement.alternate) { + this.prewalkStatement(statement.alternate); + } + } -class ModuleNotFoundError extends WebpackError { - constructor(module, err) { - super("Module not found: " + err); + walkIfStatement(statement) { + const result = this.hooks.statementIf.call(statement); + if (result === undefined) { + this.walkExpression(statement.test); + this.walkStatement(statement.consequent); + if (statement.alternate) { + this.walkStatement(statement.alternate); + } + } else { + if (result) { + this.walkStatement(statement.consequent); + } else if (statement.alternate) { + this.walkStatement(statement.alternate); + } + } + } - this.name = "ModuleNotFoundError"; - this.details = err.details; - this.missing = err.missing; - this.module = module; - this.error = err; + prewalkLabeledStatement(statement) { + this.prewalkStatement(statement.body); + } - Error.captureStackTrace(this, this.constructor); + walkLabeledStatement(statement) { + const hook = this.hooks.label.get(statement.label.name); + if (hook !== undefined) { + const result = hook.call(statement); + if (result === true) return; + } + this.walkStatement(statement.body); } -} -module.exports = ModuleNotFoundError; + prewalkWithStatement(statement) { + this.prewalkStatement(statement.body); + } + walkWithStatement(statement) { + this.walkExpression(statement.object); + this.walkStatement(statement.body); + } -/***/ }), + prewalkSwitchStatement(statement) { + this.prewalkSwitchCases(statement.cases); + } -/***/ 62500: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + walkSwitchStatement(statement) { + this.walkExpression(statement.discriminant); + this.walkSwitchCases(statement.cases); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + walkTerminatingStatement(statement) { + if (statement.argument) this.walkExpression(statement.argument); + } + walkReturnStatement(statement) { + this.walkTerminatingStatement(statement); + } -const WebpackError = __webpack_require__(97391); + walkThrowStatement(statement) { + this.walkTerminatingStatement(statement); + } -/** @typedef {import("./Module")} Module */ + prewalkTryStatement(statement) { + this.prewalkStatement(statement.block); + } -class ModuleParseError extends WebpackError { - /** - * @param {Module} module the errored module - * @param {string} source source code - * @param {Error&any} err the parse error - * @param {string[]} loaders the loaders used - */ - constructor(module, source, err, loaders) { - let message = "Module parse failed: " + err.message; - let loc = undefined; - if (loaders.length >= 1) { - message += `\nFile was processed with these loaders:${loaders - .map(loader => `\n * ${loader}`) - .join("")}`; - message += - "\nYou may need an additional loader to handle the result of these loaders."; - } else { - message += - "\nYou may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders"; - } - if ( - err.loc && - typeof err.loc === "object" && - typeof err.loc.line === "number" - ) { - var lineNumber = err.loc.line; - if (/[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source)) { - // binary file - message += "\n(Source code omitted for this binary file)"; - } else { - const sourceLines = source.split(/\r?\n/); - const start = Math.max(0, lineNumber - 3); - const linesBefore = sourceLines.slice(start, lineNumber - 1); - const theLine = sourceLines[lineNumber - 1]; - const linesAfter = sourceLines.slice(lineNumber, lineNumber + 2); - message += - linesBefore.map(l => `\n| ${l}`).join("") + - `\n> ${theLine}` + - linesAfter.map(l => `\n| ${l}`).join(""); - } - loc = err.loc; + walkTryStatement(statement) { + if (this.scope.inTry) { + this.walkStatement(statement.block); } else { - message += "\n" + err.stack; + this.scope.inTry = true; + this.walkStatement(statement.block); + this.scope.inTry = false; } + if (statement.handler) this.walkCatchClause(statement.handler); + if (statement.finalizer) this.walkStatement(statement.finalizer); + } - super(message); - - this.name = "ModuleParseError"; - this.module = module; - this.loc = loc; - this.error = err; - - Error.captureStackTrace(this, this.constructor); + prewalkWhileStatement(statement) { + this.prewalkStatement(statement.body); } -} - -module.exports = ModuleParseError; + walkWhileStatement(statement) { + this.walkExpression(statement.test); + this.walkStatement(statement.body); + } -/***/ }), - -/***/ 44576: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + prewalkDoWhileStatement(statement) { + this.prewalkStatement(statement.body); + } + walkDoWhileStatement(statement) { + this.walkStatement(statement.body); + this.walkExpression(statement.test); + } -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./Dependency")} Dependency */ + prewalkForStatement(statement) { + if (statement.init) { + if (statement.init.type === "VariableDeclaration") { + this.prewalkStatement(statement.init); + } + } + this.prewalkStatement(statement.body); + } -class ModuleReason { - /** - * @param {Module} module the referencing module - * @param {Dependency} dependency the referencing dependency - * @param {string=} explanation some extra detail - */ - constructor(module, dependency, explanation) { - this.module = module; - this.dependency = dependency; - this.explanation = explanation; - this._chunks = null; + walkForStatement(statement) { + this.inBlockScope(() => { + if (statement.init) { + if (statement.init.type === "VariableDeclaration") { + this.blockPrewalkVariableDeclaration(statement.init); + this.walkStatement(statement.init); + } else { + this.walkExpression(statement.init); + } + } + if (statement.test) { + this.walkExpression(statement.test); + } + if (statement.update) { + this.walkExpression(statement.update); + } + const body = statement.body; + if (body.type === "BlockStatement") { + // no need to add additional scope + this.blockPrewalkStatements(body.body); + this.walkStatements(body.body); + } else { + this.walkStatement(body); + } + }); } - hasChunk(chunk) { - if (this._chunks) { - if (this._chunks.has(chunk)) return true; - } else if (this.module && this.module._chunks.has(chunk)) return true; - return false; + prewalkForInStatement(statement) { + if (statement.left.type === "VariableDeclaration") { + this.prewalkVariableDeclaration(statement.left); + } + this.prewalkStatement(statement.body); } - rewriteChunks(oldChunk, newChunks) { - if (!this._chunks) { - if (this.module) { - if (!this.module._chunks.has(oldChunk)) return; - this._chunks = new Set(this.module._chunks); + walkForInStatement(statement) { + this.inBlockScope(() => { + if (statement.left.type === "VariableDeclaration") { + this.blockPrewalkVariableDeclaration(statement.left); + this.walkVariableDeclaration(statement.left); } else { - this._chunks = new Set(); + this.walkPattern(statement.left); } - } - if (this._chunks.has(oldChunk)) { - this._chunks.delete(oldChunk); - for (let i = 0; i < newChunks.length; i++) { - this._chunks.add(newChunks[i]); + this.walkExpression(statement.right); + const body = statement.body; + if (body.type === "BlockStatement") { + // no need to add additional scope + this.blockPrewalkStatements(body.body); + this.walkStatements(body.body); + } else { + this.walkStatement(body); } - } + }); } -} - -module.exports = ModuleReason; - - -/***/ }), - -/***/ 75100: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const { Tapable, SyncWaterfallHook, SyncHook } = __webpack_require__(56758); - -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("./Module")} Module */ + prewalkForOfStatement(statement) { + if (statement.left.type === "VariableDeclaration") { + this.prewalkVariableDeclaration(statement.left); + } + this.prewalkStatement(statement.body); + } -module.exports = class ModuleTemplate extends Tapable { - constructor(runtimeTemplate, type) { - super(); - this.runtimeTemplate = runtimeTemplate; - this.type = type; - this.hooks = { - content: new SyncWaterfallHook([ - "source", - "module", - "options", - "dependencyTemplates" - ]), - module: new SyncWaterfallHook([ - "source", - "module", - "options", - "dependencyTemplates" - ]), - render: new SyncWaterfallHook([ - "source", - "module", - "options", - "dependencyTemplates" - ]), - package: new SyncWaterfallHook([ - "source", - "module", - "options", - "dependencyTemplates" - ]), - hash: new SyncHook(["hash"]) - }; + walkForOfStatement(statement) { + this.inBlockScope(() => { + if (statement.left.type === "VariableDeclaration") { + this.blockPrewalkVariableDeclaration(statement.left); + this.walkVariableDeclaration(statement.left); + } else { + this.walkPattern(statement.left); + } + this.walkExpression(statement.right); + const body = statement.body; + if (body.type === "BlockStatement") { + // no need to add additional scope + this.blockPrewalkStatements(body.body); + this.walkStatements(body.body); + } else { + this.walkStatement(body); + } + }); } - /** - * @param {Module} module the module - * @param {TODO} dependencyTemplates templates for dependencies - * @param {TODO} options render options - * @returns {Source} the source - */ - render(module, dependencyTemplates, options) { - try { - const moduleSource = module.source( - dependencyTemplates, - this.runtimeTemplate, - this.type - ); - const moduleSourcePostContent = this.hooks.content.call( - moduleSource, - module, - options, - dependencyTemplates - ); - const moduleSourcePostModule = this.hooks.module.call( - moduleSourcePostContent, - module, - options, - dependencyTemplates - ); - const moduleSourcePostRender = this.hooks.render.call( - moduleSourcePostModule, - module, - options, - dependencyTemplates - ); - return this.hooks.package.call( - moduleSourcePostRender, - module, - options, - dependencyTemplates - ); - } catch (e) { - e.message = `${module.identifier()}\n${e.message}`; - throw e; + // Declarations + prewalkFunctionDeclaration(statement) { + if (statement.id) { + this.scope.renames.set(statement.id.name, null); + this.scope.definitions.add(statement.id.name); } } - updateHash(hash) { - hash.update("1"); - this.hooks.hash.call(hash); + walkFunctionDeclaration(statement) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + this.inFunctionScope(true, statement.params, () => { + for (const param of statement.params) { + this.walkPattern(param); + } + if (statement.body.type === "BlockStatement") { + this.detectMode(statement.body.body); + this.prewalkStatement(statement.body); + this.walkStatement(statement.body); + } else { + this.walkExpression(statement.body); + } + }); + this.scope.topLevelScope = wasTopLevel; } -}; - - -/***/ }), - -/***/ 6372: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const WebpackError = __webpack_require__(97391); -const { cleanUp } = __webpack_require__(80140); -class ModuleWarning extends WebpackError { - constructor(module, warning, { from = null } = {}) { - let message = "Module Warning"; - if (from) { - message += ` (from ${from}):\n`; - } else { - message += ": "; - } - if (warning && typeof warning === "object" && warning.message) { - message += warning.message; - } else if (warning) { - message += warning; + prewalkImportDeclaration(statement) { + const source = statement.source.value; + this.hooks.import.call(statement, source); + for (const specifier of statement.specifiers) { + const name = specifier.local.name; + this.scope.renames.set(name, null); + this.scope.definitions.add(name); + switch (specifier.type) { + case "ImportDefaultSpecifier": + this.hooks.importSpecifier.call(statement, source, "default", name); + break; + case "ImportSpecifier": + this.hooks.importSpecifier.call( + statement, + source, + specifier.imported.name, + name + ); + break; + case "ImportNamespaceSpecifier": + this.hooks.importSpecifier.call(statement, source, null, name); + break; + } } - super(message); - this.name = "ModuleWarning"; - this.module = module; - this.warning = warning; - this.details = - warning && typeof warning === "object" && warning.stack - ? cleanUp(warning.stack, this.message) - : undefined; - - Error.captureStackTrace(this, this.constructor); } -} - -module.exports = ModuleWarning; - - -/***/ }), - -/***/ 10238: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const { Tapable, SyncHook, MultiHook } = __webpack_require__(56758); -const asyncLib = __webpack_require__(36386); -const MultiWatching = __webpack_require__(66624); -const MultiStats = __webpack_require__(55144); -const ConcurrentCompilationError = __webpack_require__(18933); -module.exports = class MultiCompiler extends Tapable { - constructor(compilers) { - super(); - this.hooks = { - done: new SyncHook(["stats"]), - invalid: new MultiHook(compilers.map(c => c.hooks.invalid)), - run: new MultiHook(compilers.map(c => c.hooks.run)), - watchClose: new SyncHook([]), - watchRun: new MultiHook(compilers.map(c => c.hooks.watchRun)), - infrastructureLog: new MultiHook( - compilers.map(c => c.hooks.infrastructureLog) - ) - }; - if (!Array.isArray(compilers)) { - compilers = Object.keys(compilers).map(name => { - compilers[name].name = name; - return compilers[name]; - }); - } - this.compilers = compilers; - let doneCompilers = 0; - let compilerStats = []; - let index = 0; - for (const compiler of this.compilers) { - let compilerDone = false; - const compilerIndex = index++; - // eslint-disable-next-line no-loop-func - compiler.hooks.done.tap("MultiCompiler", stats => { - if (!compilerDone) { - compilerDone = true; - doneCompilers++; - } - compilerStats[compilerIndex] = stats; - if (doneCompilers === this.compilers.length) { - this.hooks.done.call(new MultiStats(compilerStats)); - } - }); - // eslint-disable-next-line no-loop-func - compiler.hooks.invalid.tap("MultiCompiler", () => { - if (compilerDone) { - compilerDone = false; - doneCompilers--; + enterDeclaration(declaration, onIdent) { + switch (declaration.type) { + case "VariableDeclaration": + for (const declarator of declaration.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + this.enterPattern(declarator.id, onIdent); + break; + } + } } - }); + break; + case "FunctionDeclaration": + this.enterPattern(declaration.id, onIdent); + break; + case "ClassDeclaration": + this.enterPattern(declaration.id, onIdent); + break; } - this.running = false; } - get outputPath() { - let commonPath = this.compilers[0].outputPath; - for (const compiler of this.compilers) { - while ( - compiler.outputPath.indexOf(commonPath) !== 0 && - /[/\\]/.test(commonPath) - ) { - commonPath = commonPath.replace(/[/\\][^/\\]*$/, ""); - } + blockPrewalkExportNamedDeclaration(statement) { + if (statement.declaration) { + this.blockPrewalkStatement(statement.declaration); } - - if (!commonPath && this.compilers[0].outputPath[0] === "/") return "/"; - return commonPath; } - get inputFileSystem() { - throw new Error("Cannot read inputFileSystem of a MultiCompiler"); - } - - get outputFileSystem() { - throw new Error("Cannot read outputFileSystem of a MultiCompiler"); + prewalkExportNamedDeclaration(statement) { + let source; + if (statement.source) { + source = statement.source.value; + this.hooks.exportImport.call(statement, source); + } else { + this.hooks.export.call(statement); + } + if (statement.declaration) { + if ( + !this.hooks.exportDeclaration.call(statement, statement.declaration) + ) { + this.prewalkStatement(statement.declaration); + let index = 0; + this.enterDeclaration(statement.declaration, def => { + this.hooks.exportSpecifier.call(statement, def, def, index++); + }); + } + } + if (statement.specifiers) { + for ( + let specifierIndex = 0; + specifierIndex < statement.specifiers.length; + specifierIndex++ + ) { + const specifier = statement.specifiers[specifierIndex]; + switch (specifier.type) { + case "ExportSpecifier": { + const name = specifier.exported.name; + if (source) { + this.hooks.exportImportSpecifier.call( + statement, + source, + specifier.local.name, + name, + specifierIndex + ); + } else { + this.hooks.exportSpecifier.call( + statement, + specifier.local.name, + name, + specifierIndex + ); + } + break; + } + } + } + } } - set inputFileSystem(value) { - for (const compiler of this.compilers) { - compiler.inputFileSystem = value; + walkExportNamedDeclaration(statement) { + if (statement.declaration) { + this.walkStatement(statement.declaration); } } - set outputFileSystem(value) { - for (const compiler of this.compilers) { - compiler.outputFileSystem = value; + blockPrewalkExportDefaultDeclaration(statement) { + if (statement.declaration.type === "ClassDeclaration") { + this.blockPrewalkClassDeclaration(statement.declaration); } } - getInfrastructureLogger(name) { - return this.compilers[0].getInfrastructureLogger(name); + prewalkExportDefaultDeclaration(statement) { + this.prewalkStatement(statement.declaration); + if ( + statement.declaration.id && + statement.declaration.type !== "FunctionExpression" && + statement.declaration.type !== "ClassExpression" + ) { + this.hooks.exportSpecifier.call( + statement, + statement.declaration.id.name, + "default" + ); + } } - validateDependencies(callback) { - const edges = new Set(); - const missing = []; - const targetFound = compiler => { - for (const edge of edges) { - if (edge.target === compiler) { - return true; - } - } - return false; - }; - const sortEdges = (e1, e2) => { - return ( - e1.source.name.localeCompare(e2.source.name) || - e1.target.name.localeCompare(e2.target.name) - ); - }; - for (const source of this.compilers) { - if (source.dependencies) { - for (const dep of source.dependencies) { - const target = this.compilers.find(c => c.name === dep); - if (!target) { - missing.push(dep); - } else { - edges.add({ - source, - target - }); - } - } + walkExportDefaultDeclaration(statement) { + this.hooks.export.call(statement); + if ( + statement.declaration.id && + statement.declaration.type !== "FunctionExpression" && + statement.declaration.type !== "ClassExpression" + ) { + if ( + !this.hooks.exportDeclaration.call(statement, statement.declaration) + ) { + this.walkStatement(statement.declaration); } - } - const errors = missing.map(m => `Compiler dependency \`${m}\` not found.`); - const stack = this.compilers.filter(c => !targetFound(c)); - while (stack.length > 0) { - const current = stack.pop(); - for (const edge of edges) { - if (edge.source === current) { - edges.delete(edge); - const target = edge.target; - if (!targetFound(target)) { - stack.push(target); - } - } + } else { + // Acorn parses `export default function() {}` as `FunctionDeclaration` and + // `export default class {}` as `ClassDeclaration`, both with `id = null`. + // These nodes must be treated as expressions. + if (statement.declaration.type === "FunctionDeclaration") { + this.walkFunctionDeclaration(statement.declaration); + } else if (statement.declaration.type === "ClassDeclaration") { + this.walkClassDeclaration(statement.declaration); + } else { + this.walkExpression(statement.declaration); + } + if (!this.hooks.exportExpression.call(statement, statement.declaration)) { + this.hooks.exportSpecifier.call( + statement, + statement.declaration, + "default" + ); } } - if (edges.size > 0) { - const lines = Array.from(edges) - .sort(sortEdges) - .map(edge => `${edge.source.name} -> ${edge.target.name}`); - lines.unshift("Circular dependency found in compiler dependencies."); - errors.unshift(lines.join("\n")); - } - if (errors.length > 0) { - const message = errors.join("\n"); - callback(new Error(message)); - return false; - } - return true; } - runWithDependencies(compilers, fn, callback) { - const fulfilledNames = new Set(); - let remainingCompilers = compilers; - const isDependencyFulfilled = d => fulfilledNames.has(d); - const getReadyCompilers = () => { - let readyCompilers = []; - let list = remainingCompilers; - remainingCompilers = []; - for (const c of list) { - const ready = - !c.dependencies || c.dependencies.every(isDependencyFulfilled); - if (ready) { - readyCompilers.push(c); - } else { - remainingCompilers.push(c); - } - } - return readyCompilers; - }; - const runCompilers = callback => { - if (remainingCompilers.length === 0) return callback(); - asyncLib.map( - getReadyCompilers(), - (compiler, callback) => { - fn(compiler, err => { - if (err) return callback(err); - fulfilledNames.add(compiler.name); - runCompilers(callback); - }); - }, - callback - ); - }; - runCompilers(callback); + prewalkExportAllDeclaration(statement) { + const source = statement.source.value; + this.hooks.exportImport.call(statement, source); + this.hooks.exportImportSpecifier.call(statement, source, null, null, 0); } - watch(watchOptions, handler) { - if (this.running) return handler(new ConcurrentCompilationError()); + prewalkVariableDeclaration(statement) { + if (statement.kind !== "var") return; + this._prewalkVariableDeclaration(statement, this.hooks.varDeclarationVar); + } - let watchings = []; - let allStats = this.compilers.map(() => null); - let compilerStatus = this.compilers.map(() => false); - if (this.validateDependencies(handler)) { - this.running = true; - this.runWithDependencies( - this.compilers, - (compiler, callback) => { - const compilerIdx = this.compilers.indexOf(compiler); - let firstRun = true; - let watching = compiler.watch( - Array.isArray(watchOptions) - ? watchOptions[compilerIdx] - : watchOptions, - (err, stats) => { - if (err) handler(err); - if (stats) { - allStats[compilerIdx] = stats; - compilerStatus[compilerIdx] = "new"; - if (compilerStatus.every(Boolean)) { - const freshStats = allStats.filter((s, idx) => { - return compilerStatus[idx] === "new"; - }); - compilerStatus.fill(true); - const multiStats = new MultiStats(freshStats); - handler(null, multiStats); - } - } - if (firstRun && !err) { - firstRun = false; - callback(); + blockPrewalkVariableDeclaration(statement) { + if (statement.kind === "var") return; + const hookMap = + statement.kind === "const" + ? this.hooks.varDeclarationConst + : this.hooks.varDeclarationLet; + this._prewalkVariableDeclaration(statement, hookMap); + } + + _prewalkVariableDeclaration(statement, hookMap) { + for (const declarator of statement.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + this.enterPattern(declarator.id, (name, decl) => { + let hook = hookMap.get(name); + if (hook === undefined || !hook.call(decl)) { + hook = this.hooks.varDeclaration.get(name); + if (hook === undefined || !hook.call(decl)) { + this.scope.renames.set(name, null); + this.scope.definitions.add(name); } } - ); - watchings.push(watching); - }, - () => { - // ignore + }); + break; } - ); + } } - - return new MultiWatching(watchings, this); } - run(callback) { - if (this.running) { - return callback(new ConcurrentCompilationError()); - } - - const finalCallback = (err, stats) => { - this.running = false; - - if (callback !== undefined) { - return callback(err, stats); - } - }; - - const allStats = this.compilers.map(() => null); - if (this.validateDependencies(callback)) { - this.running = true; - this.runWithDependencies( - this.compilers, - (compiler, callback) => { - const compilerIdx = this.compilers.indexOf(compiler); - compiler.run((err, stats) => { - if (err) { - return callback(err); + walkVariableDeclaration(statement) { + for (const declarator of statement.declarations) { + switch (declarator.type) { + case "VariableDeclarator": { + const renameIdentifier = + declarator.init && this.getRenameIdentifier(declarator.init); + if (renameIdentifier && declarator.id.type === "Identifier") { + const hook = this.hooks.canRename.get(renameIdentifier); + if (hook !== undefined && hook.call(declarator.init)) { + // renaming with "var a = b;" + const hook = this.hooks.rename.get(renameIdentifier); + if (hook === undefined || !hook.call(declarator.init)) { + this.scope.renames.set( + declarator.id.name, + this.scope.renames.get(renameIdentifier) || renameIdentifier + ); + this.scope.definitions.delete(declarator.id.name); + } + break; } - allStats[compilerIdx] = stats; - callback(); - }); - }, - err => { - if (err) { - return finalCallback(err); } - finalCallback(null, new MultiStats(allStats)); + this.walkPattern(declarator.id); + if (declarator.init) this.walkExpression(declarator.init); + break; } - ); + } } } - purgeInputFileSystem() { - for (const compiler of this.compilers) { - if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { - compiler.inputFileSystem.purge(); - } + blockPrewalkClassDeclaration(statement) { + if (statement.id) { + this.scope.renames.set(statement.id.name, null); + this.scope.definitions.add(statement.id.name); } } -}; - - -/***/ }), - -/***/ 98046: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const MultiEntryDependency = __webpack_require__(7791); -const SingleEntryDependency = __webpack_require__(84828); -const MultiModuleFactory = __webpack_require__(24005); -/** @typedef {import("./Compiler")} Compiler */ + walkClassDeclaration(statement) { + this.walkClass(statement); + } -class MultiEntryPlugin { - /** - * The MultiEntryPlugin is invoked whenever this.options.entry value is an array of paths - * @param {string} context context path - * @param {string[]} entries array of entry paths - * @param {string} name entry key name - */ - constructor(context, entries, name) { - this.context = context; - this.entries = entries; - this.name = name; + prewalkSwitchCases(switchCases) { + for (let index = 0, len = switchCases.length; index < len; index++) { + const switchCase = switchCases[index]; + this.prewalkStatements(switchCase.consequent); + } } - /** - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "MultiEntryPlugin", - (compilation, { normalModuleFactory }) => { - const multiModuleFactory = new MultiModuleFactory(); + walkSwitchCases(switchCases) { + for (let index = 0, len = switchCases.length; index < len; index++) { + const switchCase = switchCases[index]; - compilation.dependencyFactories.set( - MultiEntryDependency, - multiModuleFactory - ); - compilation.dependencyFactories.set( - SingleEntryDependency, - normalModuleFactory - ); + if (switchCase.test) { + this.walkExpression(switchCase.test); } - ); - - compiler.hooks.make.tapAsync( - "MultiEntryPlugin", - (compilation, callback) => { - const { context, entries, name } = this; + this.walkStatements(switchCase.consequent); + } + } - const dep = MultiEntryPlugin.createDependency(entries, name); - compilation.addEntry(context, dep, name, callback); + walkCatchClause(catchClause) { + this.inBlockScope(() => { + // Error binding is optional in catch clause since ECMAScript 2019 + if (catchClause.param !== null) { + this.enterPattern(catchClause.param, ident => { + this.scope.renames.set(ident, null); + this.scope.definitions.add(ident); + }); + this.walkPattern(catchClause.param); } - ); + this.prewalkStatement(catchClause.body); + this.walkStatement(catchClause.body); + }); } - /** - * @param {string[]} entries each entry path string - * @param {string} name name of the entry - * @returns {MultiEntryDependency} returns a constructed Dependency - */ - static createDependency(entries, name) { - return new MultiEntryDependency( - entries.map((e, idx) => { - const dep = new SingleEntryDependency(e); - // Because entrypoints are not dependencies found in an - // existing module, we give it a synthetic id - dep.loc = { - name, - index: idx - }; - return dep; - }), - name - ); + walkPattern(pattern) { + switch (pattern.type) { + case "ArrayPattern": + this.walkArrayPattern(pattern); + break; + case "AssignmentPattern": + this.walkAssignmentPattern(pattern); + break; + case "MemberExpression": + this.walkMemberExpression(pattern); + break; + case "ObjectPattern": + this.walkObjectPattern(pattern); + break; + case "RestElement": + this.walkRestElement(pattern); + break; + } } -} - -module.exports = MultiEntryPlugin; - - -/***/ }), -/***/ 4198: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const Module = __webpack_require__(75993); -const Template = __webpack_require__(96066); -const { RawSource } = __webpack_require__(53665); + walkAssignmentPattern(pattern) { + this.walkExpression(pattern.right); + this.walkPattern(pattern.left); + } -/** @typedef {import("./util/createHash").Hash} Hash */ + walkObjectPattern(pattern) { + for (let i = 0, len = pattern.properties.length; i < len; i++) { + const prop = pattern.properties[i]; + if (prop) { + if (prop.computed) this.walkExpression(prop.key); + if (prop.value) this.walkPattern(prop.value); + } + } + } -class MultiModule extends Module { - constructor(context, dependencies, name) { - super("javascript/dynamic", context); + walkArrayPattern(pattern) { + for (let i = 0, len = pattern.elements.length; i < len; i++) { + const element = pattern.elements[i]; + if (element) this.walkPattern(element); + } + } - // Info from Factory - this.dependencies = dependencies; - this.name = name; - this._identifier = `multi ${this.dependencies - .map(d => d.request) - .join(" ")}`; + walkRestElement(pattern) { + this.walkPattern(pattern.argument); } - identifier() { - return this._identifier; + walkExpressions(expressions) { + for (const expression of expressions) { + if (expression) { + this.walkExpression(expression); + } + } } - readableIdentifier(requestShortener) { - return `multi ${this.dependencies - .map(d => requestShortener.shorten(d.request)) - .join(" ")}`; + walkExpression(expression) { + switch (expression.type) { + case "ArrayExpression": + this.walkArrayExpression(expression); + break; + case "ArrowFunctionExpression": + this.walkArrowFunctionExpression(expression); + break; + case "AssignmentExpression": + this.walkAssignmentExpression(expression); + break; + case "AwaitExpression": + this.walkAwaitExpression(expression); + break; + case "BinaryExpression": + this.walkBinaryExpression(expression); + break; + case "CallExpression": + this.walkCallExpression(expression); + break; + case "ClassExpression": + this.walkClassExpression(expression); + break; + case "ConditionalExpression": + this.walkConditionalExpression(expression); + break; + case "FunctionExpression": + this.walkFunctionExpression(expression); + break; + case "Identifier": + this.walkIdentifier(expression); + break; + case "LogicalExpression": + this.walkLogicalExpression(expression); + break; + case "MemberExpression": + this.walkMemberExpression(expression); + break; + case "NewExpression": + this.walkNewExpression(expression); + break; + case "ObjectExpression": + this.walkObjectExpression(expression); + break; + case "SequenceExpression": + this.walkSequenceExpression(expression); + break; + case "SpreadElement": + this.walkSpreadElement(expression); + break; + case "TaggedTemplateExpression": + this.walkTaggedTemplateExpression(expression); + break; + case "TemplateLiteral": + this.walkTemplateLiteral(expression); + break; + case "ThisExpression": + this.walkThisExpression(expression); + break; + case "UnaryExpression": + this.walkUnaryExpression(expression); + break; + case "UpdateExpression": + this.walkUpdateExpression(expression); + break; + case "YieldExpression": + this.walkYieldExpression(expression); + break; + } } - build(options, compilation, resolver, fs, callback) { - this.built = true; - this.buildMeta = {}; - this.buildInfo = {}; - return callback(); + walkAwaitExpression(expression) { + this.walkExpression(expression.argument); } - needRebuild() { - return false; + walkArrayExpression(expression) { + if (expression.elements) { + this.walkExpressions(expression.elements); + } } - size() { - return 16 + this.dependencies.length * 12; + walkSpreadElement(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } } - /** - * @param {Hash} hash the hash used to track dependencies - * @returns {void} - */ - updateHash(hash) { - hash.update("multi module"); - hash.update(this.name || ""); - super.updateHash(hash); - } - - source(dependencyTemplates, runtimeTemplate) { - const str = []; - let idx = 0; - for (const dep of this.dependencies) { - if (dep.module) { - if (idx === this.dependencies.length - 1) { - str.push("module.exports = "); - } - str.push("__webpack_require__("); - if (runtimeTemplate.outputOptions.pathinfo) { - str.push(Template.toComment(dep.request)); - } - str.push(`${JSON.stringify(dep.module.id)}`); - str.push(")"); - } else { - const content = __webpack_require__(75386).module( - dep.request - ); - str.push(content); + walkObjectExpression(expression) { + for ( + let propIndex = 0, len = expression.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = expression.properties[propIndex]; + if (prop.type === "SpreadElement") { + this.walkExpression(prop.argument); + continue; + } + if (prop.computed) { + this.walkExpression(prop.key); + } + if (prop.shorthand) { + this.scope.inShorthand = true; + } + this.walkExpression(prop.value); + if (prop.shorthand) { + this.scope.inShorthand = false; } - str.push(";\n"); - idx++; } - return new RawSource(str.join("")); } -} - -module.exports = MultiModule; - - -/***/ }), - -/***/ 24005: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + walkFunctionExpression(expression) { + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + const scopeParams = expression.params; -const { Tapable } = __webpack_require__(56758); -const MultiModule = __webpack_require__(4198); + // Add function name in scope for recursive calls + if (expression.id) { + scopeParams.push(expression.id.name); + } -module.exports = class MultiModuleFactory extends Tapable { - constructor() { - super(); - this.hooks = {}; + this.inFunctionScope(true, scopeParams, () => { + for (const param of expression.params) { + this.walkPattern(param); + } + if (expression.body.type === "BlockStatement") { + this.detectMode(expression.body.body); + this.prewalkStatement(expression.body); + this.walkStatement(expression.body); + } else { + this.walkExpression(expression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; } - create(data, callback) { - const dependency = data.dependencies[0]; - callback( - null, - new MultiModule(data.context, dependency.dependencies, dependency.name) - ); + walkArrowFunctionExpression(expression) { + this.inFunctionScope(false, expression.params, () => { + for (const param of expression.params) { + this.walkPattern(param); + } + if (expression.body.type === "BlockStatement") { + this.detectMode(expression.body.body); + this.prewalkStatement(expression.body); + this.walkStatement(expression.body); + } else { + this.walkExpression(expression.body); + } + }); } -}; - - -/***/ }), - -/***/ 55144: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + walkSequenceExpression(expression) { + if (expression.expressions) this.walkExpressions(expression.expressions); + } -const Stats = __webpack_require__(99977); + walkUpdateExpression(expression) { + this.walkExpression(expression.argument); + } -const optionOrFallback = (optionValue, fallbackValue) => - optionValue !== undefined ? optionValue : fallbackValue; + walkUnaryExpression(expression) { + if (expression.operator === "typeof") { + const exprName = this.getNameForExpression(expression.argument); + if (exprName && exprName.free) { + const hook = this.hooks.typeof.get(exprName.name); + if (hook !== undefined) { + const result = hook.call(expression); + if (result === true) return; + } + } + } + this.walkExpression(expression.argument); + } -class MultiStats { - constructor(stats) { - this.stats = stats; - this.hash = stats.map(stat => stat.hash).join(""); + walkLeftRightExpression(expression) { + this.walkExpression(expression.left); + this.walkExpression(expression.right); } - hasErrors() { - return this.stats - .map(stat => stat.hasErrors()) - .reduce((a, b) => a || b, false); + walkBinaryExpression(expression) { + this.walkLeftRightExpression(expression); } - hasWarnings() { - return this.stats - .map(stat => stat.hasWarnings()) - .reduce((a, b) => a || b, false); + walkLogicalExpression(expression) { + const result = this.hooks.expressionLogicalOperator.call(expression); + if (result === undefined) { + this.walkLeftRightExpression(expression); + } else { + if (result) { + this.walkExpression(expression.right); + } + } } - toJson(options, forToString) { - if (typeof options === "boolean" || typeof options === "string") { - options = Stats.presetToOptions(options); - } else if (!options) { - options = {}; + walkAssignmentExpression(expression) { + const renameIdentifier = this.getRenameIdentifier(expression.right); + if (expression.left.type === "Identifier" && renameIdentifier) { + const hook = this.hooks.canRename.get(renameIdentifier); + if (hook !== undefined && hook.call(expression.right)) { + // renaming "a = b;" + const hook = this.hooks.rename.get(renameIdentifier); + if (hook === undefined || !hook.call(expression.right)) { + this.scope.renames.set(expression.left.name, renameIdentifier); + this.scope.definitions.delete(expression.left.name); + } + return; + } } - const jsons = this.stats.map((stat, idx) => { - const childOptions = Stats.getChildOptions(options, idx); - const obj = stat.toJson(childOptions, forToString); - obj.name = stat.compilation && stat.compilation.name; - return obj; - }); - const showVersion = - options.version === undefined - ? jsons.every(j => j.version) - : options.version !== false; - const showHash = - options.hash === undefined - ? jsons.every(j => j.hash) - : options.hash !== false; - if (showVersion) { - for (const j of jsons) { - delete j.version; + if (expression.left.type === "Identifier") { + const assignedHook = this.hooks.assigned.get(expression.left.name); + if (assignedHook === undefined || !assignedHook.call(expression)) { + this.walkExpression(expression.right); + } + this.scope.renames.set(expression.left.name, null); + const assignHook = this.hooks.assign.get(expression.left.name); + if (assignHook === undefined || !assignHook.call(expression)) { + this.walkExpression(expression.left); } + return; } - const obj = { - errors: jsons.reduce((arr, j) => { - return arr.concat( - j.errors.map(msg => { - return `(${j.name}) ${msg}`; - }) - ); - }, []), - warnings: jsons.reduce((arr, j) => { - return arr.concat( - j.warnings.map(msg => { - return `(${j.name}) ${msg}`; - }) - ); - }, []) - }; - if (showVersion) obj.version = __webpack_require__(71618)/* .version */ .i8; - if (showHash) obj.hash = this.hash; - if (options.children !== false) obj.children = jsons; - return obj; + this.walkExpression(expression.right); + this.walkPattern(expression.left); + this.enterPattern(expression.left, (name, decl) => { + this.scope.renames.set(name, null); + }); } - toString(options) { - if (typeof options === "boolean" || typeof options === "string") { - options = Stats.presetToOptions(options); - } else if (!options) { - options = {}; + walkConditionalExpression(expression) { + const result = this.hooks.expressionConditionalOperator.call(expression); + if (result === undefined) { + this.walkExpression(expression.test); + this.walkExpression(expression.consequent); + if (expression.alternate) { + this.walkExpression(expression.alternate); + } + } else { + if (result) { + this.walkExpression(expression.consequent); + } else if (expression.alternate) { + this.walkExpression(expression.alternate); + } } + } - const useColors = optionOrFallback(options.colors, false); + walkNewExpression(expression) { + const callee = this.evaluateExpression(expression.callee); + if (callee.isIdentifier()) { + const hook = this.hooks.new.get(callee.identifier); + if (hook !== undefined) { + const result = hook.call(expression); + if (result === true) { + return; + } + } + } - const obj = this.toJson(options, true); + this.walkExpression(expression.callee); + if (expression.arguments) { + this.walkExpressions(expression.arguments); + } + } - return Stats.jsonToString(obj, useColors); + walkYieldExpression(expression) { + if (expression.argument) { + this.walkExpression(expression.argument); + } } -} -module.exports = MultiStats; + walkTemplateLiteral(expression) { + if (expression.expressions) { + this.walkExpressions(expression.expressions); + } + } + walkTaggedTemplateExpression(expression) { + if (expression.tag) { + this.walkExpression(expression.tag); + } + if (expression.quasi && expression.quasi.expressions) { + this.walkExpressions(expression.quasi.expressions); + } + } -/***/ }), + walkClassExpression(expression) { + this.walkClass(expression); + } -/***/ 66624: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + _walkIIFE(functionExpression, options, currentThis) { + const renameArgOrThis = argOrThis => { + const renameIdentifier = this.getRenameIdentifier(argOrThis); + if (renameIdentifier) { + const hook = this.hooks.canRename.get(renameIdentifier); + if (hook !== undefined && hook.call(argOrThis)) { + const hook = this.hooks.rename.get(renameIdentifier); + if (hook === undefined || !hook.call(argOrThis)) { + return renameIdentifier; + } + } + } + this.walkExpression(argOrThis); + }; + const params = functionExpression.params; + const renameThis = currentThis ? renameArgOrThis(currentThis) : null; + const args = options.map(renameArgOrThis); + const wasTopLevel = this.scope.topLevelScope; + this.scope.topLevelScope = false; + const scopeParams = params.filter((identifier, idx) => !args[idx]); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // Add function name in scope for recursive calls + if (functionExpression.id) { + scopeParams.push(functionExpression.id.name); + } + this.inFunctionScope(true, scopeParams, () => { + if (renameThis) { + this.scope.renames.set("this", renameThis); + } + for (let i = 0; i < args.length; i++) { + const param = args[i]; + if (!param) continue; + if (!params[i] || params[i].type !== "Identifier") continue; + this.scope.renames.set(params[i].name, param); + } + if (functionExpression.body.type === "BlockStatement") { + this.detectMode(functionExpression.body.body); + this.prewalkStatement(functionExpression.body); + this.walkStatement(functionExpression.body); + } else { + this.walkExpression(functionExpression.body); + } + }); + this.scope.topLevelScope = wasTopLevel; + } -const asyncLib = __webpack_require__(36386); + walkCallExpression(expression) { + if ( + expression.callee.type === "MemberExpression" && + expression.callee.object.type === "FunctionExpression" && + !expression.callee.computed && + (expression.callee.property.name === "call" || + expression.callee.property.name === "bind") && + expression.arguments.length > 0 + ) { + // (function(…) { }.call/bind(?, …)) + this._walkIIFE( + expression.callee.object, + expression.arguments.slice(1), + expression.arguments[0] + ); + } else if (expression.callee.type === "FunctionExpression") { + // (function(…) { }(…)) + this._walkIIFE(expression.callee, expression.arguments, null); + } else if (expression.callee.type === "Import") { + let result = this.hooks.importCall.call(expression); + if (result === true) return; -class MultiWatching { - constructor(watchings, compiler) { - this.watchings = watchings; - this.compiler = compiler; - } + if (expression.arguments) this.walkExpressions(expression.arguments); + } else { + const callee = this.evaluateExpression(expression.callee); + if (callee.isIdentifier()) { + const callHook = this.hooks.call.get(callee.identifier); + if (callHook !== undefined) { + let result = callHook.call(expression); + if (result === true) return; + } + let identifier = callee.identifier.replace(/\.[^.]+$/, ""); + if (identifier !== callee.identifier) { + const callAnyHook = this.hooks.callAnyMember.get(identifier); + if (callAnyHook !== undefined) { + let result = callAnyHook.call(expression); + if (result === true) return; + } + } + } - invalidate() { - for (const watching of this.watchings) { - watching.invalidate(); + if (expression.callee) this.walkExpression(expression.callee); + if (expression.arguments) this.walkExpressions(expression.arguments); } } - suspend() { - for (const watching of this.watchings) { - watching.suspend(); + walkMemberExpression(expression) { + const exprName = this.getNameForExpression(expression); + if (exprName && exprName.free) { + const expressionHook = this.hooks.expression.get(exprName.name); + if (expressionHook !== undefined) { + const result = expressionHook.call(expression); + if (result === true) return; + } + const expressionAnyMemberHook = this.hooks.expressionAnyMember.get( + exprName.nameGeneral + ); + if (expressionAnyMemberHook !== undefined) { + const result = expressionAnyMemberHook.call(expression); + if (result === true) return; + } } + this.walkExpression(expression.object); + if (expression.computed === true) this.walkExpression(expression.property); } - resume() { - for (const watching of this.watchings) { - watching.resume(); + walkThisExpression(expression) { + const expressionHook = this.hooks.expression.get("this"); + if (expressionHook !== undefined) { + expressionHook.call(expression); } } - close(callback) { - asyncLib.forEach( - this.watchings, - (watching, finishedCallback) => { - watching.close(finishedCallback); - }, - err => { - this.compiler.hooks.watchClose.call(); - if (typeof callback === "function") { - this.compiler.running = false; - callback(err); - } + walkIdentifier(expression) { + if (!this.scope.definitions.has(expression.name)) { + const hook = this.hooks.expression.get( + this.scope.renames.get(expression.name) || expression.name + ); + if (hook !== undefined) { + const result = hook.call(expression); + if (result === true) return; } - ); + } } -} - -module.exports = MultiWatching; - -/***/ }), + /** + * @deprecated + * @param {any} params scope params + * @param {function(): void} fn inner function + * @returns {void} + */ + inScope(params, fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: false, + inShorthand: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + definitions: oldScope.definitions.createChild(), + renames: oldScope.renames.createChild() + }; -/***/ 70419: -/***/ (function(module) { + this.scope.renames.set("this", null); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + this.enterPatterns(params, ident => { + this.scope.renames.set(ident, null); + this.scope.definitions.add(ident); + }); + fn(); -class NamedChunksPlugin { - static defaultNameResolver(chunk) { - return chunk.name || null; + this.scope = oldScope; } - constructor(nameResolver) { - this.nameResolver = nameResolver || NamedChunksPlugin.defaultNameResolver; - } + inFunctionScope(hasThis, params, fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: false, + inShorthand: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + definitions: oldScope.definitions.createChild(), + renames: oldScope.renames.createChild() + }; - apply(compiler) { - compiler.hooks.compilation.tap("NamedChunksPlugin", compilation => { - compilation.hooks.beforeChunkIds.tap("NamedChunksPlugin", chunks => { - for (const chunk of chunks) { - if (chunk.id === null) { - chunk.id = this.nameResolver(chunk); - } - } - }); + if (hasThis) { + this.scope.renames.set("this", null); + } + + this.enterPatterns(params, ident => { + this.scope.renames.set(ident, null); + this.scope.definitions.add(ident); }); + + fn(); + + this.scope = oldScope; } -} -module.exports = NamedChunksPlugin; + inBlockScope(fn) { + const oldScope = this.scope; + this.scope = { + topLevelScope: oldScope.topLevelScope, + inTry: oldScope.inTry, + inShorthand: false, + isStrict: oldScope.isStrict, + isAsmJs: oldScope.isAsmJs, + definitions: oldScope.definitions.createChild(), + renames: oldScope.renames.createChild() + }; + fn(); -/***/ }), + this.scope = oldScope; + } -/***/ 86707: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // TODO webpack 5: remove this methods + // only for backward-compat + detectStrictMode(statements) { + this.detectMode(statements); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + detectMode(statements) { + const isLiteral = + statements.length >= 1 && + statements[0].type === "ExpressionStatement" && + statements[0].expression.type === "Literal"; + if (isLiteral && statements[0].expression.value === "use strict") { + this.scope.isStrict = true; + } + if (isLiteral && statements[0].expression.value === "use asm") { + this.scope.isAsmJs = true; + } + } + enterPatterns(patterns, onIdent) { + for (const pattern of patterns) { + if (typeof pattern !== "string") { + this.enterPattern(pattern, onIdent); + } else if (pattern) { + onIdent(pattern); + } + } + } -const createHash = __webpack_require__(15660); -const RequestShortener = __webpack_require__(54254); + enterPattern(pattern, onIdent) { + if (!pattern) return; + switch (pattern.type) { + case "ArrayPattern": + this.enterArrayPattern(pattern, onIdent); + break; + case "AssignmentPattern": + this.enterAssignmentPattern(pattern, onIdent); + break; + case "Identifier": + this.enterIdentifier(pattern, onIdent); + break; + case "ObjectPattern": + this.enterObjectPattern(pattern, onIdent); + break; + case "RestElement": + this.enterRestElement(pattern, onIdent); + break; + case "Property": + this.enterPattern(pattern.value, onIdent); + break; + } + } -const getHash = str => { - const hash = createHash("md4"); - hash.update(str); - const digest = /** @type {string} */ (hash.digest("hex")); - return digest.substr(0, 4); -}; + enterIdentifier(pattern, onIdent) { + onIdent(pattern.name, pattern); + } -class NamedModulesPlugin { - constructor(options) { - this.options = options || {}; + enterObjectPattern(pattern, onIdent) { + for ( + let propIndex = 0, len = pattern.properties.length; + propIndex < len; + propIndex++ + ) { + const prop = pattern.properties[propIndex]; + this.enterPattern(prop, onIdent); + } } - apply(compiler) { - compiler.hooks.compilation.tap("NamedModulesPlugin", compilation => { - compilation.hooks.beforeModuleIds.tap("NamedModulesPlugin", modules => { - const namedModules = new Map(); - const context = this.options.context || compiler.options.context; + enterArrayPattern(pattern, onIdent) { + for ( + let elementIndex = 0, len = pattern.elements.length; + elementIndex < len; + elementIndex++ + ) { + const element = pattern.elements[elementIndex]; + this.enterPattern(element, onIdent); + } + } - for (const module of modules) { - if (module.id === null && module.libIdent) { - module.id = module.libIdent({ context }); - } + enterRestElement(pattern, onIdent) { + this.enterPattern(pattern.argument, onIdent); + } - if (module.id !== null) { - const namedModule = namedModules.get(module.id); - if (namedModule !== undefined) { - namedModule.push(module); - } else { - namedModules.set(module.id, [module]); - } + enterAssignmentPattern(pattern, onIdent) { + this.enterPattern(pattern.left, onIdent); + } + + evaluateExpression(expression) { + try { + const hook = this.hooks.evaluate.get(expression.type); + if (hook !== undefined) { + const result = hook.call(expression); + if (result !== undefined) { + if (result) { + result.setExpression(expression); } + return result; + } + } + } catch (e) { + console.warn(e); + // ignore error + } + return new BasicEvaluatedExpression() + .setRange(expression.range) + .setExpression(expression); + } + + parseString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + return ( + this.parseString(expression.left) + + this.parseString(expression.right) + ); } + break; + case "Literal": + return expression.value + ""; + } + throw new Error( + expression.type + " is not supported as parameter for require" + ); + } - for (const namedModule of namedModules.values()) { - if (namedModule.length > 1) { - for (const module of namedModule) { - const requestShortener = new RequestShortener(context); - module.id = `${module.id}?${getHash( - requestShortener.shorten(module.identifier()) - )}`; - } + parseCalculatedString(expression) { + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + const left = this.parseCalculatedString(expression.left); + const right = this.parseCalculatedString(expression.right); + if (left.code) { + return { + range: left.range, + value: left.value, + code: true, + conditional: false + }; + } else if (right.code) { + return { + range: [ + left.range[0], + right.range ? right.range[1] : left.range[1] + ], + value: left.value + right.value, + code: true, + conditional: false + }; + } else { + return { + range: [left.range[0], right.range[1]], + value: left.value + right.value, + code: false, + conditional: false + }; } } + break; + case "ConditionalExpression": { + const consequent = this.parseCalculatedString(expression.consequent); + const alternate = this.parseCalculatedString(expression.alternate); + const items = []; + if (consequent.conditional) { + items.push(...consequent.conditional); + } else if (!consequent.code) { + items.push(consequent); + } else { + break; + } + if (alternate.conditional) { + items.push(...alternate.conditional); + } else if (!alternate.code) { + items.push(alternate); + } else { + break; + } + return { + range: undefined, + value: "", + code: true, + conditional: items + }; + } + case "Literal": + return { + range: expression.range, + value: expression.value + "", + code: false, + conditional: false + }; + } + return { + range: undefined, + value: "", + code: true, + conditional: false + }; + } + + parse(source, initialState) { + let ast; + let comments; + if (typeof source === "object" && source !== null) { + ast = source; + comments = source.comments; + } else { + comments = []; + ast = Parser.parse(source, { + sourceType: this.sourceType, + onComment: comments }); + } + + const oldScope = this.scope; + const oldState = this.state; + const oldComments = this.comments; + this.scope = { + topLevelScope: true, + inTry: false, + inShorthand: false, + isStrict: false, + isAsmJs: false, + definitions: new StackedSetMap(), + renames: new StackedSetMap() + }; + const state = (this.state = initialState || {}); + this.comments = comments; + if (this.hooks.program.call(ast, comments) === undefined) { + this.detectMode(ast.body); + this.prewalkStatements(ast.body); + this.blockPrewalkStatements(ast.body); + this.walkStatements(ast.body); + } + this.scope = oldScope; + this.state = oldState; + this.comments = oldComments; + return state; + } + + evaluate(source) { + const ast = Parser.parse("(" + source + ")", { + sourceType: this.sourceType, + locations: false }); + // TODO(https://github.com/acornjs/acorn/issues/741) + // @ts-ignore + if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { + throw new Error("evaluate: Source is not a expression"); + } + // TODO(https://github.com/acornjs/acorn/issues/741) + // @ts-ignore + return this.evaluateExpression(ast.body[0].expression); } -} -module.exports = NamedModulesPlugin; + getComments(range) { + return this.comments.filter( + comment => comment.range[0] >= range[0] && comment.range[1] <= range[1] + ); + } + parseCommentOptions(range) { + const comments = this.getComments(range); + if (comments.length === 0) { + return EMPTY_COMMENT_OPTIONS; + } + let options = {}; + let errors = []; + for (const comment of comments) { + const { value } = comment; + if (value && webpackCommentRegExp.test(value)) { + // try compile only if webpack options comment is present + try { + const val = vm.runInNewContext(`(function(){return {${value}};})()`); + Object.assign(options, val); + } catch (e) { + e.comment = comment; + errors.push(e); + } + } + } + return { options, errors }; + } -/***/ }), + getNameForExpression(expression) { + let expr = expression; + const exprName = []; + while ( + expr.type === "MemberExpression" && + expr.property.type === (expr.computed ? "Literal" : "Identifier") + ) { + exprName.push(expr.computed ? expr.property.value : expr.property.name); + expr = expr.object; + } + let free; + if (expr.type === "Identifier") { + free = !this.scope.definitions.has(expr.name); + exprName.push(this.scope.renames.get(expr.name) || expr.name); + } else if ( + expr.type === "ThisExpression" && + this.scope.renames.get("this") + ) { + free = true; + exprName.push(this.scope.renames.get("this")); + } else if (expr.type === "ThisExpression") { + free = this.scope.topLevelScope; + exprName.push("this"); + } else { + return null; + } + let prefix = ""; + for (let i = exprName.length - 1; i >= 2; i--) { + prefix += exprName[i] + "."; + } + if (exprName.length > 1) { + prefix += exprName[1]; + } + const name = prefix ? prefix + "." + exprName[0] : exprName[0]; + const nameGeneral = prefix; + return { + name, + nameGeneral, + free + }; + } -/***/ 22615: -/***/ (function(module) { + static parse(code, options) { + const type = options ? options.sourceType : "module"; + const parserOptions = Object.assign( + Object.create(null), + defaultParserOptions, + options + ); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (type === "auto") { + parserOptions.sourceType = "module"; + } else if (parserOptions.sourceType === "script") { + parserOptions.allowReturnOutsideFunction = true; + } + let ast; + let error; + let threw = false; + try { + ast = acornParser.parse(code, parserOptions); + } catch (e) { + error = e; + threw = true; + } -class NoEmitOnErrorsPlugin { - apply(compiler) { - compiler.hooks.shouldEmit.tap("NoEmitOnErrorsPlugin", compilation => { - if (compilation.getStats().hasErrors()) return false; - }); - compiler.hooks.compilation.tap("NoEmitOnErrorsPlugin", compilation => { - compilation.hooks.shouldRecord.tap("NoEmitOnErrorsPlugin", () => { - if (compilation.getStats().hasErrors()) return false; - }); - }); + if (threw && type === "auto") { + parserOptions.sourceType = "script"; + parserOptions.allowReturnOutsideFunction = true; + if (Array.isArray(parserOptions.onComment)) { + parserOptions.onComment.length = 0; + } + try { + ast = acornParser.parse(code, parserOptions); + threw = false; + } catch (e) { + threw = true; + } + } + + if (threw) { + throw error; + } + + return ast; } } -module.exports = NoEmitOnErrorsPlugin; +// TODO remove in webpack 5 +Object.defineProperty(Parser.prototype, "getCommentOptions", { + configurable: false, + value: util.deprecate( + /** + * @deprecated + * @param {TODO} range Range + * @returns {void} + * @this {Parser} + */ + function(range) { + return this.parseCommentOptions(range).options; + }, + "Parser.getCommentOptions: Use Parser.parseCommentOptions(range) instead" + ) +}); + +module.exports = Parser; /***/ }), -/***/ 45759: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 23999: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -84577,29 +84821,109 @@ module.exports = NoEmitOnErrorsPlugin; Author Tobias Koppers @sokra */ +const path = __webpack_require__(85622); -const WebpackError = __webpack_require__(97391); +const BasicEvaluatedExpression = __webpack_require__(96770); +const ConstDependency = __webpack_require__(71101); +const UnsupportedFeatureWarning = __webpack_require__(99953); -module.exports = class NoModeWarning extends WebpackError { - constructor(modules) { - super(); +const ParserHelpers = exports; - this.name = "NoModeWarning"; - this.message = - "configuration\n" + - "The 'mode' option has not been set, webpack will fallback to 'production' for this value. " + - "Set 'mode' option to 'development' or 'production' to enable defaults for each environment.\n" + - "You can also set it to 'none' to disable any default behavior. " + - "Learn more: https://webpack.js.org/configuration/mode/"; +ParserHelpers.addParsedVariableToModule = (parser, name, expression) => { + if (!parser.state.current.addVariable) return false; + var deps = []; + parser.parse(expression, { + current: { + addDependency: dep => { + dep.userRequest = name; + deps.push(dep); + } + }, + module: parser.state.module + }); + parser.state.current.addVariable(name, expression, deps); + return true; +}; - Error.captureStackTrace(this, this.constructor); +ParserHelpers.requireFileAsExpression = (context, pathToModule) => { + var moduleJsPath = path.relative(context, pathToModule); + if (!/^[A-Z]:/i.test(moduleJsPath)) { + moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/"); } + return "require(" + JSON.stringify(moduleJsPath) + ")"; }; +ParserHelpers.toConstantDependency = (parser, value) => { + return function constDependency(expr) { + var dep = new ConstDependency(value, expr.range, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }; +}; -/***/ }), - -/***/ 28386: +ParserHelpers.toConstantDependencyWithWebpackRequire = (parser, value) => { + return function constDependencyWithWebpackRequire(expr) { + var dep = new ConstDependency(value, expr.range, true); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }; +}; + +ParserHelpers.evaluateToString = value => { + return function stringExpression(expr) { + return new BasicEvaluatedExpression().setString(value).setRange(expr.range); + }; +}; + +ParserHelpers.evaluateToBoolean = value => { + return function booleanExpression(expr) { + return new BasicEvaluatedExpression() + .setBoolean(value) + .setRange(expr.range); + }; +}; + +ParserHelpers.evaluateToIdentifier = (identifier, truthy) => { + return function identifierExpression(expr) { + let evex = new BasicEvaluatedExpression() + .setIdentifier(identifier) + .setRange(expr.range); + if (truthy === true) { + evex = evex.setTruthy(); + } else if (truthy === false) { + evex = evex.setFalsy(); + } + return evex; + }; +}; + +ParserHelpers.expressionIsUnsupported = (parser, message) => { + return function unsupportedExpression(expr) { + var dep = new ConstDependency("(void 0)", expr.range, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + if (!parser.state.module) return; + parser.state.module.warnings.push( + new UnsupportedFeatureWarning(parser.state.module, message, expr.loc) + ); + return true; + }; +}; + +ParserHelpers.skipTraversal = function skipTraversal() { + return true; +}; + +ParserHelpers.approve = function approve() { + return true; +}; + + +/***/ }), + +/***/ 27850: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -84608,124 +84932,43 @@ module.exports = class NoModeWarning extends WebpackError { Author Tobias Koppers @sokra */ +const PrefetchDependency = __webpack_require__(14237); -const path = __webpack_require__(85622); -const ParserHelpers = __webpack_require__(23999); -const ConstDependency = __webpack_require__(71101); - -const NullFactory = __webpack_require__(40438); - -class NodeStuffPlugin { - constructor(options) { - this.options = options; +class PrefetchPlugin { + constructor(context, request) { + if (!request) { + this.request = context; + } else { + this.context = context; + this.request = request; + } } apply(compiler) { - const options = this.options; compiler.hooks.compilation.tap( - "NodeStuffPlugin", + "PrefetchPlugin", (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set(ConstDependency, new NullFactory()); - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() + compilation.dependencyFactories.set( + PrefetchDependency, + normalModuleFactory ); - - const handler = (parser, parserOptions) => { - if (parserOptions.node === false) return; - - let localOptions = options; - if (parserOptions.node) { - localOptions = Object.assign({}, localOptions, parserOptions.node); - } - - const setConstant = (expressionName, value) => { - parser.hooks.expression - .for(expressionName) - .tap("NodeStuffPlugin", () => { - parser.state.current.addVariable( - expressionName, - JSON.stringify(value) - ); - return true; - }); - }; - - const setModuleConstant = (expressionName, fn) => { - parser.hooks.expression - .for(expressionName) - .tap("NodeStuffPlugin", () => { - parser.state.current.addVariable( - expressionName, - JSON.stringify(fn(parser.state.module)) - ); - return true; - }); - }; - const context = compiler.context; - if (localOptions.__filename) { - if (localOptions.__filename === "mock") { - setConstant("__filename", "/index.js"); - } else { - setModuleConstant("__filename", module => - path.relative(context, module.resource) - ); - } - parser.hooks.evaluateIdentifier - .for("__filename") - .tap("NodeStuffPlugin", expr => { - if (!parser.state.module) return; - const resource = parser.state.module.resource; - const i = resource.indexOf("?"); - return ParserHelpers.evaluateToString( - i < 0 ? resource : resource.substr(0, i) - )(expr); - }); - } - if (localOptions.__dirname) { - if (localOptions.__dirname === "mock") { - setConstant("__dirname", "/"); - } else { - setModuleConstant("__dirname", module => - path.relative(context, module.context) - ); - } - parser.hooks.evaluateIdentifier - .for("__dirname") - .tap("NodeStuffPlugin", expr => { - if (!parser.state.module) return; - return ParserHelpers.evaluateToString( - parser.state.module.context - )(expr); - }); - } - parser.hooks.expression - .for("require.extensions") - .tap( - "NodeStuffPlugin", - ParserHelpers.expressionIsUnsupported( - parser, - "require.extensions is not supported by webpack. Use a loader instead." - ) - ); - }; - - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("NodeStuffPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("NodeStuffPlugin", handler); } ); + compiler.hooks.make.tapAsync("PrefetchPlugin", (compilation, callback) => { + compilation.prefetch( + this.context || compiler.context, + new PrefetchDependency(this.request), + callback + ); + }); } } -module.exports = NodeStuffPlugin; +module.exports = PrefetchPlugin; /***/ }), -/***/ 25963: +/***/ 63123: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -84735,1123 +84978,824 @@ module.exports = NodeStuffPlugin; */ -const NativeModule = __webpack_require__(32282); - -const { - CachedSource, - LineToLineMappedSource, - OriginalSource, - RawSource, - SourceMapSource -} = __webpack_require__(53665); -const { getContext, runLoaders } = __webpack_require__(73278); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(26336); -const WebpackError = __webpack_require__(97391); -const Module = __webpack_require__(75993); -const ModuleParseError = __webpack_require__(62500); -const ModuleBuildError = __webpack_require__(12072); -const ModuleError = __webpack_require__(82528); -const ModuleWarning = __webpack_require__(6372); -const createHash = __webpack_require__(15660); -const contextify = __webpack_require__(94658).contextify; +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ +/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */ -/** @typedef {import("./util/createHash").Hash} Hash */ +const createDefaultHandler = (profile, logger) => { + let lastState; + let lastStateTime; -const asString = buf => { - if (Buffer.isBuffer(buf)) { - return buf.toString("utf-8"); - } - return buf; -}; + const defaultHandler = (percentage, msg, ...args) => { + logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args); + if (profile) { + let state = msg; + state = state.replace(/^\d+\/\d+\s+/, ""); + if (percentage === 0) { + lastState = null; + lastStateTime = Date.now(); + } else if (state !== lastState || percentage === 1) { + const now = Date.now(); + if (lastState) { + const diff = now - lastStateTime; + const stateMsg = `${diff}ms ${lastState}`; + if (diff > 1000) { + logger.warn(stateMsg); + } else if (diff > 10) { + logger.info(stateMsg); + } else if (diff > 0) { + logger.log(stateMsg); + } else { + logger.debug(stateMsg); + } + } + lastState = state; + lastStateTime = now; + } + } + if (percentage === 1) logger.status(); + }; -const asBuffer = str => { - if (!Buffer.isBuffer(str)) { - return Buffer.from(str, "utf-8"); - } - return str; + return defaultHandler; }; -class NonErrorEmittedError extends WebpackError { - constructor(error) { - super(); +class ProgressPlugin { + /** + * @param {ProgressPluginArgument} options options + */ + constructor(options) { + if (typeof options === "function") { + options = { + handler: options + }; + } - this.name = "NonErrorEmittedError"; - this.message = "(Emitted value instead of an instance of Error) " + error; + options = options || {}; + validateOptions(schema, options, "Progress Plugin"); + options = Object.assign({}, ProgressPlugin.defaultOptions, options); - Error.captureStackTrace(this, this.constructor); + this.profile = options.profile; + this.handler = options.handler; + this.modulesCount = options.modulesCount; + this.showEntries = options.entries; + this.showModules = options.modules; + this.showActiveModules = options.activeModules; } -} - -/** - * @typedef {Object} CachedSourceEntry - * @property {TODO} source the generated source - * @property {string} hash the hash value - */ - -class NormalModule extends Module { - constructor({ - type, - request, - userRequest, - rawRequest, - loaders, - resource, - matchResource, - parser, - generator, - resolveOptions - }) { - super(type, getContext(resource)); - - // Info from Factory - this.request = request; - this.userRequest = userRequest; - this.rawRequest = rawRequest; - this.binary = type.startsWith("webassembly"); - this.parser = parser; - this.generator = generator; - this.resource = resource; - this.matchResource = matchResource; - this.loaders = loaders; - if (resolveOptions !== undefined) this.resolveOptions = resolveOptions; - - // Info from Build - this.error = null; - this._source = null; - this._sourceSize = null; - this._buildHash = ""; - this.buildTimestamp = undefined; - /** @private @type {Map} */ - this._cachedSources = new Map(); - // Options for the NormalModule set by plugins - // TODO refactor this -> options object filled from Factory - this.useSourceMap = false; - this.lineToLine = false; + apply(compiler) { + const { modulesCount } = this; + const handler = + this.handler || + createDefaultHandler( + this.profile, + compiler.getInfrastructureLogger("webpack.Progress") + ); + const showEntries = this.showEntries; + const showModules = this.showModules; + const showActiveModules = this.showActiveModules; + if (compiler.compilers) { + const states = new Array(compiler.compilers.length); + compiler.compilers.forEach((compiler, idx) => { + new ProgressPlugin((p, msg, ...args) => { + states[idx] = [p, msg, ...args]; + handler( + states + .map(state => (state && state[0]) || 0) + .reduce((a, b) => a + b) / states.length, + `[${idx}] ${msg}`, + ...args + ); + }).apply(compiler); + }); + } else { + let lastModulesCount = 0; + let lastEntriesCount = 0; + let moduleCount = modulesCount; + let entriesCount = 1; + let doneModules = 0; + let doneEntries = 0; + const activeModules = new Set(); + let lastActiveModule = ""; - // Cache - this._lastSuccessfulBuildMeta = {}; - } + const update = () => { + const percentByModules = + doneModules / Math.max(lastModulesCount, moduleCount); + const percentByEntries = + doneEntries / Math.max(lastEntriesCount, entriesCount); - identifier() { - return this.request; - } + const items = [ + 0.1 + Math.max(percentByModules, percentByEntries) * 0.6, + "building" + ]; + if (showEntries) { + items.push(`${doneEntries}/${entriesCount} entries`); + } + if (showModules) { + items.push(`${doneModules}/${moduleCount} modules`); + } + if (showActiveModules) { + items.push(`${activeModules.size} active`); + items.push(lastActiveModule); + } + handler(...items); + }; - readableIdentifier(requestShortener) { - return requestShortener.shorten(this.userRequest); - } + const moduleAdd = module => { + moduleCount++; + if (showActiveModules) { + const ident = module.identifier(); + if (ident) { + activeModules.add(ident); + lastActiveModule = ident; + } + } + update(); + }; - libIdent(options) { - return contextify(options.context, this.userRequest); - } + const entryAdd = (entry, name) => { + entriesCount++; + update(); + }; - nameForCondition() { - const resource = this.matchResource || this.resource; - const idx = resource.indexOf("?"); - if (idx >= 0) return resource.substr(0, idx); - return resource; - } + const moduleDone = module => { + doneModules++; + if (showActiveModules) { + const ident = module.identifier(); + if (ident) { + activeModules.delete(ident); + if (lastActiveModule === ident) { + lastActiveModule = ""; + for (const m of activeModules) { + lastActiveModule = m; + } + } + } + } + update(); + }; - updateCacheModule(module) { - this.type = module.type; - this.request = module.request; - this.userRequest = module.userRequest; - this.rawRequest = module.rawRequest; - this.parser = module.parser; - this.generator = module.generator; - this.resource = module.resource; - this.matchResource = module.matchResource; - this.loaders = module.loaders; - this.resolveOptions = module.resolveOptions; - } + const entryDone = (entry, name) => { + doneEntries++; + update(); + }; - createSourceForAsset(name, content, sourceMap) { - if (!sourceMap) { - return new RawSource(content); - } + compiler.hooks.compilation.tap("ProgressPlugin", compilation => { + if (compilation.compiler.isChild()) return; + lastModulesCount = moduleCount; + lastEntriesCount = entriesCount; + moduleCount = entriesCount = 0; + doneModules = doneEntries = 0; + handler(0, "compiling"); - if (typeof sourceMap === "string") { - return new OriginalSource(content, sourceMap); - } + compilation.hooks.buildModule.tap("ProgressPlugin", moduleAdd); + compilation.hooks.failedModule.tap("ProgressPlugin", moduleDone); + compilation.hooks.succeedModule.tap("ProgressPlugin", moduleDone); - return new SourceMapSource(content, name, sourceMap); - } + compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd); + compilation.hooks.failedEntry.tap("ProgressPlugin", entryDone); + compilation.hooks.succeedEntry.tap("ProgressPlugin", entryDone); - createLoaderContext(resolver, options, compilation, fs) { - const requestShortener = compilation.runtimeTemplate.requestShortener; - const getCurrentLoaderName = () => { - const currentLoader = this.getCurrentLoader(loaderContext); - if (!currentLoader) return "(not in loader scope)"; - return requestShortener.shorten(currentLoader.loader); - }; - const loaderContext = { - version: 2, - emitWarning: warning => { - if (!(warning instanceof Error)) { - warning = new NonErrorEmittedError(warning); - } - this.warnings.push( - new ModuleWarning(this, warning, { - from: getCurrentLoaderName() - }) - ); - }, - emitError: error => { - if (!(error instanceof Error)) { - error = new NonErrorEmittedError(error); - } - this.errors.push( - new ModuleError(this, error, { - from: getCurrentLoaderName() - }) - ); - }, - getLogger: name => { - const currentLoader = this.getCurrentLoader(loaderContext); - return compilation.getLogger(() => - [currentLoader && currentLoader.loader, name, this.identifier()] - .filter(Boolean) - .join("|") - ); - }, - // TODO remove in webpack 5 - exec: (code, filename) => { - // @ts-ignore Argument of type 'this' is not assignable to parameter of type 'Module'. - const module = new NativeModule(filename, this); - // @ts-ignore _nodeModulePaths is deprecated and undocumented Node.js API - module.paths = NativeModule._nodeModulePaths(this.context); - module.filename = filename; - module._compile(code, filename); - return module.exports; - }, - resolve(context, request, callback) { - resolver.resolve({}, context, request, {}, callback); - }, - getResolve(options) { - const child = options ? resolver.withOptions(options) : resolver; - return (context, request, callback) => { - if (callback) { - child.resolve({}, context, request, {}, callback); - } else { - return new Promise((resolve, reject) => { - child.resolve({}, context, request, {}, (err, result) => { - if (err) reject(err); - else resolve(result); - }); - }); - } + const hooks = { + finishModules: "finish module graph", + seal: "sealing", + beforeChunks: "chunk graph", + afterChunks: "after chunk graph", + optimizeDependenciesBasic: "basic dependencies optimization", + optimizeDependencies: "dependencies optimization", + optimizeDependenciesAdvanced: "advanced dependencies optimization", + afterOptimizeDependencies: "after dependencies optimization", + optimize: "optimizing", + optimizeModulesBasic: "basic module optimization", + optimizeModules: "module optimization", + optimizeModulesAdvanced: "advanced module optimization", + afterOptimizeModules: "after module optimization", + optimizeChunksBasic: "basic chunk optimization", + optimizeChunks: "chunk optimization", + optimizeChunksAdvanced: "advanced chunk optimization", + afterOptimizeChunks: "after chunk optimization", + optimizeTree: "module and chunk tree optimization", + afterOptimizeTree: "after module and chunk tree optimization", + optimizeChunkModulesBasic: "basic chunk modules optimization", + optimizeChunkModules: "chunk modules optimization", + optimizeChunkModulesAdvanced: "advanced chunk modules optimization", + afterOptimizeChunkModules: "after chunk modules optimization", + reviveModules: "module reviving", + optimizeModuleOrder: "module order optimization", + advancedOptimizeModuleOrder: "advanced module order optimization", + beforeModuleIds: "before module ids", + moduleIds: "module ids", + optimizeModuleIds: "module id optimization", + afterOptimizeModuleIds: "module id optimization", + reviveChunks: "chunk reviving", + optimizeChunkOrder: "chunk order optimization", + beforeChunkIds: "before chunk ids", + optimizeChunkIds: "chunk id optimization", + afterOptimizeChunkIds: "after chunk id optimization", + recordModules: "record modules", + recordChunks: "record chunks", + beforeHash: "hashing", + afterHash: "after hashing", + recordHash: "record hash", + beforeModuleAssets: "module assets processing", + beforeChunkAssets: "chunk assets processing", + additionalChunkAssets: "additional chunk assets processing", + record: "recording", + additionalAssets: "additional asset processing", + optimizeChunkAssets: "chunk asset optimization", + afterOptimizeChunkAssets: "after chunk asset optimization", + optimizeAssets: "asset optimization", + afterOptimizeAssets: "after asset optimization", + afterSeal: "after seal" }; - }, - emitFile: (name, content, sourceMap, assetInfo) => { - if (!this.buildInfo.assets) { - this.buildInfo.assets = Object.create(null); - this.buildInfo.assetsInfo = new Map(); + const numberOfHooks = Object.keys(hooks).length; + Object.keys(hooks).forEach((name, idx) => { + const title = hooks[name]; + const percentage = (idx / numberOfHooks) * 0.25 + 0.7; + compilation.hooks[name].intercept({ + name: "ProgressPlugin", + context: true, + call: () => { + handler(percentage, title); + }, + tap: (context, tap) => { + if (context) { + // p is percentage from 0 to 1 + // args is any number of messages in a hierarchical matter + context.reportProgress = (p, ...args) => { + handler(percentage, title, tap.name, ...args); + }; + } + handler(percentage, title, tap.name); + } + }); + }); + }); + compiler.hooks.emit.intercept({ + name: "ProgressPlugin", + context: true, + call: () => { + handler(0.95, "emitting"); + }, + tap: (context, tap) => { + if (context) { + context.reportProgress = (p, ...args) => { + handler(0.95, "emitting", tap.name, ...args); + }; + } + handler(0.95, "emitting", tap.name); } - this.buildInfo.assets[name] = this.createSourceForAsset( - name, - content, - sourceMap - ); - this.buildInfo.assetsInfo.set(name, assetInfo); - }, - rootContext: options.context, - webpack: true, - sourceMap: !!this.useSourceMap, - mode: options.mode || "production", - _module: this, - _compilation: compilation, - _compiler: compilation.compiler, - fs: fs - }; - - compilation.hooks.normalModuleLoader.call(loaderContext, this); - if (options.loader) { - Object.assign(loaderContext, options.loader); - } - - return loaderContext; - } - - getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) { - if ( - this.loaders && - this.loaders.length && - index < this.loaders.length && - index >= 0 && - this.loaders[index] - ) { - return this.loaders[index]; + }); + compiler.hooks.afterEmit.intercept({ + name: "ProgressPlugin", + context: true, + call: () => { + handler(0.98, "after emitting"); + }, + tap: (context, tap) => { + if (context) { + context.reportProgress = (p, ...args) => { + handler(0.98, "after emitting", tap.name, ...args); + }; + } + handler(0.98, "after emitting", tap.name); + } + }); + compiler.hooks.done.tap("ProgressPlugin", () => { + handler(1, ""); + }); } - return null; } +} - createSource(source, resourceBuffer, sourceMap) { - // if there is no identifier return raw source - if (!this.identifier) { - return new RawSource(source); - } - - // from here on we assume we have an identifier - const identifier = this.identifier(); +ProgressPlugin.defaultOptions = { + profile: false, + modulesCount: 500, + modules: true, + activeModules: true, + // TODO webpack 5 default this to true + entries: false +}; - if (this.lineToLine && resourceBuffer) { - return new LineToLineMappedSource( - source, - identifier, - asString(resourceBuffer) - ); - } +module.exports = ProgressPlugin; - if (this.useSourceMap && sourceMap) { - return new SourceMapSource(source, identifier, sourceMap); - } - if (Buffer.isBuffer(source)) { - // @ts-ignore - // TODO We need to fix @types/webpack-sources to allow RawSource to take a Buffer | string - return new RawSource(source); - } +/***/ }), - return new OriginalSource(source, identifier); - } +/***/ 72861: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - doBuild(options, compilation, resolver, fs, callback) { - const loaderContext = this.createLoaderContext( - resolver, - options, - compilation, - fs - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - runLoaders( - { - resource: this.resource, - loaders: this.loaders, - context: loaderContext, - readResource: fs.readFile.bind(fs) - }, - (err, result) => { - if (result) { - this.buildInfo.cacheable = result.cacheable; - this.buildInfo.fileDependencies = new Set(result.fileDependencies); - this.buildInfo.contextDependencies = new Set( - result.contextDependencies - ); - } - if (err) { - if (!(err instanceof Error)) { - err = new NonErrorEmittedError(err); - } - const currentLoader = this.getCurrentLoader(loaderContext); - const error = new ModuleBuildError(this, err, { - from: - currentLoader && - compilation.runtimeTemplate.requestShortener.shorten( - currentLoader.loader - ) - }); - return callback(error); - } +const ParserHelpers = __webpack_require__(23999); +const ConstDependency = __webpack_require__(71101); - const resourceBuffer = result.resourceBuffer; - const source = result.result[0]; - const sourceMap = result.result.length >= 1 ? result.result[1] : null; - const extraInfo = result.result.length >= 2 ? result.result[2] : null; +const NullFactory = __webpack_require__(40438); - if (!Buffer.isBuffer(source) && typeof source !== "string") { - const currentLoader = this.getCurrentLoader(loaderContext, 0); - const err = new Error( - `Final loader (${ - currentLoader - ? compilation.runtimeTemplate.requestShortener.shorten( - currentLoader.loader - ) - : "unknown" - }) didn't return a Buffer or String` - ); - const error = new ModuleBuildError(this, err); - return callback(error); - } +class ProvidePlugin { + constructor(definitions) { + this.definitions = definitions; + } - this._source = this.createSource( - this.binary ? asBuffer(source) : asString(source), - resourceBuffer, - sourceMap + apply(compiler) { + const definitions = this.definitions; + compiler.hooks.compilation.tap( + "ProvidePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() ); - this._sourceSize = null; - this._ast = - typeof extraInfo === "object" && - extraInfo !== null && - extraInfo.webpackAST !== undefined - ? extraInfo.webpackAST - : null; - return callback(); + const handler = (parser, parserOptions) => { + Object.keys(definitions).forEach(name => { + var request = [].concat(definitions[name]); + var splittedName = name.split("."); + if (splittedName.length > 0) { + splittedName.slice(1).forEach((_, i) => { + const name = splittedName.slice(0, i + 1).join("."); + parser.hooks.canRename + .for(name) + .tap("ProvidePlugin", ParserHelpers.approve); + }); + } + parser.hooks.expression.for(name).tap("ProvidePlugin", expr => { + let nameIdentifier = name; + const scopedName = name.includes("."); + let expression = `require(${JSON.stringify(request[0])})`; + if (scopedName) { + nameIdentifier = `__webpack_provided_${name.replace( + /\./g, + "_dot_" + )}`; + } + if (request.length > 1) { + expression += request + .slice(1) + .map(r => `[${JSON.stringify(r)}]`) + .join(""); + } + if ( + !ParserHelpers.addParsedVariableToModule( + parser, + nameIdentifier, + expression + ) + ) { + return false; + } + if (scopedName) { + ParserHelpers.toConstantDependency( + parser, + nameIdentifier + )(expr); + } + return true; + }); + }); + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ProvidePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ProvidePlugin", handler); + + // Disable ProvidePlugin for javascript/esm, see https://github.com/webpack/webpack/issues/7032 } ); } +} +module.exports = ProvidePlugin; - markModuleAsErrored(error) { - // Restore build meta from successful build to keep importing state - this.buildMeta = Object.assign({}, this._lastSuccessfulBuildMeta); - this.error = error; - this.errors.push(this.error); - this._source = new RawSource( - "throw new Error(" + JSON.stringify(this.error.message) + ");" - ); - this._sourceSize = null; - this._ast = null; - } - applyNoParseRule(rule, content) { - // must start with "rule" if rule is a string - if (typeof rule === "string") { - return content.indexOf(rule) === 0; - } +/***/ }), - if (typeof rule === "function") { - return rule(content); - } - // we assume rule is a regexp - return rule.test(content); +/***/ 82353: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Module = __webpack_require__(75993); +const { OriginalSource, RawSource } = __webpack_require__(53665); + +module.exports = class RawModule extends Module { + constructor(source, identifier, readableIdentifier) { + super("javascript/dynamic", null); + this.sourceStr = source; + this.identifierStr = identifier || this.sourceStr; + this.readableIdentifierStr = readableIdentifier || this.identifierStr; + this.built = false; } - // check if module should not be parsed - // returns "true" if the module should !not! be parsed - // returns "false" if the module !must! be parsed - shouldPreventParsing(noParseRule, request) { - // if no noParseRule exists, return false - // the module !must! be parsed. - if (!noParseRule) { - return false; - } + identifier() { + return this.identifierStr; + } - // we only have one rule to check - if (!Array.isArray(noParseRule)) { - // returns "true" if the module is !not! to be parsed - return this.applyNoParseRule(noParseRule, request); - } + size() { + return this.sourceStr.length; + } - for (let i = 0; i < noParseRule.length; i++) { - const rule = noParseRule[i]; - // early exit on first truthy match - // this module is !not! to be parsed - if (this.applyNoParseRule(rule, request)) { - return true; - } - } - // no match found, so this module !should! be parsed - return false; + readableIdentifier(requestShortener) { + return requestShortener.shorten(this.readableIdentifierStr); } - _initBuildHash(compilation) { - const hash = createHash(compilation.outputOptions.hashFunction); - if (this._source) { - hash.update("source"); - this._source.updateHash(hash); - } - hash.update("meta"); - hash.update(JSON.stringify(this.buildMeta)); - this._buildHash = /** @type {string} */ (hash.digest("hex")); + needRebuild() { + return false; } - build(options, compilation, resolver, fs, callback) { - this.buildTimestamp = Date.now(); + build(options, compilations, resolver, fs, callback) { this.built = true; - this._source = null; - this._sourceSize = null; - this._ast = null; - this._buildHash = ""; - this.error = null; - this.errors.length = 0; - this.warnings.length = 0; this.buildMeta = {}; this.buildInfo = { - cacheable: false, - fileDependencies: new Set(), - contextDependencies: new Set(), - assets: undefined, - assetsInfo: undefined + cacheable: true }; + callback(); + } - return this.doBuild(options, compilation, resolver, fs, err => { - this._cachedSources.clear(); + source() { + if (this.useSourceMap) { + return new OriginalSource(this.sourceStr, this.identifier()); + } else { + return new RawSource(this.sourceStr); + } + } - // if we have an error mark module as failed and exit - if (err) { - this.markModuleAsErrored(err); - this._initBuildHash(compilation); - return callback(); - } + updateHash(hash) { + hash.update(this.sourceStr); + super.updateHash(hash); + } +}; - // check if this module should !not! be parsed. - // if so, exit here; - const noParseRule = options.module && options.module.noParse; - if (this.shouldPreventParsing(noParseRule, this.request)) { - this._initBuildHash(compilation); - return callback(); - } - const handleParseError = e => { - const source = this._source.source(); - const loaders = this.loaders.map(item => - contextify(options.context, item.loader) - ); - const error = new ModuleParseError(this, source, e, loaders); - this.markModuleAsErrored(error); - this._initBuildHash(compilation); - return callback(); - }; +/***/ }), - const handleParseResult = result => { - this._lastSuccessfulBuildMeta = this.buildMeta; - this._initBuildHash(compilation); - return callback(); - }; +/***/ 40355: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - try { - const result = this.parser.parse( - this._ast || this._source.source(), - { - current: this, - module: this, - compilation: compilation, - options: options - }, - (err, result) => { - if (err) { - handleParseError(err); - } else { - handleParseResult(result); - } - } - ); - if (result !== undefined) { - // parse is sync - handleParseResult(result); - } - } catch (e) { - handleParseError(e); - } - }); - } - - getHashDigest(dependencyTemplates) { - // TODO webpack 5 refactor - let dtHash = dependencyTemplates.get("hash"); - return `${this.hash}-${dtHash}`; - } - - source(dependencyTemplates, runtimeTemplate, type = "javascript") { - const hashDigest = this.getHashDigest(dependencyTemplates); - const cacheEntry = this._cachedSources.get(type); - if (cacheEntry !== undefined && cacheEntry.hash === hashDigest) { - // We can reuse the cached source - return cacheEntry.source; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const source = this.generator.generate( - this, - dependencyTemplates, - runtimeTemplate, - type - ); - const cachedSource = new CachedSource(source); - this._cachedSources.set(type, { - source: cachedSource, - hash: hashDigest - }); - return cachedSource; - } +const identifierUtils = __webpack_require__(94658); - originalSource() { - return this._source; - } +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./Module")} Module */ - needRebuild(fileTimestamps, contextTimestamps) { - // always try to rebuild in case of an error - if (this.error) return true; +/** + * @typedef {Object} RecordsChunks + * @property {Record=} byName + * @property {Record=} bySource + * @property {number[]=} usedIds + */ - // always rebuild when module is not cacheable - if (!this.buildInfo.cacheable) return true; +/** + * @typedef {Object} RecordsModules + * @property {Record=} byIdentifier + * @property {Record=} bySource + * @property {Record=} usedIds + */ - // Check timestamps of all dependencies - // Missing timestamp -> need rebuild - // Timestamp bigger than buildTimestamp -> need rebuild - for (const file of this.buildInfo.fileDependencies) { - const timestamp = fileTimestamps.get(file); - if (!timestamp) return true; - if (timestamp >= this.buildTimestamp) return true; - } - for (const file of this.buildInfo.contextDependencies) { - const timestamp = contextTimestamps.get(file); - if (!timestamp) return true; - if (timestamp >= this.buildTimestamp) return true; - } - // elsewise -> no rebuild needed - return false; - } +/** + * @typedef {Object} Records + * @property {RecordsChunks=} chunks + * @property {RecordsModules=} modules + */ - size() { - if (this._sourceSize === null) { - this._sourceSize = this._source ? this._source.size() : -1; - } - return this._sourceSize; +class RecordIdsPlugin { + /** + * @param {Object} options Options object + * @param {boolean=} options.portableIds true, when ids need to be portable + */ + constructor(options) { + this.options = options || {}; } /** - * @param {Hash} hash the hash used to track dependencies + * @param {Compiler} compiler the Compiler * @returns {void} */ - updateHash(hash) { - hash.update(this._buildHash); - super.updateHash(hash); + apply(compiler) { + const portableIds = this.options.portableIds; + compiler.hooks.compilation.tap("RecordIdsPlugin", compilation => { + compilation.hooks.recordModules.tap( + "RecordIdsPlugin", + /** + * @param {Module[]} modules the modules array + * @param {Records} records the records object + * @returns {void} + */ + (modules, records) => { + if (!records.modules) records.modules = {}; + if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; + if (!records.modules.usedIds) records.modules.usedIds = {}; + for (const module of modules) { + if (typeof module.id !== "number") continue; + const identifier = portableIds + ? identifierUtils.makePathsRelative( + compiler.context, + module.identifier(), + compilation.cache + ) + : module.identifier(); + records.modules.byIdentifier[identifier] = module.id; + records.modules.usedIds[module.id] = module.id; + } + } + ); + compilation.hooks.reviveModules.tap( + "RecordIdsPlugin", + /** + * @param {Module[]} modules the modules array + * @param {Records} records the records object + * @returns {void} + */ + (modules, records) => { + if (!records.modules) return; + if (records.modules.byIdentifier) { + /** @type {Set} */ + const usedIds = new Set(); + for (const module of modules) { + if (module.id !== null) continue; + const identifier = portableIds + ? identifierUtils.makePathsRelative( + compiler.context, + module.identifier(), + compilation.cache + ) + : module.identifier(); + const id = records.modules.byIdentifier[identifier]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + module.id = id; + } + } + if (Array.isArray(records.modules.usedIds)) { + compilation.usedModuleIds = new Set(records.modules.usedIds); + } + } + ); + + /** + * @param {Module} module the module + * @returns {string} the (portable) identifier + */ + const getModuleIdentifier = module => { + if (portableIds) { + return identifierUtils.makePathsRelative( + compiler.context, + module.identifier(), + compilation.cache + ); + } + return module.identifier(); + }; + + /** + * @param {Chunk} chunk the chunk + * @returns {string[]} sources of the chunk + */ + const getChunkSources = chunk => { + /** @type {string[]} */ + const sources = []; + for (const chunkGroup of chunk.groupsIterable) { + const index = chunkGroup.chunks.indexOf(chunk); + if (chunkGroup.name) { + sources.push(`${index} ${chunkGroup.name}`); + } else { + for (const origin of chunkGroup.origins) { + if (origin.module) { + if (origin.request) { + sources.push( + `${index} ${getModuleIdentifier(origin.module)} ${ + origin.request + }` + ); + } else if (typeof origin.loc === "string") { + sources.push( + `${index} ${getModuleIdentifier(origin.module)} ${ + origin.loc + }` + ); + } else if ( + origin.loc && + typeof origin.loc === "object" && + origin.loc.start + ) { + sources.push( + `${index} ${getModuleIdentifier( + origin.module + )} ${JSON.stringify(origin.loc.start)}` + ); + } + } + } + } + } + return sources; + }; + + compilation.hooks.recordChunks.tap( + "RecordIdsPlugin", + /** + * @param {Chunk[]} chunks the chunks array + * @param {Records} records the records object + * @returns {void} + */ + (chunks, records) => { + if (!records.chunks) records.chunks = {}; + if (!records.chunks.byName) records.chunks.byName = {}; + if (!records.chunks.bySource) records.chunks.bySource = {}; + /** @type {Set} */ + const usedIds = new Set(); + for (const chunk of chunks) { + if (typeof chunk.id !== "number") continue; + const name = chunk.name; + if (name) records.chunks.byName[name] = chunk.id; + const sources = getChunkSources(chunk); + for (const source of sources) { + records.chunks.bySource[source] = chunk.id; + } + usedIds.add(chunk.id); + } + records.chunks.usedIds = Array.from(usedIds).sort(); + } + ); + compilation.hooks.reviveChunks.tap( + "RecordIdsPlugin", + /** + * @param {Chunk[]} chunks the chunks array + * @param {Records} records the records object + * @returns {void} + */ + (chunks, records) => { + if (!records.chunks) return; + /** @type {Set} */ + const usedIds = new Set(); + if (records.chunks.byName) { + for (const chunk of chunks) { + if (chunk.id !== null) continue; + if (!chunk.name) continue; + const id = records.chunks.byName[chunk.name]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunk.id = id; + } + } + if (records.chunks.bySource) { + for (const chunk of chunks) { + const sources = getChunkSources(chunk); + for (const source of sources) { + const id = records.chunks.bySource[source]; + if (id === undefined) continue; + if (usedIds.has(id)) continue; + usedIds.add(id); + chunk.id = id; + break; + } + } + } + if (Array.isArray(records.chunks.usedIds)) { + compilation.usedChunkIds = new Set(records.chunks.usedIds); + } + } + ); + }); } } - -module.exports = NormalModule; +module.exports = RecordIdsPlugin; /***/ }), -/***/ 22298: +/***/ 15377: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ - - -const path = __webpack_require__(85622); -const asyncLib = __webpack_require__(36386); -const { - Tapable, - AsyncSeriesWaterfallHook, - SyncWaterfallHook, - SyncBailHook, - SyncHook, - HookMap -} = __webpack_require__(56758); -const NormalModule = __webpack_require__(25963); -const RawModule = __webpack_require__(82353); -const RuleSet = __webpack_require__(84247); -const { cachedCleverMerge } = __webpack_require__(67916); -const EMPTY_RESOLVE_OPTIONS = {}; -const MATCH_RESOURCE_REGEX = /^([^!]+)!=!/; +const WebpackError = __webpack_require__(97391); -const loaderToIdent = data => { - if (!data.options) { - return data.loader; - } - if (typeof data.options === "string") { - return data.loader + "?" + data.options; - } - if (typeof data.options !== "object") { - throw new Error("loader options must be string or object"); - } - if (data.ident) { - return data.loader + "??" + data.ident; - } - return data.loader + "?" + JSON.stringify(data.options); -}; +module.exports = class RemovedPluginError extends WebpackError { + constructor(message) { + super(message); -const identToLoaderRequest = resultString => { - const idx = resultString.indexOf("?"); - if (idx >= 0) { - const loader = resultString.substr(0, idx); - const options = resultString.substr(idx + 1); - return { - loader, - options - }; - } else { - return { - loader: resultString, - options: undefined - }; + Error.captureStackTrace(this, this.constructor); } }; -const dependencyCache = new WeakMap(); - -class NormalModuleFactory extends Tapable { - constructor(context, resolverFactory, options) { - super(); - this.hooks = { - resolver: new SyncWaterfallHook(["resolver"]), - factory: new SyncWaterfallHook(["factory"]), - beforeResolve: new AsyncSeriesWaterfallHook(["data"]), - afterResolve: new AsyncSeriesWaterfallHook(["data"]), - createModule: new SyncBailHook(["data"]), - module: new SyncWaterfallHook(["module", "data"]), - createParser: new HookMap(() => new SyncBailHook(["parserOptions"])), - parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])), - createGenerator: new HookMap( - () => new SyncBailHook(["generatorOptions"]) - ), - generator: new HookMap( - () => new SyncHook(["generator", "generatorOptions"]) - ) - }; - this._pluginCompat.tap("NormalModuleFactory", options => { - switch (options.name) { - case "before-resolve": - case "after-resolve": - options.async = true; - break; - case "parser": - this.hooks.parser - .for("javascript/auto") - .tap(options.fn.name || "unnamed compat plugin", options.fn); - return true; - } - let match; - match = /^parser (.+)$/.exec(options.name); - if (match) { - this.hooks.parser - .for(match[1]) - .tap( - options.fn.name || "unnamed compat plugin", - options.fn.bind(this) - ); - return true; - } - match = /^create-parser (.+)$/.exec(options.name); - if (match) { - this.hooks.createParser - .for(match[1]) - .tap( - options.fn.name || "unnamed compat plugin", - options.fn.bind(this) - ); - return true; - } - }); - this.resolverFactory = resolverFactory; - this.ruleSet = new RuleSet(options.defaultRules.concat(options.rules)); - this.cachePredicate = - typeof options.unsafeCache === "function" - ? options.unsafeCache - : Boolean.bind(null, options.unsafeCache); - this.context = context || ""; - this.parserCache = Object.create(null); - this.generatorCache = Object.create(null); - this.hooks.factory.tap("NormalModuleFactory", () => (result, callback) => { - let resolver = this.hooks.resolver.call(null); - // Ignored - if (!resolver) return callback(); +/***/ }), - resolver(result, (err, data) => { - if (err) return callback(err); +/***/ 54254: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Ignored - if (!data) return callback(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // direct module - if (typeof data.source === "function") return callback(null, data); - this.hooks.afterResolve.callAsync(data, (err, result) => { - if (err) return callback(err); +const path = __webpack_require__(85622); +const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g; +const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g; +const SEPARATOR_REGEXP = /[/\\]$/; +const FRONT_OR_BACK_BANG_REGEXP = /^!|!$/g; +const INDEX_JS_REGEXP = /\/index.js(!|\?|\(query\))/g; +const MATCH_RESOURCE_REGEXP = /!=!/; - // Ignored - if (!result) return callback(); +const normalizeBackSlashDirection = request => { + return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/"); +}; - let createdModule = this.hooks.createModule.call(result); - if (!createdModule) { - if (!result.request) { - return callback(new Error("Empty dependency (no request)")); - } +const createRegExpForPath = path => { + const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&"); + return new RegExp(`(^|!)${regexpTypePartial}`, "g"); +}; - createdModule = new NormalModule(result); - } +class RequestShortener { + constructor(directory) { + directory = normalizeBackSlashDirection(directory); + if (SEPARATOR_REGEXP.test(directory)) { + directory = directory.substr(0, directory.length - 1); + } - createdModule = this.hooks.module.call(createdModule, result); + if (directory) { + this.currentDirectoryRegExp = createRegExpForPath(directory); + } - return callback(null, createdModule); - }); - }); - }); - this.hooks.resolver.tap("NormalModuleFactory", () => (data, callback) => { - const contextInfo = data.contextInfo; - const context = data.context; - const request = data.request; + const dirname = path.dirname(directory); + const endsWithSeparator = SEPARATOR_REGEXP.test(dirname); + const parentDirectory = endsWithSeparator + ? dirname.substr(0, dirname.length - 1) + : dirname; + if (parentDirectory && parentDirectory !== directory) { + this.parentDirectoryRegExp = createRegExpForPath(`${parentDirectory}/`); + } - const loaderResolver = this.getResolver("loader"); - const normalResolver = this.getResolver("normal", data.resolveOptions); + if (__dirname.length >= 2) { + const buildins = normalizeBackSlashDirection(path.join(__dirname, "..")); + const buildinsAsModule = + this.currentDirectoryRegExp && + this.currentDirectoryRegExp.test(buildins); + this.buildinsAsModule = buildinsAsModule; + this.buildinsRegExp = createRegExpForPath(buildins); + } - let matchResource = undefined; - let requestWithoutMatchResource = request; - const matchResourceMatch = MATCH_RESOURCE_REGEX.exec(request); - if (matchResourceMatch) { - matchResource = matchResourceMatch[1]; - if (/^\.\.?\//.test(matchResource)) { - matchResource = path.join(context, matchResource); - } - requestWithoutMatchResource = request.substr( - matchResourceMatch[0].length - ); - } + this.cache = new Map(); + } - const noPreAutoLoaders = requestWithoutMatchResource.startsWith("-!"); - const noAutoLoaders = - noPreAutoLoaders || requestWithoutMatchResource.startsWith("!"); - const noPrePostAutoLoaders = requestWithoutMatchResource.startsWith("!!"); - let elements = requestWithoutMatchResource - .replace(/^-?!+/, "") - .replace(/!!+/g, "!") - .split("!"); - let resource = elements.pop(); - elements = elements.map(identToLoaderRequest); - - asyncLib.parallel( - [ - callback => - this.resolveRequestArray( - contextInfo, - context, - elements, - loaderResolver, - callback - ), - callback => { - if (resource === "" || resource[0] === "?") { - return callback(null, { - resource - }); - } - - normalResolver.resolve( - contextInfo, - context, - resource, - {}, - (err, resource, resourceResolveData) => { - if (err) return callback(err); - callback(null, { - resourceResolveData, - resource - }); - } - ); - } - ], - (err, results) => { - if (err) return callback(err); - let loaders = results[0]; - const resourceResolveData = results[1].resourceResolveData; - resource = results[1].resource; - - // translate option idents - try { - for (const item of loaders) { - if (typeof item.options === "string" && item.options[0] === "?") { - const ident = item.options.substr(1); - item.options = this.ruleSet.findOptionsByIdent(ident); - item.ident = ident; - } - } - } catch (e) { - return callback(e); - } - - if (resource === false) { - // ignored - return callback( - null, - new RawModule( - "/* (ignored) */", - `ignored ${context} ${request}`, - `${request} (ignored)` - ) - ); - } - - const userRequest = - (matchResource !== undefined ? `${matchResource}!=!` : "") + - loaders - .map(loaderToIdent) - .concat([resource]) - .join("!"); - - let resourcePath = - matchResource !== undefined ? matchResource : resource; - let resourceQuery = ""; - const queryIndex = resourcePath.indexOf("?"); - if (queryIndex >= 0) { - resourceQuery = resourcePath.substr(queryIndex); - resourcePath = resourcePath.substr(0, queryIndex); - } - - const result = this.ruleSet.exec({ - resource: resourcePath, - realResource: - matchResource !== undefined - ? resource.replace(/\?.*/, "") - : resourcePath, - resourceQuery, - issuer: contextInfo.issuer, - compiler: contextInfo.compiler - }); - const settings = {}; - const useLoadersPost = []; - const useLoaders = []; - const useLoadersPre = []; - for (const r of result) { - if (r.type === "use") { - if (r.enforce === "post" && !noPrePostAutoLoaders) { - useLoadersPost.push(r.value); - } else if ( - r.enforce === "pre" && - !noPreAutoLoaders && - !noPrePostAutoLoaders - ) { - useLoadersPre.push(r.value); - } else if ( - !r.enforce && - !noAutoLoaders && - !noPrePostAutoLoaders - ) { - useLoaders.push(r.value); - } - } else if ( - typeof r.value === "object" && - r.value !== null && - typeof settings[r.type] === "object" && - settings[r.type] !== null - ) { - settings[r.type] = cachedCleverMerge(settings[r.type], r.value); - } else { - settings[r.type] = r.value; - } - } - asyncLib.parallel( - [ - this.resolveRequestArray.bind( - this, - contextInfo, - this.context, - useLoadersPost, - loaderResolver - ), - this.resolveRequestArray.bind( - this, - contextInfo, - this.context, - useLoaders, - loaderResolver - ), - this.resolveRequestArray.bind( - this, - contextInfo, - this.context, - useLoadersPre, - loaderResolver - ) - ], - (err, results) => { - if (err) return callback(err); - if (matchResource === undefined) { - loaders = results[0].concat(loaders, results[1], results[2]); - } else { - loaders = results[0].concat(results[1], loaders, results[2]); - } - process.nextTick(() => { - const type = settings.type; - const resolveOptions = settings.resolve; - callback(null, { - context: context, - request: loaders - .map(loaderToIdent) - .concat([resource]) - .join("!"), - dependencies: data.dependencies, - userRequest, - rawRequest: request, - loaders, - resource, - matchResource, - resourceResolveData, - settings, - type, - parser: this.getParser(type, settings.parser), - generator: this.getGenerator(type, settings.generator), - resolveOptions - }); - }); - } - ); - } - ); - }); - } - - create(data, callback) { - const dependencies = data.dependencies; - const cacheEntry = dependencyCache.get(dependencies[0]); - if (cacheEntry) return callback(null, cacheEntry); - const context = data.context || this.context; - const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS; - const request = dependencies[0].request; - const contextInfo = data.contextInfo || {}; - this.hooks.beforeResolve.callAsync( - { - contextInfo, - resolveOptions, - context, - request, - dependencies - }, - (err, result) => { - if (err) return callback(err); - - // Ignored - if (!result) return callback(); - - const factory = this.hooks.factory.call(null); - - // Ignored - if (!factory) return callback(); - - factory(result, (err, module) => { - if (err) return callback(err); - - if (module && this.cachePredicate(module)) { - for (const d of dependencies) { - dependencyCache.set(d, module); - } - } - - callback(null, module); - }); - } - ); - } - - resolveRequestArray(contextInfo, context, array, resolver, callback) { - if (array.length === 0) return callback(null, []); - asyncLib.map( - array, - (item, callback) => { - resolver.resolve( - contextInfo, - context, - item.loader, - {}, - (err, result) => { - if ( - err && - /^[^/]*$/.test(item.loader) && - !/-loader$/.test(item.loader) - ) { - return resolver.resolve( - contextInfo, - context, - item.loader + "-loader", - {}, - err2 => { - if (!err2) { - err.message = - err.message + - "\n" + - "BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" + - ` You need to specify '${item.loader}-loader' instead of '${item.loader}',\n` + - " see https://webpack.js.org/migrate/3/#automatic-loader-module-name-extension-removed"; - } - callback(err); - } - ); - } - if (err) return callback(err); - - const optionsOnly = item.options - ? { - options: item.options - } - : undefined; - return callback( - null, - Object.assign({}, item, identToLoaderRequest(result), optionsOnly) - ); - } - ); - }, - callback - ); - } - - getParser(type, parserOptions) { - let ident = type; - if (parserOptions) { - if (parserOptions.ident) { - ident = `${type}|${parserOptions.ident}`; - } else { - ident = JSON.stringify([type, parserOptions]); - } - } - if (ident in this.parserCache) { - return this.parserCache[ident]; + shorten(request) { + if (!request) return request; + const cacheEntry = this.cache.get(request); + if (cacheEntry !== undefined) { + return cacheEntry; } - return (this.parserCache[ident] = this.createParser(type, parserOptions)); - } - - createParser(type, parserOptions = {}) { - const parser = this.hooks.createParser.for(type).call(parserOptions); - if (!parser) { - throw new Error(`No parser registered for ${type}`); + let result = normalizeBackSlashDirection(request); + if (this.buildinsAsModule && this.buildinsRegExp) { + result = result.replace(this.buildinsRegExp, "!(webpack)"); } - this.hooks.parser.for(type).call(parser, parserOptions); - return parser; - } - - getGenerator(type, generatorOptions) { - let ident = type; - if (generatorOptions) { - if (generatorOptions.ident) { - ident = `${type}|${generatorOptions.ident}`; - } else { - ident = JSON.stringify([type, generatorOptions]); - } + if (this.currentDirectoryRegExp) { + result = result.replace(this.currentDirectoryRegExp, "!."); } - if (ident in this.generatorCache) { - return this.generatorCache[ident]; + if (this.parentDirectoryRegExp) { + result = result.replace(this.parentDirectoryRegExp, "!../"); } - return (this.generatorCache[ident] = this.createGenerator( - type, - generatorOptions - )); - } - - createGenerator(type, generatorOptions = {}) { - const generator = this.hooks.createGenerator - .for(type) - .call(generatorOptions); - if (!generator) { - throw new Error(`No generator registered for ${type}`); + if (!this.buildinsAsModule && this.buildinsRegExp) { + result = result.replace(this.buildinsRegExp, "!(webpack)"); } - this.hooks.generator.for(type).call(generator, generatorOptions); - return generator; - } - - getResolver(type, resolveOptions) { - return this.resolverFactory.get( - type, - resolveOptions || EMPTY_RESOLVE_OPTIONS - ); + result = result.replace(INDEX_JS_REGEXP, "$1"); + result = result.replace(FRONT_OR_BACK_BANG_REGEXP, ""); + result = result.replace(MATCH_RESOURCE_REGEXP, " = "); + this.cache.set(request, result); + return result; } } -module.exports = NormalModuleFactory; +module.exports = RequestShortener; /***/ }), -/***/ 73253: +/***/ 88226: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -85861,94 +85805,153 @@ module.exports = NormalModuleFactory; */ -const path = __webpack_require__(85622); - -class NormalModuleReplacementPlugin { - constructor(resourceRegExp, newResource) { - this.resourceRegExp = resourceRegExp; - this.newResource = newResource; - } +const ParserHelpers = __webpack_require__(23999); +const ConstDependency = __webpack_require__(71101); +const NullFactory = __webpack_require__(40438); +module.exports = class RequireJsStuffPlugin { apply(compiler) { - const resourceRegExp = this.resourceRegExp; - const newResource = this.newResource; - compiler.hooks.normalModuleFactory.tap( - "NormalModuleReplacementPlugin", - nmf => { - nmf.hooks.beforeResolve.tap("NormalModuleReplacementPlugin", result => { - if (!result) return; - if (resourceRegExp.test(result.request)) { - if (typeof newResource === "function") { - newResource(result); - } else { - result.request = newResource; - } - } - return result; - }); - nmf.hooks.afterResolve.tap("NormalModuleReplacementPlugin", result => { - if (!result) return; - if (resourceRegExp.test(result.resource)) { - if (typeof newResource === "function") { - newResource(result); - } else { - result.resource = path.resolve( - path.dirname(result.resource), - newResource - ); - } - } - return result; - }); + compiler.hooks.compilation.tap( + "RequireJsStuffPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set(ConstDependency, new NullFactory()); + compilation.dependencyTemplates.set( + ConstDependency, + new ConstDependency.Template() + ); + const handler = (parser, parserOptions) => { + if (parserOptions.requireJs !== undefined && !parserOptions.requireJs) + return; + + parser.hooks.call + .for("require.config") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependency(parser, "undefined") + ); + parser.hooks.call + .for("requirejs.config") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependency(parser, "undefined") + ); + + parser.hooks.expression + .for("require.version") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("0.0.0") + ) + ); + parser.hooks.expression + .for("requirejs.onError") + .tap( + "RequireJsStuffPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.oe" + ) + ); + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireJsStuffPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireJsStuffPlugin", handler); } ); } -} - -module.exports = NormalModuleReplacementPlugin; +}; /***/ }), -/***/ 40438: -/***/ (function(module) { +/***/ 50588: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ -class NullFactory { - create(data, callback) { - return callback(); - } -} -module.exports = NullFactory; +const { Tapable, HookMap, SyncHook, SyncWaterfallHook } = __webpack_require__(56758); +const Factory = __webpack_require__(87450).ResolverFactory; +const { cachedCleverMerge } = __webpack_require__(67916); +/** @typedef {import("enhanced-resolve").Resolver} Resolver */ -/***/ }), +const EMTPY_RESOLVE_OPTIONS = {}; -/***/ 4428: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +module.exports = class ResolverFactory extends Tapable { + constructor() { + super(); + this.hooks = { + resolveOptions: new HookMap( + () => new SyncWaterfallHook(["resolveOptions"]) + ), + resolver: new HookMap(() => new SyncHook(["resolver", "resolveOptions"])) + }; + this._pluginCompat.tap("ResolverFactory", options => { + let match; + match = /^resolve-options (.+)$/.exec(options.name); + if (match) { + this.hooks.resolveOptions + .for(match[1]) + .tap(options.fn.name || "unnamed compat plugin", options.fn); + return true; + } + match = /^resolver (.+)$/.exec(options.name); + if (match) { + this.hooks.resolver + .for(match[1]) + .tap(options.fn.name || "unnamed compat plugin", options.fn); + return true; + } + }); + this.cache2 = new Map(); + } + get(type, resolveOptions) { + resolveOptions = resolveOptions || EMTPY_RESOLVE_OPTIONS; + const ident = `${type}|${JSON.stringify(resolveOptions)}`; + const resolver = this.cache2.get(ident); + if (resolver) return resolver; + const newResolver = this._create(type, resolveOptions); + this.cache2.set(ident, newResolver); + return newResolver; + } -class OptionsApply { - process(options, compiler) {} -} -module.exports = OptionsApply; + _create(type, resolveOptions) { + const originalResolveOptions = Object.assign({}, resolveOptions); + resolveOptions = this.hooks.resolveOptions.for(type).call(resolveOptions); + const resolver = Factory.createResolver(resolveOptions); + if (!resolver) { + throw new Error("No resolver created"); + } + /** @type {Map} */ + const childCache = new Map(); + resolver.withOptions = options => { + const cacheEntry = childCache.get(options); + if (cacheEntry !== undefined) return cacheEntry; + const mergedOptions = cachedCleverMerge(originalResolveOptions, options); + const resolver = this.get(type, mergedOptions); + childCache.set(options, resolver); + return resolver; + }; + this.hooks.resolver.for(type).call(resolver, resolveOptions); + return resolver; + } +}; /***/ }), -/***/ 3414: +/***/ 84247: /***/ (function(module) { "use strict"; @@ -85956,4324 +85959,4262 @@ module.exports = OptionsApply; MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ +/* +: +: [] +: { + resource: { + test: , + include: , + exclude: , + }, + resource: , -> resource.test + test: , -> resource.test + include: , -> resource.include + exclude: , -> resource.exclude + resourceQuery: , + compiler: , + issuer: , + use: "loader", -> use[0].loader + loader: <>, -> use[0].loader + loaders: <>, -> use + options: {}, -> use[0].options, + query: {}, -> options + parser: {}, + use: [ + "loader" -> use[x].loader + ], + use: [ + { + loader: "loader", + options: {} + } + ], + rules: [ + + ], + oneOf: [ + + ] +} + +: /regExp/ +: function(arg) {} +: "starting" +: [] // or +: { and: [] } +: { or: [] } +: { not: [] } +: { test: , include: , exclude: } + + +normalized: + +{ + resource: function(), + resourceQuery: function(), + compiler: function(), + issuer: function(), + use: [ + { + loader: string, + options: string, + : + } + ], + rules: [], + oneOf: [], + : , +} + +*/ -/** - * Gets the value at path of object - * @param {object} obj object to query - * @param {string} path query path - * @returns {any} - if {@param path} requests element from array, then `undefined` will be returned - */ -const getProperty = (obj, path) => { - let name = path.split("."); - for (let i = 0; i < name.length - 1; i++) { - obj = obj[name[i]]; - if (typeof obj !== "object" || !obj || Array.isArray(obj)) return; - } - return obj[name.pop()]; + +const notMatcher = matcher => { + return str => { + return !matcher(str); + }; }; -/** - * Sets the value at path of object. Stops execution, if {@param path} requests element from array to be set - * @param {object} obj object to query - * @param {string} path query path - * @param {any} value value to be set - * @returns {void} - */ -const setProperty = (obj, path, value) => { - let name = path.split("."); - for (let i = 0; i < name.length - 1; i++) { - if (typeof obj[name[i]] !== "object" && obj[name[i]] !== undefined) return; - if (Array.isArray(obj[name[i]])) return; - if (!obj[name[i]]) obj[name[i]] = {}; - obj = obj[name[i]]; - } - obj[name.pop()] = value; +const orMatcher = items => { + return str => { + for (let i = 0; i < items.length; i++) { + if (items[i](str)) return true; + } + return false; + }; }; -/** - * @typedef {'call' | 'make' | 'append'} ConfigType - */ -/** - * @typedef {(options: object) => any} MakeConfigHandler - */ -/** - * @typedef {(value: any, options: object) => any} CallConfigHandler - */ -/** - * @typedef {any[]} AppendConfigValues - */ +const andMatcher = items => { + return str => { + for (let i = 0; i < items.length; i++) { + if (!items[i](str)) return false; + } + return true; + }; +}; -class OptionsDefaulter { - constructor() { - /** - * Stores default options settings or functions for computing them - */ - this.defaults = {}; - /** - * Stores configuration for options - * @type {{[key: string]: ConfigType}} - */ - this.config = {}; +module.exports = class RuleSet { + constructor(rules) { + this.references = Object.create(null); + this.rules = RuleSet.normalizeRules(rules, this.references, "ref-"); } - /** - * Enhancing {@param options} with default values - * @param {object} options provided options - * @returns {object} - enhanced options - * @throws {Error} - will throw error, if configuration value is other then `undefined` or {@link ConfigType} - */ - process(options) { - options = Object.assign({}, options); - for (let name in this.defaults) { - switch (this.config[name]) { - /** - * If {@link ConfigType} doesn't specified and current value is `undefined`, then default value will be assigned - */ - case undefined: - if (getProperty(options, name) === undefined) { - setProperty(options, name, this.defaults[name]); - } - break; - /** - * Assign result of {@link CallConfigHandler} - */ - case "call": - setProperty( - options, - name, - this.defaults[name].call(this, getProperty(options, name), options) - ); - break; - /** - * Assign result of {@link MakeConfigHandler}, if current value is `undefined` - */ - case "make": - if (getProperty(options, name) === undefined) { - setProperty(options, name, this.defaults[name].call(this, options)); - } - break; - /** - * Adding {@link AppendConfigValues} at the end of the current array - */ - case "append": { - let oldValue = getProperty(options, name); - if (!Array.isArray(oldValue)) { - oldValue = []; + static normalizeRules(rules, refs, ident) { + if (Array.isArray(rules)) { + return rules.map((rule, idx) => { + return RuleSet.normalizeRule(rule, refs, `${ident}-${idx}`); + }); + } else if (rules) { + return [RuleSet.normalizeRule(rules, refs, ident)]; + } else { + return []; + } + } + + static normalizeRule(rule, refs, ident) { + if (typeof rule === "string") { + return { + use: [ + { + loader: rule } - oldValue.push(...this.defaults[name]); - setProperty(options, name, oldValue); - break; - } - default: - throw new Error( - "OptionsDefaulter cannot process " + this.config[name] - ); + ] + }; + } + if (!rule) { + throw new Error("Unexcepted null when object was expected as rule"); + } + if (typeof rule !== "object") { + throw new Error( + "Unexcepted " + + typeof rule + + " when object was expected as rule (" + + rule + + ")" + ); + } + + const newRule = {}; + let useSource; + let resourceSource; + let condition; + + const checkUseSource = newSource => { + if (useSource && useSource !== newSource) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "Rule can only have one result source (provided " + + newSource + + " and " + + useSource + + ")" + ) + ) + ); + } + useSource = newSource; + }; + + const checkResourceSource = newSource => { + if (resourceSource && resourceSource !== newSource) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "Rule can only have one resource source (provided " + + newSource + + " and " + + resourceSource + + ")" + ) + ) + ); + } + resourceSource = newSource; + }; + + if (rule.test || rule.include || rule.exclude) { + checkResourceSource("test + include + exclude"); + condition = { + test: rule.test, + include: rule.include, + exclude: rule.exclude + }; + try { + newRule.resource = RuleSet.normalizeCondition(condition); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(condition, error)); } } - return options; - } - /** - * Builds up default values - * @param {string} name option path - * @param {ConfigType | any} config if {@param def} is provided, then only {@link ConfigType} is allowed - * @param {MakeConfigHandler | CallConfigHandler | AppendConfigValues} [def] defaults - * @returns {void} - */ - set(name, config, def) { - if (def !== undefined) { - this.defaults[name] = def; - this.config[name] = config; - } else { - this.defaults[name] = config; - delete this.config[name]; + if (rule.resource) { + checkResourceSource("resource"); + try { + newRule.resource = RuleSet.normalizeCondition(rule.resource); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.resource, error)); + } } - } -} -module.exports = OptionsDefaulter; + if (rule.realResource) { + try { + newRule.realResource = RuleSet.normalizeCondition(rule.realResource); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.realResource, error)); + } + } + if (rule.resourceQuery) { + try { + newRule.resourceQuery = RuleSet.normalizeCondition(rule.resourceQuery); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.resourceQuery, error)); + } + } -/***/ }), + if (rule.compiler) { + try { + newRule.compiler = RuleSet.normalizeCondition(rule.compiler); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.compiler, error)); + } + } -/***/ 70558: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (rule.issuer) { + try { + newRule.issuer = RuleSet.normalizeCondition(rule.issuer); + } catch (error) { + throw new Error(RuleSet.buildErrorMessage(rule.issuer, error)); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (rule.loader && rule.loaders) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "Provided loader and loaders for rule (use only one of them)" + ) + ) + ); + } + const loader = rule.loaders || rule.loader; + if (typeof loader === "string" && !rule.options && !rule.query) { + checkUseSource("loader"); + newRule.use = RuleSet.normalizeUse(loader.split("!"), ident); + } else if (typeof loader === "string" && (rule.options || rule.query)) { + checkUseSource("loader + options/query"); + newRule.use = RuleSet.normalizeUse( + { + loader: loader, + options: rule.options, + query: rule.query + }, + ident + ); + } else if (loader && (rule.options || rule.query)) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "options/query cannot be used with loaders (use options for each array item)" + ) + ) + ); + } else if (loader) { + checkUseSource("loaders"); + newRule.use = RuleSet.normalizeUse(loader, ident); + } else if (rule.options || rule.query) { + throw new Error( + RuleSet.buildErrorMessage( + rule, + new Error( + "options/query provided without loader (use loader + options)" + ) + ) + ); + } -// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API + if (rule.use) { + checkUseSource("use"); + newRule.use = RuleSet.normalizeUse(rule.use, ident); + } -const acorn = __webpack_require__(77087); -const { Tapable, SyncBailHook, HookMap } = __webpack_require__(56758); -const util = __webpack_require__(31669); -const vm = __webpack_require__(92184); -const BasicEvaluatedExpression = __webpack_require__(96770); -const StackedSetMap = __webpack_require__(92251); + if (rule.rules) { + newRule.rules = RuleSet.normalizeRules( + rule.rules, + refs, + `${ident}-rules` + ); + } -const acornParser = acorn.Parser; + if (rule.oneOf) { + newRule.oneOf = RuleSet.normalizeRules( + rule.oneOf, + refs, + `${ident}-oneOf` + ); + } -const joinRanges = (startRange, endRange) => { - if (!endRange) return startRange; - if (!startRange) return endRange; - return [startRange[0], endRange[1]]; -}; + const keys = Object.keys(rule).filter(key => { + return ![ + "resource", + "resourceQuery", + "compiler", + "test", + "include", + "exclude", + "issuer", + "loader", + "options", + "query", + "loaders", + "use", + "rules", + "oneOf" + ].includes(key); + }); + for (const key of keys) { + newRule[key] = rule[key]; + } -const defaultParserOptions = { - ranges: true, - locations: true, - ecmaVersion: 11, - sourceType: "module", - onComment: null -}; + if (Array.isArray(newRule.use)) { + for (const item of newRule.use) { + if (item.ident) { + refs[item.ident] = item.options; + } + } + } -// regexp to match at least one "magic comment" -const webpackCommentRegExp = new RegExp(/(^|\W)webpack[A-Z]{1,}[A-Za-z]{1,}:/); + return newRule; + } -const EMPTY_COMMENT_OPTIONS = { - options: null, - errors: null -}; + static buildErrorMessage(condition, error) { + const conditionAsText = JSON.stringify( + condition, + (key, value) => { + return value === undefined ? "undefined" : value; + }, + 2 + ); + return error.message + " in " + conditionAsText; + } -class Parser extends Tapable { - constructor(options, sourceType = "auto") { - super(); - this.hooks = { - evaluateTypeof: new HookMap(() => new SyncBailHook(["expression"])), - evaluate: new HookMap(() => new SyncBailHook(["expression"])), - evaluateIdentifier: new HookMap(() => new SyncBailHook(["expression"])), - evaluateDefinedIdentifier: new HookMap( - () => new SyncBailHook(["expression"]) - ), - evaluateCallExpressionMember: new HookMap( - () => new SyncBailHook(["expression", "param"]) - ), - statement: new SyncBailHook(["statement"]), - statementIf: new SyncBailHook(["statement"]), - label: new HookMap(() => new SyncBailHook(["statement"])), - import: new SyncBailHook(["statement", "source"]), - importSpecifier: new SyncBailHook([ - "statement", - "source", - "exportName", - "identifierName" - ]), - export: new SyncBailHook(["statement"]), - exportImport: new SyncBailHook(["statement", "source"]), - exportDeclaration: new SyncBailHook(["statement", "declaration"]), - exportExpression: new SyncBailHook(["statement", "declaration"]), - exportSpecifier: new SyncBailHook([ - "statement", - "identifierName", - "exportName", - "index" - ]), - exportImportSpecifier: new SyncBailHook([ - "statement", - "source", - "identifierName", - "exportName", - "index" - ]), - varDeclaration: new HookMap(() => new SyncBailHook(["declaration"])), - varDeclarationLet: new HookMap(() => new SyncBailHook(["declaration"])), - varDeclarationConst: new HookMap(() => new SyncBailHook(["declaration"])), - varDeclarationVar: new HookMap(() => new SyncBailHook(["declaration"])), - canRename: new HookMap(() => new SyncBailHook(["initExpression"])), - rename: new HookMap(() => new SyncBailHook(["initExpression"])), - assigned: new HookMap(() => new SyncBailHook(["expression"])), - assign: new HookMap(() => new SyncBailHook(["expression"])), - typeof: new HookMap(() => new SyncBailHook(["expression"])), - importCall: new SyncBailHook(["expression"]), - call: new HookMap(() => new SyncBailHook(["expression"])), - callAnyMember: new HookMap(() => new SyncBailHook(["expression"])), - new: new HookMap(() => new SyncBailHook(["expression"])), - expression: new HookMap(() => new SyncBailHook(["expression"])), - expressionAnyMember: new HookMap(() => new SyncBailHook(["expression"])), - expressionConditionalOperator: new SyncBailHook(["expression"]), - expressionLogicalOperator: new SyncBailHook(["expression"]), - program: new SyncBailHook(["ast", "comments"]) - }; - const HOOK_MAP_COMPAT_CONFIG = { - evaluateTypeof: /^evaluate typeof (.+)$/, - evaluateIdentifier: /^evaluate Identifier (.+)$/, - evaluateDefinedIdentifier: /^evaluate defined Identifier (.+)$/, - evaluateCallExpressionMember: /^evaluate CallExpression .(.+)$/, - evaluate: /^evaluate (.+)$/, - label: /^label (.+)$/, - varDeclarationLet: /^var-let (.+)$/, - varDeclarationConst: /^var-const (.+)$/, - varDeclarationVar: /^var-var (.+)$/, - varDeclaration: /^var (.+)$/, - canRename: /^can-rename (.+)$/, - rename: /^rename (.+)$/, - typeof: /^typeof (.+)$/, - assigned: /^assigned (.+)$/, - assign: /^assign (.+)$/, - callAnyMember: /^call (.+)\.\*$/, - call: /^call (.+)$/, - new: /^new (.+)$/, - expressionConditionalOperator: /^expression \?:$/, - expressionAnyMember: /^expression (.+)\.\*$/, - expression: /^expression (.+)$/ + static normalizeUse(use, ident) { + if (typeof use === "function") { + return data => RuleSet.normalizeUse(use(data), ident); + } + if (Array.isArray(use)) { + return use + .map((item, idx) => RuleSet.normalizeUse(item, `${ident}-${idx}`)) + .reduce((arr, items) => arr.concat(items), []); + } + return [RuleSet.normalizeUseItem(use, ident)]; + } + + static normalizeUseItemString(useItemString) { + const idx = useItemString.indexOf("?"); + if (idx >= 0) { + return { + loader: useItemString.substr(0, idx), + options: useItemString.substr(idx + 1) + }; + } + return { + loader: useItemString, + options: undefined }; - this._pluginCompat.tap("Parser", options => { - for (const name of Object.keys(HOOK_MAP_COMPAT_CONFIG)) { - const regexp = HOOK_MAP_COMPAT_CONFIG[name]; - const match = regexp.exec(options.name); - if (match) { - if (match[1]) { - this.hooks[name].tap( - match[1], - options.fn.name || "unnamed compat plugin", - options.fn.bind(this) - ); - } else { - this.hooks[name].tap( - options.fn.name || "unnamed compat plugin", - options.fn.bind(this) - ); - } - return true; - } + } + + static normalizeUseItem(item, ident) { + if (typeof item === "string") { + return RuleSet.normalizeUseItemString(item); + } + + const newItem = {}; + + if (item.options && item.query) { + throw new Error("Provided options and query in use"); + } + + if (!item.loader) { + throw new Error("No loader specified"); + } + + newItem.options = item.options || item.query; + + if (typeof newItem.options === "object" && newItem.options) { + if (newItem.options.ident) { + newItem.ident = newItem.options.ident; + } else { + newItem.ident = ident; } + } + + const keys = Object.keys(item).filter(function(key) { + return !["options", "query"].includes(key); }); - this.options = options; - this.sourceType = sourceType; - this.scope = undefined; - this.state = undefined; - this.comments = undefined; - this.initializeEvaluating(); + + for (const key of keys) { + newItem[key] = item[key]; + } + + return newItem; } - initializeEvaluating() { - this.hooks.evaluate.for("Literal").tap("Parser", expr => { - switch (typeof expr.value) { - case "number": - return new BasicEvaluatedExpression() - .setNumber(expr.value) - .setRange(expr.range); - case "string": - return new BasicEvaluatedExpression() - .setString(expr.value) - .setRange(expr.range); - case "boolean": - return new BasicEvaluatedExpression() - .setBoolean(expr.value) - .setRange(expr.range); - } - if (expr.value === null) { - return new BasicEvaluatedExpression().setNull().setRange(expr.range); - } - if (expr.value instanceof RegExp) { - return new BasicEvaluatedExpression() - .setRegExp(expr.value) - .setRange(expr.range); + static normalizeCondition(condition) { + if (!condition) throw new Error("Expected condition but got falsy value"); + if (typeof condition === "string") { + return str => str.indexOf(condition) === 0; + } + if (typeof condition === "function") { + return condition; + } + if (condition instanceof RegExp) { + return condition.test.bind(condition); + } + if (Array.isArray(condition)) { + const items = condition.map(c => RuleSet.normalizeCondition(c)); + return orMatcher(items); + } + if (typeof condition !== "object") { + throw Error( + "Unexcepted " + + typeof condition + + " when condition was expected (" + + condition + + ")" + ); + } + + const matchers = []; + Object.keys(condition).forEach(key => { + const value = condition[key]; + switch (key) { + case "or": + case "include": + case "test": + if (value) matchers.push(RuleSet.normalizeCondition(value)); + break; + case "and": + if (value) { + const items = value.map(c => RuleSet.normalizeCondition(c)); + matchers.push(andMatcher(items)); + } + break; + case "not": + case "exclude": + if (value) { + const matcher = RuleSet.normalizeCondition(value); + matchers.push(notMatcher(matcher)); + } + break; + default: + throw new Error("Unexcepted property " + key + " in condition"); } }); - this.hooks.evaluate.for("LogicalExpression").tap("Parser", expr => { - let left; - let leftAsBool; - let right; - if (expr.operator === "&&") { - left = this.evaluateExpression(expr.left); - leftAsBool = left && left.asBool(); - if (leftAsBool === false) return left.setRange(expr.range); - if (leftAsBool !== true) return; - right = this.evaluateExpression(expr.right); - return right.setRange(expr.range); - } else if (expr.operator === "||") { - left = this.evaluateExpression(expr.left); - leftAsBool = left && left.asBool(); - if (leftAsBool === true) return left.setRange(expr.range); - if (leftAsBool !== false) return; - right = this.evaluateExpression(expr.right); - return right.setRange(expr.range); - } + if (matchers.length === 0) { + throw new Error("Excepted condition but got " + condition); + } + if (matchers.length === 1) { + return matchers[0]; + } + return andMatcher(matchers); + } + + exec(data) { + const result = []; + this._run( + data, + { + rules: this.rules + }, + result + ); + return result; + } + + _run(data, rule, result) { + // test conditions + if (rule.resource && !data.resource) return false; + if (rule.realResource && !data.realResource) return false; + if (rule.resourceQuery && !data.resourceQuery) return false; + if (rule.compiler && !data.compiler) return false; + if (rule.issuer && !data.issuer) return false; + if (rule.resource && !rule.resource(data.resource)) return false; + if (rule.realResource && !rule.realResource(data.realResource)) + return false; + if (data.issuer && rule.issuer && !rule.issuer(data.issuer)) return false; + if ( + data.resourceQuery && + rule.resourceQuery && + !rule.resourceQuery(data.resourceQuery) + ) { + return false; + } + if (data.compiler && rule.compiler && !rule.compiler(data.compiler)) { + return false; + } + + // apply + const keys = Object.keys(rule).filter(key => { + return ![ + "resource", + "realResource", + "resourceQuery", + "compiler", + "issuer", + "rules", + "oneOf", + "use", + "enforce" + ].includes(key); }); - this.hooks.evaluate.for("BinaryExpression").tap("Parser", expr => { - let left; - let right; - let res; - if (expr.operator === "+") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - res = new BasicEvaluatedExpression(); - if (left.isString()) { - if (right.isString()) { - res.setString(left.string + right.string); - } else if (right.isNumber()) { - res.setString(left.string + right.number); - } else if ( - right.isWrapped() && - right.prefix && - right.prefix.isString() - ) { - // "left" + ("prefix" + inner + "postfix") - // => ("leftprefix" + inner + "postfix") - res.setWrapped( - new BasicEvaluatedExpression() - .setString(left.string + right.prefix.string) - .setRange(joinRanges(left.range, right.prefix.range)), - right.postfix, - right.wrappedInnerExpressions - ); - } else if (right.isWrapped()) { - // "left" + ([null] + inner + "postfix") - // => ("left" + inner + "postfix") - res.setWrapped(left, right.postfix, right.wrappedInnerExpressions); - } else { - // "left" + expr - // => ("left" + expr + "") - res.setWrapped(left, null, [right]); - } - } else if (left.isNumber()) { - if (right.isString()) { - res.setString(left.number + right.string); - } else if (right.isNumber()) { - res.setNumber(left.number + right.number); - } else { - return; - } - } else if (left.isWrapped()) { - if (left.postfix && left.postfix.isString() && right.isString()) { - // ("prefix" + inner + "postfix") + "right" - // => ("prefix" + inner + "postfixright") - res.setWrapped( - left.prefix, - new BasicEvaluatedExpression() - .setString(left.postfix.string + right.string) - .setRange(joinRanges(left.postfix.range, right.range)), - left.wrappedInnerExpressions - ); - } else if ( - left.postfix && - left.postfix.isString() && - right.isNumber() - ) { - // ("prefix" + inner + "postfix") + 123 - // => ("prefix" + inner + "postfix123") - res.setWrapped( - left.prefix, - new BasicEvaluatedExpression() - .setString(left.postfix.string + right.number) - .setRange(joinRanges(left.postfix.range, right.range)), - left.wrappedInnerExpressions - ); - } else if (right.isString()) { - // ("prefix" + inner + [null]) + "right" - // => ("prefix" + inner + "right") - res.setWrapped(left.prefix, right, left.wrappedInnerExpressions); - } else if (right.isNumber()) { - // ("prefix" + inner + [null]) + 123 - // => ("prefix" + inner + "123") - res.setWrapped( - left.prefix, - new BasicEvaluatedExpression() - .setString(right.number + "") - .setRange(right.range), - left.wrappedInnerExpressions - ); - } else if (right.isWrapped()) { - // ("prefix1" + inner1 + "postfix1") + ("prefix2" + inner2 + "postfix2") - // ("prefix1" + inner1 + "postfix1" + "prefix2" + inner2 + "postfix2") - res.setWrapped( - left.prefix, - right.postfix, - left.wrappedInnerExpressions && - right.wrappedInnerExpressions && - left.wrappedInnerExpressions - .concat(left.postfix ? [left.postfix] : []) - .concat(right.prefix ? [right.prefix] : []) - .concat(right.wrappedInnerExpressions) - ); - } else { - // ("prefix" + inner + postfix) + expr - // => ("prefix" + inner + postfix + expr + [null]) - res.setWrapped( - left.prefix, - null, - left.wrappedInnerExpressions && - left.wrappedInnerExpressions.concat( - left.postfix ? [left.postfix, right] : [right] - ) - ); - } + for (const key of keys) { + result.push({ + type: key, + value: rule[key] + }); + } + + if (rule.use) { + const process = use => { + if (typeof use === "function") { + process(use(data)); + } else if (Array.isArray(use)) { + use.forEach(process); } else { - if (right.isString()) { - // left + "right" - // => ([null] + left + "right") - res.setWrapped(null, right, [left]); - } else if (right.isWrapped()) { - // left + (prefix + inner + "postfix") - // => ([null] + left + prefix + inner + "postfix") - res.setWrapped( - null, - right.postfix, - right.wrappedInnerExpressions && - (right.prefix ? [left, right.prefix] : [left]).concat( - right.wrappedInnerExpressions - ) - ); - } else { - return; - } - } - res.setRange(expr.range); - return res; - } else if (expr.operator === "-") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - if (!left.isNumber() || !right.isNumber()) return; - res = new BasicEvaluatedExpression(); - res.setNumber(left.number - right.number); - res.setRange(expr.range); - return res; - } else if (expr.operator === "*") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - if (!left.isNumber() || !right.isNumber()) return; - res = new BasicEvaluatedExpression(); - res.setNumber(left.number * right.number); - res.setRange(expr.range); - return res; - } else if (expr.operator === "/") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - if (!left.isNumber() || !right.isNumber()) return; - res = new BasicEvaluatedExpression(); - res.setNumber(left.number / right.number); - res.setRange(expr.range); - return res; - } else if (expr.operator === "**") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - if (!left.isNumber() || !right.isNumber()) return; - res = new BasicEvaluatedExpression(); - res.setNumber(Math.pow(left.number, right.number)); - res.setRange(expr.range); - return res; - } else if (expr.operator === "==" || expr.operator === "===") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - res = new BasicEvaluatedExpression(); - res.setRange(expr.range); - if (left.isString() && right.isString()) { - return res.setBoolean(left.string === right.string); - } else if (left.isNumber() && right.isNumber()) { - return res.setBoolean(left.number === right.number); - } else if (left.isBoolean() && right.isBoolean()) { - return res.setBoolean(left.bool === right.bool); + result.push({ + type: "use", + value: use, + enforce: rule.enforce + }); } - } else if (expr.operator === "!=" || expr.operator === "!==") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - res = new BasicEvaluatedExpression(); - res.setRange(expr.range); - if (left.isString() && right.isString()) { - return res.setBoolean(left.string !== right.string); - } else if (left.isNumber() && right.isNumber()) { - return res.setBoolean(left.number !== right.number); - } else if (left.isBoolean() && right.isBoolean()) { - return res.setBoolean(left.bool !== right.bool); - } - } else if (expr.operator === "&") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - if (!left.isNumber() || !right.isNumber()) return; - res = new BasicEvaluatedExpression(); - res.setNumber(left.number & right.number); - res.setRange(expr.range); - return res; - } else if (expr.operator === "|") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - if (!left.isNumber() || !right.isNumber()) return; - res = new BasicEvaluatedExpression(); - res.setNumber(left.number | right.number); - res.setRange(expr.range); - return res; - } else if (expr.operator === "^") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - if (!left.isNumber() || !right.isNumber()) return; - res = new BasicEvaluatedExpression(); - res.setNumber(left.number ^ right.number); - res.setRange(expr.range); - return res; - } else if (expr.operator === ">>>") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - if (!left.isNumber() || !right.isNumber()) return; - res = new BasicEvaluatedExpression(); - res.setNumber(left.number >>> right.number); - res.setRange(expr.range); - return res; - } else if (expr.operator === ">>") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - if (!left.isNumber() || !right.isNumber()) return; - res = new BasicEvaluatedExpression(); - res.setNumber(left.number >> right.number); - res.setRange(expr.range); - return res; - } else if (expr.operator === "<<") { - left = this.evaluateExpression(expr.left); - right = this.evaluateExpression(expr.right); - if (!left || !right) return; - if (!left.isNumber() || !right.isNumber()) return; - res = new BasicEvaluatedExpression(); - res.setNumber(left.number << right.number); - res.setRange(expr.range); - return res; - } - }); - this.hooks.evaluate.for("UnaryExpression").tap("Parser", expr => { - if (expr.operator === "typeof") { - let res; - let name; - if (expr.argument.type === "Identifier") { - name = - this.scope.renames.get(expr.argument.name) || expr.argument.name; - if (!this.scope.definitions.has(name)) { - const hook = this.hooks.evaluateTypeof.get(name); - if (hook !== undefined) { - res = hook.call(expr); - if (res !== undefined) return res; - } - } - } - if (expr.argument.type === "MemberExpression") { - const exprName = this.getNameForExpression(expr.argument); - if (exprName && exprName.free) { - const hook = this.hooks.evaluateTypeof.get(exprName.name); - if (hook !== undefined) { - res = hook.call(expr); - if (res !== undefined) return res; - } - } - } - if (expr.argument.type === "FunctionExpression") { - return new BasicEvaluatedExpression() - .setString("function") - .setRange(expr.range); - } - const arg = this.evaluateExpression(expr.argument); - if (arg.isString() || arg.isWrapped()) { - return new BasicEvaluatedExpression() - .setString("string") - .setRange(expr.range); - } - if (arg.isNumber()) { - return new BasicEvaluatedExpression() - .setString("number") - .setRange(expr.range); - } - if (arg.isBoolean()) { - return new BasicEvaluatedExpression() - .setString("boolean") - .setRange(expr.range); - } - if (arg.isArray() || arg.isConstArray() || arg.isRegExp()) { - return new BasicEvaluatedExpression() - .setString("object") - .setRange(expr.range); - } - } else if (expr.operator === "!") { - const argument = this.evaluateExpression(expr.argument); - if (!argument) return; - if (argument.isBoolean()) { - return new BasicEvaluatedExpression() - .setBoolean(!argument.bool) - .setRange(expr.range); - } - if (argument.isTruthy()) { - return new BasicEvaluatedExpression() - .setBoolean(false) - .setRange(expr.range); - } - if (argument.isFalsy()) { - return new BasicEvaluatedExpression() - .setBoolean(true) - .setRange(expr.range); - } - if (argument.isString()) { - return new BasicEvaluatedExpression() - .setBoolean(!argument.string) - .setRange(expr.range); - } - if (argument.isNumber()) { - return new BasicEvaluatedExpression() - .setBoolean(!argument.number) - .setRange(expr.range); - } - } else if (expr.operator === "~") { - const argument = this.evaluateExpression(expr.argument); - if (!argument) return; - if (!argument.isNumber()) return; - const res = new BasicEvaluatedExpression(); - res.setNumber(~argument.number); - res.setRange(expr.range); - return res; - } - }); - this.hooks.evaluateTypeof.for("undefined").tap("Parser", expr => { - return new BasicEvaluatedExpression() - .setString("undefined") - .setRange(expr.range); - }); - this.hooks.evaluate.for("Identifier").tap("Parser", expr => { - const name = this.scope.renames.get(expr.name) || expr.name; - if (!this.scope.definitions.has(expr.name)) { - const hook = this.hooks.evaluateIdentifier.get(name); - if (hook !== undefined) { - const result = hook.call(expr); - if (result) return result; - } - return new BasicEvaluatedExpression() - .setIdentifier(name) - .setRange(expr.range); - } else { - const hook = this.hooks.evaluateDefinedIdentifier.get(name); - if (hook !== undefined) { - return hook.call(expr); - } - } - }); - this.hooks.evaluate.for("ThisExpression").tap("Parser", expr => { - const name = this.scope.renames.get("this"); - if (name) { - const hook = this.hooks.evaluateIdentifier.get(name); - if (hook !== undefined) { - const result = hook.call(expr); - if (result) return result; - } - return new BasicEvaluatedExpression() - .setIdentifier(name) - .setRange(expr.range); - } - }); - this.hooks.evaluate.for("MemberExpression").tap("Parser", expression => { - let exprName = this.getNameForExpression(expression); - if (exprName) { - if (exprName.free) { - const hook = this.hooks.evaluateIdentifier.get(exprName.name); - if (hook !== undefined) { - const result = hook.call(expression); - if (result) return result; - } - return new BasicEvaluatedExpression() - .setIdentifier(exprName.name) - .setRange(expression.range); - } else { - const hook = this.hooks.evaluateDefinedIdentifier.get(exprName.name); - if (hook !== undefined) { - return hook.call(expression); - } - } - } - }); - this.hooks.evaluate.for("CallExpression").tap("Parser", expr => { - if (expr.callee.type !== "MemberExpression") return; - if ( - expr.callee.property.type !== - (expr.callee.computed ? "Literal" : "Identifier") - ) - return; - const param = this.evaluateExpression(expr.callee.object); - if (!param) return; - const property = expr.callee.property.name || expr.callee.property.value; - const hook = this.hooks.evaluateCallExpressionMember.get(property); - if (hook !== undefined) { - return hook.call(expr, param); + }; + process(rule.use); + } + + if (rule.rules) { + for (let i = 0; i < rule.rules.length; i++) { + this._run(data, rule.rules[i], result); } - }); - this.hooks.evaluateCallExpressionMember - .for("replace") - .tap("Parser", (expr, param) => { - if (!param.isString()) return; - if (expr.arguments.length !== 2) return; - let arg1 = this.evaluateExpression(expr.arguments[0]); - let arg2 = this.evaluateExpression(expr.arguments[1]); - if (!arg1.isString() && !arg1.isRegExp()) return; - arg1 = arg1.regExp || arg1.string; - if (!arg2.isString()) return; - arg2 = arg2.string; - return new BasicEvaluatedExpression() - .setString(param.string.replace(arg1, arg2)) - .setRange(expr.range); - }); - ["substr", "substring"].forEach(fn => { - this.hooks.evaluateCallExpressionMember - .for(fn) - .tap("Parser", (expr, param) => { - if (!param.isString()) return; - let arg1; - let result, - str = param.string; - switch (expr.arguments.length) { - case 1: - arg1 = this.evaluateExpression(expr.arguments[0]); - if (!arg1.isNumber()) return; - result = str[fn](arg1.number); - break; - case 2: { - arg1 = this.evaluateExpression(expr.arguments[0]); - const arg2 = this.evaluateExpression(expr.arguments[1]); - if (!arg1.isNumber()) return; - if (!arg2.isNumber()) return; - result = str[fn](arg1.number, arg2.number); - break; - } - default: - return; - } - return new BasicEvaluatedExpression() - .setString(result) - .setRange(expr.range); - }); - }); + } - /** - * @param {string} kind "cooked" | "raw" - * @param {TODO} templateLiteralExpr TemplateLiteral expr - * @returns {{quasis: BasicEvaluatedExpression[], parts: BasicEvaluatedExpression[]}} Simplified template - */ - const getSimplifiedTemplateResult = (kind, templateLiteralExpr) => { - const quasis = []; - const parts = []; + if (rule.oneOf) { + for (let i = 0; i < rule.oneOf.length; i++) { + if (this._run(data, rule.oneOf[i], result)) break; + } + } - for (let i = 0; i < templateLiteralExpr.quasis.length; i++) { - const quasiExpr = templateLiteralExpr.quasis[i]; - const quasi = quasiExpr.value[kind]; + return true; + } - if (i > 0) { - const prevExpr = parts[parts.length - 1]; - const expr = this.evaluateExpression( - templateLiteralExpr.expressions[i - 1] - ); - const exprAsString = expr.asString(); - if (typeof exprAsString === "string") { - // We can merge quasi + expr + quasi when expr - // is a const string + findOptionsByIdent(ident) { + const options = this.references[ident]; + if (!options) { + throw new Error("Can't find options with ident '" + ident + "'"); + } + return options; + } +}; - prevExpr.setString(prevExpr.string + exprAsString + quasi); - prevExpr.setRange([prevExpr.range[0], quasiExpr.range[1]]); - // We unset the expression as it doesn't match to a single expression - prevExpr.setExpression(undefined); - continue; - } - parts.push(expr); - } - const part = new BasicEvaluatedExpression() - .setString(quasi) - .setRange(quasiExpr.range) - .setExpression(quasiExpr); - quasis.push(part); - parts.push(part); - } - return { - quasis, - parts - }; - }; +/***/ }), - this.hooks.evaluate.for("TemplateLiteral").tap("Parser", node => { - const { quasis, parts } = getSimplifiedTemplateResult("cooked", node); - if (parts.length === 1) { - return parts[0].setRange(node.range); - } - return new BasicEvaluatedExpression() - .setTemplateString(quasis, parts, "cooked") - .setRange(node.range); - }); - this.hooks.evaluate.for("TaggedTemplateExpression").tap("Parser", node => { - if (this.evaluateExpression(node.tag).identifier !== "String.raw") return; - const { quasis, parts } = getSimplifiedTemplateResult("raw", node.quasi); - if (parts.length === 1) { - return parts[0].setRange(node.range); - } - return new BasicEvaluatedExpression() - .setTemplateString(quasis, parts, "raw") - .setRange(node.range); - }); +/***/ 44006: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - this.hooks.evaluateCallExpressionMember - .for("concat") - .tap("Parser", (expr, param) => { - if (!param.isString() && !param.isWrapped()) return; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - let stringSuffix = null; - let hasUnknownParams = false; - for (let i = expr.arguments.length - 1; i >= 0; i--) { - const argExpr = this.evaluateExpression(expr.arguments[i]); - if (!argExpr.isString() && !argExpr.isNumber()) { - hasUnknownParams = true; - break; - } - const value = argExpr.isString() - ? argExpr.string - : "" + argExpr.number; +const Template = __webpack_require__(96066); - const newString = value + (stringSuffix ? stringSuffix.string : ""); - const newRange = [ - argExpr.range[0], - (stringSuffix || argExpr).range[1] - ]; - stringSuffix = new BasicEvaluatedExpression() - .setString(newString) - .setRange(newRange); - } +/** @typedef {import("./Module")} Module */ - if (hasUnknownParams) { - const prefix = param.isString() ? param : param.prefix; - return new BasicEvaluatedExpression() - .setWrapped(prefix, stringSuffix) - .setRange(expr.range); - } else if (param.isWrapped()) { - const postfix = stringSuffix || param.postfix; - return new BasicEvaluatedExpression() - .setWrapped(param.prefix, postfix) - .setRange(expr.range); - } else { - const newString = - param.string + (stringSuffix ? stringSuffix.string : ""); - return new BasicEvaluatedExpression() - .setString(newString) - .setRange(expr.range); - } - }); - this.hooks.evaluateCallExpressionMember - .for("split") - .tap("Parser", (expr, param) => { - if (!param.isString()) return; - if (expr.arguments.length !== 1) return; - let result; - const arg = this.evaluateExpression(expr.arguments[0]); - if (arg.isString()) { - result = param.string.split(arg.string); - } else if (arg.isRegExp()) { - result = param.string.split(arg.regExp); - } else { - return; - } - return new BasicEvaluatedExpression() - .setArray(result) - .setRange(expr.range); - }); - this.hooks.evaluate.for("ConditionalExpression").tap("Parser", expr => { - const condition = this.evaluateExpression(expr.test); - const conditionValue = condition.asBool(); - let res; - if (conditionValue === undefined) { - const consequent = this.evaluateExpression(expr.consequent); - const alternate = this.evaluateExpression(expr.alternate); - if (!consequent || !alternate) return; - res = new BasicEvaluatedExpression(); - if (consequent.isConditional()) { - res.setOptions(consequent.options); - } else { - res.setOptions([consequent]); - } - if (alternate.isConditional()) { - res.addOptions(alternate.options); - } else { - res.addOptions([alternate]); - } - } else { - res = this.evaluateExpression( - conditionValue ? expr.consequent : expr.alternate - ); - } - res.setRange(expr.range); - return res; - }); - this.hooks.evaluate.for("ArrayExpression").tap("Parser", expr => { - const items = expr.elements.map(element => { - return element !== null && this.evaluateExpression(element); - }); - if (!items.every(Boolean)) return; - return new BasicEvaluatedExpression() - .setItems(items) - .setRange(expr.range); - }); +module.exports = class RuntimeTemplate { + constructor(outputOptions, requestShortener) { + this.outputOptions = outputOptions || {}; + this.requestShortener = requestShortener; } - getRenameIdentifier(expr) { - const result = this.evaluateExpression(expr); - if (result && result.isIdentifier()) { - return result.identifier; + /** + * Add a comment + * @param {object} options Information content of the comment + * @param {string=} options.request request string used originally + * @param {string=} options.chunkName name of the chunk referenced + * @param {string=} options.chunkReason reason information of the chunk + * @param {string=} options.message additional message + * @param {string=} options.exportName name of the export + * @returns {string} comment + */ + comment({ request, chunkName, chunkReason, message, exportName }) { + let content; + if (this.outputOptions.pathinfo) { + content = [message, request, chunkName, chunkReason] + .filter(Boolean) + .map(item => this.requestShortener.shorten(item)) + .join(" | "); + } else { + content = [message, chunkName, chunkReason] + .filter(Boolean) + .map(item => this.requestShortener.shorten(item)) + .join(" | "); + } + if (!content) return ""; + if (this.outputOptions.pathinfo) { + return Template.toComment(content) + " "; + } else { + return Template.toNormalComment(content) + " "; } } - walkClass(classy) { - if (classy.superClass) this.walkExpression(classy.superClass); - if (classy.body && classy.body.type === "ClassBody") { - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = false; - for (const methodDefinition of classy.body.body) { - if (methodDefinition.type === "MethodDefinition") { - this.walkMethodDefinition(methodDefinition); - } - } - this.scope.topLevelScope = wasTopLevel; - } + throwMissingModuleErrorFunction({ request }) { + const err = `Cannot find module '${request}'`; + return `function webpackMissingModule() { var e = new Error(${JSON.stringify( + err + )}); e.code = 'MODULE_NOT_FOUND'; throw e; }`; } - walkMethodDefinition(methodDefinition) { - if (methodDefinition.computed && methodDefinition.key) { - this.walkExpression(methodDefinition.key); - } - if (methodDefinition.value) { - this.walkExpression(methodDefinition.value); - } + missingModule({ request }) { + return `!(${this.throwMissingModuleErrorFunction({ request })}())`; } - // Prewalking iterates the scope for variable declarations - prewalkStatements(statements) { - for (let index = 0, len = statements.length; index < len; index++) { - const statement = statements[index]; - this.prewalkStatement(statement); - } + missingModuleStatement({ request }) { + return `${this.missingModule({ request })};\n`; } - // Block-Prewalking iterates the scope for block variable declarations - blockPrewalkStatements(statements) { - for (let index = 0, len = statements.length; index < len; index++) { - const statement = statements[index]; - this.blockPrewalkStatement(statement); - } + missingModulePromise({ request }) { + return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({ + request + })})`; } - // Walking iterates the statements and expressions and processes them - walkStatements(statements) { - for (let index = 0, len = statements.length; index < len; index++) { - const statement = statements[index]; - this.walkStatement(statement); + moduleId({ module, request }) { + if (!module) { + return this.missingModule({ + request + }); } + if (module.id === null) { + throw new Error( + `RuntimeTemplate.moduleId(): Module ${module.identifier()} has no id. This should not happen.` + ); + } + return `${this.comment({ request })}${JSON.stringify(module.id)}`; } - prewalkStatement(statement) { - switch (statement.type) { - case "BlockStatement": - this.prewalkBlockStatement(statement); - break; - case "DoWhileStatement": - this.prewalkDoWhileStatement(statement); - break; - case "ExportAllDeclaration": - this.prewalkExportAllDeclaration(statement); - break; - case "ExportDefaultDeclaration": - this.prewalkExportDefaultDeclaration(statement); - break; - case "ExportNamedDeclaration": - this.prewalkExportNamedDeclaration(statement); - break; - case "ForInStatement": - this.prewalkForInStatement(statement); - break; - case "ForOfStatement": - this.prewalkForOfStatement(statement); - break; - case "ForStatement": - this.prewalkForStatement(statement); - break; - case "FunctionDeclaration": - this.prewalkFunctionDeclaration(statement); - break; - case "IfStatement": - this.prewalkIfStatement(statement); - break; - case "ImportDeclaration": - this.prewalkImportDeclaration(statement); - break; - case "LabeledStatement": - this.prewalkLabeledStatement(statement); - break; - case "SwitchStatement": - this.prewalkSwitchStatement(statement); - break; - case "TryStatement": - this.prewalkTryStatement(statement); - break; - case "VariableDeclaration": - this.prewalkVariableDeclaration(statement); - break; - case "WhileStatement": - this.prewalkWhileStatement(statement); - break; - case "WithStatement": - this.prewalkWithStatement(statement); - break; + moduleRaw({ module, request }) { + if (!module) { + return this.missingModule({ + request + }); } + return `__webpack_require__(${this.moduleId({ module, request })})`; } - blockPrewalkStatement(statement) { - switch (statement.type) { - case "VariableDeclaration": - this.blockPrewalkVariableDeclaration(statement); - break; - case "ExportDefaultDeclaration": - this.blockPrewalkExportDefaultDeclaration(statement); - break; - case "ExportNamedDeclaration": - this.blockPrewalkExportNamedDeclaration(statement); - break; - case "ClassDeclaration": - this.blockPrewalkClassDeclaration(statement); - break; - } + moduleExports({ module, request }) { + return this.moduleRaw({ + module, + request + }); } - walkStatement(statement) { - if (this.hooks.statement.call(statement) !== undefined) return; - switch (statement.type) { - case "BlockStatement": - this.walkBlockStatement(statement); - break; - case "ClassDeclaration": - this.walkClassDeclaration(statement); - break; - case "DoWhileStatement": - this.walkDoWhileStatement(statement); - break; - case "ExportDefaultDeclaration": - this.walkExportDefaultDeclaration(statement); - break; - case "ExportNamedDeclaration": - this.walkExportNamedDeclaration(statement); - break; - case "ExpressionStatement": - this.walkExpressionStatement(statement); - break; - case "ForInStatement": - this.walkForInStatement(statement); - break; - case "ForOfStatement": - this.walkForOfStatement(statement); - break; - case "ForStatement": - this.walkForStatement(statement); - break; - case "FunctionDeclaration": - this.walkFunctionDeclaration(statement); - break; - case "IfStatement": - this.walkIfStatement(statement); - break; - case "LabeledStatement": - this.walkLabeledStatement(statement); - break; - case "ReturnStatement": - this.walkReturnStatement(statement); - break; - case "SwitchStatement": - this.walkSwitchStatement(statement); - break; - case "ThrowStatement": - this.walkThrowStatement(statement); - break; - case "TryStatement": - this.walkTryStatement(statement); - break; - case "VariableDeclaration": - this.walkVariableDeclaration(statement); - break; - case "WhileStatement": - this.walkWhileStatement(statement); - break; - case "WithStatement": - this.walkWithStatement(statement); - break; + moduleNamespace({ module, request, strict }) { + if (!module) { + return this.missingModule({ + request + }); + } + const moduleId = this.moduleId({ + module, + request + }); + const exportsType = module.buildMeta && module.buildMeta.exportsType; + if (exportsType === "namespace") { + const rawModule = this.moduleRaw({ + module, + request + }); + return rawModule; + } else if (exportsType === "named") { + return `__webpack_require__.t(${moduleId}, 3)`; + } else if (strict) { + return `__webpack_require__.t(${moduleId}, 1)`; + } else { + return `__webpack_require__.t(${moduleId}, 7)`; } } - // Real Statements - prewalkBlockStatement(statement) { - this.prewalkStatements(statement.body); - } + moduleNamespacePromise({ block, module, request, message, strict, weak }) { + if (!module) { + return this.missingModulePromise({ + request + }); + } + if (module.id === null) { + throw new Error( + `RuntimeTemplate.moduleNamespacePromise(): Module ${module.identifier()} has no id. This should not happen.` + ); + } + const promise = this.blockPromise({ + block, + message + }); - walkBlockStatement(statement) { - this.inBlockScope(() => { - const body = statement.body; - this.blockPrewalkStatements(body); - this.walkStatements(body); + let getModuleFunction; + let idExpr = JSON.stringify(module.id); + const comment = this.comment({ + request }); - } + let header = ""; + if (weak) { + if (idExpr.length > 8) { + // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"' + header += `var id = ${idExpr}; `; + idExpr = "id"; + } + header += `if(!__webpack_require__.m[${idExpr}]) { var e = new Error("Module '" + ${idExpr} + "' is not available (weak dependency)"); e.code = 'MODULE_NOT_FOUND'; throw e; } `; + } + const moduleId = this.moduleId({ + module, + request + }); + const exportsType = module.buildMeta && module.buildMeta.exportsType; + if (exportsType === "namespace") { + if (header) { + const rawModule = this.moduleRaw({ + module, + request + }); + getModuleFunction = `function() { ${header}return ${rawModule}; }`; + } else { + getModuleFunction = `__webpack_require__.bind(null, ${comment}${idExpr})`; + } + } else if (exportsType === "named") { + if (header) { + getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 3); }`; + } else { + getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 3)`; + } + } else if (strict) { + if (header) { + getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 1); }`; + } else { + getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 1)`; + } + } else { + if (header) { + getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 7); }`; + } else { + getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 7)`; + } + } - walkExpressionStatement(statement) { - this.walkExpression(statement.expression); + return `${promise || "Promise.resolve()"}.then(${getModuleFunction})`; } - prewalkIfStatement(statement) { - this.prewalkStatement(statement.consequent); - if (statement.alternate) { - this.prewalkStatement(statement.alternate); + /** + * + * @param {Object} options options object + * @param {boolean=} options.update whether a new variable should be created or the existing one updated + * @param {Module} options.module the module + * @param {string} options.request the request that should be printed as comment + * @param {string} options.importVar name of the import variable + * @param {Module} options.originModule module in which the statement is emitted + * @returns {string} the import statement + */ + importStatement({ update, module, request, importVar, originModule }) { + if (!module) { + return this.missingModuleStatement({ + request + }); } - } + const moduleId = this.moduleId({ + module, + request + }); + const optDeclaration = update ? "" : "var "; - walkIfStatement(statement) { - const result = this.hooks.statementIf.call(statement); - if (result === undefined) { - this.walkExpression(statement.test); - this.walkStatement(statement.consequent); - if (statement.alternate) { - this.walkStatement(statement.alternate); - } - } else { - if (result) { - this.walkStatement(statement.consequent); - } else if (statement.alternate) { - this.walkStatement(statement.alternate); + const exportsType = module.buildMeta && module.buildMeta.exportsType; + let content = `/* harmony import */ ${optDeclaration}${importVar} = __webpack_require__(${moduleId});\n`; + + if (!exportsType && !originModule.buildMeta.strictHarmonyModule) { + content += `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/__webpack_require__.n(${importVar});\n`; + } + if (exportsType === "named") { + if (Array.isArray(module.buildMeta.providedExports)) { + content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/__webpack_require__.t(${moduleId}, 1);\n`; + } else { + content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/__webpack_require__.t(${moduleId});\n`; } } + return content; } - prewalkLabeledStatement(statement) { - this.prewalkStatement(statement.body); - } + exportFromImport({ + module, + request, + exportName, + originModule, + asiSafe, + isCall, + callContext, + importVar + }) { + if (!module) { + return this.missingModule({ + request + }); + } + const exportsType = module.buildMeta && module.buildMeta.exportsType; - walkLabeledStatement(statement) { - const hook = this.hooks.label.get(statement.label.name); - if (hook !== undefined) { - const result = hook.call(statement); - if (result === true) return; + if (!exportsType) { + if (exportName === "default") { + if (!originModule.buildMeta.strictHarmonyModule) { + if (isCall) { + return `${importVar}_default()`; + } else if (asiSafe) { + return `(${importVar}_default())`; + } else { + return `${importVar}_default.a`; + } + } else { + return importVar; + } + } else if (originModule.buildMeta.strictHarmonyModule) { + if (exportName) { + return "/* non-default import from non-esm module */undefined"; + } else { + return `/*#__PURE__*/__webpack_require__.t(${importVar})`; + } + } } - this.walkStatement(statement.body); - } - prewalkWithStatement(statement) { - this.prewalkStatement(statement.body); - } + if (exportsType === "named") { + if (exportName === "default") { + return importVar; + } else if (!exportName) { + return `${importVar}_namespace`; + } + } - walkWithStatement(statement) { - this.walkExpression(statement.object); - this.walkStatement(statement.body); + if (exportName) { + const used = module.isUsed(exportName); + if (!used) { + const comment = Template.toNormalComment(`unused export ${exportName}`); + return `${comment} undefined`; + } + const comment = + used !== exportName ? Template.toNormalComment(exportName) + " " : ""; + const access = `${importVar}[${comment}${JSON.stringify(used)}]`; + if (isCall) { + if (callContext === false && asiSafe) { + return `(0,${access})`; + } else if (callContext === false) { + return `Object(${access})`; + } + } + return access; + } else { + return importVar; + } } - prewalkSwitchStatement(statement) { - this.prewalkSwitchCases(statement.cases); + blockPromise({ block, message }) { + if (!block || !block.chunkGroup || block.chunkGroup.chunks.length === 0) { + const comment = this.comment({ + message + }); + return `Promise.resolve(${comment.trim()})`; + } + const chunks = block.chunkGroup.chunks.filter( + chunk => !chunk.hasRuntime() && chunk.id !== null + ); + const comment = this.comment({ + message, + chunkName: block.chunkName, + chunkReason: block.chunkReason + }); + if (chunks.length === 1) { + const chunkId = JSON.stringify(chunks[0].id); + return `__webpack_require__.e(${comment}${chunkId})`; + } else if (chunks.length > 0) { + const requireChunkId = chunk => + `__webpack_require__.e(${JSON.stringify(chunk.id)})`; + return `Promise.all(${comment.trim()}[${chunks + .map(requireChunkId) + .join(", ")}])`; + } else { + return `Promise.resolve(${comment.trim()})`; + } } - walkSwitchStatement(statement) { - this.walkExpression(statement.discriminant); - this.walkSwitchCases(statement.cases); + onError() { + return "__webpack_require__.oe"; } - walkTerminatingStatement(statement) { - if (statement.argument) this.walkExpression(statement.argument); + defineEsModuleFlagStatement({ exportsArgument }) { + return `__webpack_require__.r(${exportsArgument});\n`; } +}; - walkReturnStatement(statement) { - this.walkTerminatingStatement(statement); - } - walkThrowStatement(statement) { - this.walkTerminatingStatement(statement); - } +/***/ }), - prewalkTryStatement(statement) { - this.prewalkStatement(statement.block); - } +/***/ 37098: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - walkTryStatement(statement) { - if (this.scope.inTry) { - this.walkStatement(statement.block); - } else { - this.scope.inTry = true; - this.walkStatement(statement.block); - this.scope.inTry = false; - } - if (statement.handler) this.walkCatchClause(statement.handler); - if (statement.finalizer) this.walkStatement(statement.finalizer); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - prewalkWhileStatement(statement) { - this.prewalkStatement(statement.body); - } - walkWhileStatement(statement) { - this.walkExpression(statement.test); - this.walkStatement(statement.body); - } +const { ConcatSource } = __webpack_require__(53665); - prewalkDoWhileStatement(statement) { - this.prewalkStatement(statement.body); - } +/** @typedef {import("./Compilation")} Compilation */ - walkDoWhileStatement(statement) { - this.walkStatement(statement.body); - this.walkExpression(statement.test); +class SetVarMainTemplatePlugin { + /** + * @param {string} varExpression the accessor where the library is exported + * @param {boolean} copyObject specify copying the exports + */ + constructor(varExpression, copyObject) { + /** @type {string} */ + this.varExpression = varExpression; + /** @type {boolean} */ + this.copyObject = copyObject; } - prewalkForStatement(statement) { - if (statement.init) { - if (statement.init.type === "VariableDeclaration") { - this.prewalkStatement(statement.init); - } - } - this.prewalkStatement(statement.body); - } + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; - walkForStatement(statement) { - this.inBlockScope(() => { - if (statement.init) { - if (statement.init.type === "VariableDeclaration") { - this.blockPrewalkVariableDeclaration(statement.init); - this.walkStatement(statement.init); - } else { - this.walkExpression(statement.init); - } - } - if (statement.test) { - this.walkExpression(statement.test); - } - if (statement.update) { - this.walkExpression(statement.update); - } - const body = statement.body; - if (body.type === "BlockStatement") { - // no need to add additional scope - this.blockPrewalkStatements(body.body); - this.walkStatements(body.body); + const onRenderWithEntry = (source, chunk, hash) => { + const varExpression = mainTemplate.getAssetPath(this.varExpression, { + hash, + chunk + }); + if (this.copyObject) { + return new ConcatSource( + `(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `, + source, + "))" + ); } else { - this.walkStatement(body); + const prefix = `${varExpression} =\n`; + return new ConcatSource(prefix, source); } - }); - } + }; - prewalkForInStatement(statement) { - if (statement.left.type === "VariableDeclaration") { - this.prewalkVariableDeclaration(statement.left); + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "SetVarMainTemplatePlugin", + onRenderWithEntry + ); } - this.prewalkStatement(statement.body); - } - walkForInStatement(statement) { - this.inBlockScope(() => { - if (statement.left.type === "VariableDeclaration") { - this.blockPrewalkVariableDeclaration(statement.left); - this.walkVariableDeclaration(statement.left); - } else { - this.walkPattern(statement.left); - } - this.walkExpression(statement.right); - const body = statement.body; - if (body.type === "BlockStatement") { - // no need to add additional scope - this.blockPrewalkStatements(body.body); - this.walkStatements(body.body); - } else { - this.walkStatement(body); + mainTemplate.hooks.globalHashPaths.tap( + "SetVarMainTemplatePlugin", + paths => { + if (this.varExpression) paths.push(this.varExpression); + return paths; } + ); + mainTemplate.hooks.hash.tap("SetVarMainTemplatePlugin", hash => { + hash.update("set var"); + hash.update(`${this.varExpression}`); + hash.update(`${this.copyObject}`); }); } +} - prewalkForOfStatement(statement) { - if (statement.left.type === "VariableDeclaration") { - this.prewalkVariableDeclaration(statement.left); - } - this.prewalkStatement(statement.body); - } +module.exports = SetVarMainTemplatePlugin; - walkForOfStatement(statement) { - this.inBlockScope(() => { - if (statement.left.type === "VariableDeclaration") { - this.blockPrewalkVariableDeclaration(statement.left); - this.walkVariableDeclaration(statement.left); - } else { - this.walkPattern(statement.left); - } - this.walkExpression(statement.right); - const body = statement.body; - if (body.type === "BlockStatement") { - // no need to add additional scope - this.blockPrewalkStatements(body.body); - this.walkStatements(body.body); - } else { - this.walkStatement(body); - } - }); - } - // Declarations - prewalkFunctionDeclaration(statement) { - if (statement.id) { - this.scope.renames.set(statement.id.name, null); - this.scope.definitions.add(statement.id.name); - } - } +/***/ }), - walkFunctionDeclaration(statement) { - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = false; - this.inFunctionScope(true, statement.params, () => { - for (const param of statement.params) { - this.walkPattern(param); - } - if (statement.body.type === "BlockStatement") { - this.detectMode(statement.body.body); - this.prewalkStatement(statement.body); - this.walkStatement(statement.body); - } else { - this.walkExpression(statement.body); - } - }); - this.scope.topLevelScope = wasTopLevel; - } +/***/ 19070: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - prewalkImportDeclaration(statement) { - const source = statement.source.value; - this.hooks.import.call(statement, source); - for (const specifier of statement.specifiers) { - const name = specifier.local.name; - this.scope.renames.set(name, null); - this.scope.definitions.add(name); - switch (specifier.type) { - case "ImportDefaultSpecifier": - this.hooks.importSpecifier.call(statement, source, "default", name); - break; - case "ImportSpecifier": - this.hooks.importSpecifier.call( - statement, - source, - specifier.imported.name, - name - ); - break; - case "ImportNamespaceSpecifier": - this.hooks.importSpecifier.call(statement, source, null, name); - break; - } - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - enterDeclaration(declaration, onIdent) { - switch (declaration.type) { - case "VariableDeclaration": - for (const declarator of declaration.declarations) { - switch (declarator.type) { - case "VariableDeclarator": { - this.enterPattern(declarator.id, onIdent); - break; - } - } - } - break; - case "FunctionDeclaration": - this.enterPattern(declaration.id, onIdent); - break; - case "ClassDeclaration": - this.enterPattern(declaration.id, onIdent); - break; - } - } +const SingleEntryDependency = __webpack_require__(84828); - blockPrewalkExportNamedDeclaration(statement) { - if (statement.declaration) { - this.blockPrewalkStatement(statement.declaration); - } +/** @typedef {import("./Compiler")} Compiler */ + +class SingleEntryPlugin { + /** + * An entry plugin which will handle + * creation of the SingleEntryDependency + * + * @param {string} context context path + * @param {string} entry entry path + * @param {string} name entry key name + */ + constructor(context, entry, name) { + this.context = context; + this.entry = entry; + this.name = name; } - prewalkExportNamedDeclaration(statement) { - let source; - if (statement.source) { - source = statement.source.value; - this.hooks.exportImport.call(statement, source); - } else { - this.hooks.export.call(statement); - } - if (statement.declaration) { - if ( - !this.hooks.exportDeclaration.call(statement, statement.declaration) - ) { - this.prewalkStatement(statement.declaration); - let index = 0; - this.enterDeclaration(statement.declaration, def => { - this.hooks.exportSpecifier.call(statement, def, def, index++); - }); - } - } - if (statement.specifiers) { - for ( - let specifierIndex = 0; - specifierIndex < statement.specifiers.length; - specifierIndex++ - ) { - const specifier = statement.specifiers[specifierIndex]; - switch (specifier.type) { - case "ExportSpecifier": { - const name = specifier.exported.name; - if (source) { - this.hooks.exportImportSpecifier.call( - statement, - source, - specifier.local.name, - name, - specifierIndex - ); - } else { - this.hooks.exportSpecifier.call( - statement, - specifier.local.name, - name, - specifierIndex - ); - } - break; - } - } + /** + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap( + "SingleEntryPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + SingleEntryDependency, + normalModuleFactory + ); } - } - } + ); - walkExportNamedDeclaration(statement) { - if (statement.declaration) { - this.walkStatement(statement.declaration); - } - } + compiler.hooks.make.tapAsync( + "SingleEntryPlugin", + (compilation, callback) => { + const { entry, name, context } = this; - blockPrewalkExportDefaultDeclaration(statement) { - if (statement.declaration.type === "ClassDeclaration") { - this.blockPrewalkClassDeclaration(statement.declaration); - } + const dep = SingleEntryPlugin.createDependency(entry, name); + compilation.addEntry(context, dep, name, callback); + } + ); } - prewalkExportDefaultDeclaration(statement) { - this.prewalkStatement(statement.declaration); - if ( - statement.declaration.id && - statement.declaration.type !== "FunctionExpression" && - statement.declaration.type !== "ClassExpression" - ) { - this.hooks.exportSpecifier.call( - statement, - statement.declaration.id.name, - "default" - ); - } + /** + * @param {string} entry entry request + * @param {string} name entry name + * @returns {SingleEntryDependency} the dependency + */ + static createDependency(entry, name) { + const dep = new SingleEntryDependency(entry); + dep.loc = { name }; + return dep; } +} - walkExportDefaultDeclaration(statement) { - this.hooks.export.call(statement); - if ( - statement.declaration.id && - statement.declaration.type !== "FunctionExpression" && - statement.declaration.type !== "ClassExpression" - ) { - if ( - !this.hooks.exportDeclaration.call(statement, statement.declaration) - ) { - this.walkStatement(statement.declaration); - } - } else { - // Acorn parses `export default function() {}` as `FunctionDeclaration` and - // `export default class {}` as `ClassDeclaration`, both with `id = null`. - // These nodes must be treated as expressions. - if (statement.declaration.type === "FunctionDeclaration") { - this.walkFunctionDeclaration(statement.declaration); - } else if (statement.declaration.type === "ClassDeclaration") { - this.walkClassDeclaration(statement.declaration); - } else { - this.walkExpression(statement.declaration); - } - if (!this.hooks.exportExpression.call(statement, statement.declaration)) { - this.hooks.exportSpecifier.call( - statement, - statement.declaration, - "default" - ); - } - } - } +module.exports = SingleEntryPlugin; - prewalkExportAllDeclaration(statement) { - const source = statement.source.value; - this.hooks.exportImport.call(statement, source); - this.hooks.exportImportSpecifier.call(statement, source, null, null, 0); - } - prewalkVariableDeclaration(statement) { - if (statement.kind !== "var") return; - this._prewalkVariableDeclaration(statement, this.hooks.varDeclarationVar); - } +/***/ }), - blockPrewalkVariableDeclaration(statement) { - if (statement.kind === "var") return; - const hookMap = - statement.kind === "const" - ? this.hooks.varDeclarationConst - : this.hooks.varDeclarationLet; - this._prewalkVariableDeclaration(statement, hookMap); - } +/***/ 12496: +/***/ (function(__unused_webpack_module, exports) { - _prewalkVariableDeclaration(statement, hookMap) { - for (const declarator of statement.declarations) { - switch (declarator.type) { - case "VariableDeclarator": { - this.enterPattern(declarator.id, (name, decl) => { - let hook = hookMap.get(name); - if (hook === undefined || !hook.call(decl)) { - hook = this.hooks.varDeclaration.get(name); - if (hook === undefined || !hook.call(decl)) { - this.scope.renames.set(name, null); - this.scope.definitions.add(name); - } - } - }); - break; - } - } - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Sean Larkin @thelarkinn +*/ - walkVariableDeclaration(statement) { - for (const declarator of statement.declarations) { - switch (declarator.type) { - case "VariableDeclarator": { - const renameIdentifier = - declarator.init && this.getRenameIdentifier(declarator.init); - if (renameIdentifier && declarator.id.type === "Identifier") { - const hook = this.hooks.canRename.get(renameIdentifier); - if (hook !== undefined && hook.call(declarator.init)) { - // renaming with "var a = b;" - const hook = this.hooks.rename.get(renameIdentifier); - if (hook === undefined || !hook.call(declarator.init)) { - this.scope.renames.set( - declarator.id.name, - this.scope.renames.get(renameIdentifier) || renameIdentifier - ); - this.scope.definitions.delete(declarator.id.name); - } - break; - } - } - this.walkPattern(declarator.id); - if (declarator.init) this.walkExpression(declarator.init); - break; - } - } - } - } - blockPrewalkClassDeclaration(statement) { - if (statement.id) { - this.scope.renames.set(statement.id.name, null); - this.scope.definitions.add(statement.id.name); - } - } +const SizeFormatHelpers = exports; - walkClassDeclaration(statement) { - this.walkClass(statement); +SizeFormatHelpers.formatSize = size => { + if (typeof size !== "number" || Number.isNaN(size) === true) { + return "unknown size"; } - prewalkSwitchCases(switchCases) { - for (let index = 0, len = switchCases.length; index < len; index++) { - const switchCase = switchCases[index]; - this.prewalkStatements(switchCase.consequent); - } + if (size <= 0) { + return "0 bytes"; } - walkSwitchCases(switchCases) { - for (let index = 0, len = switchCases.length; index < len; index++) { - const switchCase = switchCases[index]; + const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; + const index = Math.floor(Math.log(size) / Math.log(1024)); - if (switchCase.test) { - this.walkExpression(switchCase.test); - } - this.walkStatements(switchCase.consequent); - } - } + return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${ + abbreviations[index] + }`; +}; - walkCatchClause(catchClause) { - this.inBlockScope(() => { - // Error binding is optional in catch clause since ECMAScript 2019 - if (catchClause.param !== null) { - this.enterPattern(catchClause.param, ident => { - this.scope.renames.set(ident, null); - this.scope.definitions.add(ident); - }); - this.walkPattern(catchClause.param); - } - this.prewalkStatement(catchClause.body); - this.walkStatement(catchClause.body); - }); - } - walkPattern(pattern) { - switch (pattern.type) { - case "ArrayPattern": - this.walkArrayPattern(pattern); - break; - case "AssignmentPattern": - this.walkAssignmentPattern(pattern); - break; - case "MemberExpression": - this.walkMemberExpression(pattern); - break; - case "ObjectPattern": - this.walkObjectPattern(pattern); - break; - case "RestElement": - this.walkRestElement(pattern); - break; - } - } +/***/ }), - walkAssignmentPattern(pattern) { - this.walkExpression(pattern.right); - this.walkPattern(pattern.left); - } +/***/ 24113: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - walkObjectPattern(pattern) { - for (let i = 0, len = pattern.properties.length; i < len; i++) { - const prop = pattern.properties[i]; - if (prop) { - if (prop.computed) this.walkExpression(prop.key); - if (prop.value) this.walkPattern(prop.value); - } - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - walkArrayPattern(pattern) { - for (let i = 0, len = pattern.elements.length; i < len; i++) { - const element = pattern.elements[i]; - if (element) this.walkPattern(element); - } - } - walkRestElement(pattern) { - this.walkPattern(pattern.argument); - } +const ModuleFilenameHelpers = __webpack_require__(71474); - walkExpressions(expressions) { - for (const expression of expressions) { - if (expression) { - this.walkExpression(expression); - } - } +class SourceMapDevToolModuleOptionsPlugin { + constructor(options) { + this.options = options; } - walkExpression(expression) { - switch (expression.type) { - case "ArrayExpression": - this.walkArrayExpression(expression); - break; - case "ArrowFunctionExpression": - this.walkArrowFunctionExpression(expression); - break; - case "AssignmentExpression": - this.walkAssignmentExpression(expression); - break; - case "AwaitExpression": - this.walkAwaitExpression(expression); - break; - case "BinaryExpression": - this.walkBinaryExpression(expression); - break; - case "CallExpression": - this.walkCallExpression(expression); - break; - case "ClassExpression": - this.walkClassExpression(expression); - break; - case "ConditionalExpression": - this.walkConditionalExpression(expression); - break; - case "FunctionExpression": - this.walkFunctionExpression(expression); - break; - case "Identifier": - this.walkIdentifier(expression); - break; - case "LogicalExpression": - this.walkLogicalExpression(expression); - break; - case "MemberExpression": - this.walkMemberExpression(expression); - break; - case "NewExpression": - this.walkNewExpression(expression); - break; - case "ObjectExpression": - this.walkObjectExpression(expression); - break; - case "SequenceExpression": - this.walkSequenceExpression(expression); - break; - case "SpreadElement": - this.walkSpreadElement(expression); - break; - case "TaggedTemplateExpression": - this.walkTaggedTemplateExpression(expression); - break; - case "TemplateLiteral": - this.walkTemplateLiteral(expression); - break; - case "ThisExpression": - this.walkThisExpression(expression); - break; - case "UnaryExpression": - this.walkUnaryExpression(expression); - break; - case "UpdateExpression": - this.walkUpdateExpression(expression); - break; - case "YieldExpression": - this.walkYieldExpression(expression); - break; + apply(compilation) { + const options = this.options; + if (options.module !== false) { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.useSourceMap = true; + } + ); + } + if (options.lineToLine === true) { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + module.lineToLine = true; + } + ); + } else if (options.lineToLine) { + compilation.hooks.buildModule.tap( + "SourceMapDevToolModuleOptionsPlugin", + module => { + if (!module.resource) return; + let resourcePath = module.resource; + const idx = resourcePath.indexOf("?"); + if (idx >= 0) resourcePath = resourcePath.substr(0, idx); + module.lineToLine = ModuleFilenameHelpers.matchObject( + options.lineToLine, + resourcePath + ); + } + ); } } +} - walkAwaitExpression(expression) { - this.walkExpression(expression.argument); - } +module.exports = SourceMapDevToolModuleOptionsPlugin; - walkArrayExpression(expression) { - if (expression.elements) { - this.walkExpressions(expression.elements); - } - } - walkSpreadElement(expression) { - if (expression.argument) { - this.walkExpression(expression.argument); - } - } +/***/ }), - walkObjectExpression(expression) { - for ( - let propIndex = 0, len = expression.properties.length; - propIndex < len; - propIndex++ - ) { - const prop = expression.properties[propIndex]; - if (prop.type === "SpreadElement") { - this.walkExpression(prop.argument); - continue; - } - if (prop.computed) { - this.walkExpression(prop.key); - } - if (prop.shorthand) { - this.scope.inShorthand = true; - } - this.walkExpression(prop.value); - if (prop.shorthand) { - this.scope.inShorthand = false; - } - } - } +/***/ 11851: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - walkFunctionExpression(expression) { - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = false; - const scopeParams = expression.params; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Add function name in scope for recursive calls - if (expression.id) { - scopeParams.push(expression.id.name); - } - this.inFunctionScope(true, scopeParams, () => { - for (const param of expression.params) { - this.walkPattern(param); - } - if (expression.body.type === "BlockStatement") { - this.detectMode(expression.body.body); - this.prewalkStatement(expression.body); - this.walkStatement(expression.body); - } else { - this.walkExpression(expression.body); - } - }); - this.scope.topLevelScope = wasTopLevel; - } +const path = __webpack_require__(85622); +const { ConcatSource, RawSource } = __webpack_require__(53665); +const ModuleFilenameHelpers = __webpack_require__(71474); +const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(24113); +const createHash = __webpack_require__(15660); +const { absolutify } = __webpack_require__(94658); - walkArrowFunctionExpression(expression) { - this.inFunctionScope(false, expression.params, () => { - for (const param of expression.params) { - this.walkPattern(param); - } - if (expression.body.type === "BlockStatement") { - this.detectMode(expression.body.body); - this.prewalkStatement(expression.body); - this.walkStatement(expression.body); - } else { - this.walkExpression(expression.body); - } - }); - } +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(7368); - walkSequenceExpression(expression) { - if (expression.expressions) this.walkExpressions(expression.expressions); - } +/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("source-map").RawSourceMap} SourceMap */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./Compiler")} Compiler */ +/** @typedef {import("./Compilation")} SourceMapDefinition */ - walkUpdateExpression(expression) { - this.walkExpression(expression.argument); - } +/** + * @typedef {object} SourceMapTask + * @property {Source} asset + * @property {Array} [modules] + * @property {string} source + * @property {string} file + * @property {SourceMap} sourceMap + * @property {Chunk} chunk + */ - walkUnaryExpression(expression) { - if (expression.operator === "typeof") { - const exprName = this.getNameForExpression(expression.argument); - if (exprName && exprName.free) { - const hook = this.hooks.typeof.get(exprName.name); - if (hook !== undefined) { - const result = hook.call(expression); - if (result === true) return; - } - } - } - this.walkExpression(expression.argument); - } +/** + * @param {string} name file path + * @returns {string} file name + */ +const basename = name => { + if (!name.includes("/")) return name; + return name.substr(name.lastIndexOf("/") + 1); +}; - walkLeftRightExpression(expression) { - this.walkExpression(expression.left); - this.walkExpression(expression.right); - } +/** + * @type {WeakMap} + */ +const assetsCache = new WeakMap(); - walkBinaryExpression(expression) { - this.walkLeftRightExpression(expression); +/** + * Creating {@link SourceMapTask} for given file + * @param {string} file current compiled file + * @param {Source} asset the asset + * @param {Chunk} chunk related chunk + * @param {SourceMapDevToolPluginOptions} options source map options + * @param {Compilation} compilation compilation instance + * @returns {SourceMapTask | undefined} created task instance or `undefined` + */ +const getTaskForFile = (file, asset, chunk, options, compilation) => { + let source, sourceMap; + /** + * Check if asset can build source map + */ + if (asset.sourceAndMap) { + const sourceAndMap = asset.sourceAndMap(options); + sourceMap = sourceAndMap.map; + source = sourceAndMap.source; + } else { + sourceMap = asset.map(options); + source = asset.source(); } - - walkLogicalExpression(expression) { - const result = this.hooks.expressionLogicalOperator.call(expression); - if (result === undefined) { - this.walkLeftRightExpression(expression); - } else { - if (result) { - this.walkExpression(expression.right); - } + if (!sourceMap || typeof source !== "string") return; + const context = compilation.options.context; + const modules = sourceMap.sources.map(source => { + if (source.startsWith("webpack://")) { + source = absolutify(context, source.slice(10)); } - } + const module = compilation.findModule(source); + return module || source; + }); - walkAssignmentExpression(expression) { - const renameIdentifier = this.getRenameIdentifier(expression.right); - if (expression.left.type === "Identifier" && renameIdentifier) { - const hook = this.hooks.canRename.get(renameIdentifier); - if (hook !== undefined && hook.call(expression.right)) { - // renaming "a = b;" - const hook = this.hooks.rename.get(renameIdentifier); - if (hook === undefined || !hook.call(expression.right)) { - this.scope.renames.set(expression.left.name, renameIdentifier); - this.scope.definitions.delete(expression.left.name); - } - return; - } - } - if (expression.left.type === "Identifier") { - const assignedHook = this.hooks.assigned.get(expression.left.name); - if (assignedHook === undefined || !assignedHook.call(expression)) { - this.walkExpression(expression.right); - } - this.scope.renames.set(expression.left.name, null); - const assignHook = this.hooks.assign.get(expression.left.name); - if (assignHook === undefined || !assignHook.call(expression)) { - this.walkExpression(expression.left); - } - return; - } - this.walkExpression(expression.right); - this.walkPattern(expression.left); - this.enterPattern(expression.left, (name, decl) => { - this.scope.renames.set(name, null); - }); - } + return { + chunk, + file, + asset, + source, + sourceMap, + modules + }; +}; - walkConditionalExpression(expression) { - const result = this.hooks.expressionConditionalOperator.call(expression); - if (result === undefined) { - this.walkExpression(expression.test); - this.walkExpression(expression.consequent); - if (expression.alternate) { - this.walkExpression(expression.alternate); - } - } else { - if (result) { - this.walkExpression(expression.consequent); - } else if (expression.alternate) { - this.walkExpression(expression.alternate); - } +class SourceMapDevToolPlugin { + /** + * @param {SourceMapDevToolPluginOptions} [options] options object + * @throws {Error} throws error, if got more than 1 arguments + */ + constructor(options) { + if (arguments.length > 1) { + throw new Error( + "SourceMapDevToolPlugin only takes one argument (pass an options object)" + ); } - } - walkNewExpression(expression) { - const callee = this.evaluateExpression(expression.callee); - if (callee.isIdentifier()) { - const hook = this.hooks.new.get(callee.identifier); - if (hook !== undefined) { - const result = hook.call(expression); - if (result === true) { - return; - } - } - } + if (!options) options = {}; - this.walkExpression(expression.callee); - if (expression.arguments) { - this.walkExpressions(expression.arguments); - } - } + validateOptions(schema, options, "SourceMap DevTool Plugin"); - walkYieldExpression(expression) { - if (expression.argument) { - this.walkExpression(expression.argument); - } + /** @type {string | false} */ + this.sourceMapFilename = options.filename; + /** @type {string | false} */ + this.sourceMappingURLComment = + options.append === false + ? false + : options.append || "\n//# sourceMappingURL=[url]"; + /** @type {string | Function} */ + this.moduleFilenameTemplate = + options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]"; + /** @type {string | Function} */ + this.fallbackModuleFilenameTemplate = + options.fallbackModuleFilenameTemplate || + "webpack://[namespace]/[resourcePath]?[hash]"; + /** @type {string} */ + this.namespace = options.namespace || ""; + /** @type {SourceMapDevToolPluginOptions} */ + this.options = options; } - walkTemplateLiteral(expression) { - if (expression.expressions) { - this.walkExpressions(expression.expressions); - } - } + /** + * Apply compiler + * @param {Compiler} compiler compiler instance + * @returns {void} + */ + apply(compiler) { + const sourceMapFilename = this.sourceMapFilename; + const sourceMappingURLComment = this.sourceMappingURLComment; + const moduleFilenameTemplate = this.moduleFilenameTemplate; + const namespace = this.namespace; + const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; + const requestShortener = compiler.requestShortener; + const options = this.options; + options.test = options.test || /\.(m?js|css)($|\?)/i; - walkTaggedTemplateExpression(expression) { - if (expression.tag) { - this.walkExpression(expression.tag); - } - if (expression.quasi && expression.quasi.expressions) { - this.walkExpressions(expression.quasi.expressions); - } - } + const matchObject = ModuleFilenameHelpers.matchObject.bind( + undefined, + options + ); - walkClassExpression(expression) { - this.walkClass(expression); - } + compiler.hooks.compilation.tap("SourceMapDevToolPlugin", compilation => { + new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); - _walkIIFE(functionExpression, options, currentThis) { - const renameArgOrThis = argOrThis => { - const renameIdentifier = this.getRenameIdentifier(argOrThis); - if (renameIdentifier) { - const hook = this.hooks.canRename.get(renameIdentifier); - if (hook !== undefined && hook.call(argOrThis)) { - const hook = this.hooks.rename.get(renameIdentifier); - if (hook === undefined || !hook.call(argOrThis)) { - return renameIdentifier; + compilation.hooks.afterOptimizeChunkAssets.tap( + /** @type {TODO} */ + ({ name: "SourceMapDevToolPlugin", context: true }), + /** + * @param {object} context hook context + * @param {Array} chunks resulted chunks + * @throws {Error} throws error, if `sourceMapFilename === false && sourceMappingURLComment === false` + * @returns {void} + */ + (context, chunks) => { + /** @type {Map} */ + const moduleToSourceNameMapping = new Map(); + /** + * @type {Function} + * @returns {void} + */ + const reportProgress = + context && context.reportProgress + ? context.reportProgress + : () => {}; + + const files = []; + for (const chunk of chunks) { + for (const file of chunk.files) { + if (matchObject(file)) { + files.push({ + file, + chunk + }); + } + } } - } - } - this.walkExpression(argOrThis); - }; - const params = functionExpression.params; - const renameThis = currentThis ? renameArgOrThis(currentThis) : null; - const args = options.map(renameArgOrThis); - const wasTopLevel = this.scope.topLevelScope; - this.scope.topLevelScope = false; - const scopeParams = params.filter((identifier, idx) => !args[idx]); - // Add function name in scope for recursive calls - if (functionExpression.id) { - scopeParams.push(functionExpression.id.name); - } + reportProgress(0.0); + const tasks = []; + files.forEach(({ file, chunk }, idx) => { + const asset = compilation.getAsset(file).source; + const cache = assetsCache.get(asset); + /** + * If presented in cache, reassigns assets. Cache assets already have source maps. + */ + if (cache && cache.file === file) { + for (const cachedFile in cache.assets) { + if (cachedFile === file) { + compilation.updateAsset(cachedFile, cache.assets[cachedFile]); + } else { + compilation.emitAsset(cachedFile, cache.assets[cachedFile], { + development: true + }); + } + /** + * Add file to chunk, if not presented there + */ + if (cachedFile !== file) chunk.files.push(cachedFile); + } + return; + } - this.inFunctionScope(true, scopeParams, () => { - if (renameThis) { - this.scope.renames.set("this", renameThis); - } - for (let i = 0; i < args.length; i++) { - const param = args[i]; - if (!param) continue; - if (!params[i] || params[i].type !== "Identifier") continue; - this.scope.renames.set(params[i].name, param); - } - if (functionExpression.body.type === "BlockStatement") { - this.detectMode(functionExpression.body.body); - this.prewalkStatement(functionExpression.body); - this.walkStatement(functionExpression.body); - } else { - this.walkExpression(functionExpression.body); - } - }); - this.scope.topLevelScope = wasTopLevel; - } + reportProgress( + (0.5 * idx) / files.length, + file, + "generate SourceMap" + ); + /** @type {SourceMapTask | undefined} */ + const task = getTaskForFile( + file, + asset, + chunk, + options, + compilation + ); - walkCallExpression(expression) { - if ( - expression.callee.type === "MemberExpression" && - expression.callee.object.type === "FunctionExpression" && - !expression.callee.computed && - (expression.callee.property.name === "call" || - expression.callee.property.name === "bind") && - expression.arguments.length > 0 - ) { - // (function(…) { }.call/bind(?, …)) - this._walkIIFE( - expression.callee.object, - expression.arguments.slice(1), - expression.arguments[0] - ); - } else if (expression.callee.type === "FunctionExpression") { - // (function(…) { }(…)) - this._walkIIFE(expression.callee, expression.arguments, null); - } else if (expression.callee.type === "Import") { - let result = this.hooks.importCall.call(expression); - if (result === true) return; + if (task) { + const modules = task.modules; - if (expression.arguments) this.walkExpressions(expression.arguments); - } else { - const callee = this.evaluateExpression(expression.callee); - if (callee.isIdentifier()) { - const callHook = this.hooks.call.get(callee.identifier); - if (callHook !== undefined) { - let result = callHook.call(expression); - if (result === true) return; - } - let identifier = callee.identifier.replace(/\.[^.]+$/, ""); - if (identifier !== callee.identifier) { - const callAnyHook = this.hooks.callAnyMember.get(identifier); - if (callAnyHook !== undefined) { - let result = callAnyHook.call(expression); - if (result === true) return; - } - } - } + for (let idx = 0; idx < modules.length; idx++) { + const module = modules[idx]; + if (!moduleToSourceNameMapping.get(module)) { + moduleToSourceNameMapping.set( + module, + ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: moduleFilenameTemplate, + namespace: namespace + }, + requestShortener + ) + ); + } + } - if (expression.callee) this.walkExpression(expression.callee); - if (expression.arguments) this.walkExpressions(expression.arguments); - } - } + tasks.push(task); + } + }); - walkMemberExpression(expression) { - const exprName = this.getNameForExpression(expression); - if (exprName && exprName.free) { - const expressionHook = this.hooks.expression.get(exprName.name); - if (expressionHook !== undefined) { - const result = expressionHook.call(expression); - if (result === true) return; - } - const expressionAnyMemberHook = this.hooks.expressionAnyMember.get( - exprName.nameGeneral - ); - if (expressionAnyMemberHook !== undefined) { - const result = expressionAnyMemberHook.call(expression); - if (result === true) return; - } - } - this.walkExpression(expression.object); - if (expression.computed === true) this.walkExpression(expression.property); - } + reportProgress(0.5, "resolve sources"); + /** @type {Set} */ + const usedNamesSet = new Set(moduleToSourceNameMapping.values()); + /** @type {Set} */ + const conflictDetectionSet = new Set(); - walkThisExpression(expression) { - const expressionHook = this.hooks.expression.get("this"); - if (expressionHook !== undefined) { - expressionHook.call(expression); - } - } + /** + * all modules in defined order (longest identifier first) + * @type {Array} + */ + const allModules = Array.from(moduleToSourceNameMapping.keys()).sort( + (a, b) => { + const ai = typeof a === "string" ? a : a.identifier(); + const bi = typeof b === "string" ? b : b.identifier(); + return ai.length - bi.length; + } + ); - walkIdentifier(expression) { - if (!this.scope.definitions.has(expression.name)) { - const hook = this.hooks.expression.get( - this.scope.renames.get(expression.name) || expression.name + // find modules with conflicting source names + for (let idx = 0; idx < allModules.length; idx++) { + const module = allModules[idx]; + let sourceName = moduleToSourceNameMapping.get(module); + let hasName = conflictDetectionSet.has(sourceName); + if (!hasName) { + conflictDetectionSet.add(sourceName); + continue; + } + + // try the fallback name first + sourceName = ModuleFilenameHelpers.createFilename( + module, + { + moduleFilenameTemplate: fallbackModuleFilenameTemplate, + namespace: namespace + }, + requestShortener + ); + hasName = usedNamesSet.has(sourceName); + if (!hasName) { + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + continue; + } + + // elsewise just append stars until we have a valid name + while (hasName) { + sourceName += "*"; + hasName = usedNamesSet.has(sourceName); + } + moduleToSourceNameMapping.set(module, sourceName); + usedNamesSet.add(sourceName); + } + tasks.forEach((task, index) => { + reportProgress( + 0.5 + (0.5 * index) / tasks.length, + task.file, + "attach SourceMap" + ); + const assets = Object.create(null); + const chunk = task.chunk; + const file = task.file; + const asset = task.asset; + const sourceMap = task.sourceMap; + const source = task.source; + const modules = task.modules; + const moduleFilenames = modules.map(m => + moduleToSourceNameMapping.get(m) + ); + sourceMap.sources = moduleFilenames; + if (options.noSources) { + sourceMap.sourcesContent = undefined; + } + sourceMap.sourceRoot = options.sourceRoot || ""; + sourceMap.file = file; + assetsCache.set(asset, { file, assets }); + /** @type {string | false} */ + let currentSourceMappingURLComment = sourceMappingURLComment; + if ( + currentSourceMappingURLComment !== false && + /\.css($|\?)/i.test(file) + ) { + currentSourceMappingURLComment = currentSourceMappingURLComment.replace( + /^\n\/\/(.*)$/, + "\n/*$1*/" + ); + } + const sourceMapString = JSON.stringify(sourceMap); + if (sourceMapFilename) { + let filename = file; + let query = ""; + const idx = filename.indexOf("?"); + if (idx >= 0) { + query = filename.substr(idx); + filename = filename.substr(0, idx); + } + const pathParams = { + chunk, + filename: options.fileContext + ? path.relative(options.fileContext, filename) + : filename, + query, + basename: basename(filename), + contentHash: createHash("md4") + .update(sourceMapString) + .digest("hex") + }; + let sourceMapFile = compilation.getPath( + sourceMapFilename, + pathParams + ); + const sourceMapUrl = options.publicPath + ? options.publicPath + sourceMapFile.replace(/\\/g, "/") + : path + .relative(path.dirname(file), sourceMapFile) + .replace(/\\/g, "/"); + /** + * Add source map url to compilation asset, if {@link currentSourceMappingURLComment} presented + */ + if (currentSourceMappingURLComment !== false) { + const asset = new ConcatSource( + new RawSource(source), + compilation.getPath( + currentSourceMappingURLComment, + Object.assign({ url: sourceMapUrl }, pathParams) + ) + ); + assets[file] = asset; + compilation.updateAsset(file, asset); + } + /** + * Add source map file to compilation assets and chunk files + */ + const asset = new RawSource(sourceMapString); + assets[sourceMapFile] = asset; + compilation.emitAsset(sourceMapFile, asset, { + development: true + }); + chunk.files.push(sourceMapFile); + } else { + if (currentSourceMappingURLComment === false) { + throw new Error( + "SourceMapDevToolPlugin: append can't be false when no filename is provided" + ); + } + /** + * Add source map as data url to asset + */ + const asset = new ConcatSource( + new RawSource(source), + currentSourceMappingURLComment + .replace(/\[map\]/g, () => sourceMapString) + .replace( + /\[url\]/g, + () => + `data:application/json;charset=utf-8;base64,${Buffer.from( + sourceMapString, + "utf-8" + ).toString("base64")}` + ) + ); + assets[file] = asset; + compilation.updateAsset(file, asset); + } + }); + reportProgress(1.0); + } ); - if (hook !== undefined) { - const result = hook.call(expression); - if (result === true) return; - } - } + }); } +} - /** - * @deprecated - * @param {any} params scope params - * @param {function(): void} fn inner function - * @returns {void} - */ - inScope(params, fn) { - const oldScope = this.scope; - this.scope = { - topLevelScope: oldScope.topLevelScope, - inTry: false, - inShorthand: false, - isStrict: oldScope.isStrict, - isAsmJs: oldScope.isAsmJs, - definitions: oldScope.definitions.createChild(), - renames: oldScope.renames.createChild() - }; +module.exports = SourceMapDevToolPlugin; - this.scope.renames.set("this", null); - this.enterPatterns(params, ident => { - this.scope.renames.set(ident, null); - this.scope.definitions.add(ident); - }); +/***/ }), - fn(); +/***/ 99977: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - this.scope = oldScope; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - inFunctionScope(hasThis, params, fn) { - const oldScope = this.scope; - this.scope = { - topLevelScope: oldScope.topLevelScope, - inTry: false, - inShorthand: false, - isStrict: oldScope.isStrict, - isAsmJs: oldScope.isAsmJs, - definitions: oldScope.definitions.createChild(), - renames: oldScope.renames.createChild() - }; - if (hasThis) { - this.scope.renames.set("this", null); - } +const RequestShortener = __webpack_require__(54254); +const SizeFormatHelpers = __webpack_require__(12496); +const formatLocation = __webpack_require__(49); +const identifierUtils = __webpack_require__(94658); +const compareLocations = __webpack_require__(22562); +const { LogType } = __webpack_require__(47194); - this.enterPatterns(params, ident => { - this.scope.renames.set(ident, null); - this.scope.definitions.add(ident); - }); +const optionsOrFallback = (...args) => { + let optionValues = []; + optionValues.push(...args); + return optionValues.find(optionValue => optionValue !== undefined); +}; - fn(); +const compareId = (a, b) => { + if (typeof a !== typeof b) { + return typeof a < typeof b ? -1 : 1; + } + if (a < b) return -1; + if (a > b) return 1; + return 0; +}; - this.scope = oldScope; +class Stats { + constructor(compilation) { + this.compilation = compilation; + this.hash = compilation.hash; + this.startTime = undefined; + this.endTime = undefined; } - inBlockScope(fn) { - const oldScope = this.scope; - this.scope = { - topLevelScope: oldScope.topLevelScope, - inTry: oldScope.inTry, - inShorthand: false, - isStrict: oldScope.isStrict, - isAsmJs: oldScope.isAsmJs, - definitions: oldScope.definitions.createChild(), - renames: oldScope.renames.createChild() - }; + static filterWarnings(warnings, warningsFilter) { + // we dont have anything to filter so all warnings can be shown + if (!warningsFilter) { + return warnings; + } - fn(); + // create a chain of filters + // if they return "true" a warning should be suppressed + const normalizedWarningsFilters = [].concat(warningsFilter).map(filter => { + if (typeof filter === "string") { + return warning => warning.includes(filter); + } - this.scope = oldScope; - } + if (filter instanceof RegExp) { + return warning => filter.test(warning); + } - // TODO webpack 5: remove this methods - // only for backward-compat - detectStrictMode(statements) { - this.detectMode(statements); - } + if (typeof filter === "function") { + return filter; + } - detectMode(statements) { - const isLiteral = - statements.length >= 1 && - statements[0].type === "ExpressionStatement" && - statements[0].expression.type === "Literal"; - if (isLiteral && statements[0].expression.value === "use strict") { - this.scope.isStrict = true; - } - if (isLiteral && statements[0].expression.value === "use asm") { - this.scope.isAsmJs = true; - } + throw new Error( + `Can only filter warnings with Strings or RegExps. (Given: ${filter})` + ); + }); + return warnings.filter(warning => { + return !normalizedWarningsFilters.some(check => check(warning)); + }); } - enterPatterns(patterns, onIdent) { - for (const pattern of patterns) { - if (typeof pattern !== "string") { - this.enterPattern(pattern, onIdent); - } else if (pattern) { - onIdent(pattern); - } - } + formatFilePath(filePath) { + const OPTIONS_REGEXP = /^(\s|\S)*!/; + return filePath.includes("!") + ? `${filePath.replace(OPTIONS_REGEXP, "")} (${filePath})` + : `${filePath}`; } - enterPattern(pattern, onIdent) { - if (!pattern) return; - switch (pattern.type) { - case "ArrayPattern": - this.enterArrayPattern(pattern, onIdent); - break; - case "AssignmentPattern": - this.enterAssignmentPattern(pattern, onIdent); - break; - case "Identifier": - this.enterIdentifier(pattern, onIdent); - break; - case "ObjectPattern": - this.enterObjectPattern(pattern, onIdent); - break; - case "RestElement": - this.enterRestElement(pattern, onIdent); - break; - case "Property": - this.enterPattern(pattern.value, onIdent); - break; - } + hasWarnings() { + return ( + this.compilation.warnings.length > 0 || + this.compilation.children.some(child => child.getStats().hasWarnings()) + ); } - enterIdentifier(pattern, onIdent) { - onIdent(pattern.name, pattern); + hasErrors() { + return ( + this.compilation.errors.length > 0 || + this.compilation.children.some(child => child.getStats().hasErrors()) + ); } - enterObjectPattern(pattern, onIdent) { - for ( - let propIndex = 0, len = pattern.properties.length; - propIndex < len; - propIndex++ - ) { - const prop = pattern.properties[propIndex]; - this.enterPattern(prop, onIdent); + // remove a prefixed "!" that can be specified to reverse sort order + normalizeFieldKey(field) { + if (field[0] === "!") { + return field.substr(1); } + return field; } - enterArrayPattern(pattern, onIdent) { - for ( - let elementIndex = 0, len = pattern.elements.length; - elementIndex < len; - elementIndex++ - ) { - const element = pattern.elements[elementIndex]; - this.enterPattern(element, onIdent); + // if a field is prefixed by a "!" reverse sort order + sortOrderRegular(field) { + if (field[0] === "!") { + return false; } + return true; } - enterRestElement(pattern, onIdent) { - this.enterPattern(pattern.argument, onIdent); - } + toJson(options, forToString) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } - enterAssignmentPattern(pattern, onIdent) { - this.enterPattern(pattern.left, onIdent); - } + const optionOrLocalFallback = (v, def) => + v !== undefined ? v : options.all !== undefined ? options.all : def; - evaluateExpression(expression) { - try { - const hook = this.hooks.evaluate.get(expression.type); - if (hook !== undefined) { - const result = hook.call(expression); - if (result !== undefined) { - if (result) { - result.setExpression(expression); - } - return result; - } + const testAgainstGivenOption = item => { + if (typeof item === "string") { + const regExp = new RegExp( + `[\\\\/]${item.replace( + // eslint-disable-next-line no-useless-escape + /[-[\]{}()*+?.\\^$|]/g, + "\\$&" + )}([\\\\/]|$|!|\\?)` + ); + return ident => regExp.test(ident); } - } catch (e) { - console.warn(e); - // ignore error + if (item && typeof item === "object" && typeof item.test === "function") { + return ident => item.test(ident); + } + if (typeof item === "function") { + return item; + } + if (typeof item === "boolean") { + return () => item; + } + }; + + const compilation = this.compilation; + const context = optionsOrFallback( + options.context, + compilation.compiler.context + ); + const requestShortener = + compilation.compiler.context === context + ? compilation.requestShortener + : new RequestShortener(context); + const showPerformance = optionOrLocalFallback(options.performance, true); + const showHash = optionOrLocalFallback(options.hash, true); + const showEnv = optionOrLocalFallback(options.env, false); + const showVersion = optionOrLocalFallback(options.version, true); + const showTimings = optionOrLocalFallback(options.timings, true); + const showBuiltAt = optionOrLocalFallback(options.builtAt, true); + const showAssets = optionOrLocalFallback(options.assets, true); + const showEntrypoints = optionOrLocalFallback(options.entrypoints, true); + const showChunkGroups = optionOrLocalFallback( + options.chunkGroups, + !forToString + ); + const showChunks = optionOrLocalFallback(options.chunks, !forToString); + const showChunkModules = optionOrLocalFallback(options.chunkModules, true); + const showChunkOrigins = optionOrLocalFallback( + options.chunkOrigins, + !forToString + ); + const showModules = optionOrLocalFallback(options.modules, true); + const showNestedModules = optionOrLocalFallback( + options.nestedModules, + true + ); + const showModuleAssets = optionOrLocalFallback( + options.moduleAssets, + !forToString + ); + const showDepth = optionOrLocalFallback(options.depth, !forToString); + const showCachedModules = optionOrLocalFallback(options.cached, true); + const showCachedAssets = optionOrLocalFallback(options.cachedAssets, true); + const showReasons = optionOrLocalFallback(options.reasons, !forToString); + const showUsedExports = optionOrLocalFallback( + options.usedExports, + !forToString + ); + const showProvidedExports = optionOrLocalFallback( + options.providedExports, + !forToString + ); + const showOptimizationBailout = optionOrLocalFallback( + options.optimizationBailout, + !forToString + ); + const showChildren = optionOrLocalFallback(options.children, true); + const showSource = optionOrLocalFallback(options.source, !forToString); + const showModuleTrace = optionOrLocalFallback(options.moduleTrace, true); + const showErrors = optionOrLocalFallback(options.errors, true); + const showErrorDetails = optionOrLocalFallback( + options.errorDetails, + !forToString + ); + const showWarnings = optionOrLocalFallback(options.warnings, true); + const warningsFilter = optionsOrFallback(options.warningsFilter, null); + const showPublicPath = optionOrLocalFallback( + options.publicPath, + !forToString + ); + const showLogging = optionOrLocalFallback( + options.logging, + forToString ? "info" : true + ); + const showLoggingTrace = optionOrLocalFallback( + options.loggingTrace, + !forToString + ); + const loggingDebug = [] + .concat(optionsOrFallback(options.loggingDebug, [])) + .map(testAgainstGivenOption); + + const excludeModules = [] + .concat(optionsOrFallback(options.excludeModules, options.exclude, [])) + .map(testAgainstGivenOption); + const excludeAssets = [] + .concat(optionsOrFallback(options.excludeAssets, [])) + .map(testAgainstGivenOption); + const maxModules = optionsOrFallback( + options.maxModules, + forToString ? 15 : Infinity + ); + const sortModules = optionsOrFallback(options.modulesSort, "id"); + const sortChunks = optionsOrFallback(options.chunksSort, "id"); + const sortAssets = optionsOrFallback(options.assetsSort, ""); + const showOutputPath = optionOrLocalFallback( + options.outputPath, + !forToString + ); + + if (!showCachedModules) { + excludeModules.push((ident, module) => !module.built); } - return new BasicEvaluatedExpression() - .setRange(expression.range) - .setExpression(expression); - } - parseString(expression) { - switch (expression.type) { - case "BinaryExpression": - if (expression.operator === "+") { - return ( - this.parseString(expression.left) + - this.parseString(expression.right) + const createModuleFilter = () => { + let i = 0; + return module => { + if (excludeModules.length > 0) { + const ident = requestShortener.shorten(module.resource); + const excluded = excludeModules.some(fn => fn(ident, module)); + if (excluded) return false; + } + const result = i < maxModules; + i++; + return result; + }; + }; + + const createAssetFilter = () => { + return asset => { + if (excludeAssets.length > 0) { + const ident = asset.name; + const excluded = excludeAssets.some(fn => fn(ident, asset)); + if (excluded) return false; + } + return showCachedAssets || asset.emitted; + }; + }; + + const sortByFieldAndOrder = (fieldKey, a, b) => { + if (a[fieldKey] === null && b[fieldKey] === null) return 0; + if (a[fieldKey] === null) return 1; + if (b[fieldKey] === null) return -1; + if (a[fieldKey] === b[fieldKey]) return 0; + if (typeof a[fieldKey] !== typeof b[fieldKey]) + return typeof a[fieldKey] < typeof b[fieldKey] ? -1 : 1; + return a[fieldKey] < b[fieldKey] ? -1 : 1; + }; + + const sortByField = (field, originalArray) => { + const originalMap = originalArray.reduce((map, v, i) => { + map.set(v, i); + return map; + }, new Map()); + return (a, b) => { + if (field) { + const fieldKey = this.normalizeFieldKey(field); + + // if a field is prefixed with a "!" the sort is reversed! + const sortIsRegular = this.sortOrderRegular(field); + + const cmp = sortByFieldAndOrder( + fieldKey, + sortIsRegular ? a : b, + sortIsRegular ? b : a ); + if (cmp) return cmp; } - break; - case "Literal": - return expression.value + ""; - } - throw new Error( - expression.type + " is not supported as parameter for require" - ); - } + return originalMap.get(a) - originalMap.get(b); + }; + }; - parseCalculatedString(expression) { - switch (expression.type) { - case "BinaryExpression": - if (expression.operator === "+") { - const left = this.parseCalculatedString(expression.left); - const right = this.parseCalculatedString(expression.right); - if (left.code) { - return { - range: left.range, - value: left.value, - code: true, - conditional: false - }; - } else if (right.code) { - return { - range: [ - left.range[0], - right.range ? right.range[1] : left.range[1] - ], - value: left.value + right.value, - code: true, - conditional: false - }; - } else { - return { - range: [left.range[0], right.range[1]], - value: left.value + right.value, - code: false, - conditional: false - }; - } + const formatError = e => { + let text = ""; + if (typeof e === "string") { + e = { message: e }; + } + if (e.chunk) { + text += `chunk ${e.chunk.name || e.chunk.id}${ + e.chunk.hasRuntime() + ? " [entry]" + : e.chunk.canBeInitial() + ? " [initial]" + : "" + }\n`; + } + if (e.file) { + text += `${e.file}\n`; + } + if ( + e.module && + e.module.readableIdentifier && + typeof e.module.readableIdentifier === "function" + ) { + text += this.formatFilePath( + e.module.readableIdentifier(requestShortener) + ); + if (typeof e.loc === "object") { + const locInfo = formatLocation(e.loc); + if (locInfo) text += ` ${locInfo}`; } - break; - case "ConditionalExpression": { - const consequent = this.parseCalculatedString(expression.consequent); - const alternate = this.parseCalculatedString(expression.alternate); - const items = []; - if (consequent.conditional) { - items.push(...consequent.conditional); - } else if (!consequent.code) { - items.push(consequent); - } else { - break; + text += "\n"; + } + text += e.message; + if (showErrorDetails && e.details) { + text += `\n${e.details}`; + } + if (showErrorDetails && e.missing) { + text += e.missing.map(item => `\n[${item}]`).join(""); + } + if (showModuleTrace && e.origin) { + text += `\n @ ${this.formatFilePath( + e.origin.readableIdentifier(requestShortener) + )}`; + if (typeof e.originLoc === "object") { + const locInfo = formatLocation(e.originLoc); + if (locInfo) text += ` ${locInfo}`; } - if (alternate.conditional) { - items.push(...alternate.conditional); - } else if (!alternate.code) { - items.push(alternate); - } else { - break; + if (e.dependencies) { + for (const dep of e.dependencies) { + if (!dep.loc) continue; + if (typeof dep.loc === "string") continue; + const locInfo = formatLocation(dep.loc); + if (!locInfo) continue; + text += ` ${locInfo}`; + } + } + let current = e.origin; + while (current.issuer) { + current = current.issuer; + text += `\n @ ${current.readableIdentifier(requestShortener)}`; } - return { - range: undefined, - value: "", - code: true, - conditional: items - }; } - case "Literal": - return { - range: expression.range, - value: expression.value + "", - code: false, - conditional: false - }; - } - return { - range: undefined, - value: "", - code: true, - conditional: false + return text; }; - } - - parse(source, initialState) { - let ast; - let comments; - if (typeof source === "object" && source !== null) { - ast = source; - comments = source.comments; - } else { - comments = []; - ast = Parser.parse(source, { - sourceType: this.sourceType, - onComment: comments - }); - } - const oldScope = this.scope; - const oldState = this.state; - const oldComments = this.comments; - this.scope = { - topLevelScope: true, - inTry: false, - inShorthand: false, - isStrict: false, - isAsmJs: false, - definitions: new StackedSetMap(), - renames: new StackedSetMap() + const obj = { + errors: compilation.errors.map(formatError), + warnings: Stats.filterWarnings( + compilation.warnings.map(formatError), + warningsFilter + ) }; - const state = (this.state = initialState || {}); - this.comments = comments; - if (this.hooks.program.call(ast, comments) === undefined) { - this.detectMode(ast.body); - this.prewalkStatements(ast.body); - this.blockPrewalkStatements(ast.body); - this.walkStatements(ast.body); - } - this.scope = oldScope; - this.state = oldState; - this.comments = oldComments; - return state; - } - evaluate(source) { - const ast = Parser.parse("(" + source + ")", { - sourceType: this.sourceType, - locations: false + //We just hint other renderers since actually omitting + //errors/warnings from the JSON would be kind of weird. + Object.defineProperty(obj, "_showWarnings", { + value: showWarnings, + enumerable: false + }); + Object.defineProperty(obj, "_showErrors", { + value: showErrors, + enumerable: false }); - // TODO(https://github.com/acornjs/acorn/issues/741) - // @ts-ignore - if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { - throw new Error("evaluate: Source is not a expression"); - } - // TODO(https://github.com/acornjs/acorn/issues/741) - // @ts-ignore - return this.evaluateExpression(ast.body[0].expression); - } - getComments(range) { - return this.comments.filter( - comment => comment.range[0] >= range[0] && comment.range[1] <= range[1] - ); - } + if (showVersion) { + obj.version = __webpack_require__(71618)/* .version */ .i8; + } - parseCommentOptions(range) { - const comments = this.getComments(range); - if (comments.length === 0) { - return EMPTY_COMMENT_OPTIONS; + if (showHash) obj.hash = this.hash; + if (showTimings && this.startTime && this.endTime) { + obj.time = this.endTime - this.startTime; } - let options = {}; - let errors = []; - for (const comment of comments) { - const { value } = comment; - if (value && webpackCommentRegExp.test(value)) { - // try compile only if webpack options comment is present - try { - const val = vm.runInNewContext(`(function(){return {${value}};})()`); - Object.assign(options, val); - } catch (e) { - e.comment = comment; - errors.push(e); - } - } + + if (showBuiltAt && this.endTime) { + obj.builtAt = this.endTime; } - return { options, errors }; - } - getNameForExpression(expression) { - let expr = expression; - const exprName = []; - while ( - expr.type === "MemberExpression" && - expr.property.type === (expr.computed ? "Literal" : "Identifier") - ) { - exprName.push(expr.computed ? expr.property.value : expr.property.name); - expr = expr.object; + if (showEnv && options._env) { + obj.env = options._env; } - let free; - if (expr.type === "Identifier") { - free = !this.scope.definitions.has(expr.name); - exprName.push(this.scope.renames.get(expr.name) || expr.name); - } else if ( - expr.type === "ThisExpression" && - this.scope.renames.get("this") - ) { - free = true; - exprName.push(this.scope.renames.get("this")); - } else if (expr.type === "ThisExpression") { - free = this.scope.topLevelScope; - exprName.push("this"); - } else { - return null; + + if (compilation.needAdditionalPass) { + obj.needAdditionalPass = true; } - let prefix = ""; - for (let i = exprName.length - 1; i >= 2; i--) { - prefix += exprName[i] + "."; + if (showPublicPath) { + obj.publicPath = this.compilation.mainTemplate.getPublicPath({ + hash: this.compilation.hash + }); } - if (exprName.length > 1) { - prefix += exprName[1]; + if (showOutputPath) { + obj.outputPath = this.compilation.mainTemplate.outputOptions.path; } - const name = prefix ? prefix + "." + exprName[0] : exprName[0]; - const nameGeneral = prefix; - return { - name, - nameGeneral, - free - }; - } + if (showAssets) { + const assetsByFile = {}; + const compilationAssets = compilation + .getAssets() + .sort((a, b) => (a.name < b.name ? -1 : 1)); + obj.assetsByChunkName = {}; + obj.assets = compilationAssets + .map(({ name, source, info }) => { + const obj = { + name, + size: source.size(), + chunks: [], + chunkNames: [], + info, + // TODO webpack 5: remove .emitted + emitted: source.emitted || compilation.emittedAssets.has(name) + }; - static parse(code, options) { - const type = options ? options.sourceType : "module"; - const parserOptions = Object.assign( - Object.create(null), - defaultParserOptions, - options - ); + if (showPerformance) { + obj.isOverSizeLimit = source.isOverSizeLimit; + } - if (type === "auto") { - parserOptions.sourceType = "module"; - } else if (parserOptions.sourceType === "script") { - parserOptions.allowReturnOutsideFunction = true; - } + assetsByFile[name] = obj; + return obj; + }) + .filter(createAssetFilter()); + obj.filteredAssets = compilationAssets.length - obj.assets.length; - let ast; - let error; - let threw = false; - try { - ast = acornParser.parse(code, parserOptions); - } catch (e) { - error = e; - threw = true; + for (const chunk of compilation.chunks) { + for (const asset of chunk.files) { + if (assetsByFile[asset]) { + for (const id of chunk.ids) { + assetsByFile[asset].chunks.push(id); + } + if (chunk.name) { + assetsByFile[asset].chunkNames.push(chunk.name); + if (obj.assetsByChunkName[chunk.name]) { + obj.assetsByChunkName[chunk.name] = [] + .concat(obj.assetsByChunkName[chunk.name]) + .concat([asset]); + } else { + obj.assetsByChunkName[chunk.name] = asset; + } + } + } + } + } + obj.assets.sort(sortByField(sortAssets, obj.assets)); } - if (threw && type === "auto") { - parserOptions.sourceType = "script"; - parserOptions.allowReturnOutsideFunction = true; - if (Array.isArray(parserOptions.onComment)) { - parserOptions.onComment.length = 0; - } - try { - ast = acornParser.parse(code, parserOptions); - threw = false; - } catch (e) { - threw = true; + const fnChunkGroup = groupMap => { + const obj = {}; + for (const keyValuePair of groupMap) { + const name = keyValuePair[0]; + const cg = keyValuePair[1]; + const children = cg.getChildrenByOrders(); + obj[name] = { + chunks: cg.chunks.map(c => c.id), + assets: cg.chunks.reduce( + (array, c) => array.concat(c.files || []), + [] + ), + children: Object.keys(children).reduce((obj, key) => { + const groups = children[key]; + obj[key] = groups.map(group => ({ + name: group.name, + chunks: group.chunks.map(c => c.id), + assets: group.chunks.reduce( + (array, c) => array.concat(c.files || []), + [] + ) + })); + return obj; + }, Object.create(null)), + childAssets: Object.keys(children).reduce((obj, key) => { + const groups = children[key]; + obj[key] = Array.from( + groups.reduce((set, group) => { + for (const chunk of group.chunks) { + for (const asset of chunk.files) { + set.add(asset); + } + } + return set; + }, new Set()) + ); + return obj; + }, Object.create(null)) + }; + if (showPerformance) { + obj[name].isOverSizeLimit = cg.isOverSizeLimit; + } } + + return obj; + }; + + if (showEntrypoints) { + obj.entrypoints = fnChunkGroup(compilation.entrypoints); } - if (threw) { - throw error; + if (showChunkGroups) { + obj.namedChunkGroups = fnChunkGroup(compilation.namedChunkGroups); } - return ast; + const fnModule = module => { + const path = []; + let current = module; + while (current.issuer) { + path.push((current = current.issuer)); + } + path.reverse(); + const obj = { + id: module.id, + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener), + index: module.index, + index2: module.index2, + size: module.size(), + cacheable: module.buildInfo.cacheable, + built: !!module.built, + optional: module.optional, + prefetched: module.prefetched, + chunks: Array.from(module.chunksIterable, chunk => chunk.id), + issuer: module.issuer && module.issuer.identifier(), + issuerId: module.issuer && module.issuer.id, + issuerName: + module.issuer && module.issuer.readableIdentifier(requestShortener), + issuerPath: + module.issuer && + path.map(module => ({ + id: module.id, + identifier: module.identifier(), + name: module.readableIdentifier(requestShortener), + profile: module.profile + })), + profile: module.profile, + failed: !!module.error, + errors: module.errors ? module.errors.length : 0, + warnings: module.warnings ? module.warnings.length : 0 + }; + if (showModuleAssets) { + obj.assets = Object.keys(module.buildInfo.assets || {}); + } + if (showReasons) { + obj.reasons = module.reasons + .sort((a, b) => { + if (a.module && !b.module) return -1; + if (!a.module && b.module) return 1; + if (a.module && b.module) { + const cmp = compareId(a.module.id, b.module.id); + if (cmp) return cmp; + } + if (a.dependency && !b.dependency) return -1; + if (!a.dependency && b.dependency) return 1; + if (a.dependency && b.dependency) { + const cmp = compareLocations(a.dependency.loc, b.dependency.loc); + if (cmp) return cmp; + if (a.dependency.type < b.dependency.type) return -1; + if (a.dependency.type > b.dependency.type) return 1; + } + return 0; + }) + .map(reason => { + const obj = { + moduleId: reason.module ? reason.module.id : null, + moduleIdentifier: reason.module + ? reason.module.identifier() + : null, + module: reason.module + ? reason.module.readableIdentifier(requestShortener) + : null, + moduleName: reason.module + ? reason.module.readableIdentifier(requestShortener) + : null, + type: reason.dependency ? reason.dependency.type : null, + explanation: reason.explanation, + userRequest: reason.dependency + ? reason.dependency.userRequest + : null + }; + if (reason.dependency) { + const locInfo = formatLocation(reason.dependency.loc); + if (locInfo) { + obj.loc = locInfo; + } + } + return obj; + }); + } + if (showUsedExports) { + if (module.used === true) { + obj.usedExports = module.usedExports; + } else if (module.used === false) { + obj.usedExports = false; + } + } + if (showProvidedExports) { + obj.providedExports = Array.isArray(module.buildMeta.providedExports) + ? module.buildMeta.providedExports + : null; + } + if (showOptimizationBailout) { + obj.optimizationBailout = module.optimizationBailout.map(item => { + if (typeof item === "function") return item(requestShortener); + return item; + }); + } + if (showDepth) { + obj.depth = module.depth; + } + if (showNestedModules) { + if (module.modules) { + const modules = module.modules; + obj.modules = modules + .sort(sortByField("depth", modules)) + .filter(createModuleFilter()) + .map(fnModule); + obj.filteredModules = modules.length - obj.modules.length; + obj.modules.sort(sortByField(sortModules, obj.modules)); + } + } + if (showSource && module._source) { + obj.source = module._source.source(); + } + return obj; + }; + if (showChunks) { + obj.chunks = compilation.chunks.map(chunk => { + const parents = new Set(); + const children = new Set(); + const siblings = new Set(); + const childIdByOrder = chunk.getChildIdsByOrders(); + for (const chunkGroup of chunk.groupsIterable) { + for (const parentGroup of chunkGroup.parentsIterable) { + for (const chunk of parentGroup.chunks) { + parents.add(chunk.id); + } + } + for (const childGroup of chunkGroup.childrenIterable) { + for (const chunk of childGroup.chunks) { + children.add(chunk.id); + } + } + for (const sibling of chunkGroup.chunks) { + if (sibling !== chunk) siblings.add(sibling.id); + } + } + const obj = { + id: chunk.id, + rendered: chunk.rendered, + initial: chunk.canBeInitial(), + entry: chunk.hasRuntime(), + recorded: chunk.recorded, + reason: chunk.chunkReason, + size: chunk.modulesSize(), + names: chunk.name ? [chunk.name] : [], + files: chunk.files.slice(), + hash: chunk.renderedHash, + siblings: Array.from(siblings).sort(compareId), + parents: Array.from(parents).sort(compareId), + children: Array.from(children).sort(compareId), + childrenByOrder: childIdByOrder + }; + if (showChunkModules) { + const modules = chunk.getModules(); + obj.modules = modules + .slice() + .sort(sortByField("depth", modules)) + .filter(createModuleFilter()) + .map(fnModule); + obj.filteredModules = chunk.getNumberOfModules() - obj.modules.length; + obj.modules.sort(sortByField(sortModules, obj.modules)); + } + if (showChunkOrigins) { + obj.origins = Array.from(chunk.groupsIterable, g => g.origins) + .reduce((a, b) => a.concat(b), []) + .map(origin => ({ + moduleId: origin.module ? origin.module.id : undefined, + module: origin.module ? origin.module.identifier() : "", + moduleIdentifier: origin.module ? origin.module.identifier() : "", + moduleName: origin.module + ? origin.module.readableIdentifier(requestShortener) + : "", + loc: formatLocation(origin.loc), + request: origin.request, + reasons: origin.reasons || [] + })) + .sort((a, b) => { + const cmp1 = compareId(a.moduleId, b.moduleId); + if (cmp1) return cmp1; + const cmp2 = compareId(a.loc, b.loc); + if (cmp2) return cmp2; + const cmp3 = compareId(a.request, b.request); + if (cmp3) return cmp3; + return 0; + }); + } + return obj; + }); + obj.chunks.sort(sortByField(sortChunks, obj.chunks)); + } + if (showModules) { + obj.modules = compilation.modules + .slice() + .sort(sortByField("depth", compilation.modules)) + .filter(createModuleFilter()) + .map(fnModule); + obj.filteredModules = compilation.modules.length - obj.modules.length; + obj.modules.sort(sortByField(sortModules, obj.modules)); + } + if (showLogging) { + const util = __webpack_require__(31669); + obj.logging = {}; + let acceptedTypes; + let collapsedGroups = false; + switch (showLogging) { + case "none": + acceptedTypes = new Set([]); + break; + case "error": + acceptedTypes = new Set([LogType.error]); + break; + case "warn": + acceptedTypes = new Set([LogType.error, LogType.warn]); + break; + case "info": + acceptedTypes = new Set([LogType.error, LogType.warn, LogType.info]); + break; + case true: + case "log": + acceptedTypes = new Set([ + LogType.error, + LogType.warn, + LogType.info, + LogType.log, + LogType.group, + LogType.groupEnd, + LogType.groupCollapsed, + LogType.clear + ]); + break; + case "verbose": + acceptedTypes = new Set([ + LogType.error, + LogType.warn, + LogType.info, + LogType.log, + LogType.group, + LogType.groupEnd, + LogType.groupCollapsed, + LogType.profile, + LogType.profileEnd, + LogType.time, + LogType.status, + LogType.clear + ]); + collapsedGroups = true; + break; + } + for (const [origin, logEntries] of compilation.logging) { + const debugMode = loggingDebug.some(fn => fn(origin)); + let collapseCounter = 0; + let processedLogEntries = logEntries; + if (!debugMode) { + processedLogEntries = processedLogEntries.filter(entry => { + if (!acceptedTypes.has(entry.type)) return false; + if (!collapsedGroups) { + switch (entry.type) { + case LogType.groupCollapsed: + collapseCounter++; + return collapseCounter === 1; + case LogType.group: + if (collapseCounter > 0) collapseCounter++; + return collapseCounter === 0; + case LogType.groupEnd: + if (collapseCounter > 0) { + collapseCounter--; + return false; + } + return true; + default: + return collapseCounter === 0; + } + } + return true; + }); + } + processedLogEntries = processedLogEntries.map(entry => { + let message = undefined; + if (entry.type === LogType.time) { + message = `${entry.args[0]}: ${entry.args[1] * 1000 + + entry.args[2] / 1000000}ms`; + } else if (entry.args && entry.args.length > 0) { + message = util.format(entry.args[0], ...entry.args.slice(1)); + } + return { + type: + (debugMode || collapsedGroups) && + entry.type === LogType.groupCollapsed + ? LogType.group + : entry.type, + message, + trace: showLoggingTrace && entry.trace ? entry.trace : undefined + }; + }); + let name = identifierUtils + .makePathsRelative(context, origin, compilation.cache) + .replace(/\|/g, " "); + if (name in obj.logging) { + let i = 1; + while (`${name}#${i}` in obj.logging) { + i++; + } + name = `${name}#${i}`; + } + obj.logging[name] = { + entries: processedLogEntries, + filteredEntries: logEntries.length - processedLogEntries.length, + debug: debugMode + }; + } + } + if (showChildren) { + obj.children = compilation.children.map((child, idx) => { + const childOptions = Stats.getChildOptions(options, idx); + const obj = new Stats(child).toJson(childOptions, forToString); + delete obj.hash; + delete obj.version; + if (child.name) { + obj.name = identifierUtils.makePathsRelative( + context, + child.name, + compilation.cache + ); + } + return obj; + }); + } + + return obj; } -} -// TODO remove in webpack 5 -Object.defineProperty(Parser.prototype, "getCommentOptions", { - configurable: false, - value: util.deprecate( - /** - * @deprecated - * @param {TODO} range Range - * @returns {void} - * @this {Parser} - */ - function(range) { - return this.parseCommentOptions(range).options; - }, - "Parser.getCommentOptions: Use Parser.parseCommentOptions(range) instead" - ) -}); + toString(options) { + if (typeof options === "boolean" || typeof options === "string") { + options = Stats.presetToOptions(options); + } else if (!options) { + options = {}; + } -module.exports = Parser; + const useColors = optionsOrFallback(options.colors, false); + const obj = this.toJson(options, true); -/***/ }), + return Stats.jsonToString(obj, useColors); + } -/***/ 23999: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + static jsonToString(obj, useColors) { + const buf = []; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const defaultColors = { + bold: "\u001b[1m", + yellow: "\u001b[1m\u001b[33m", + red: "\u001b[1m\u001b[31m", + green: "\u001b[1m\u001b[32m", + cyan: "\u001b[1m\u001b[36m", + magenta: "\u001b[1m\u001b[35m" + }; -const path = __webpack_require__(85622); + const colors = Object.keys(defaultColors).reduce( + (obj, color) => { + obj[color] = str => { + if (useColors) { + buf.push( + useColors === true || useColors[color] === undefined + ? defaultColors[color] + : useColors[color] + ); + } + buf.push(str); + if (useColors) { + buf.push("\u001b[39m\u001b[22m"); + } + }; + return obj; + }, + { + normal: str => buf.push(str) + } + ); -const BasicEvaluatedExpression = __webpack_require__(96770); -const ConstDependency = __webpack_require__(71101); -const UnsupportedFeatureWarning = __webpack_require__(99953); + const coloredTime = time => { + let times = [800, 400, 200, 100]; + if (obj.time) { + times = [obj.time / 2, obj.time / 4, obj.time / 8, obj.time / 16]; + } + if (time < times[3]) colors.normal(`${time}ms`); + else if (time < times[2]) colors.bold(`${time}ms`); + else if (time < times[1]) colors.green(`${time}ms`); + else if (time < times[0]) colors.yellow(`${time}ms`); + else colors.red(`${time}ms`); + }; -const ParserHelpers = exports; + const newline = () => buf.push("\n"); -ParserHelpers.addParsedVariableToModule = (parser, name, expression) => { - if (!parser.state.current.addVariable) return false; - var deps = []; - parser.parse(expression, { - current: { - addDependency: dep => { - dep.userRequest = name; - deps.push(dep); - } - }, - module: parser.state.module - }); - parser.state.current.addVariable(name, expression, deps); - return true; -}; - -ParserHelpers.requireFileAsExpression = (context, pathToModule) => { - var moduleJsPath = path.relative(context, pathToModule); - if (!/^[A-Z]:/i.test(moduleJsPath)) { - moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/"); - } - return "require(" + JSON.stringify(moduleJsPath) + ")"; -}; - -ParserHelpers.toConstantDependency = (parser, value) => { - return function constDependency(expr) { - var dep = new ConstDependency(value, expr.range, false); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return true; - }; -}; + const getText = (arr, row, col) => { + return arr[row][col].value; + }; -ParserHelpers.toConstantDependencyWithWebpackRequire = (parser, value) => { - return function constDependencyWithWebpackRequire(expr) { - var dep = new ConstDependency(value, expr.range, true); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return true; - }; -}; + const table = (array, align, splitter) => { + const rows = array.length; + const cols = array[0].length; + const colSizes = new Array(cols); + for (let col = 0; col < cols; col++) { + colSizes[col] = 0; + } + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + const value = `${getText(array, row, col)}`; + if (value.length > colSizes[col]) { + colSizes[col] = value.length; + } + } + } + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + const format = array[row][col].color; + const value = `${getText(array, row, col)}`; + let l = value.length; + if (align[col] === "l") { + format(value); + } + for (; l < colSizes[col] && col !== cols - 1; l++) { + colors.normal(" "); + } + if (align[col] === "r") { + format(value); + } + if (col + 1 < cols && colSizes[col] !== 0) { + colors.normal(splitter || " "); + } + } + newline(); + } + }; -ParserHelpers.evaluateToString = value => { - return function stringExpression(expr) { - return new BasicEvaluatedExpression().setString(value).setRange(expr.range); - }; -}; + const getAssetColor = (asset, defaultColor) => { + if (asset.isOverSizeLimit) { + return colors.yellow; + } -ParserHelpers.evaluateToBoolean = value => { - return function booleanExpression(expr) { - return new BasicEvaluatedExpression() - .setBoolean(value) - .setRange(expr.range); - }; -}; + return defaultColor; + }; -ParserHelpers.evaluateToIdentifier = (identifier, truthy) => { - return function identifierExpression(expr) { - let evex = new BasicEvaluatedExpression() - .setIdentifier(identifier) - .setRange(expr.range); - if (truthy === true) { - evex = evex.setTruthy(); - } else if (truthy === false) { - evex = evex.setFalsy(); + if (obj.hash) { + colors.normal("Hash: "); + colors.bold(obj.hash); + newline(); } - return evex; - }; -}; - -ParserHelpers.expressionIsUnsupported = (parser, message) => { - return function unsupportedExpression(expr) { - var dep = new ConstDependency("(void 0)", expr.range, false); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - if (!parser.state.module) return; - parser.state.module.warnings.push( - new UnsupportedFeatureWarning(parser.state.module, message, expr.loc) - ); - return true; - }; -}; - -ParserHelpers.skipTraversal = function skipTraversal() { - return true; -}; - -ParserHelpers.approve = function approve() { - return true; -}; - - -/***/ }), - -/***/ 27850: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const PrefetchDependency = __webpack_require__(14237); - -class PrefetchPlugin { - constructor(context, request) { - if (!request) { - this.request = context; - } else { - this.context = context; - this.request = request; + if (obj.version) { + colors.normal("Version: webpack "); + colors.bold(obj.version); + newline(); } - } + if (typeof obj.time === "number") { + colors.normal("Time: "); + colors.bold(obj.time); + colors.normal("ms"); + newline(); + } + if (typeof obj.builtAt === "number") { + const builtAtDate = new Date(obj.builtAt); + let timeZone = undefined; - apply(compiler) { - compiler.hooks.compilation.tap( - "PrefetchPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - PrefetchDependency, - normalModuleFactory - ); + try { + builtAtDate.toLocaleTimeString(); + } catch (err) { + // Force UTC if runtime timezone is unsupported + timeZone = "UTC"; } - ); - compiler.hooks.make.tapAsync("PrefetchPlugin", (compilation, callback) => { - compilation.prefetch( - this.context || compiler.context, - new PrefetchDependency(this.request), - callback - ); - }); - } -} -module.exports = PrefetchPlugin; - - -/***/ }), - -/***/ 63123: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(26336); - -/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */ -/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginOptions} ProgressPluginOptions */ -const createDefaultHandler = (profile, logger) => { - let lastState; - let lastStateTime; + colors.normal("Built at: "); + colors.normal( + builtAtDate.toLocaleDateString(undefined, { + day: "2-digit", + month: "2-digit", + year: "numeric", + timeZone + }) + ); + colors.normal(" "); + colors.bold(builtAtDate.toLocaleTimeString(undefined, { timeZone })); + newline(); + } + if (obj.env) { + colors.normal("Environment (--env): "); + colors.bold(JSON.stringify(obj.env, null, 2)); + newline(); + } + if (obj.publicPath) { + colors.normal("PublicPath: "); + colors.bold(obj.publicPath); + newline(); + } - const defaultHandler = (percentage, msg, ...args) => { - logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args); - if (profile) { - let state = msg; - state = state.replace(/^\d+\/\d+\s+/, ""); - if (percentage === 0) { - lastState = null; - lastStateTime = Date.now(); - } else if (state !== lastState || percentage === 1) { - const now = Date.now(); - if (lastState) { - const diff = now - lastStateTime; - const stateMsg = `${diff}ms ${lastState}`; - if (diff > 1000) { - logger.warn(stateMsg); - } else if (diff > 10) { - logger.info(stateMsg); - } else if (diff > 0) { - logger.log(stateMsg); - } else { - logger.debug(stateMsg); + if (obj.assets && obj.assets.length > 0) { + const t = [ + [ + { + value: "Asset", + color: colors.bold + }, + { + value: "Size", + color: colors.bold + }, + { + value: "Chunks", + color: colors.bold + }, + { + value: "", + color: colors.bold + }, + { + value: "", + color: colors.bold + }, + { + value: "Chunk Names", + color: colors.bold } - } - lastState = state; - lastStateTime = now; + ] + ]; + for (const asset of obj.assets) { + t.push([ + { + value: asset.name, + color: getAssetColor(asset, colors.green) + }, + { + value: SizeFormatHelpers.formatSize(asset.size), + color: getAssetColor(asset, colors.normal) + }, + { + value: asset.chunks.join(", "), + color: colors.bold + }, + { + value: [ + asset.emitted && "[emitted]", + asset.info.immutable && "[immutable]", + asset.info.development && "[dev]", + asset.info.hotModuleReplacement && "[hmr]" + ] + .filter(Boolean) + .join(" "), + color: colors.green + }, + { + value: asset.isOverSizeLimit ? "[big]" : "", + color: getAssetColor(asset, colors.normal) + }, + { + value: asset.chunkNames.join(", "), + color: colors.normal + } + ]); } + table(t, "rrrlll"); } - if (percentage === 1) logger.status(); - }; - - return defaultHandler; -}; - -class ProgressPlugin { - /** - * @param {ProgressPluginArgument} options options - */ - constructor(options) { - if (typeof options === "function") { - options = { - handler: options - }; + if (obj.filteredAssets > 0) { + colors.normal(" "); + if (obj.assets.length > 0) colors.normal("+ "); + colors.normal(obj.filteredAssets); + if (obj.assets.length > 0) colors.normal(" hidden"); + colors.normal(obj.filteredAssets !== 1 ? " assets" : " asset"); + newline(); } - options = options || {}; - validateOptions(schema, options, "Progress Plugin"); - options = Object.assign({}, ProgressPlugin.defaultOptions, options); - - this.profile = options.profile; - this.handler = options.handler; - this.modulesCount = options.modulesCount; - this.showEntries = options.entries; - this.showModules = options.modules; - this.showActiveModules = options.activeModules; - } - - apply(compiler) { - const { modulesCount } = this; - const handler = - this.handler || - createDefaultHandler( - this.profile, - compiler.getInfrastructureLogger("webpack.Progress") - ); - const showEntries = this.showEntries; - const showModules = this.showModules; - const showActiveModules = this.showActiveModules; - if (compiler.compilers) { - const states = new Array(compiler.compilers.length); - compiler.compilers.forEach((compiler, idx) => { - new ProgressPlugin((p, msg, ...args) => { - states[idx] = [p, msg, ...args]; - handler( - states - .map(state => (state && state[0]) || 0) - .reduce((a, b) => a + b) / states.length, - `[${idx}] ${msg}`, - ...args - ); - }).apply(compiler); - }); - } else { - let lastModulesCount = 0; - let lastEntriesCount = 0; - let moduleCount = modulesCount; - let entriesCount = 1; - let doneModules = 0; - let doneEntries = 0; - const activeModules = new Set(); - let lastActiveModule = ""; - - const update = () => { - const percentByModules = - doneModules / Math.max(lastModulesCount, moduleCount); - const percentByEntries = - doneEntries / Math.max(lastEntriesCount, entriesCount); - - const items = [ - 0.1 + Math.max(percentByModules, percentByEntries) * 0.6, - "building" - ]; - if (showEntries) { - items.push(`${doneEntries}/${entriesCount} entries`); - } - if (showModules) { - items.push(`${doneModules}/${moduleCount} modules`); + const processChunkGroups = (namedGroups, prefix) => { + for (const name of Object.keys(namedGroups)) { + const cg = namedGroups[name]; + colors.normal(`${prefix} `); + colors.bold(name); + if (cg.isOverSizeLimit) { + colors.normal(" "); + colors.yellow("[big]"); } - if (showActiveModules) { - items.push(`${activeModules.size} active`); - items.push(lastActiveModule); + colors.normal(" ="); + for (const asset of cg.assets) { + colors.normal(" "); + colors.green(asset); } - handler(...items); - }; - - const moduleAdd = module => { - moduleCount++; - if (showActiveModules) { - const ident = module.identifier(); - if (ident) { - activeModules.add(ident); - lastActiveModule = ident; + for (const name of Object.keys(cg.childAssets)) { + const assets = cg.childAssets[name]; + if (assets && assets.length > 0) { + colors.normal(" "); + colors.magenta(`(${name}:`); + for (const asset of assets) { + colors.normal(" "); + colors.green(asset); + } + colors.magenta(")"); } } - update(); - }; + newline(); + } + }; - const entryAdd = (entry, name) => { - entriesCount++; - update(); - }; + if (obj.entrypoints) { + processChunkGroups(obj.entrypoints, "Entrypoint"); + } - const moduleDone = module => { - doneModules++; - if (showActiveModules) { - const ident = module.identifier(); - if (ident) { - activeModules.delete(ident); - if (lastActiveModule === ident) { - lastActiveModule = ""; - for (const m of activeModules) { - lastActiveModule = m; - } - } + if (obj.namedChunkGroups) { + let outputChunkGroups = obj.namedChunkGroups; + if (obj.entrypoints) { + outputChunkGroups = Object.keys(outputChunkGroups) + .filter(name => !obj.entrypoints[name]) + .reduce((result, name) => { + result[name] = obj.namedChunkGroups[name]; + return result; + }, {}); + } + processChunkGroups(outputChunkGroups, "Chunk Group"); + } + + const modulesByIdentifier = {}; + if (obj.modules) { + for (const module of obj.modules) { + modulesByIdentifier[`$${module.identifier}`] = module; + } + } else if (obj.chunks) { + for (const chunk of obj.chunks) { + if (chunk.modules) { + for (const module of chunk.modules) { + modulesByIdentifier[`$${module.identifier}`] = module; } } - update(); - }; - - const entryDone = (entry, name) => { - doneEntries++; - update(); - }; - - compiler.hooks.compilation.tap("ProgressPlugin", compilation => { - if (compilation.compiler.isChild()) return; - lastModulesCount = moduleCount; - lastEntriesCount = entriesCount; - moduleCount = entriesCount = 0; - doneModules = doneEntries = 0; - handler(0, "compiling"); + } + } - compilation.hooks.buildModule.tap("ProgressPlugin", moduleAdd); - compilation.hooks.failedModule.tap("ProgressPlugin", moduleDone); - compilation.hooks.succeedModule.tap("ProgressPlugin", moduleDone); - - compilation.hooks.addEntry.tap("ProgressPlugin", entryAdd); - compilation.hooks.failedEntry.tap("ProgressPlugin", entryDone); - compilation.hooks.succeedEntry.tap("ProgressPlugin", entryDone); + const processModuleAttributes = module => { + colors.normal(" "); + colors.normal(SizeFormatHelpers.formatSize(module.size)); + if (module.chunks) { + for (const chunk of module.chunks) { + colors.normal(" {"); + colors.yellow(chunk); + colors.normal("}"); + } + } + if (typeof module.depth === "number") { + colors.normal(` [depth ${module.depth}]`); + } + if (module.cacheable === false) { + colors.red(" [not cacheable]"); + } + if (module.optional) { + colors.yellow(" [optional]"); + } + if (module.built) { + colors.green(" [built]"); + } + if (module.assets && module.assets.length) { + colors.magenta( + ` [${module.assets.length} asset${ + module.assets.length === 1 ? "" : "s" + }]` + ); + } + if (module.prefetched) { + colors.magenta(" [prefetched]"); + } + if (module.failed) colors.red(" [failed]"); + if (module.warnings) { + colors.yellow( + ` [${module.warnings} warning${module.warnings === 1 ? "" : "s"}]` + ); + } + if (module.errors) { + colors.red( + ` [${module.errors} error${module.errors === 1 ? "" : "s"}]` + ); + } + }; - const hooks = { - finishModules: "finish module graph", - seal: "sealing", - beforeChunks: "chunk graph", - afterChunks: "after chunk graph", - optimizeDependenciesBasic: "basic dependencies optimization", - optimizeDependencies: "dependencies optimization", - optimizeDependenciesAdvanced: "advanced dependencies optimization", - afterOptimizeDependencies: "after dependencies optimization", - optimize: "optimizing", - optimizeModulesBasic: "basic module optimization", - optimizeModules: "module optimization", - optimizeModulesAdvanced: "advanced module optimization", - afterOptimizeModules: "after module optimization", - optimizeChunksBasic: "basic chunk optimization", - optimizeChunks: "chunk optimization", - optimizeChunksAdvanced: "advanced chunk optimization", - afterOptimizeChunks: "after chunk optimization", - optimizeTree: "module and chunk tree optimization", - afterOptimizeTree: "after module and chunk tree optimization", - optimizeChunkModulesBasic: "basic chunk modules optimization", - optimizeChunkModules: "chunk modules optimization", - optimizeChunkModulesAdvanced: "advanced chunk modules optimization", - afterOptimizeChunkModules: "after chunk modules optimization", - reviveModules: "module reviving", - optimizeModuleOrder: "module order optimization", - advancedOptimizeModuleOrder: "advanced module order optimization", - beforeModuleIds: "before module ids", - moduleIds: "module ids", - optimizeModuleIds: "module id optimization", - afterOptimizeModuleIds: "module id optimization", - reviveChunks: "chunk reviving", - optimizeChunkOrder: "chunk order optimization", - beforeChunkIds: "before chunk ids", - optimizeChunkIds: "chunk id optimization", - afterOptimizeChunkIds: "after chunk id optimization", - recordModules: "record modules", - recordChunks: "record chunks", - beforeHash: "hashing", - afterHash: "after hashing", - recordHash: "record hash", - beforeModuleAssets: "module assets processing", - beforeChunkAssets: "chunk assets processing", - additionalChunkAssets: "additional chunk assets processing", - record: "recording", - additionalAssets: "additional asset processing", - optimizeChunkAssets: "chunk asset optimization", - afterOptimizeChunkAssets: "after chunk asset optimization", - optimizeAssets: "asset optimization", - afterOptimizeAssets: "after asset optimization", - afterSeal: "after seal" - }; - const numberOfHooks = Object.keys(hooks).length; - Object.keys(hooks).forEach((name, idx) => { - const title = hooks[name]; - const percentage = (idx / numberOfHooks) * 0.25 + 0.7; - compilation.hooks[name].intercept({ - name: "ProgressPlugin", - context: true, - call: () => { - handler(percentage, title); - }, - tap: (context, tap) => { - if (context) { - // p is percentage from 0 to 1 - // args is any number of messages in a hierarchical matter - context.reportProgress = (p, ...args) => { - handler(percentage, title, tap.name, ...args); - }; - } - handler(percentage, title, tap.name); + const processModuleContent = (module, prefix) => { + if (Array.isArray(module.providedExports)) { + colors.normal(prefix); + if (module.providedExports.length === 0) { + colors.cyan("[no exports]"); + } else { + colors.cyan(`[exports: ${module.providedExports.join(", ")}]`); + } + newline(); + } + if (module.usedExports !== undefined) { + if (module.usedExports !== true) { + colors.normal(prefix); + if (module.usedExports === null) { + colors.cyan("[used exports unknown]"); + } else if (module.usedExports === false) { + colors.cyan("[no exports used]"); + } else if ( + Array.isArray(module.usedExports) && + module.usedExports.length === 0 + ) { + colors.cyan("[no exports used]"); + } else if (Array.isArray(module.usedExports)) { + const providedExportsCount = Array.isArray(module.providedExports) + ? module.providedExports.length + : null; + if ( + providedExportsCount !== null && + providedExportsCount === module.usedExports.length + ) { + colors.cyan("[all exports used]"); + } else { + colors.cyan( + `[only some exports used: ${module.usedExports.join(", ")}]` + ); } - }); - }); - }); - compiler.hooks.emit.intercept({ - name: "ProgressPlugin", - context: true, - call: () => { - handler(0.95, "emitting"); - }, - tap: (context, tap) => { - if (context) { - context.reportProgress = (p, ...args) => { - handler(0.95, "emitting", tap.name, ...args); - }; } - handler(0.95, "emitting", tap.name); + newline(); } - }); - compiler.hooks.afterEmit.intercept({ - name: "ProgressPlugin", - context: true, - call: () => { - handler(0.98, "after emitting"); - }, - tap: (context, tap) => { - if (context) { - context.reportProgress = (p, ...args) => { - handler(0.98, "after emitting", tap.name, ...args); - }; + } + if (Array.isArray(module.optimizationBailout)) { + for (const item of module.optimizationBailout) { + colors.normal(prefix); + colors.yellow(item); + newline(); + } + } + if (module.reasons) { + for (const reason of module.reasons) { + colors.normal(prefix); + if (reason.type) { + colors.normal(reason.type); + colors.normal(" "); } - handler(0.98, "after emitting", tap.name); + if (reason.userRequest) { + colors.cyan(reason.userRequest); + colors.normal(" "); + } + if (reason.moduleId !== null) { + colors.normal("["); + colors.normal(reason.moduleId); + colors.normal("]"); + } + if (reason.module && reason.module !== reason.moduleId) { + colors.normal(" "); + colors.magenta(reason.module); + } + if (reason.loc) { + colors.normal(" "); + colors.normal(reason.loc); + } + if (reason.explanation) { + colors.normal(" "); + colors.cyan(reason.explanation); + } + newline(); } - }); - compiler.hooks.done.tap("ProgressPlugin", () => { - handler(1, ""); - }); - } - } -} - -ProgressPlugin.defaultOptions = { - profile: false, - modulesCount: 500, - modules: true, - activeModules: true, - // TODO webpack 5 default this to true - entries: false -}; - -module.exports = ProgressPlugin; - - -/***/ }), - -/***/ 72861: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const ParserHelpers = __webpack_require__(23999); -const ConstDependency = __webpack_require__(71101); - -const NullFactory = __webpack_require__(40438); + } + if (module.profile) { + colors.normal(prefix); + let sum = 0; + if (module.issuerPath) { + for (const m of module.issuerPath) { + colors.normal("["); + colors.normal(m.id); + colors.normal("] "); + if (m.profile) { + const time = (m.profile.factory || 0) + (m.profile.building || 0); + coloredTime(time); + sum += time; + colors.normal(" "); + } + colors.normal("-> "); + } + } + for (const key of Object.keys(module.profile)) { + colors.normal(`${key}:`); + const time = module.profile[key]; + coloredTime(time); + colors.normal(" "); + sum += time; + } + colors.normal("= "); + coloredTime(sum); + newline(); + } + if (module.modules) { + processModulesList(module, prefix + "| "); + } + }; -class ProvidePlugin { - constructor(definitions) { - this.definitions = definitions; - } + const processModulesList = (obj, prefix) => { + if (obj.modules) { + let maxModuleId = 0; + for (const module of obj.modules) { + if (typeof module.id === "number") { + if (maxModuleId < module.id) maxModuleId = module.id; + } + } + let contentPrefix = prefix + " "; + if (maxModuleId >= 10) contentPrefix += " "; + if (maxModuleId >= 100) contentPrefix += " "; + if (maxModuleId >= 1000) contentPrefix += " "; + for (const module of obj.modules) { + colors.normal(prefix); + const name = module.name || module.identifier; + if (typeof module.id === "string" || typeof module.id === "number") { + if (typeof module.id === "number") { + if (module.id < 1000 && maxModuleId >= 1000) colors.normal(" "); + if (module.id < 100 && maxModuleId >= 100) colors.normal(" "); + if (module.id < 10 && maxModuleId >= 10) colors.normal(" "); + } else { + if (maxModuleId >= 1000) colors.normal(" "); + if (maxModuleId >= 100) colors.normal(" "); + if (maxModuleId >= 10) colors.normal(" "); + } + if (name !== module.id) { + colors.normal("["); + colors.normal(module.id); + colors.normal("]"); + colors.normal(" "); + } else { + colors.normal("["); + colors.bold(module.id); + colors.normal("]"); + } + } + if (name !== module.id) { + colors.bold(name); + } + processModuleAttributes(module); + newline(); + processModuleContent(module, contentPrefix); + } + if (obj.filteredModules > 0) { + colors.normal(prefix); + colors.normal(" "); + if (obj.modules.length > 0) colors.normal(" + "); + colors.normal(obj.filteredModules); + if (obj.modules.length > 0) colors.normal(" hidden"); + colors.normal(obj.filteredModules !== 1 ? " modules" : " module"); + newline(); + } + } + }; - apply(compiler) { - const definitions = this.definitions; - compiler.hooks.compilation.tap( - "ProvidePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set(ConstDependency, new NullFactory()); - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); - const handler = (parser, parserOptions) => { - Object.keys(definitions).forEach(name => { - var request = [].concat(definitions[name]); - var splittedName = name.split("."); - if (splittedName.length > 0) { - splittedName.slice(1).forEach((_, i) => { - const name = splittedName.slice(0, i + 1).join("."); - parser.hooks.canRename - .for(name) - .tap("ProvidePlugin", ParserHelpers.approve); - }); + if (obj.chunks) { + for (const chunk of obj.chunks) { + colors.normal("chunk "); + if (chunk.id < 1000) colors.normal(" "); + if (chunk.id < 100) colors.normal(" "); + if (chunk.id < 10) colors.normal(" "); + colors.normal("{"); + colors.yellow(chunk.id); + colors.normal("} "); + colors.green(chunk.files.join(", ")); + if (chunk.names && chunk.names.length > 0) { + colors.normal(" ("); + colors.normal(chunk.names.join(", ")); + colors.normal(")"); + } + colors.normal(" "); + colors.normal(SizeFormatHelpers.formatSize(chunk.size)); + for (const id of chunk.parents) { + colors.normal(" <{"); + colors.yellow(id); + colors.normal("}>"); + } + for (const id of chunk.siblings) { + colors.normal(" ={"); + colors.yellow(id); + colors.normal("}="); + } + for (const id of chunk.children) { + colors.normal(" >{"); + colors.yellow(id); + colors.normal("}<"); + } + if (chunk.childrenByOrder) { + for (const name of Object.keys(chunk.childrenByOrder)) { + const children = chunk.childrenByOrder[name]; + colors.normal(" "); + colors.magenta(`(${name}:`); + for (const id of children) { + colors.normal(" {"); + colors.yellow(id); + colors.normal("}"); } - parser.hooks.expression.for(name).tap("ProvidePlugin", expr => { - let nameIdentifier = name; - const scopedName = name.includes("."); - let expression = `require(${JSON.stringify(request[0])})`; - if (scopedName) { - nameIdentifier = `__webpack_provided_${name.replace( - /\./g, - "_dot_" - )}`; - } - if (request.length > 1) { - expression += request - .slice(1) - .map(r => `[${JSON.stringify(r)}]`) - .join(""); - } - if ( - !ParserHelpers.addParsedVariableToModule( - parser, - nameIdentifier, - expression - ) - ) { - return false; - } - if (scopedName) { - ParserHelpers.toConstantDependency( - parser, - nameIdentifier - )(expr); + colors.magenta(")"); + } + } + if (chunk.entry) { + colors.yellow(" [entry]"); + } else if (chunk.initial) { + colors.yellow(" [initial]"); + } + if (chunk.rendered) { + colors.green(" [rendered]"); + } + if (chunk.recorded) { + colors.green(" [recorded]"); + } + if (chunk.reason) { + colors.yellow(` ${chunk.reason}`); + } + newline(); + if (chunk.origins) { + for (const origin of chunk.origins) { + colors.normal(" > "); + if (origin.reasons && origin.reasons.length) { + colors.yellow(origin.reasons.join(" ")); + colors.normal(" "); + } + if (origin.request) { + colors.normal(origin.request); + colors.normal(" "); + } + if (origin.module) { + colors.normal("["); + colors.normal(origin.moduleId); + colors.normal("] "); + const module = modulesByIdentifier[`$${origin.module}`]; + if (module) { + colors.bold(module.name); + colors.normal(" "); } - return true; - }); - }); - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("ProvidePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("ProvidePlugin", handler); - - // Disable ProvidePlugin for javascript/esm, see https://github.com/webpack/webpack/issues/7032 + } + if (origin.loc) { + colors.normal(origin.loc); + } + newline(); + } + } + processModulesList(chunk, " "); } - ); - } -} -module.exports = ProvidePlugin; - - -/***/ }), - -/***/ 82353: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + processModulesList(obj, ""); + if (obj.logging) { + for (const origin of Object.keys(obj.logging)) { + const logData = obj.logging[origin]; + if (logData.entries.length > 0) { + newline(); + if (logData.debug) { + colors.red("DEBUG "); + } + colors.bold("LOG from " + origin); + newline(); + let indent = ""; + for (const entry of logData.entries) { + let color = colors.normal; + let prefix = " "; + switch (entry.type) { + case LogType.clear: + colors.normal(`${indent}-------`); + newline(); + continue; + case LogType.error: + color = colors.red; + prefix = " "; + break; + case LogType.warn: + color = colors.yellow; + prefix = " "; + break; + case LogType.info: + color = colors.green; + prefix = " "; + break; + case LogType.log: + color = colors.bold; + break; + case LogType.trace: + case LogType.debug: + color = colors.normal; + break; + case LogType.status: + color = colors.magenta; + prefix = " "; + break; + case LogType.profile: + color = colors.magenta; + prefix = "

"; + break; + case LogType.profileEnd: + color = colors.magenta; + prefix = "

"; + break; + case LogType.time: + color = colors.magenta; + prefix = " "; + break; + case LogType.group: + color = colors.cyan; + prefix = "<-> "; + break; + case LogType.groupCollapsed: + color = colors.cyan; + prefix = "<+> "; + break; + case LogType.groupEnd: + if (indent.length >= 2) + indent = indent.slice(0, indent.length - 2); + continue; + } + if (entry.message) { + for (const line of entry.message.split("\n")) { + colors.normal(`${indent}${prefix}`); + color(line); + newline(); + } + } + if (entry.trace) { + for (const line of entry.trace) { + colors.normal(`${indent}| ${line}`); + newline(); + } + } + switch (entry.type) { + case LogType.group: + indent += " "; + break; + } + } + if (logData.filteredEntries) { + colors.normal(`+ ${logData.filteredEntries} hidden lines`); + newline(); + } + } + } + } -const Module = __webpack_require__(75993); -const { OriginalSource, RawSource } = __webpack_require__(53665); + if (obj._showWarnings && obj.warnings) { + for (const warning of obj.warnings) { + newline(); + colors.yellow(`WARNING in ${warning}`); + newline(); + } + } + if (obj._showErrors && obj.errors) { + for (const error of obj.errors) { + newline(); + colors.red(`ERROR in ${error}`); + newline(); + } + } + if (obj.children) { + for (const child of obj.children) { + const childString = Stats.jsonToString(child, useColors); + if (childString) { + if (child.name) { + colors.normal("Child "); + colors.bold(child.name); + colors.normal(":"); + } else { + colors.normal("Child"); + } + newline(); + buf.push(" "); + buf.push(childString.replace(/\n/g, "\n ")); + newline(); + } + } + } + if (obj.needAdditionalPass) { + colors.yellow( + "Compilation needs an additional pass and will compile again." + ); + } -module.exports = class RawModule extends Module { - constructor(source, identifier, readableIdentifier) { - super("javascript/dynamic", null); - this.sourceStr = source; - this.identifierStr = identifier || this.sourceStr; - this.readableIdentifierStr = readableIdentifier || this.identifierStr; - this.built = false; + while (buf[buf.length - 1] === "\n") { + buf.pop(); + } + return buf.join(""); } - identifier() { - return this.identifierStr; + static presetToOptions(name) { + // Accepted values: none, errors-only, minimal, normal, detailed, verbose + // Any other falsy value will behave as 'none', truthy values as 'normal' + const pn = + (typeof name === "string" && name.toLowerCase()) || name || "none"; + switch (pn) { + case "none": + return { + all: false + }; + case "verbose": + return { + entrypoints: true, + chunkGroups: true, + modules: false, + chunks: true, + chunkModules: true, + chunkOrigins: true, + depth: true, + env: true, + reasons: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + publicPath: true, + logging: "verbose", + exclude: false, + maxModules: Infinity + }; + case "detailed": + return { + entrypoints: true, + chunkGroups: true, + chunks: true, + chunkModules: false, + chunkOrigins: true, + depth: true, + usedExports: true, + providedExports: true, + optimizationBailout: true, + errorDetails: true, + publicPath: true, + logging: true, + exclude: false, + maxModules: Infinity + }; + case "minimal": + return { + all: false, + modules: true, + maxModules: 0, + errors: true, + warnings: true, + logging: "warn" + }; + case "errors-only": + return { + all: false, + errors: true, + moduleTrace: true, + logging: "error" + }; + case "errors-warnings": + return { + all: false, + errors: true, + warnings: true, + logging: "warn" + }; + default: + return {}; + } } - size() { - return this.sourceStr.length; + static getChildOptions(options, idx) { + let innerOptions; + if (Array.isArray(options.children)) { + if (idx < options.children.length) { + innerOptions = options.children[idx]; + } + } else if (typeof options.children === "object" && options.children) { + innerOptions = options.children; + } + if (typeof innerOptions === "boolean" || typeof innerOptions === "string") { + innerOptions = Stats.presetToOptions(innerOptions); + } + if (!innerOptions) { + return options; + } + const childOptions = Object.assign({}, options); + delete childOptions.children; // do not inherit children + return Object.assign(childOptions, innerOptions); } +} - readableIdentifier(requestShortener) { - return requestShortener.shorten(this.readableIdentifierStr); - } +module.exports = Stats; - needRebuild() { - return false; + +/***/ }), + +/***/ 97365: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Joel Denning @joeldenning + */ + + + +const { ConcatSource } = __webpack_require__(53665); +const Template = __webpack_require__(96066); + +/** @typedef {import("./Compilation")} Compilation */ + +/** + * @typedef {Object} SystemMainTemplatePluginOptions + * @param {string=} name the library name + */ + +class SystemMainTemplatePlugin { + /** + * @param {SystemMainTemplatePluginOptions} options the plugin options + */ + constructor(options) { + this.name = options.name; } - build(options, compilations, resolver, fs, callback) { - this.built = true; - this.buildMeta = {}; - this.buildInfo = { - cacheable: true + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + const externals = chunk.getModules().filter(m => m.external); + + // The name this bundle should be registered as with System + const name = this.name + ? `${JSON.stringify( + mainTemplate.getAssetPath(this.name, { hash, chunk }) + )}, ` + : ""; + + // The array of dependencies that are external to webpack and will be provided by System + const systemDependencies = JSON.stringify( + externals.map(m => + typeof m.request === "object" ? m.request.amd : m.request + ) + ); + + // The name of the variable provided by System for exporting + const dynamicExport = "__WEBPACK_DYNAMIC_EXPORT__"; + + // An array of the internal variable names for the webpack externals + const externalWebpackNames = externals.map( + m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` + ); + + // Declaring variables for the internal variable names for the webpack externals + const externalVarDeclarations = + externalWebpackNames.length > 0 + ? `var ${externalWebpackNames.join(", ")};` + : ""; + + // The system.register format requires an array of setter functions for externals. + const setters = + externalWebpackNames.length === 0 + ? "" + : Template.asString([ + "setters: [", + Template.indent( + externalWebpackNames + .map(external => + Template.asString([ + "function(module) {", + Template.indent(`${external} = module;`), + "}" + ]) + ) + .join(",\n") + ), + "]," + ]); + + return new ConcatSource( + Template.asString([ + `System.register(${name}${systemDependencies}, function(${dynamicExport}) {`, + Template.indent([ + externalVarDeclarations, + "return {", + Template.indent([ + setters, + "execute: function() {", + Template.indent(`${dynamicExport}(`) + ]) + ]) + ]) + "\n", + source, + "\n" + + Template.asString([ + Template.indent([ + Template.indent([Template.indent([");"]), "}"]), + "};" + ]), + "})" + ]) + ); }; - callback(); - } - source() { - if (this.useSourceMap) { - return new OriginalSource(this.sourceStr, this.identifier()); - } else { - return new RawSource(this.sourceStr); + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "SystemMainTemplatePlugin", + onRenderWithEntry + ); } - } - updateHash(hash) { - hash.update(this.sourceStr); - super.updateHash(hash); + mainTemplate.hooks.globalHashPaths.tap( + "SystemMainTemplatePlugin", + paths => { + if (this.name) { + paths.push(this.name); + } + return paths; + } + ); + + mainTemplate.hooks.hash.tap("SystemMainTemplatePlugin", hash => { + hash.update("exports system"); + if (this.name) { + hash.update(this.name); + } + }); } -}; +} + +module.exports = SystemMainTemplatePlugin; /***/ }), -/***/ 40355: +/***/ 96066: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ +/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ +const { ConcatSource } = __webpack_require__(53665); +const HotUpdateChunk = __webpack_require__(26782); -const identifierUtils = __webpack_require__(94658); +const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0); +const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0); +const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1; +const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g; +const INDENT_MULTILINE_REGEX = /^\t/gm; +const LINE_SEPARATOR_REGEX = /\r?\n/g; +const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/; +const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g; +const COMMENT_END_REGEX = /\*\//g; +const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g; +const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./Module")} Module */ +/** @typedef {import("webpack-sources").Source} Source */ /** - * @typedef {Object} RecordsChunks - * @property {Record=} byName - * @property {Record=} bySource - * @property {number[]=} usedIds + * @typedef {Object} HasId + * @property {number | string} id */ /** - * @typedef {Object} RecordsModules - * @property {Record=} byIdentifier - * @property {Record=} bySource - * @property {Record=} usedIds + * @typedef {function(Module, number): boolean} ModuleFilterPredicate */ /** - * @typedef {Object} Records - * @property {RecordsChunks=} chunks - * @property {RecordsModules=} modules + * @param {HasId} a first id object to be sorted + * @param {HasId} b second id object to be sorted against + * @returns {-1|0|1} the sort value */ +const stringifyIdSortPredicate = (a, b) => { + const aId = a.id + ""; + const bId = b.id + ""; + if (aId < bId) return -1; + if (aId > bId) return 1; + return 0; +}; -class RecordIdsPlugin { +class Template { /** - * @param {Object} options Options object - * @param {boolean=} options.portableIds true, when ids need to be portable + * + * @param {Function} fn a runtime function (.runtime.js) "template" + * @returns {string} the updated and normalized function string */ - constructor(options) { - this.options = options || {}; + static getFunctionContent(fn) { + return fn + .toString() + .replace(FUNCTION_CONTENT_REGEX, "") + .replace(INDENT_MULTILINE_REGEX, "") + .replace(LINE_SEPARATOR_REGEX, "\n"); } /** - * @param {Compiler} compiler the Compiler - * @returns {void} + * @param {string} str the string converted to identifier + * @returns {string} created identifier */ - apply(compiler) { - const portableIds = this.options.portableIds; - compiler.hooks.compilation.tap("RecordIdsPlugin", compilation => { - compilation.hooks.recordModules.tap( - "RecordIdsPlugin", - /** - * @param {Module[]} modules the modules array - * @param {Records} records the records object - * @returns {void} - */ - (modules, records) => { - if (!records.modules) records.modules = {}; - if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; - if (!records.modules.usedIds) records.modules.usedIds = {}; - for (const module of modules) { - if (typeof module.id !== "number") continue; - const identifier = portableIds - ? identifierUtils.makePathsRelative( - compiler.context, - module.identifier(), - compilation.cache - ) - : module.identifier(); - records.modules.byIdentifier[identifier] = module.id; - records.modules.usedIds[module.id] = module.id; - } - } - ); - compilation.hooks.reviveModules.tap( - "RecordIdsPlugin", - /** - * @param {Module[]} modules the modules array - * @param {Records} records the records object - * @returns {void} - */ - (modules, records) => { - if (!records.modules) return; - if (records.modules.byIdentifier) { - /** @type {Set} */ - const usedIds = new Set(); - for (const module of modules) { - if (module.id !== null) continue; - const identifier = portableIds - ? identifierUtils.makePathsRelative( - compiler.context, - module.identifier(), - compilation.cache - ) - : module.identifier(); - const id = records.modules.byIdentifier[identifier]; - if (id === undefined) continue; - if (usedIds.has(id)) continue; - usedIds.add(id); - module.id = id; - } - } - if (Array.isArray(records.modules.usedIds)) { - compilation.usedModuleIds = new Set(records.modules.usedIds); - } - } - ); - - /** - * @param {Module} module the module - * @returns {string} the (portable) identifier - */ - const getModuleIdentifier = module => { - if (portableIds) { - return identifierUtils.makePathsRelative( - compiler.context, - module.identifier(), - compilation.cache - ); - } - return module.identifier(); - }; - - /** - * @param {Chunk} chunk the chunk - * @returns {string[]} sources of the chunk - */ - const getChunkSources = chunk => { - /** @type {string[]} */ - const sources = []; - for (const chunkGroup of chunk.groupsIterable) { - const index = chunkGroup.chunks.indexOf(chunk); - if (chunkGroup.name) { - sources.push(`${index} ${chunkGroup.name}`); - } else { - for (const origin of chunkGroup.origins) { - if (origin.module) { - if (origin.request) { - sources.push( - `${index} ${getModuleIdentifier(origin.module)} ${ - origin.request - }` - ); - } else if (typeof origin.loc === "string") { - sources.push( - `${index} ${getModuleIdentifier(origin.module)} ${ - origin.loc - }` - ); - } else if ( - origin.loc && - typeof origin.loc === "object" && - origin.loc.start - ) { - sources.push( - `${index} ${getModuleIdentifier( - origin.module - )} ${JSON.stringify(origin.loc.start)}` - ); - } - } - } - } - } - return sources; - }; - - compilation.hooks.recordChunks.tap( - "RecordIdsPlugin", - /** - * @param {Chunk[]} chunks the chunks array - * @param {Records} records the records object - * @returns {void} - */ - (chunks, records) => { - if (!records.chunks) records.chunks = {}; - if (!records.chunks.byName) records.chunks.byName = {}; - if (!records.chunks.bySource) records.chunks.bySource = {}; - /** @type {Set} */ - const usedIds = new Set(); - for (const chunk of chunks) { - if (typeof chunk.id !== "number") continue; - const name = chunk.name; - if (name) records.chunks.byName[name] = chunk.id; - const sources = getChunkSources(chunk); - for (const source of sources) { - records.chunks.bySource[source] = chunk.id; - } - usedIds.add(chunk.id); - } - records.chunks.usedIds = Array.from(usedIds).sort(); - } - ); - compilation.hooks.reviveChunks.tap( - "RecordIdsPlugin", - /** - * @param {Chunk[]} chunks the chunks array - * @param {Records} records the records object - * @returns {void} - */ - (chunks, records) => { - if (!records.chunks) return; - /** @type {Set} */ - const usedIds = new Set(); - if (records.chunks.byName) { - for (const chunk of chunks) { - if (chunk.id !== null) continue; - if (!chunk.name) continue; - const id = records.chunks.byName[chunk.name]; - if (id === undefined) continue; - if (usedIds.has(id)) continue; - usedIds.add(id); - chunk.id = id; - } - } - if (records.chunks.bySource) { - for (const chunk of chunks) { - const sources = getChunkSources(chunk); - for (const source of sources) { - const id = records.chunks.bySource[source]; - if (id === undefined) continue; - if (usedIds.has(id)) continue; - usedIds.add(id); - chunk.id = id; - break; - } - } - } - if (Array.isArray(records.chunks.usedIds)) { - compilation.usedChunkIds = new Set(records.chunks.usedIds); - } - } - ); - }); + static toIdentifier(str) { + if (typeof str !== "string") return ""; + return str + .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1") + .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_"); } -} -module.exports = RecordIdsPlugin; - - -/***/ }), - -/***/ 15377: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; - - -const WebpackError = __webpack_require__(97391); - -module.exports = class RemovedPluginError extends WebpackError { - constructor(message) { - super(message); - - Error.captureStackTrace(this, this.constructor); + /** + * + * @param {string} str string to be converted to commented in bundle code + * @returns {string} returns a commented version of string + */ + static toComment(str) { + if (!str) return ""; + return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`; } -}; + /** + * + * @param {string} str string to be converted to "normal comment" + * @returns {string} returns a commented version of string + */ + static toNormalComment(str) { + if (!str) return ""; + return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`; + } -/***/ }), - -/***/ 54254: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + /** + * @param {string} str string path to be normalized + * @returns {string} normalized bundle-safe path + */ + static toPath(str) { + if (typeof str !== "string") return ""; + return str + .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-") + .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, ""); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // map number to a single character a-z, A-Z or <_ + number> if number is too big + /** + * + * @param {number} n number to convert to ident + * @returns {string} returns single character ident + */ + static numberToIdentifer(n) { + // lower case + if (n < DELTA_A_TO_Z) { + return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); + } + // upper case + if (n < DELTA_A_TO_Z * 2) { + return String.fromCharCode( + START_UPPERCASE_ALPHABET_CODE + n - DELTA_A_TO_Z + ); + } -const path = __webpack_require__(85622); -const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g; -const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g; -const SEPARATOR_REGEXP = /[/\\]$/; -const FRONT_OR_BACK_BANG_REGEXP = /^!|!$/g; -const INDEX_JS_REGEXP = /\/index.js(!|\?|\(query\))/g; -const MATCH_RESOURCE_REGEXP = /!=!/; + // use multiple letters + return ( + Template.numberToIdentifer(n % (2 * DELTA_A_TO_Z)) + + Template.numberToIdentifer(Math.floor(n / (2 * DELTA_A_TO_Z))) + ); + } -const normalizeBackSlashDirection = request => { - return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/"); -}; + /** + * + * @param {string | string[]} s string to convert to identity + * @returns {string} converted identity + */ + static indent(s) { + if (Array.isArray(s)) { + return s.map(Template.indent).join("\n"); + } else { + const str = s.trimRight(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : "\t"; + return ind + str.replace(/\n([^\n])/g, "\n\t$1"); + } + } -const createRegExpForPath = path => { - const regexpTypePartial = path.replace(PATH_CHARS_REGEXP, "\\$&"); - return new RegExp(`(^|!)${regexpTypePartial}`, "g"); -}; + /** + * + * @param {string|string[]} s string to create prefix for + * @param {string} prefix prefix to compose + * @returns {string} returns new prefix string + */ + static prefix(s, prefix) { + const str = Template.asString(s).trim(); + if (!str) return ""; + const ind = str[0] === "\n" ? "" : prefix; + return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); + } -class RequestShortener { - constructor(directory) { - directory = normalizeBackSlashDirection(directory); - if (SEPARATOR_REGEXP.test(directory)) { - directory = directory.substr(0, directory.length - 1); + /** + * + * @param {string|string[]} str string or string collection + * @returns {string} returns a single string from array + */ + static asString(str) { + if (Array.isArray(str)) { + return str.join("\n"); } + return str; + } - if (directory) { - this.currentDirectoryRegExp = createRegExpForPath(directory); - } + /** + * @typedef {Object} WithId + * @property {string|number} id + */ - const dirname = path.dirname(directory); - const endsWithSeparator = SEPARATOR_REGEXP.test(dirname); - const parentDirectory = endsWithSeparator - ? dirname.substr(0, dirname.length - 1) - : dirname; - if (parentDirectory && parentDirectory !== directory) { - this.parentDirectoryRegExp = createRegExpForPath(`${parentDirectory}/`); + /** + * @param {WithId[]} modules a collection of modules to get array bounds for + * @returns {[number, number] | false} returns the upper and lower array bounds + * or false if not every module has a number based id + */ + static getModulesArrayBounds(modules) { + let maxId = -Infinity; + let minId = Infinity; + for (const module of modules) { + if (typeof module.id !== "number") return false; + if (maxId < module.id) maxId = /** @type {number} */ (module.id); + if (minId > module.id) minId = /** @type {number} */ (module.id); } - - if (__dirname.length >= 2) { - const buildins = normalizeBackSlashDirection(path.join(__dirname, "..")); - const buildinsAsModule = - this.currentDirectoryRegExp && - this.currentDirectoryRegExp.test(buildins); - this.buildinsAsModule = buildinsAsModule; - this.buildinsRegExp = createRegExpForPath(buildins); + if (minId < 16 + ("" + minId).length) { + // add minId x ',' instead of 'Array(minId).concat(…)' + minId = 0; } - - this.cache = new Map(); + const objectOverhead = modules + .map(module => (module.id + "").length + 2) + .reduce((a, b) => a + b, -1); + const arrayOverhead = + minId === 0 ? maxId : 16 + ("" + minId).length + maxId; + return arrayOverhead < objectOverhead ? [minId, maxId] : false; } - shorten(request) { - if (!request) return request; - const cacheEntry = this.cache.get(request); - if (cacheEntry !== undefined) { - return cacheEntry; - } - let result = normalizeBackSlashDirection(request); - if (this.buildinsAsModule && this.buildinsRegExp) { - result = result.replace(this.buildinsRegExp, "!(webpack)"); + /** + * @param {Chunk} chunk chunk whose modules will be rendered + * @param {ModuleFilterPredicate} filterFn function used to filter modules from chunk to render + * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance used to render modules + * @param {TODO | TODO[]} dependencyTemplates templates needed for each module to render dependencies + * @param {string=} prefix applying prefix strings + * @returns {ConcatSource} rendered chunk modules in a Source object + */ + static renderChunkModules( + chunk, + filterFn, + moduleTemplate, + dependencyTemplates, + prefix = "" + ) { + const source = new ConcatSource(); + const modules = chunk.getModules().filter(filterFn); + let removedModules; + if (chunk instanceof HotUpdateChunk) { + removedModules = chunk.removedModules; } - if (this.currentDirectoryRegExp) { - result = result.replace(this.currentDirectoryRegExp, "!."); + if ( + modules.length === 0 && + (!removedModules || removedModules.length === 0) + ) { + source.add("[]"); + return source; } - if (this.parentDirectoryRegExp) { - result = result.replace(this.parentDirectoryRegExp, "!../"); + /** @type {{id: string|number, source: Source|string}[]} */ + const allModules = modules.map(module => { + return { + id: module.id, + source: moduleTemplate.render(module, dependencyTemplates, { + chunk + }) + }; + }); + if (removedModules && removedModules.length > 0) { + for (const id of removedModules) { + allModules.push({ + id, + source: "false" + }); + } } - if (!this.buildinsAsModule && this.buildinsRegExp) { - result = result.replace(this.buildinsRegExp, "!(webpack)"); + const bounds = Template.getModulesArrayBounds(allModules); + if (bounds) { + // Render a spare array + const minId = bounds[0]; + const maxId = bounds[1]; + if (minId !== 0) { + source.add(`Array(${minId}).concat(`); + } + source.add("[\n"); + /** @type {Map} */ + const modules = new Map(); + for (const module of allModules) { + modules.set(module.id, module); + } + for (let idx = minId; idx <= maxId; idx++) { + const module = modules.get(idx); + if (idx !== minId) { + source.add(",\n"); + } + source.add(`/* ${idx} */`); + if (module) { + source.add("\n"); + source.add(module.source); + } + } + source.add("\n" + prefix + "]"); + if (minId !== 0) { + source.add(")"); + } + } else { + // Render an object + source.add("{\n"); + allModules.sort(stringifyIdSortPredicate).forEach((module, idx) => { + if (idx !== 0) { + source.add(",\n"); + } + source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`); + source.add(module.source); + }); + source.add(`\n\n${prefix}}`); } - result = result.replace(INDEX_JS_REGEXP, "$1"); - result = result.replace(FRONT_OR_BACK_BANG_REGEXP, ""); - result = result.replace(MATCH_RESOURCE_REGEXP, " = "); - this.cache.set(request, result); - return result; + return source; } } -module.exports = RequestShortener; +module.exports = Template; /***/ }), -/***/ 88226: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 76032: +/***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Jason Anderson @diurnalist */ -const ParserHelpers = __webpack_require__(23999); -const ConstDependency = __webpack_require__(71101); -const NullFactory = __webpack_require__(40438); +const REGEXP_HASH = /\[hash(?::(\d+))?\]/gi, + REGEXP_CHUNKHASH = /\[chunkhash(?::(\d+))?\]/gi, + REGEXP_MODULEHASH = /\[modulehash(?::(\d+))?\]/gi, + REGEXP_CONTENTHASH = /\[contenthash(?::(\d+))?\]/gi, + REGEXP_NAME = /\[name\]/gi, + REGEXP_ID = /\[id\]/gi, + REGEXP_MODULEID = /\[moduleid\]/gi, + REGEXP_FILE = /\[file\]/gi, + REGEXP_QUERY = /\[query\]/gi, + REGEXP_FILEBASE = /\[filebase\]/gi, + REGEXP_URL = /\[url\]/gi; -module.exports = class RequireJsStuffPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "RequireJsStuffPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set(ConstDependency, new NullFactory()); - compilation.dependencyTemplates.set( - ConstDependency, - new ConstDependency.Template() - ); - const handler = (parser, parserOptions) => { - if (parserOptions.requireJs !== undefined && !parserOptions.requireJs) - return; +// Using global RegExp for .test is dangerous +// We use a normal RegExp instead of .test +const REGEXP_HASH_FOR_TEST = new RegExp(REGEXP_HASH.source, "i"), + REGEXP_CHUNKHASH_FOR_TEST = new RegExp(REGEXP_CHUNKHASH.source, "i"), + REGEXP_CONTENTHASH_FOR_TEST = new RegExp(REGEXP_CONTENTHASH.source, "i"), + REGEXP_NAME_FOR_TEST = new RegExp(REGEXP_NAME.source, "i"); - parser.hooks.call - .for("require.config") - .tap( - "RequireJsStuffPlugin", - ParserHelpers.toConstantDependency(parser, "undefined") - ); - parser.hooks.call - .for("requirejs.config") - .tap( - "RequireJsStuffPlugin", - ParserHelpers.toConstantDependency(parser, "undefined") - ); +const withHashLength = (replacer, handlerFn, assetInfo) => { + const fn = (match, hashLength, ...args) => { + if (assetInfo) assetInfo.immutable = true; + const length = hashLength && parseInt(hashLength, 10); + if (length && handlerFn) { + return handlerFn(length); + } + const hash = replacer(match, hashLength, ...args); + return length ? hash.slice(0, length) : hash; + }; + return fn; +}; - parser.hooks.expression - .for("require.version") - .tap( - "RequireJsStuffPlugin", - ParserHelpers.toConstantDependency( - parser, - JSON.stringify("0.0.0") - ) - ); - parser.hooks.expression - .for("requirejs.onError") - .tap( - "RequireJsStuffPlugin", - ParserHelpers.toConstantDependencyWithWebpackRequire( - parser, - "__webpack_require__.oe" - ) - ); - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireJsStuffPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireJsStuffPlugin", handler); +const getReplacer = (value, allowEmpty) => { + const fn = (match, ...args) => { + // last argument in replacer is the entire input string + const input = args[args.length - 1]; + if (value === null || value === undefined) { + if (!allowEmpty) { + throw new Error( + `Path variable ${match} not implemented in this context: ${input}` + ); } - ); - } + return ""; + } else { + return `${escapePathVariables(value)}`; + } + }; + return fn; }; +const escapePathVariables = value => { + return typeof value === "string" + ? value.replace(/\[(\\*[\w:]+\\*)\]/gi, "[\\$1\\]") + : value; +}; -/***/ }), +const replacePathVariables = (path, data, assetInfo) => { + const chunk = data.chunk; + const chunkId = chunk && chunk.id; + const chunkName = chunk && (chunk.name || chunk.id); + const chunkHash = chunk && (chunk.renderedHash || chunk.hash); + const chunkHashWithLength = chunk && chunk.hashWithLength; + const contentHashType = data.contentHashType; + const contentHash = + (chunk && chunk.contentHash && chunk.contentHash[contentHashType]) || + data.contentHash; + const contentHashWithLength = + (chunk && + chunk.contentHashWithLength && + chunk.contentHashWithLength[contentHashType]) || + data.contentHashWithLength; + const module = data.module; + const moduleId = module && module.id; + const moduleHash = module && (module.renderedHash || module.hash); + const moduleHashWithLength = module && module.hashWithLength; -/***/ 50588: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (typeof path === "function") { + path = path(data); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ + if ( + data.noChunkHash && + (REGEXP_CHUNKHASH_FOR_TEST.test(path) || + REGEXP_CONTENTHASH_FOR_TEST.test(path)) + ) { + throw new Error( + `Cannot use [chunkhash] or [contenthash] for chunk in '${path}' (use [hash] instead)` + ); + } + return ( + path + .replace( + REGEXP_HASH, + withHashLength(getReplacer(data.hash), data.hashWithLength, assetInfo) + ) + .replace( + REGEXP_CHUNKHASH, + withHashLength(getReplacer(chunkHash), chunkHashWithLength, assetInfo) + ) + .replace( + REGEXP_CONTENTHASH, + withHashLength( + getReplacer(contentHash), + contentHashWithLength, + assetInfo + ) + ) + .replace( + REGEXP_MODULEHASH, + withHashLength(getReplacer(moduleHash), moduleHashWithLength, assetInfo) + ) + .replace(REGEXP_ID, getReplacer(chunkId)) + .replace(REGEXP_MODULEID, getReplacer(moduleId)) + .replace(REGEXP_NAME, getReplacer(chunkName)) + .replace(REGEXP_FILE, getReplacer(data.filename)) + .replace(REGEXP_FILEBASE, getReplacer(data.basename)) + // query is optional, it's OK if it's in a path but there's nothing to replace it with + .replace(REGEXP_QUERY, getReplacer(data.query, true)) + // only available in sourceMappingURLComment + .replace(REGEXP_URL, getReplacer(data.url)) + .replace(/\[\\(\\*[\w:]+\\*)\\\]/gi, "[$1]") + ); +}; -const { Tapable, HookMap, SyncHook, SyncWaterfallHook } = __webpack_require__(56758); -const Factory = __webpack_require__(87450).ResolverFactory; -const { cachedCleverMerge } = __webpack_require__(67916); +class TemplatedPathPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("TemplatedPathPlugin", compilation => { + const mainTemplate = compilation.mainTemplate; -/** @typedef {import("enhanced-resolve").Resolver} Resolver */ + mainTemplate.hooks.assetPath.tap( + "TemplatedPathPlugin", + replacePathVariables + ); -const EMTPY_RESOLVE_OPTIONS = {}; + mainTemplate.hooks.globalHash.tap( + "TemplatedPathPlugin", + (chunk, paths) => { + const outputOptions = mainTemplate.outputOptions; + const publicPath = outputOptions.publicPath || ""; + const filename = outputOptions.filename || ""; + const chunkFilename = + outputOptions.chunkFilename || outputOptions.filename; + if ( + REGEXP_HASH_FOR_TEST.test(publicPath) || + REGEXP_CHUNKHASH_FOR_TEST.test(publicPath) || + REGEXP_CONTENTHASH_FOR_TEST.test(publicPath) || + REGEXP_NAME_FOR_TEST.test(publicPath) + ) + return true; + if (REGEXP_HASH_FOR_TEST.test(filename)) return true; + if (REGEXP_HASH_FOR_TEST.test(chunkFilename)) return true; + if (REGEXP_HASH_FOR_TEST.test(paths.join("|"))) return true; + } + ); -module.exports = class ResolverFactory extends Tapable { - constructor() { - super(); - this.hooks = { - resolveOptions: new HookMap( - () => new SyncWaterfallHook(["resolveOptions"]) - ), - resolver: new HookMap(() => new SyncHook(["resolver", "resolveOptions"])) - }; - this._pluginCompat.tap("ResolverFactory", options => { - let match; - match = /^resolve-options (.+)$/.exec(options.name); - if (match) { - this.hooks.resolveOptions - .for(match[1]) - .tap(options.fn.name || "unnamed compat plugin", options.fn); - return true; - } - match = /^resolver (.+)$/.exec(options.name); - if (match) { - this.hooks.resolver - .for(match[1]) - .tap(options.fn.name || "unnamed compat plugin", options.fn); - return true; - } + mainTemplate.hooks.hashForChunk.tap( + "TemplatedPathPlugin", + (hash, chunk) => { + const outputOptions = mainTemplate.outputOptions; + const chunkFilename = + outputOptions.chunkFilename || outputOptions.filename; + if (REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename)) { + hash.update(JSON.stringify(chunk.getChunkMaps(true).hash)); + } + if (REGEXP_CONTENTHASH_FOR_TEST.test(chunkFilename)) { + hash.update( + JSON.stringify( + chunk.getChunkMaps(true).contentHash.javascript || {} + ) + ); + } + if (REGEXP_NAME_FOR_TEST.test(chunkFilename)) { + hash.update(JSON.stringify(chunk.getChunkMaps(true).name)); + } + } + ); }); - this.cache2 = new Map(); - } - - get(type, resolveOptions) { - resolveOptions = resolveOptions || EMTPY_RESOLVE_OPTIONS; - const ident = `${type}|${JSON.stringify(resolveOptions)}`; - const resolver = this.cache2.get(ident); - if (resolver) return resolver; - const newResolver = this._create(type, resolveOptions); - this.cache2.set(ident, newResolver); - return newResolver; } +} - _create(type, resolveOptions) { - const originalResolveOptions = Object.assign({}, resolveOptions); - resolveOptions = this.hooks.resolveOptions.for(type).call(resolveOptions); - const resolver = Factory.createResolver(resolveOptions); - if (!resolver) { - throw new Error("No resolver created"); - } - /** @type {Map} */ - const childCache = new Map(); - resolver.withOptions = options => { - const cacheEntry = childCache.get(options); - if (cacheEntry !== undefined) return cacheEntry; - const mergedOptions = cachedCleverMerge(originalResolveOptions, options); - const resolver = this.get(type, mergedOptions); - childCache.set(options, resolver); - return resolver; - }; - this.hooks.resolver.for(type).call(resolver, resolveOptions); - return resolver; - } -}; +module.exports = TemplatedPathPlugin; /***/ }), -/***/ 84247: -/***/ (function(module) { +/***/ 75374: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -/* -: -: [] -: { - resource: { - test: , - include: , - exclude: , - }, - resource: , -> resource.test - test: , -> resource.test - include: , -> resource.include - exclude: , -> resource.exclude - resourceQuery: , - compiler: , - issuer: , - use: "loader", -> use[0].loader - loader: <>, -> use[0].loader - loaders: <>, -> use - options: {}, -> use[0].options, - query: {}, -> options - parser: {}, - use: [ - "loader" -> use[x].loader - ], - use: [ - { - loader: "loader", - options: {} - } - ], - rules: [ - - ], - oneOf: [ - - ] -} - -: /regExp/ -: function(arg) {} -: "starting" -: [] // or -: { and: [] } -: { or: [] } -: { not: [] } -: { test: , include: , exclude: } - - -normalized: - -{ - resource: function(), - resourceQuery: function(), - compiler: function(), - issuer: function(), - use: [ - { - loader: string, - options: string, - : - } - ], - rules: [], - oneOf: [], - : , -} -*/ +const { ConcatSource, OriginalSource } = __webpack_require__(53665); +const Template = __webpack_require__(96066); +/** @typedef {import("../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ +/** @typedef {import("./Compilation")} Compilation */ -const notMatcher = matcher => { - return str => { - return !matcher(str); - }; +/** + * @param {string[]} accessor the accessor to convert to path + * @returns {string} the path + */ +const accessorToObjectAccess = accessor => { + return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); }; -const orMatcher = items => { - return str => { - for (let i = 0; i < items.length; i++) { - if (items[i](str)) return true; - } - return false; - }; +/** + * @param {string=} base the path prefix + * @param {string|string[]} accessor the accessor + * @param {string=} joinWith the element separator + * @returns {string} the path + */ +const accessorAccess = (base, accessor, joinWith = ", ") => { + const accessors = Array.isArray(accessor) ? accessor : [accessor]; + return accessors + .map((_, idx) => { + const a = base + ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) + : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); + if (idx === accessors.length - 1) return a; + if (idx === 0 && base === undefined) + return `${a} = typeof ${a} === "object" ? ${a} : {}`; + return `${a} = ${a} || {}`; + }) + .join(joinWith); }; -const andMatcher = items => { - return str => { - for (let i = 0; i < items.length; i++) { - if (!items[i](str)) return false; - } - return true; - }; -}; +/** @typedef {string | string[] | LibraryCustomUmdObject} UmdMainTemplatePluginName */ -module.exports = class RuleSet { - constructor(rules) { - this.references = Object.create(null); - this.rules = RuleSet.normalizeRules(rules, this.references, "ref-"); - } +/** + * @typedef {Object} AuxiliaryCommentObject + * @property {string} root + * @property {string} commonjs + * @property {string} commonjs2 + * @property {string} amd + */ - static normalizeRules(rules, refs, ident) { - if (Array.isArray(rules)) { - return rules.map((rule, idx) => { - return RuleSet.normalizeRule(rule, refs, `${ident}-${idx}`); - }); - } else if (rules) { - return [RuleSet.normalizeRule(rules, refs, ident)]; - } else { - return []; - } - } +/** + * @typedef {Object} UmdMainTemplatePluginOption + * @property {boolean=} optionalAmdExternalAsGlobal + * @property {boolean} namedDefine + * @property {string | AuxiliaryCommentObject} auxiliaryComment + */ - static normalizeRule(rule, refs, ident) { - if (typeof rule === "string") { - return { - use: [ - { - loader: rule - } - ] +class UmdMainTemplatePlugin { + /** + * @param {UmdMainTemplatePluginName} name the name of the UMD library + * @param {UmdMainTemplatePluginOption} options the plugin option + */ + constructor(name, options) { + if (typeof name === "object" && !Array.isArray(name)) { + this.name = name.root || name.amd || name.commonjs; + this.names = name; + } else { + this.name = name; + this.names = { + commonjs: name, + root: name, + amd: name }; } - if (!rule) { - throw new Error("Unexcepted null when object was expected as rule"); - } - if (typeof rule !== "object") { - throw new Error( - "Unexcepted " + - typeof rule + - " when object was expected as rule (" + - rule + - ")" - ); - } + this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal; + this.namedDefine = options.namedDefine; + this.auxiliaryComment = options.auxiliaryComment; + } - const newRule = {}; - let useSource; - let resourceSource; - let condition; + /** + * @param {Compilation} compilation the compilation instance + * @returns {void} + */ + apply(compilation) { + const { mainTemplate, chunkTemplate, runtimeTemplate } = compilation; - const checkUseSource = newSource => { - if (useSource && useSource !== newSource) { - throw new Error( - RuleSet.buildErrorMessage( - rule, - new Error( - "Rule can only have one result source (provided " + - newSource + - " and " + - useSource + - ")" - ) - ) + const onRenderWithEntry = (source, chunk, hash) => { + let externals = chunk + .getModules() + .filter( + m => + m.external && + (m.externalType === "umd" || m.externalType === "umd2") ); + const optionalExternals = []; + let requiredExternals = []; + if (this.optionalAmdExternalAsGlobal) { + for (const m of externals) { + if (m.optional) { + optionalExternals.push(m); + } else { + requiredExternals.push(m); + } + } + externals = requiredExternals.concat(optionalExternals); + } else { + requiredExternals = externals; } - useSource = newSource; - }; - const checkResourceSource = newSource => { - if (resourceSource && resourceSource !== newSource) { - throw new Error( - RuleSet.buildErrorMessage( - rule, - new Error( - "Rule can only have one resource source (provided " + - newSource + - " and " + - resourceSource + - ")" + const replaceKeys = str => { + return mainTemplate.getAssetPath(str, { + hash, + chunk + }); + }; + + const externalsDepsArray = modules => { + return `[${replaceKeys( + modules + .map(m => + JSON.stringify( + typeof m.request === "object" ? m.request.amd : m.request + ) ) - ) - ); - } - resourceSource = newSource; - }; + .join(", ") + )}]`; + }; - if (rule.test || rule.include || rule.exclude) { - checkResourceSource("test + include + exclude"); - condition = { - test: rule.test, - include: rule.include, - exclude: rule.exclude + const externalsRootArray = modules => { + return replaceKeys( + modules + .map(m => { + let request = m.request; + if (typeof request === "object") request = request.root; + return `root${accessorToObjectAccess([].concat(request))}`; + }) + .join(", ") + ); }; - try { - newRule.resource = RuleSet.normalizeCondition(condition); - } catch (error) { - throw new Error(RuleSet.buildErrorMessage(condition, error)); - } - } - if (rule.resource) { - checkResourceSource("resource"); - try { - newRule.resource = RuleSet.normalizeCondition(rule.resource); - } catch (error) { - throw new Error(RuleSet.buildErrorMessage(rule.resource, error)); - } - } - - if (rule.realResource) { - try { - newRule.realResource = RuleSet.normalizeCondition(rule.realResource); - } catch (error) { - throw new Error(RuleSet.buildErrorMessage(rule.realResource, error)); - } - } + const externalsRequireArray = type => { + return replaceKeys( + externals + .map(m => { + let expr; + let request = m.request; + if (typeof request === "object") { + request = request[type]; + } + if (request === undefined) { + throw new Error( + "Missing external configuration for type:" + type + ); + } + if (Array.isArray(request)) { + expr = `require(${JSON.stringify( + request[0] + )})${accessorToObjectAccess(request.slice(1))}`; + } else { + expr = `require(${JSON.stringify(request)})`; + } + if (m.optional) { + expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; + } + return expr; + }) + .join(", ") + ); + }; - if (rule.resourceQuery) { - try { - newRule.resourceQuery = RuleSet.normalizeCondition(rule.resourceQuery); - } catch (error) { - throw new Error(RuleSet.buildErrorMessage(rule.resourceQuery, error)); - } - } + const externalsArguments = modules => { + return modules + .map( + m => + `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` + ) + .join(", "); + }; - if (rule.compiler) { - try { - newRule.compiler = RuleSet.normalizeCondition(rule.compiler); - } catch (error) { - throw new Error(RuleSet.buildErrorMessage(rule.compiler, error)); - } - } + const libraryName = library => { + return JSON.stringify(replaceKeys([].concat(library).pop())); + }; - if (rule.issuer) { - try { - newRule.issuer = RuleSet.normalizeCondition(rule.issuer); - } catch (error) { - throw new Error(RuleSet.buildErrorMessage(rule.issuer, error)); + let amdFactory; + if (optionalExternals.length > 0) { + const wrapperArguments = externalsArguments(requiredExternals); + const factoryArguments = + requiredExternals.length > 0 + ? externalsArguments(requiredExternals) + + ", " + + externalsRootArray(optionalExternals) + : externalsRootArray(optionalExternals); + amdFactory = + `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` + + ` return factory(${factoryArguments});\n` + + " }"; + } else { + amdFactory = "factory"; } - } - - if (rule.loader && rule.loaders) { - throw new Error( - RuleSet.buildErrorMessage( - rule, - new Error( - "Provided loader and loaders for rule (use only one of them)" - ) - ) - ); - } - const loader = rule.loaders || rule.loader; - if (typeof loader === "string" && !rule.options && !rule.query) { - checkUseSource("loader"); - newRule.use = RuleSet.normalizeUse(loader.split("!"), ident); - } else if (typeof loader === "string" && (rule.options || rule.query)) { - checkUseSource("loader + options/query"); - newRule.use = RuleSet.normalizeUse( - { - loader: loader, - options: rule.options, - query: rule.query - }, - ident - ); - } else if (loader && (rule.options || rule.query)) { - throw new Error( - RuleSet.buildErrorMessage( - rule, - new Error( - "options/query cannot be used with loaders (use options for each array item)" - ) - ) - ); - } else if (loader) { - checkUseSource("loaders"); - newRule.use = RuleSet.normalizeUse(loader, ident); - } else if (rule.options || rule.query) { - throw new Error( - RuleSet.buildErrorMessage( - rule, - new Error( - "options/query provided without loader (use loader + options)" - ) - ) - ); - } + const auxiliaryComment = this.auxiliaryComment; - if (rule.use) { - checkUseSource("use"); - newRule.use = RuleSet.normalizeUse(rule.use, ident); - } + const getAuxilaryComment = type => { + if (auxiliaryComment) { + if (typeof auxiliaryComment === "string") + return "\t//" + auxiliaryComment + "\n"; + if (auxiliaryComment[type]) + return "\t//" + auxiliaryComment[type] + "\n"; + } + return ""; + }; - if (rule.rules) { - newRule.rules = RuleSet.normalizeRules( - rule.rules, - refs, - `${ident}-rules` + return new ConcatSource( + new OriginalSource( + "(function webpackUniversalModuleDefinition(root, factory) {\n" + + getAuxilaryComment("commonjs2") + + " if(typeof exports === 'object' && typeof module === 'object')\n" + + " module.exports = factory(" + + externalsRequireArray("commonjs2") + + ");\n" + + getAuxilaryComment("amd") + + " else if(typeof define === 'function' && define.amd)\n" + + (requiredExternals.length > 0 + ? this.names.amd && this.namedDefine === true + ? " define(" + + libraryName(this.names.amd) + + ", " + + externalsDepsArray(requiredExternals) + + ", " + + amdFactory + + ");\n" + : " define(" + + externalsDepsArray(requiredExternals) + + ", " + + amdFactory + + ");\n" + : this.names.amd && this.namedDefine === true + ? " define(" + + libraryName(this.names.amd) + + ", [], " + + amdFactory + + ");\n" + : " define([], " + amdFactory + ");\n") + + (this.names.root || this.names.commonjs + ? getAuxilaryComment("commonjs") + + " else if(typeof exports === 'object')\n" + + " exports[" + + libraryName(this.names.commonjs || this.names.root) + + "] = factory(" + + externalsRequireArray("commonjs") + + ");\n" + + getAuxilaryComment("root") + + " else\n" + + " " + + replaceKeys( + accessorAccess("root", this.names.root || this.names.commonjs) + ) + + " = factory(" + + externalsRootArray(externals) + + ");\n" + : " else {\n" + + (externals.length > 0 + ? " var a = typeof exports === 'object' ? factory(" + + externalsRequireArray("commonjs") + + ") : factory(" + + externalsRootArray(externals) + + ");\n" + : " var a = factory();\n") + + " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" + + " }\n") + + `})(${ + runtimeTemplate.outputOptions.globalObject + }, function(${externalsArguments(externals)}) {\nreturn `, + "webpack/universalModuleDefinition" + ), + source, + ";\n})" ); - } + }; - if (rule.oneOf) { - newRule.oneOf = RuleSet.normalizeRules( - rule.oneOf, - refs, - `${ident}-oneOf` + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "UmdMainTemplatePlugin", + onRenderWithEntry ); } - const keys = Object.keys(rule).filter(key => { - return ![ - "resource", - "resourceQuery", - "compiler", - "test", - "include", - "exclude", - "issuer", - "loader", - "options", - "query", - "loaders", - "use", - "rules", - "oneOf" - ].includes(key); + mainTemplate.hooks.globalHashPaths.tap("UmdMainTemplatePlugin", paths => { + if (this.names.root) paths = paths.concat(this.names.root); + if (this.names.amd) paths = paths.concat(this.names.amd); + if (this.names.commonjs) paths = paths.concat(this.names.commonjs); + return paths; }); - for (const key of keys) { - newRule[key] = rule[key]; - } - - if (Array.isArray(newRule.use)) { - for (const item of newRule.use) { - if (item.ident) { - refs[item.ident] = item.options; - } - } - } - - return newRule; - } - - static buildErrorMessage(condition, error) { - const conditionAsText = JSON.stringify( - condition, - (key, value) => { - return value === undefined ? "undefined" : value; - }, - 2 - ); - return error.message + " in " + conditionAsText; - } - - static normalizeUse(use, ident) { - if (typeof use === "function") { - return data => RuleSet.normalizeUse(use(data), ident); - } - if (Array.isArray(use)) { - return use - .map((item, idx) => RuleSet.normalizeUse(item, `${ident}-${idx}`)) - .reduce((arr, items) => arr.concat(items), []); - } - return [RuleSet.normalizeUseItem(use, ident)]; - } - - static normalizeUseItemString(useItemString) { - const idx = useItemString.indexOf("?"); - if (idx >= 0) { - return { - loader: useItemString.substr(0, idx), - options: useItemString.substr(idx + 1) - }; - } - return { - loader: useItemString, - options: undefined - }; - } - - static normalizeUseItem(item, ident) { - if (typeof item === "string") { - return RuleSet.normalizeUseItemString(item); - } - - const newItem = {}; - - if (item.options && item.query) { - throw new Error("Provided options and query in use"); - } - - if (!item.loader) { - throw new Error("No loader specified"); - } - - newItem.options = item.options || item.query; - - if (typeof newItem.options === "object" && newItem.options) { - if (newItem.options.ident) { - newItem.ident = newItem.options.ident; - } else { - newItem.ident = ident; - } - } - const keys = Object.keys(item).filter(function(key) { - return !["options", "query"].includes(key); + mainTemplate.hooks.hash.tap("UmdMainTemplatePlugin", hash => { + hash.update("umd"); + hash.update(`${this.names.root}`); + hash.update(`${this.names.amd}`); + hash.update(`${this.names.commonjs}`); }); + } +} - for (const key of keys) { - newItem[key] = item[key]; - } +module.exports = UmdMainTemplatePlugin; - return newItem; - } - static normalizeCondition(condition) { - if (!condition) throw new Error("Expected condition but got falsy value"); - if (typeof condition === "string") { - return str => str.indexOf(condition) === 0; - } - if (typeof condition === "function") { - return condition; - } - if (condition instanceof RegExp) { - return condition.test.bind(condition); - } - if (Array.isArray(condition)) { - const items = condition.map(c => RuleSet.normalizeCondition(c)); - return orMatcher(items); - } - if (typeof condition !== "object") { - throw Error( - "Unexcepted " + - typeof condition + - " when condition was expected (" + - condition + - ")" - ); - } +/***/ }), - const matchers = []; - Object.keys(condition).forEach(key => { - const value = condition[key]; - switch (key) { - case "or": - case "include": - case "test": - if (value) matchers.push(RuleSet.normalizeCondition(value)); - break; - case "and": - if (value) { - const items = value.map(c => RuleSet.normalizeCondition(c)); - matchers.push(andMatcher(items)); - } - break; - case "not": - case "exclude": - if (value) { - const matcher = RuleSet.normalizeCondition(value); - matchers.push(notMatcher(matcher)); - } - break; - default: - throw new Error("Unexcepted property " + key + " in condition"); - } - }); - if (matchers.length === 0) { - throw new Error("Excepted condition but got " + condition); - } - if (matchers.length === 1) { - return matchers[0]; - } - return andMatcher(matchers); - } +/***/ 99953: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - exec(data) { - const result = []; - this._run( - data, - { - rules: this.rules - }, - result - ); - return result; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - _run(data, rule, result) { - // test conditions - if (rule.resource && !data.resource) return false; - if (rule.realResource && !data.realResource) return false; - if (rule.resourceQuery && !data.resourceQuery) return false; - if (rule.compiler && !data.compiler) return false; - if (rule.issuer && !data.issuer) return false; - if (rule.resource && !rule.resource(data.resource)) return false; - if (rule.realResource && !rule.realResource(data.realResource)) - return false; - if (data.issuer && rule.issuer && !rule.issuer(data.issuer)) return false; - if ( - data.resourceQuery && - rule.resourceQuery && - !rule.resourceQuery(data.resourceQuery) - ) { - return false; - } - if (data.compiler && rule.compiler && !rule.compiler(data.compiler)) { - return false; - } - // apply - const keys = Object.keys(rule).filter(key => { - return ![ - "resource", - "realResource", - "resourceQuery", - "compiler", - "issuer", - "rules", - "oneOf", - "use", - "enforce" - ].includes(key); - }); - for (const key of keys) { - result.push({ - type: key, - value: rule[key] - }); - } +const WebpackError = __webpack_require__(97391); - if (rule.use) { - const process = use => { - if (typeof use === "function") { - process(use(data)); - } else if (Array.isArray(use)) { - use.forEach(process); - } else { - result.push({ - type: "use", - value: use, - enforce: rule.enforce - }); - } - }; - process(rule.use); - } +/** @typedef {import("./Module")} Module */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ - if (rule.rules) { - for (let i = 0; i < rule.rules.length; i++) { - this._run(data, rule.rules[i], result); - } - } +class UnsupportedFeatureWarning extends WebpackError { + /** + * @param {Module} module module relevant to warning + * @param {string} message description of warning + * @param {DependencyLocation} loc location start and end positions of the module + */ + constructor(module, message, loc) { + super(message); - if (rule.oneOf) { - for (let i = 0; i < rule.oneOf.length; i++) { - if (this._run(data, rule.oneOf[i], result)) break; - } - } + this.name = "UnsupportedFeatureWarning"; + this.module = module; + this.loc = loc; + this.hideStack = true; - return true; + Error.captureStackTrace(this, this.constructor); } +} - findOptionsByIdent(ident) { - const options = this.references[ident]; - if (!options) { - throw new Error("Can't find options with ident '" + ident + "'"); - } - return options; - } -}; +module.exports = UnsupportedFeatureWarning; /***/ }), -/***/ 44006: +/***/ 73554: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90283,341 +90224,59 @@ module.exports = class RuleSet { */ -const Template = __webpack_require__(96066); - -/** @typedef {import("./Module")} Module */ - -module.exports = class RuntimeTemplate { - constructor(outputOptions, requestShortener) { - this.outputOptions = outputOptions || {}; - this.requestShortener = requestShortener; - } - - /** - * Add a comment - * @param {object} options Information content of the comment - * @param {string=} options.request request string used originally - * @param {string=} options.chunkName name of the chunk referenced - * @param {string=} options.chunkReason reason information of the chunk - * @param {string=} options.message additional message - * @param {string=} options.exportName name of the export - * @returns {string} comment - */ - comment({ request, chunkName, chunkReason, message, exportName }) { - let content; - if (this.outputOptions.pathinfo) { - content = [message, request, chunkName, chunkReason] - .filter(Boolean) - .map(item => this.requestShortener.shorten(item)) - .join(" | "); - } else { - content = [message, chunkName, chunkReason] - .filter(Boolean) - .map(item => this.requestShortener.shorten(item)) - .join(" | "); - } - if (!content) return ""; - if (this.outputOptions.pathinfo) { - return Template.toComment(content) + " "; - } else { - return Template.toNormalComment(content) + " "; - } - } - - throwMissingModuleErrorFunction({ request }) { - const err = `Cannot find module '${request}'`; - return `function webpackMissingModule() { var e = new Error(${JSON.stringify( - err - )}); e.code = 'MODULE_NOT_FOUND'; throw e; }`; - } - - missingModule({ request }) { - return `!(${this.throwMissingModuleErrorFunction({ request })}())`; - } - - missingModuleStatement({ request }) { - return `${this.missingModule({ request })};\n`; - } - - missingModulePromise({ request }) { - return `Promise.resolve().then(${this.throwMissingModuleErrorFunction({ - request - })})`; - } - - moduleId({ module, request }) { - if (!module) { - return this.missingModule({ - request - }); - } - if (module.id === null) { - throw new Error( - `RuntimeTemplate.moduleId(): Module ${module.identifier()} has no id. This should not happen.` - ); - } - return `${this.comment({ request })}${JSON.stringify(module.id)}`; - } - - moduleRaw({ module, request }) { - if (!module) { - return this.missingModule({ - request - }); - } - return `__webpack_require__(${this.moduleId({ module, request })})`; - } - - moduleExports({ module, request }) { - return this.moduleRaw({ - module, - request - }); - } - - moduleNamespace({ module, request, strict }) { - if (!module) { - return this.missingModule({ - request - }); - } - const moduleId = this.moduleId({ - module, - request - }); - const exportsType = module.buildMeta && module.buildMeta.exportsType; - if (exportsType === "namespace") { - const rawModule = this.moduleRaw({ - module, - request - }); - return rawModule; - } else if (exportsType === "named") { - return `__webpack_require__.t(${moduleId}, 3)`; - } else if (strict) { - return `__webpack_require__.t(${moduleId}, 1)`; - } else { - return `__webpack_require__.t(${moduleId}, 7)`; - } - } - - moduleNamespacePromise({ block, module, request, message, strict, weak }) { - if (!module) { - return this.missingModulePromise({ - request - }); - } - if (module.id === null) { - throw new Error( - `RuntimeTemplate.moduleNamespacePromise(): Module ${module.identifier()} has no id. This should not happen.` - ); - } - const promise = this.blockPromise({ - block, - message - }); - - let getModuleFunction; - let idExpr = JSON.stringify(module.id); - const comment = this.comment({ - request - }); - let header = ""; - if (weak) { - if (idExpr.length > 8) { - // 'var x="nnnnnn";x,"+x+",x' vs '"nnnnnn",nnnnnn,"nnnnnn"' - header += `var id = ${idExpr}; `; - idExpr = "id"; - } - header += `if(!__webpack_require__.m[${idExpr}]) { var e = new Error("Module '" + ${idExpr} + "' is not available (weak dependency)"); e.code = 'MODULE_NOT_FOUND'; throw e; } `; - } - const moduleId = this.moduleId({ - module, - request - }); - const exportsType = module.buildMeta && module.buildMeta.exportsType; - if (exportsType === "namespace") { - if (header) { - const rawModule = this.moduleRaw({ - module, - request - }); - getModuleFunction = `function() { ${header}return ${rawModule}; }`; - } else { - getModuleFunction = `__webpack_require__.bind(null, ${comment}${idExpr})`; - } - } else if (exportsType === "named") { - if (header) { - getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 3); }`; - } else { - getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 3)`; - } - } else if (strict) { - if (header) { - getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 1); }`; - } else { - getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 1)`; - } - } else { - if (header) { - getModuleFunction = `function() { ${header}return __webpack_require__.t(${moduleId}, 7); }`; - } else { - getModuleFunction = `__webpack_require__.t.bind(null, ${comment}${idExpr}, 7)`; - } - } +const ConstDependency = __webpack_require__(71101); - return `${promise || "Promise.resolve()"}.then(${getModuleFunction})`; - } +/** @typedef {import("./Compiler")} Compiler */ +class UseStrictPlugin { /** - * - * @param {Object} options options object - * @param {boolean=} options.update whether a new variable should be created or the existing one updated - * @param {Module} options.module the module - * @param {string} options.request the request that should be printed as comment - * @param {string} options.importVar name of the import variable - * @param {Module} options.originModule module in which the statement is emitted - * @returns {string} the import statement + * @param {Compiler} compiler Webpack Compiler + * @returns {void} */ - importStatement({ update, module, request, importVar, originModule }) { - if (!module) { - return this.missingModuleStatement({ - request - }); - } - const moduleId = this.moduleId({ - module, - request - }); - const optDeclaration = update ? "" : "var "; - - const exportsType = module.buildMeta && module.buildMeta.exportsType; - let content = `/* harmony import */ ${optDeclaration}${importVar} = __webpack_require__(${moduleId});\n`; - - if (!exportsType && !originModule.buildMeta.strictHarmonyModule) { - content += `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/__webpack_require__.n(${importVar});\n`; - } - if (exportsType === "named") { - if (Array.isArray(module.buildMeta.providedExports)) { - content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/__webpack_require__.t(${moduleId}, 1);\n`; - } else { - content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/__webpack_require__.t(${moduleId});\n`; - } - } - return content; - } - - exportFromImport({ - module, - request, - exportName, - originModule, - asiSafe, - isCall, - callContext, - importVar - }) { - if (!module) { - return this.missingModule({ - request - }); - } - const exportsType = module.buildMeta && module.buildMeta.exportsType; - - if (!exportsType) { - if (exportName === "default") { - if (!originModule.buildMeta.strictHarmonyModule) { - if (isCall) { - return `${importVar}_default()`; - } else if (asiSafe) { - return `(${importVar}_default())`; - } else { - return `${importVar}_default.a`; - } - } else { - return importVar; - } - } else if (originModule.buildMeta.strictHarmonyModule) { - if (exportName) { - return "/* non-default import from non-esm module */undefined"; - } else { - return `/*#__PURE__*/__webpack_require__.t(${importVar})`; - } - } - } - - if (exportsType === "named") { - if (exportName === "default") { - return importVar; - } else if (!exportName) { - return `${importVar}_namespace`; - } - } + apply(compiler) { + compiler.hooks.compilation.tap( + "UseStrictPlugin", + (compilation, { normalModuleFactory }) => { + const handler = parser => { + parser.hooks.program.tap("UseStrictPlugin", ast => { + const firstNode = ast.body[0]; + if ( + firstNode && + firstNode.type === "ExpressionStatement" && + firstNode.expression.type === "Literal" && + firstNode.expression.value === "use strict" + ) { + // Remove "use strict" expression. It will be added later by the renderer again. + // This is necessary in order to not break the strict mode when webpack prepends code. + // @see https://github.com/webpack/webpack/issues/1970 + const dep = new ConstDependency("", firstNode.range); + dep.loc = firstNode.loc; + parser.state.current.addDependency(dep); + parser.state.module.buildInfo.strict = true; + } + }); + }; - if (exportName) { - const used = module.isUsed(exportName); - if (!used) { - const comment = Template.toNormalComment(`unused export ${exportName}`); - return `${comment} undefined`; - } - const comment = - used !== exportName ? Template.toNormalComment(exportName) + " " : ""; - const access = `${importVar}[${comment}${JSON.stringify(used)}]`; - if (isCall) { - if (callContext === false && asiSafe) { - return `(0,${access})`; - } else if (callContext === false) { - return `Object(${access})`; - } + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("UseStrictPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("UseStrictPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("UseStrictPlugin", handler); } - return access; - } else { - return importVar; - } - } - - blockPromise({ block, message }) { - if (!block || !block.chunkGroup || block.chunkGroup.chunks.length === 0) { - const comment = this.comment({ - message - }); - return `Promise.resolve(${comment.trim()})`; - } - const chunks = block.chunkGroup.chunks.filter( - chunk => !chunk.hasRuntime() && chunk.id !== null ); - const comment = this.comment({ - message, - chunkName: block.chunkName, - chunkReason: block.chunkReason - }); - if (chunks.length === 1) { - const chunkId = JSON.stringify(chunks[0].id); - return `__webpack_require__.e(${comment}${chunkId})`; - } else if (chunks.length > 0) { - const requireChunkId = chunk => - `__webpack_require__.e(${JSON.stringify(chunk.id)})`; - return `Promise.all(${comment.trim()}[${chunks - .map(requireChunkId) - .join(", ")}])`; - } else { - return `Promise.resolve(${comment.trim()})`; - } - } - - onError() { - return "__webpack_require__.oe"; } +} - defineEsModuleFlagStatement({ exportsArgument }) { - return `__webpack_require__.r(${exportsArgument});\n`; - } -}; +module.exports = UseStrictPlugin; /***/ }), -/***/ 37098: +/***/ 40269: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90627,74 +90286,42 @@ module.exports = class RuntimeTemplate { */ -const { ConcatSource } = __webpack_require__(53665); - -/** @typedef {import("./Compilation")} Compilation */ - -class SetVarMainTemplatePlugin { - /** - * @param {string} varExpression the accessor where the library is exported - * @param {boolean} copyObject specify copying the exports - */ - constructor(varExpression, copyObject) { - /** @type {string} */ - this.varExpression = varExpression; - /** @type {boolean} */ - this.copyObject = copyObject; - } - - /** - * @param {Compilation} compilation the compilation instance - * @returns {void} - */ - apply(compilation) { - const { mainTemplate, chunkTemplate } = compilation; - - const onRenderWithEntry = (source, chunk, hash) => { - const varExpression = mainTemplate.getAssetPath(this.varExpression, { - hash, - chunk - }); - if (this.copyObject) { - return new ConcatSource( - `(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `, - source, - "))" - ); - } else { - const prefix = `${varExpression} =\n`; - return new ConcatSource(prefix, source); - } - }; - - for (const template of [mainTemplate, chunkTemplate]) { - template.hooks.renderWithEntry.tap( - "SetVarMainTemplatePlugin", - onRenderWithEntry - ); - } +const CaseSensitiveModulesWarning = __webpack_require__(8335); - mainTemplate.hooks.globalHashPaths.tap( - "SetVarMainTemplatePlugin", - paths => { - if (this.varExpression) paths.push(this.varExpression); - return paths; +class WarnCaseSensitiveModulesPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "WarnCaseSensitiveModulesPlugin", + compilation => { + compilation.hooks.seal.tap("WarnCaseSensitiveModulesPlugin", () => { + const moduleWithoutCase = new Map(); + for (const module of compilation.modules) { + const identifier = module.identifier().toLowerCase(); + const array = moduleWithoutCase.get(identifier); + if (array) { + array.push(module); + } else { + moduleWithoutCase.set(identifier, [module]); + } + } + for (const pair of moduleWithoutCase) { + const array = pair[1]; + if (array.length > 1) { + compilation.warnings.push(new CaseSensitiveModulesWarning(array)); + } + } + }); } ); - mainTemplate.hooks.hash.tap("SetVarMainTemplatePlugin", hash => { - hash.update("set var"); - hash.update(`${this.varExpression}`); - hash.update(`${this.copyObject}`); - }); } } -module.exports = SetVarMainTemplatePlugin; +module.exports = WarnCaseSensitiveModulesPlugin; /***/ }), -/***/ 19070: +/***/ 71245: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90703,101 +90330,137 @@ module.exports = SetVarMainTemplatePlugin; Author Tobias Koppers @sokra */ -const SingleEntryDependency = __webpack_require__(84828); - -/** @typedef {import("./Compiler")} Compiler */ -class SingleEntryPlugin { - /** - * An entry plugin which will handle - * creation of the SingleEntryDependency - * - * @param {string} context context path - * @param {string} entry entry path - * @param {string} name entry key name - */ - constructor(context, entry, name) { - this.context = context; - this.entry = entry; - this.name = name; - } +const NoModeWarning = __webpack_require__(45759); - /** - * @param {Compiler} compiler the compiler instance - * @returns {void} - */ +class WarnNoModeSetPlugin { apply(compiler) { - compiler.hooks.compilation.tap( - "SingleEntryPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - SingleEntryDependency, - normalModuleFactory - ); - } - ); - - compiler.hooks.make.tapAsync( - "SingleEntryPlugin", - (compilation, callback) => { - const { entry, name, context } = this; - - const dep = SingleEntryPlugin.createDependency(entry, name); - compilation.addEntry(context, dep, name, callback); - } - ); - } - - /** - * @param {string} entry entry request - * @param {string} name entry name - * @returns {SingleEntryDependency} the dependency - */ - static createDependency(entry, name) { - const dep = new SingleEntryDependency(entry); - dep.loc = { name }; - return dep; + compiler.hooks.thisCompilation.tap("WarnNoModeSetPlugin", compilation => { + compilation.warnings.push(new NoModeWarning()); + }); } } -module.exports = SingleEntryPlugin; +module.exports = WarnNoModeSetPlugin; /***/ }), -/***/ 12496: -/***/ (function(__unused_webpack_module, exports) { +/***/ 88015: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn + Author Tobias Koppers @sokra */ -const SizeFormatHelpers = exports; +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(97009); -SizeFormatHelpers.formatSize = size => { - if (typeof size !== "number" || Number.isNaN(size) === true) { - return "unknown size"; +/** @typedef {import("../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions} WatchIgnorePluginOptions */ + +class IgnoringWatchFileSystem { + constructor(wfs, paths) { + this.wfs = wfs; + this.paths = paths; } - if (size <= 0) { - return "0 bytes"; + watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { + const ignored = path => + this.paths.some(p => + p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0 + ); + + const notIgnored = path => !ignored(path); + + const ignoredFiles = files.filter(ignored); + const ignoredDirs = dirs.filter(ignored); + + const watcher = this.wfs.watch( + files.filter(notIgnored), + dirs.filter(notIgnored), + missing, + startTime, + options, + ( + err, + filesModified, + dirsModified, + missingModified, + fileTimestamps, + dirTimestamps, + removedFiles + ) => { + if (err) return callback(err); + for (const path of ignoredFiles) { + fileTimestamps.set(path, 1); + } + + for (const path of ignoredDirs) { + dirTimestamps.set(path, 1); + } + + callback( + err, + filesModified, + dirsModified, + missingModified, + fileTimestamps, + dirTimestamps, + removedFiles + ); + }, + callbackUndelayed + ); + + return { + close: () => watcher.close(), + pause: () => watcher.pause(), + getContextTimestamps: () => { + const dirTimestamps = watcher.getContextTimestamps(); + for (const path of ignoredDirs) { + dirTimestamps.set(path, 1); + } + return dirTimestamps; + }, + getFileTimestamps: () => { + const fileTimestamps = watcher.getFileTimestamps(); + for (const path of ignoredFiles) { + fileTimestamps.set(path, 1); + } + return fileTimestamps; + } + }; } +} - const abbreviations = ["bytes", "KiB", "MiB", "GiB"]; - const index = Math.floor(Math.log(size) / Math.log(1024)); +class WatchIgnorePlugin { + /** + * @param {WatchIgnorePluginOptions} paths list of paths + */ + constructor(paths) { + validateOptions(schema, paths, "Watch Ignore Plugin"); + this.paths = paths; + } - return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${ - abbreviations[index] - }`; -}; + apply(compiler) { + compiler.hooks.afterEnvironment.tap("WatchIgnorePlugin", () => { + compiler.watchFileSystem = new IgnoringWatchFileSystem( + compiler.watchFileSystem, + this.paths + ); + }); + } +} + +module.exports = WatchIgnorePlugin; /***/ }), -/***/ 24113: +/***/ 29580: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -90807,3123 +90470,2837 @@ SizeFormatHelpers.formatSize = size => { */ -const ModuleFilenameHelpers = __webpack_require__(71474); +const Stats = __webpack_require__(99977); -class SourceMapDevToolModuleOptionsPlugin { - constructor(options) { - this.options = options; +class Watching { + constructor(compiler, watchOptions, handler) { + this.startTime = null; + this.invalid = false; + this.handler = handler; + this.callbacks = []; + this.closed = false; + this.suspended = false; + if (typeof watchOptions === "number") { + this.watchOptions = { + aggregateTimeout: watchOptions + }; + } else if (watchOptions && typeof watchOptions === "object") { + this.watchOptions = Object.assign({}, watchOptions); + } else { + this.watchOptions = {}; + } + this.watchOptions.aggregateTimeout = + this.watchOptions.aggregateTimeout || 200; + this.compiler = compiler; + this.running = true; + this.compiler.readRecords(err => { + if (err) return this._done(err); + + this._go(); + }); } - apply(compilation) { - const options = this.options; - if (options.module !== false) { - compilation.hooks.buildModule.tap( - "SourceMapDevToolModuleOptionsPlugin", - module => { - module.useSourceMap = true; + _go() { + this.startTime = Date.now(); + this.running = true; + this.invalid = false; + this.compiler.hooks.watchRun.callAsync(this.compiler, err => { + if (err) return this._done(err); + const onCompiled = (err, compilation) => { + if (err) return this._done(err); + if (this.invalid) return this._done(); + + if (this.compiler.hooks.shouldEmit.call(compilation) === false) { + return this._done(null, compilation); } - ); + + this.compiler.emitAssets(compilation, err => { + if (err) return this._done(err); + if (this.invalid) return this._done(); + this.compiler.emitRecords(err => { + if (err) return this._done(err); + + if (compilation.hooks.needAdditionalPass.call()) { + compilation.needAdditionalPass = true; + + const stats = new Stats(compilation); + stats.startTime = this.startTime; + stats.endTime = Date.now(); + this.compiler.hooks.done.callAsync(stats, err => { + if (err) return this._done(err); + + this.compiler.hooks.additionalPass.callAsync(err => { + if (err) return this._done(err); + this.compiler.compile(onCompiled); + }); + }); + return; + } + return this._done(null, compilation); + }); + }); + }; + this.compiler.compile(onCompiled); + }); + } + + _getStats(compilation) { + const stats = new Stats(compilation); + stats.startTime = this.startTime; + stats.endTime = Date.now(); + return stats; + } + + _done(err, compilation) { + this.running = false; + if (this.invalid) return this._go(); + + const stats = compilation ? this._getStats(compilation) : null; + if (err) { + this.compiler.hooks.failed.call(err); + this.handler(err, stats); + return; } - if (options.lineToLine === true) { - compilation.hooks.buildModule.tap( - "SourceMapDevToolModuleOptionsPlugin", - module => { - module.lineToLine = true; + this.compiler.hooks.done.callAsync(stats, () => { + this.handler(null, stats); + if (!this.closed) { + this.watch( + Array.from(compilation.fileDependencies), + Array.from(compilation.contextDependencies), + Array.from(compilation.missingDependencies) + ); + } + for (const cb of this.callbacks) cb(); + this.callbacks.length = 0; + }); + } + + watch(files, dirs, missing) { + this.pausedWatcher = null; + this.watcher = this.compiler.watchFileSystem.watch( + files, + dirs, + missing, + this.startTime, + this.watchOptions, + ( + err, + filesModified, + contextModified, + missingModified, + fileTimestamps, + contextTimestamps, + removedFiles + ) => { + this.pausedWatcher = this.watcher; + this.watcher = null; + if (err) { + return this.handler(err); } - ); - } else if (options.lineToLine) { - compilation.hooks.buildModule.tap( - "SourceMapDevToolModuleOptionsPlugin", - module => { - if (!module.resource) return; - let resourcePath = module.resource; - const idx = resourcePath.indexOf("?"); - if (idx >= 0) resourcePath = resourcePath.substr(0, idx); - module.lineToLine = ModuleFilenameHelpers.matchObject( - options.lineToLine, - resourcePath - ); + this.compiler.fileTimestamps = fileTimestamps; + this.compiler.contextTimestamps = contextTimestamps; + this.compiler.removedFiles = removedFiles; + if (!this.suspended) { + this._invalidate(); } - ); + }, + (fileName, changeTime) => { + this.compiler.hooks.invalid.call(fileName, changeTime); + } + ); + } + + invalidate(callback) { + if (callback) { + this.callbacks.push(callback); + } + if (this.watcher) { + this.compiler.fileTimestamps = this.watcher.getFileTimestamps(); + this.compiler.contextTimestamps = this.watcher.getContextTimestamps(); + } + return this._invalidate(); + } + + _invalidate() { + if (this.watcher) { + this.pausedWatcher = this.watcher; + this.watcher.pause(); + this.watcher = null; + } + + if (this.running) { + this.invalid = true; + return false; + } else { + this._go(); + } + } + + suspend() { + this.suspended = true; + this.invalid = false; + } + + resume() { + if (this.suspended) { + this.suspended = false; + this._invalidate(); + } + } + + close(callback) { + const finalCallback = () => { + this.compiler.hooks.watchClose.call(); + this.compiler.running = false; + this.compiler.watchMode = false; + if (callback !== undefined) callback(); + }; + + this.closed = true; + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + if (this.pausedWatcher) { + this.pausedWatcher.close(); + this.pausedWatcher = null; + } + if (this.running) { + this.invalid = true; + this._done = finalCallback; + } else { + finalCallback(); } } } -module.exports = SourceMapDevToolModuleOptionsPlugin; +module.exports = Watching; /***/ }), -/***/ 11851: +/***/ 97391: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Jarid Margolin @jaridmargolin */ -const path = __webpack_require__(85622); -const { ConcatSource, RawSource } = __webpack_require__(53665); -const ModuleFilenameHelpers = __webpack_require__(71474); -const SourceMapDevToolModuleOptionsPlugin = __webpack_require__(24113); -const createHash = __webpack_require__(15660); -const { absolutify } = __webpack_require__(94658); +const inspect = __webpack_require__(31669).inspect.custom; -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(7368); +class WebpackError extends Error { + /** + * Creates an instance of WebpackError. + * @param {string=} message error message + */ + constructor(message) { + super(message); -/** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("source-map").RawSourceMap} SourceMap */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./Compiler")} Compiler */ -/** @typedef {import("./Compilation")} SourceMapDefinition */ + this.details = undefined; + this.missing = undefined; + this.origin = undefined; + this.dependencies = undefined; + this.module = undefined; -/** - * @typedef {object} SourceMapTask - * @property {Source} asset - * @property {Array} [modules] - * @property {string} source - * @property {string} file - * @property {SourceMap} sourceMap - * @property {Chunk} chunk - */ + Error.captureStackTrace(this, this.constructor); + } -/** - * @param {string} name file path - * @returns {string} file name - */ -const basename = name => { - if (!name.includes("/")) return name; - return name.substr(name.lastIndexOf("/") + 1); -}; + [inspect]() { + return this.stack + (this.details ? `\n${this.details}` : ""); + } +} -/** - * @type {WeakMap} - */ -const assetsCache = new WeakMap(); +module.exports = WebpackError; -/** - * Creating {@link SourceMapTask} for given file - * @param {string} file current compiled file - * @param {Source} asset the asset - * @param {Chunk} chunk related chunk - * @param {SourceMapDevToolPluginOptions} options source map options - * @param {Compilation} compilation compilation instance - * @returns {SourceMapTask | undefined} created task instance or `undefined` - */ -const getTaskForFile = (file, asset, chunk, options, compilation) => { - let source, sourceMap; - /** - * Check if asset can build source map - */ - if (asset.sourceAndMap) { - const sourceAndMap = asset.sourceAndMap(options); - sourceMap = sourceAndMap.map; - source = sourceAndMap.source; - } else { - sourceMap = asset.map(options); - source = asset.source(); - } - if (!sourceMap || typeof source !== "string") return; - const context = compilation.options.context; - const modules = sourceMap.sources.map(source => { - if (source.startsWith("webpack://")) { - source = absolutify(context, source.slice(10)); - } - const module = compilation.findModule(source); - return module || source; - }); - return { - chunk, - file, - asset, - source, - sourceMap, - modules - }; -}; +/***/ }), -class SourceMapDevToolPlugin { - /** - * @param {SourceMapDevToolPluginOptions} [options] options object - * @throws {Error} throws error, if got more than 1 arguments - */ - constructor(options) { - if (arguments.length > 1) { - throw new Error( - "SourceMapDevToolPlugin only takes one argument (pass an options object)" - ); - } +/***/ 2779: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (!options) options = {}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - validateOptions(schema, options, "SourceMap DevTool Plugin"); - /** @type {string | false} */ - this.sourceMapFilename = options.filename; - /** @type {string | false} */ - this.sourceMappingURLComment = - options.append === false - ? false - : options.append || "\n//# sourceMappingURL=[url]"; - /** @type {string | Function} */ - this.moduleFilenameTemplate = - options.moduleFilenameTemplate || "webpack://[namespace]/[resourcePath]"; - /** @type {string | Function} */ - this.fallbackModuleFilenameTemplate = - options.fallbackModuleFilenameTemplate || - "webpack://[namespace]/[resourcePath]?[hash]"; - /** @type {string} */ - this.namespace = options.namespace || ""; - /** @type {SourceMapDevToolPluginOptions} */ - this.options = options; - } +const OptionsApply = __webpack_require__(4428); - /** - * Apply compiler - * @param {Compiler} compiler compiler instance - * @returns {void} - */ - apply(compiler) { - const sourceMapFilename = this.sourceMapFilename; - const sourceMappingURLComment = this.sourceMappingURLComment; - const moduleFilenameTemplate = this.moduleFilenameTemplate; - const namespace = this.namespace; - const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; - const requestShortener = compiler.requestShortener; - const options = this.options; - options.test = options.test || /\.(m?js|css)($|\?)/i; +const JavascriptModulesPlugin = __webpack_require__(10339); +const JsonModulesPlugin = __webpack_require__(2859); +const WebAssemblyModulesPlugin = __webpack_require__(99510); - const matchObject = ModuleFilenameHelpers.matchObject.bind( - undefined, - options - ); +const LoaderTargetPlugin = __webpack_require__(95154); +const FunctionModulePlugin = __webpack_require__(31221); +const EvalDevToolModulePlugin = __webpack_require__(65200); +const SourceMapDevToolPlugin = __webpack_require__(11851); +const EvalSourceMapDevToolPlugin = __webpack_require__(99994); - compiler.hooks.compilation.tap("SourceMapDevToolPlugin", compilation => { - new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); +const EntryOptionPlugin = __webpack_require__(14604); +const RecordIdsPlugin = __webpack_require__(40355); - compilation.hooks.afterOptimizeChunkAssets.tap( - /** @type {TODO} */ - ({ name: "SourceMapDevToolPlugin", context: true }), - /** - * @param {object} context hook context - * @param {Array} chunks resulted chunks - * @throws {Error} throws error, if `sourceMapFilename === false && sourceMappingURLComment === false` - * @returns {void} - */ - (context, chunks) => { - /** @type {Map} */ - const moduleToSourceNameMapping = new Map(); - /** - * @type {Function} - * @returns {void} - */ - const reportProgress = - context && context.reportProgress - ? context.reportProgress - : () => {}; - - const files = []; - for (const chunk of chunks) { - for (const file of chunk.files) { - if (matchObject(file)) { - files.push({ - file, - chunk - }); - } - } - } - - reportProgress(0.0); - const tasks = []; - files.forEach(({ file, chunk }, idx) => { - const asset = compilation.getAsset(file).source; - const cache = assetsCache.get(asset); - /** - * If presented in cache, reassigns assets. Cache assets already have source maps. - */ - if (cache && cache.file === file) { - for (const cachedFile in cache.assets) { - if (cachedFile === file) { - compilation.updateAsset(cachedFile, cache.assets[cachedFile]); - } else { - compilation.emitAsset(cachedFile, cache.assets[cachedFile], { - development: true - }); - } - /** - * Add file to chunk, if not presented there - */ - if (cachedFile !== file) chunk.files.push(cachedFile); - } - return; - } - - reportProgress( - (0.5 * idx) / files.length, - file, - "generate SourceMap" - ); - /** @type {SourceMapTask | undefined} */ - const task = getTaskForFile( - file, - asset, - chunk, - options, - compilation - ); - - if (task) { - const modules = task.modules; +const APIPlugin = __webpack_require__(71118); +const ConstPlugin = __webpack_require__(84072); +const CommonJsStuffPlugin = __webpack_require__(85736); +const CompatibilityPlugin = __webpack_require__(85918); - for (let idx = 0; idx < modules.length; idx++) { - const module = modules[idx]; - if (!moduleToSourceNameMapping.get(module)) { - moduleToSourceNameMapping.set( - module, - ModuleFilenameHelpers.createFilename( - module, - { - moduleFilenameTemplate: moduleFilenameTemplate, - namespace: namespace - }, - requestShortener - ) - ); - } - } +const TemplatedPathPlugin = __webpack_require__(76032); +const WarnCaseSensitiveModulesPlugin = __webpack_require__(40269); +const UseStrictPlugin = __webpack_require__(73554); - tasks.push(task); - } - }); +const LoaderPlugin = __webpack_require__(31559); +const CommonJsPlugin = __webpack_require__(85358); +const HarmonyModulesPlugin = __webpack_require__(66792); +const SystemPlugin = __webpack_require__(68166); +const ImportPlugin = __webpack_require__(58839); +const RequireContextPlugin = __webpack_require__(89042); +const RequireEnsurePlugin = __webpack_require__(98655); +const RequireIncludePlugin = __webpack_require__(16522); - reportProgress(0.5, "resolve sources"); - /** @type {Set} */ - const usedNamesSet = new Set(moduleToSourceNameMapping.values()); - /** @type {Set} */ - const conflictDetectionSet = new Set(); +const { cachedCleverMerge } = __webpack_require__(67916); - /** - * all modules in defined order (longest identifier first) - * @type {Array} - */ - const allModules = Array.from(moduleToSourceNameMapping.keys()).sort( - (a, b) => { - const ai = typeof a === "string" ? a : a.identifier(); - const bi = typeof b === "string" ? b : b.identifier(); - return ai.length - bi.length; - } - ); +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/** @typedef {import("./Compiler")} Compiler */ - // find modules with conflicting source names - for (let idx = 0; idx < allModules.length; idx++) { - const module = allModules[idx]; - let sourceName = moduleToSourceNameMapping.get(module); - let hasName = conflictDetectionSet.has(sourceName); - if (!hasName) { - conflictDetectionSet.add(sourceName); - continue; - } +class WebpackOptionsApply extends OptionsApply { + constructor() { + super(); + } - // try the fallback name first - sourceName = ModuleFilenameHelpers.createFilename( - module, - { - moduleFilenameTemplate: fallbackModuleFilenameTemplate, - namespace: namespace - }, - requestShortener - ); - hasName = usedNamesSet.has(sourceName); - if (!hasName) { - moduleToSourceNameMapping.set(module, sourceName); - usedNamesSet.add(sourceName); - continue; - } + /** + * @param {WebpackOptions} options options object + * @param {Compiler} compiler compiler object + * @returns {WebpackOptions} options object + */ + process(options, compiler) { + let ExternalsPlugin; + compiler.outputPath = options.output.path; + compiler.recordsInputPath = options.recordsInputPath || options.recordsPath; + compiler.recordsOutputPath = + options.recordsOutputPath || options.recordsPath; + compiler.name = options.name; + // TODO webpack 5 refactor this to MultiCompiler.setDependencies() with a WeakMap + // @ts-ignore TODO + compiler.dependencies = options.dependencies; + if (typeof options.target === "string") { + let JsonpTemplatePlugin; + let FetchCompileWasmTemplatePlugin; + let ReadFileCompileWasmTemplatePlugin; + let NodeSourcePlugin; + let NodeTargetPlugin; + let NodeTemplatePlugin; - // elsewise just append stars until we have a valid name - while (hasName) { - sourceName += "*"; - hasName = usedNamesSet.has(sourceName); - } - moduleToSourceNameMapping.set(module, sourceName); - usedNamesSet.add(sourceName); - } - tasks.forEach((task, index) => { - reportProgress( - 0.5 + (0.5 * index) / tasks.length, - task.file, - "attach SourceMap" - ); - const assets = Object.create(null); - const chunk = task.chunk; - const file = task.file; - const asset = task.asset; - const sourceMap = task.sourceMap; - const source = task.source; - const modules = task.modules; - const moduleFilenames = modules.map(m => - moduleToSourceNameMapping.get(m) - ); - sourceMap.sources = moduleFilenames; - if (options.noSources) { - sourceMap.sourcesContent = undefined; - } - sourceMap.sourceRoot = options.sourceRoot || ""; - sourceMap.file = file; - assetsCache.set(asset, { file, assets }); - /** @type {string | false} */ - let currentSourceMappingURLComment = sourceMappingURLComment; - if ( - currentSourceMappingURLComment !== false && - /\.css($|\?)/i.test(file) - ) { - currentSourceMappingURLComment = currentSourceMappingURLComment.replace( - /^\n\/\/(.*)$/, - "\n/*$1*/" - ); - } - const sourceMapString = JSON.stringify(sourceMap); - if (sourceMapFilename) { - let filename = file; - let query = ""; - const idx = filename.indexOf("?"); - if (idx >= 0) { - query = filename.substr(idx); - filename = filename.substr(0, idx); - } - const pathParams = { - chunk, - filename: options.fileContext - ? path.relative(options.fileContext, filename) - : filename, - query, - basename: basename(filename), - contentHash: createHash("md4") - .update(sourceMapString) - .digest("hex") - }; - let sourceMapFile = compilation.getPath( - sourceMapFilename, - pathParams - ); - const sourceMapUrl = options.publicPath - ? options.publicPath + sourceMapFile.replace(/\\/g, "/") - : path - .relative(path.dirname(file), sourceMapFile) - .replace(/\\/g, "/"); - /** - * Add source map url to compilation asset, if {@link currentSourceMappingURLComment} presented - */ - if (currentSourceMappingURLComment !== false) { - const asset = new ConcatSource( - new RawSource(source), - compilation.getPath( - currentSourceMappingURLComment, - Object.assign({ url: sourceMapUrl }, pathParams) - ) - ); - assets[file] = asset; - compilation.updateAsset(file, asset); - } - /** - * Add source map file to compilation assets and chunk files - */ - const asset = new RawSource(sourceMapString); - assets[sourceMapFile] = asset; - compilation.emitAsset(sourceMapFile, asset, { - development: true - }); - chunk.files.push(sourceMapFile); - } else { - if (currentSourceMappingURLComment === false) { - throw new Error( - "SourceMapDevToolPlugin: append can't be false when no filename is provided" - ); - } - /** - * Add source map as data url to asset - */ - const asset = new ConcatSource( - new RawSource(source), - currentSourceMappingURLComment - .replace(/\[map\]/g, () => sourceMapString) - .replace( - /\[url\]/g, - () => - `data:application/json;charset=utf-8;base64,${Buffer.from( - sourceMapString, - "utf-8" - ).toString("base64")}` - ) - ); - assets[file] = asset; - compilation.updateAsset(file, asset); - } - }); - reportProgress(1.0); + switch (options.target) { + case "web": + JsonpTemplatePlugin = __webpack_require__(92764); + FetchCompileWasmTemplatePlugin = __webpack_require__(52669); + NodeSourcePlugin = __webpack_require__(9128); + new JsonpTemplatePlugin().apply(compiler); + new FetchCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeSourcePlugin(options.node).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + case "webworker": { + let WebWorkerTemplatePlugin = __webpack_require__(21328); + FetchCompileWasmTemplatePlugin = __webpack_require__(52669); + NodeSourcePlugin = __webpack_require__(9128); + new WebWorkerTemplatePlugin().apply(compiler); + new FetchCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeSourcePlugin(options.node).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; } - ); - }); - } -} + case "node": + case "async-node": + NodeTemplatePlugin = __webpack_require__(90010); + ReadFileCompileWasmTemplatePlugin = __webpack_require__(73839); + NodeTargetPlugin = __webpack_require__(59743); + new NodeTemplatePlugin({ + asyncChunkLoading: options.target === "async-node" + }).apply(compiler); + new ReadFileCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new LoaderTargetPlugin("node").apply(compiler); + break; + case "node-webkit": + JsonpTemplatePlugin = __webpack_require__(92764); + NodeTargetPlugin = __webpack_require__(59743); + ExternalsPlugin = __webpack_require__(75705); + new JsonpTemplatePlugin().apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new ExternalsPlugin("commonjs", "nw.gui").apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + case "electron-main": + NodeTemplatePlugin = __webpack_require__(90010); + NodeTargetPlugin = __webpack_require__(59743); + ExternalsPlugin = __webpack_require__(75705); + new NodeTemplatePlugin({ + asyncChunkLoading: true + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new ExternalsPlugin("commonjs", [ + "app", + "auto-updater", + "browser-window", + "clipboard", + "content-tracing", + "crash-reporter", + "dialog", + "electron", + "global-shortcut", + "ipc", + "ipc-main", + "menu", + "menu-item", + "native-image", + "original-fs", + "power-monitor", + "power-save-blocker", + "protocol", + "screen", + "session", + "shell", + "tray", + "web-contents" + ]).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + case "electron-renderer": + case "electron-preload": + FetchCompileWasmTemplatePlugin = __webpack_require__(52669); + NodeTargetPlugin = __webpack_require__(59743); + ExternalsPlugin = __webpack_require__(75705); + if (options.target === "electron-renderer") { + JsonpTemplatePlugin = __webpack_require__(92764); + new JsonpTemplatePlugin().apply(compiler); + } else if (options.target === "electron-preload") { + NodeTemplatePlugin = __webpack_require__(90010); + new NodeTemplatePlugin({ + asyncChunkLoading: true + }).apply(compiler); + } + new FetchCompileWasmTemplatePlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); + new FunctionModulePlugin().apply(compiler); + new NodeTargetPlugin().apply(compiler); + new ExternalsPlugin("commonjs", [ + "clipboard", + "crash-reporter", + "desktop-capturer", + "electron", + "ipc", + "ipc-renderer", + "native-image", + "original-fs", + "remote", + "screen", + "shell", + "web-frame" + ]).apply(compiler); + new LoaderTargetPlugin(options.target).apply(compiler); + break; + default: + throw new Error("Unsupported target '" + options.target + "'."); + } + } + // @ts-ignore This is always true, which is good this way + else if (options.target !== false) { + options.target(compiler); + } else { + throw new Error("Unsupported target '" + options.target + "'."); + } -module.exports = SourceMapDevToolPlugin; + if (options.output.library || options.output.libraryTarget !== "var") { + const LibraryTemplatePlugin = __webpack_require__(65237); + new LibraryTemplatePlugin( + options.output.library, + options.output.libraryTarget, + options.output.umdNamedDefine, + options.output.auxiliaryComment || "", + options.output.libraryExport + ).apply(compiler); + } + if (options.externals) { + ExternalsPlugin = __webpack_require__(75705); + new ExternalsPlugin( + options.output.libraryTarget, + options.externals + ).apply(compiler); + } + let noSources; + let legacy; + let modern; + let comment; + if ( + options.devtool && + (options.devtool.includes("sourcemap") || + options.devtool.includes("source-map")) + ) { + const hidden = options.devtool.includes("hidden"); + const inline = options.devtool.includes("inline"); + const evalWrapped = options.devtool.includes("eval"); + const cheap = options.devtool.includes("cheap"); + const moduleMaps = options.devtool.includes("module"); + noSources = options.devtool.includes("nosources"); + legacy = options.devtool.includes("@"); + modern = options.devtool.includes("#"); + comment = + legacy && modern + ? "\n/*\n//@ source" + + "MappingURL=[url]\n//# source" + + "MappingURL=[url]\n*/" + : legacy + ? "\n/*\n//@ source" + "MappingURL=[url]\n*/" + : modern + ? "\n//# source" + "MappingURL=[url]" + : null; + const Plugin = evalWrapped + ? EvalSourceMapDevToolPlugin + : SourceMapDevToolPlugin; + new Plugin({ + filename: inline ? null : options.output.sourceMapFilename, + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + fallbackModuleFilenameTemplate: + options.output.devtoolFallbackModuleFilenameTemplate, + append: hidden ? false : comment, + module: moduleMaps ? true : cheap ? false : true, + columns: cheap ? false : true, + lineToLine: options.output.devtoolLineToLine, + noSources: noSources, + namespace: options.output.devtoolNamespace + }).apply(compiler); + } else if (options.devtool && options.devtool.includes("eval")) { + legacy = options.devtool.includes("@"); + modern = options.devtool.includes("#"); + comment = + legacy && modern + ? "\n//@ sourceURL=[url]\n//# sourceURL=[url]" + : legacy + ? "\n//@ sourceURL=[url]" + : modern + ? "\n//# sourceURL=[url]" + : null; + new EvalDevToolModulePlugin({ + sourceUrlComment: comment, + moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, + namespace: options.output.devtoolNamespace + }).apply(compiler); + } -/***/ }), + new JavascriptModulesPlugin().apply(compiler); + new JsonModulesPlugin().apply(compiler); + new WebAssemblyModulesPlugin({ + mangleImports: options.optimization.mangleWasmImports + }).apply(compiler); -/***/ 99977: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + new EntryOptionPlugin().apply(compiler); + compiler.hooks.entryOption.call(options.context, options.entry); -"use strict"; + new CompatibilityPlugin().apply(compiler); + new HarmonyModulesPlugin(options.module).apply(compiler); + if (options.amd !== false) { + const AMDPlugin = __webpack_require__(85812); + const RequireJsStuffPlugin = __webpack_require__(88226); + new AMDPlugin(options.module, options.amd || {}).apply(compiler); + new RequireJsStuffPlugin().apply(compiler); + } + new CommonJsPlugin(options.module).apply(compiler); + new LoaderPlugin().apply(compiler); + if (options.node !== false) { + const NodeStuffPlugin = __webpack_require__(28386); + new NodeStuffPlugin(options.node).apply(compiler); + } + new CommonJsStuffPlugin().apply(compiler); + new APIPlugin().apply(compiler); + new ConstPlugin().apply(compiler); + new UseStrictPlugin().apply(compiler); + new RequireIncludePlugin().apply(compiler); + new RequireEnsurePlugin().apply(compiler); + new RequireContextPlugin( + options.resolve.modules, + options.resolve.extensions, + options.resolve.mainFiles + ).apply(compiler); + new ImportPlugin(options.module).apply(compiler); + new SystemPlugin(options.module).apply(compiler); + + if (typeof options.mode !== "string") { + const WarnNoModeSetPlugin = __webpack_require__(71245); + new WarnNoModeSetPlugin().apply(compiler); + } + + const EnsureChunkConditionsPlugin = __webpack_require__(29720); + new EnsureChunkConditionsPlugin().apply(compiler); + if (options.optimization.removeAvailableModules) { + const RemoveParentModulesPlugin = __webpack_require__(58142); + new RemoveParentModulesPlugin().apply(compiler); + } + if (options.optimization.removeEmptyChunks) { + const RemoveEmptyChunksPlugin = __webpack_require__(78085); + new RemoveEmptyChunksPlugin().apply(compiler); + } + if (options.optimization.mergeDuplicateChunks) { + const MergeDuplicateChunksPlugin = __webpack_require__(46214); + new MergeDuplicateChunksPlugin().apply(compiler); + } + if (options.optimization.flagIncludedChunks) { + const FlagIncludedChunksPlugin = __webpack_require__(25850); + new FlagIncludedChunksPlugin().apply(compiler); + } + if (options.optimization.sideEffects) { + const SideEffectsFlagPlugin = __webpack_require__(83654); + new SideEffectsFlagPlugin().apply(compiler); + } + if (options.optimization.providedExports) { + const FlagDependencyExportsPlugin = __webpack_require__(73599); + new FlagDependencyExportsPlugin().apply(compiler); + } + if (options.optimization.usedExports) { + const FlagDependencyUsagePlugin = __webpack_require__(33632); + new FlagDependencyUsagePlugin().apply(compiler); + } + if (options.optimization.concatenateModules) { + const ModuleConcatenationPlugin = __webpack_require__(45184); + new ModuleConcatenationPlugin().apply(compiler); + } + if (options.optimization.splitChunks) { + const SplitChunksPlugin = __webpack_require__(60474); + new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler); + } + if (options.optimization.runtimeChunk) { + const RuntimeChunkPlugin = __webpack_require__(76894); + new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler); + } + if (options.optimization.noEmitOnErrors) { + const NoEmitOnErrorsPlugin = __webpack_require__(22615); + new NoEmitOnErrorsPlugin().apply(compiler); + } + if (options.optimization.checkWasmTypes) { + const WasmFinalizeExportsPlugin = __webpack_require__(10557); + new WasmFinalizeExportsPlugin().apply(compiler); + } + let moduleIds = options.optimization.moduleIds; + if (moduleIds === undefined) { + // TODO webpack 5 remove all these options + if (options.optimization.occurrenceOrder) { + moduleIds = "size"; + } + if (options.optimization.namedModules) { + moduleIds = "named"; + } + if (options.optimization.hashedModuleIds) { + moduleIds = "hashed"; + } + if (moduleIds === undefined) { + moduleIds = "natural"; + } + } + if (moduleIds) { + const NamedModulesPlugin = __webpack_require__(86707); + const HashedModuleIdsPlugin = __webpack_require__(50268); + const OccurrenceModuleOrderPlugin = __webpack_require__(62000); + switch (moduleIds) { + case "natural": + // TODO webpack 5: see hint in Compilation.sortModules + break; + case "named": + new NamedModulesPlugin().apply(compiler); + break; + case "hashed": + new HashedModuleIdsPlugin().apply(compiler); + break; + case "size": + new OccurrenceModuleOrderPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + case "total-size": + new OccurrenceModuleOrderPlugin({ + prioritiseInitial: false + }).apply(compiler); + break; + default: + throw new Error( + `webpack bug: moduleIds: ${moduleIds} is not implemented` + ); + } + } + let chunkIds = options.optimization.chunkIds; + if (chunkIds === undefined) { + // TODO webpack 5 remove all these options + if (options.optimization.occurrenceOrder) { + // This looks weird but it's for backward-compat + // This bug already existed before adding this feature + chunkIds = "total-size"; + } + if (options.optimization.namedChunks) { + chunkIds = "named"; + } + if (chunkIds === undefined) { + chunkIds = "natural"; + } + } + if (chunkIds) { + const NaturalChunkOrderPlugin = __webpack_require__(68053); + const NamedChunksPlugin = __webpack_require__(70419); + const OccurrenceChunkOrderPlugin = __webpack_require__(83741); + switch (chunkIds) { + case "natural": + new NaturalChunkOrderPlugin().apply(compiler); + break; + case "named": + // TODO webapck 5: for backward-compat this need to have OccurrenceChunkOrderPlugin too + // The NamedChunksPlugin doesn't give every chunk a name + // This should be fixed, and the OccurrenceChunkOrderPlugin should be removed here. + new OccurrenceChunkOrderPlugin({ + prioritiseInitial: false + }).apply(compiler); + new NamedChunksPlugin().apply(compiler); + break; + case "size": + new OccurrenceChunkOrderPlugin({ + prioritiseInitial: true + }).apply(compiler); + break; + case "total-size": + new OccurrenceChunkOrderPlugin({ + prioritiseInitial: false + }).apply(compiler); + break; + default: + throw new Error( + `webpack bug: chunkIds: ${chunkIds} is not implemented` + ); + } + } + if (options.optimization.nodeEnv) { + const DefinePlugin = __webpack_require__(97374); + new DefinePlugin({ + "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv) + }).apply(compiler); + } + if (options.optimization.minimize) { + for (const minimizer of options.optimization.minimizer) { + if (typeof minimizer === "function") { + minimizer.call(compiler, compiler); + } else { + minimizer.apply(compiler); + } + } + } + + if (options.performance) { + const SizeLimitsPlugin = __webpack_require__(68310); + new SizeLimitsPlugin(options.performance).apply(compiler); + } + + new TemplatedPathPlugin().apply(compiler); + + new RecordIdsPlugin({ + portableIds: options.optimization.portableRecords + }).apply(compiler); + + new WarnCaseSensitiveModulesPlugin().apply(compiler); + + if (options.cache) { + const CachePlugin = __webpack_require__(6465); + new CachePlugin( + typeof options.cache === "object" ? options.cache : null + ).apply(compiler); + } + + compiler.hooks.afterPlugins.call(compiler); + if (!compiler.inputFileSystem) { + throw new Error("No input filesystem provided"); + } + compiler.resolverFactory.hooks.resolveOptions + .for("normal") + .tap("WebpackOptionsApply", resolveOptions => { + return Object.assign( + { + fileSystem: compiler.inputFileSystem + }, + cachedCleverMerge(options.resolve, resolveOptions) + ); + }); + compiler.resolverFactory.hooks.resolveOptions + .for("context") + .tap("WebpackOptionsApply", resolveOptions => { + return Object.assign( + { + fileSystem: compiler.inputFileSystem, + resolveToContext: true + }, + cachedCleverMerge(options.resolve, resolveOptions) + ); + }); + compiler.resolverFactory.hooks.resolveOptions + .for("loader") + .tap("WebpackOptionsApply", resolveOptions => { + return Object.assign( + { + fileSystem: compiler.inputFileSystem + }, + cachedCleverMerge(options.resolveLoader, resolveOptions) + ); + }); + compiler.hooks.afterResolvers.call(compiler); + return options; + } +} + +module.exports = WebpackOptionsApply; + + +/***/ }), + +/***/ 60016: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -const RequestShortener = __webpack_require__(54254); -const SizeFormatHelpers = __webpack_require__(12496); -const formatLocation = __webpack_require__(49); -const identifierUtils = __webpack_require__(94658); -const compareLocations = __webpack_require__(22562); -const { LogType } = __webpack_require__(47194); +const path = __webpack_require__(85622); -const optionsOrFallback = (...args) => { - let optionValues = []; - optionValues.push(...args); - return optionValues.find(optionValue => optionValue !== undefined); +const OptionsDefaulter = __webpack_require__(3414); +const Template = __webpack_require__(96066); + +const isProductionLikeMode = options => { + return options.mode === "production" || !options.mode; }; -const compareId = (a, b) => { - if (typeof a !== typeof b) { - return typeof a < typeof b ? -1 : 1; - } - if (a < b) return -1; - if (a > b) return 1; - return 0; +const isWebLikeTarget = options => { + return options.target === "web" || options.target === "webworker"; }; -class Stats { - constructor(compilation) { - this.compilation = compilation; - this.hash = compilation.hash; - this.startTime = undefined; - this.endTime = undefined; +const getDevtoolNamespace = library => { + // if options.output.library is a string + if (Array.isArray(library)) { + return library.join("."); + } else if (typeof library === "object") { + return getDevtoolNamespace(library.root); } + return library || ""; +}; - static filterWarnings(warnings, warningsFilter) { - // we dont have anything to filter so all warnings can be shown - if (!warningsFilter) { - return warnings; - } +class WebpackOptionsDefaulter extends OptionsDefaulter { + constructor() { + super(); - // create a chain of filters - // if they return "true" a warning should be suppressed - const normalizedWarningsFilters = [].concat(warningsFilter).map(filter => { - if (typeof filter === "string") { - return warning => warning.includes(filter); - } + this.set("entry", "./src"); - if (filter instanceof RegExp) { - return warning => filter.test(warning); + this.set("devtool", "make", options => + options.mode === "development" ? "eval" : false + ); + this.set("cache", "make", options => options.mode === "development"); + + this.set("context", process.cwd()); + this.set("target", "web"); + + this.set("module", "call", value => Object.assign({}, value)); + this.set("module.unknownContextRequest", "."); + this.set("module.unknownContextRegExp", false); + this.set("module.unknownContextRecursive", true); + this.set("module.unknownContextCritical", true); + this.set("module.exprContextRequest", "."); + this.set("module.exprContextRegExp", false); + this.set("module.exprContextRecursive", true); + this.set("module.exprContextCritical", true); + this.set("module.wrappedContextRegExp", /.*/); + this.set("module.wrappedContextRecursive", true); + this.set("module.wrappedContextCritical", false); + this.set("module.strictExportPresence", false); + this.set("module.strictThisContextOnImports", false); + this.set("module.unsafeCache", "make", options => !!options.cache); + this.set("module.rules", []); + this.set("module.defaultRules", "make", options => [ + { + type: "javascript/auto", + resolve: {} + }, + { + test: /\.mjs$/i, + type: "javascript/esm", + resolve: { + mainFields: + options.target === "web" || + options.target === "webworker" || + options.target === "electron-renderer" + ? ["browser", "main"] + : ["main"] + } + }, + { + test: /\.json$/i, + type: "json" + }, + { + test: /\.wasm$/i, + type: "webassembly/experimental" } + ]); - if (typeof filter === "function") { - return filter; + this.set("output", "call", (value, options) => { + if (typeof value === "string") { + return { + filename: value + }; + } else if (typeof value !== "object") { + return {}; + } else { + return Object.assign({}, value); } + }); - throw new Error( - `Can only filter warnings with Strings or RegExps. (Given: ${filter})` + this.set("output.filename", "[name].js"); + this.set("output.chunkFilename", "make", options => { + const filename = options.output.filename; + if (typeof filename !== "function") { + const hasName = filename.includes("[name]"); + const hasId = filename.includes("[id]"); + const hasChunkHash = filename.includes("[chunkhash]"); + // Anything changing depending on chunk is fine + if (hasChunkHash || hasName || hasId) return filename; + // Elsewise prefix "[id]." in front of the basename to make it changing + return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2"); + } + return "[id].js"; + }); + this.set("output.webassemblyModuleFilename", "[modulehash].module.wasm"); + this.set("output.library", ""); + this.set("output.hotUpdateFunction", "make", options => { + return Template.toIdentifier( + "webpackHotUpdate" + Template.toIdentifier(options.output.library) ); }); - return warnings.filter(warning => { - return !normalizedWarningsFilters.some(check => check(warning)); + this.set("output.jsonpFunction", "make", options => { + return Template.toIdentifier( + "webpackJsonp" + Template.toIdentifier(options.output.library) + ); }); - } + this.set("output.chunkCallbackName", "make", options => { + return Template.toIdentifier( + "webpackChunk" + Template.toIdentifier(options.output.library) + ); + }); + this.set("output.globalObject", "make", options => { + switch (options.target) { + case "web": + case "electron-renderer": + case "node-webkit": + return "window"; + case "webworker": + return "self"; + case "node": + case "async-node": + case "electron-main": + return "global"; + default: + return "self"; + } + }); + this.set("output.devtoolNamespace", "make", options => { + return getDevtoolNamespace(options.output.library); + }); + this.set("output.libraryTarget", "var"); + this.set("output.path", path.join(process.cwd(), "dist")); + this.set( + "output.pathinfo", + "make", + options => options.mode === "development" + ); + this.set("output.sourceMapFilename", "[file].map[query]"); + this.set("output.hotUpdateChunkFilename", "[id].[hash].hot-update.js"); + this.set("output.hotUpdateMainFilename", "[hash].hot-update.json"); + this.set("output.crossOriginLoading", false); + this.set("output.jsonpScriptType", false); + this.set("output.chunkLoadTimeout", 120000); + this.set("output.hashFunction", "md4"); + this.set("output.hashDigest", "hex"); + this.set("output.hashDigestLength", 20); + this.set("output.devtoolLineToLine", false); + this.set("output.strictModuleExceptionHandling", false); - formatFilePath(filePath) { - const OPTIONS_REGEXP = /^(\s|\S)*!/; - return filePath.includes("!") - ? `${filePath.replace(OPTIONS_REGEXP, "")} (${filePath})` - : `${filePath}`; - } + this.set("node", "call", value => { + if (typeof value === "boolean") { + return value; + } else { + return Object.assign({}, value); + } + }); + this.set("node.console", false); + this.set("node.process", true); + this.set("node.global", true); + this.set("node.Buffer", true); + this.set("node.setImmediate", true); + this.set("node.__filename", "mock"); + this.set("node.__dirname", "mock"); - hasWarnings() { - return ( - this.compilation.warnings.length > 0 || - this.compilation.children.some(child => child.getStats().hasWarnings()) + this.set("performance", "call", (value, options) => { + if (value === false) return false; + if ( + value === undefined && + (!isProductionLikeMode(options) || !isWebLikeTarget(options)) + ) + return false; + return Object.assign({}, value); + }); + this.set("performance.maxAssetSize", 250000); + this.set("performance.maxEntrypointSize", 250000); + this.set("performance.hints", "make", options => + isProductionLikeMode(options) ? "warning" : false ); - } - hasErrors() { - return ( - this.compilation.errors.length > 0 || - this.compilation.children.some(child => child.getStats().hasErrors()) + this.set("optimization", "call", value => Object.assign({}, value)); + // TODO webpack 5: Disable by default in a modes + this.set( + "optimization.removeAvailableModules", + "make", + options => options.mode !== "development" ); - } - - // remove a prefixed "!" that can be specified to reverse sort order - normalizeFieldKey(field) { - if (field[0] === "!") { - return field.substr(1); - } - return field; - } - - // if a field is prefixed by a "!" reverse sort order - sortOrderRegular(field) { - if (field[0] === "!") { - return false; - } - return true; - } - - toJson(options, forToString) { - if (typeof options === "boolean" || typeof options === "string") { - options = Stats.presetToOptions(options); - } else if (!options) { - options = {}; - } - - const optionOrLocalFallback = (v, def) => - v !== undefined ? v : options.all !== undefined ? options.all : def; - - const testAgainstGivenOption = item => { - if (typeof item === "string") { - const regExp = new RegExp( - `[\\\\/]${item.replace( - // eslint-disable-next-line no-useless-escape - /[-[\]{}()*+?.\\^$|]/g, - "\\$&" - )}([\\\\/]|$|!|\\?)` - ); - return ident => regExp.test(ident); - } - if (item && typeof item === "object" && typeof item.test === "function") { - return ident => item.test(ident); - } - if (typeof item === "function") { - return item; - } - if (typeof item === "boolean") { - return () => item; - } - }; - - const compilation = this.compilation; - const context = optionsOrFallback( - options.context, - compilation.compiler.context - ); - const requestShortener = - compilation.compiler.context === context - ? compilation.requestShortener - : new RequestShortener(context); - const showPerformance = optionOrLocalFallback(options.performance, true); - const showHash = optionOrLocalFallback(options.hash, true); - const showEnv = optionOrLocalFallback(options.env, false); - const showVersion = optionOrLocalFallback(options.version, true); - const showTimings = optionOrLocalFallback(options.timings, true); - const showBuiltAt = optionOrLocalFallback(options.builtAt, true); - const showAssets = optionOrLocalFallback(options.assets, true); - const showEntrypoints = optionOrLocalFallback(options.entrypoints, true); - const showChunkGroups = optionOrLocalFallback( - options.chunkGroups, - !forToString - ); - const showChunks = optionOrLocalFallback(options.chunks, !forToString); - const showChunkModules = optionOrLocalFallback(options.chunkModules, true); - const showChunkOrigins = optionOrLocalFallback( - options.chunkOrigins, - !forToString - ); - const showModules = optionOrLocalFallback(options.modules, true); - const showNestedModules = optionOrLocalFallback( - options.nestedModules, - true + this.set("optimization.removeEmptyChunks", true); + this.set("optimization.mergeDuplicateChunks", true); + this.set("optimization.flagIncludedChunks", "make", options => + isProductionLikeMode(options) ); - const showModuleAssets = optionOrLocalFallback( - options.moduleAssets, - !forToString + // TODO webpack 5 add `moduleIds: "named"` default for development + // TODO webpack 5 add `moduleIds: "size"` default for production + // TODO webpack 5 remove optimization.occurrenceOrder + this.set("optimization.occurrenceOrder", "make", options => + isProductionLikeMode(options) ); - const showDepth = optionOrLocalFallback(options.depth, !forToString); - const showCachedModules = optionOrLocalFallback(options.cached, true); - const showCachedAssets = optionOrLocalFallback(options.cachedAssets, true); - const showReasons = optionOrLocalFallback(options.reasons, !forToString); - const showUsedExports = optionOrLocalFallback( - options.usedExports, - !forToString + this.set("optimization.sideEffects", "make", options => + isProductionLikeMode(options) ); - const showProvidedExports = optionOrLocalFallback( - options.providedExports, - !forToString + this.set("optimization.providedExports", true); + this.set("optimization.usedExports", "make", options => + isProductionLikeMode(options) ); - const showOptimizationBailout = optionOrLocalFallback( - options.optimizationBailout, - !forToString + this.set("optimization.concatenateModules", "make", options => + isProductionLikeMode(options) ); - const showChildren = optionOrLocalFallback(options.children, true); - const showSource = optionOrLocalFallback(options.source, !forToString); - const showModuleTrace = optionOrLocalFallback(options.moduleTrace, true); - const showErrors = optionOrLocalFallback(options.errors, true); - const showErrorDetails = optionOrLocalFallback( - options.errorDetails, - !forToString + this.set("optimization.splitChunks", {}); + this.set("optimization.splitChunks.hidePathInfo", "make", options => { + return isProductionLikeMode(options); + }); + this.set("optimization.splitChunks.chunks", "async"); + this.set("optimization.splitChunks.minSize", "make", options => { + return isProductionLikeMode(options) ? 30000 : 10000; + }); + this.set("optimization.splitChunks.minChunks", 1); + this.set("optimization.splitChunks.maxAsyncRequests", "make", options => { + return isProductionLikeMode(options) ? 5 : Infinity; + }); + this.set("optimization.splitChunks.automaticNameDelimiter", "~"); + this.set("optimization.splitChunks.automaticNameMaxLength", 109); + this.set("optimization.splitChunks.maxInitialRequests", "make", options => { + return isProductionLikeMode(options) ? 3 : Infinity; + }); + this.set("optimization.splitChunks.name", true); + this.set("optimization.splitChunks.cacheGroups", {}); + this.set("optimization.splitChunks.cacheGroups.default", { + automaticNamePrefix: "", + reuseExistingChunk: true, + minChunks: 2, + priority: -20 + }); + this.set("optimization.splitChunks.cacheGroups.vendors", { + automaticNamePrefix: "vendors", + test: /[\\/]node_modules[\\/]/, + priority: -10 + }); + this.set("optimization.runtimeChunk", "call", value => { + if (value === "single") { + return { + name: "runtime" + }; + } + if (value === true || value === "multiple") { + return { + name: entrypoint => `runtime~${entrypoint.name}` + }; + } + return value; + }); + this.set("optimization.noEmitOnErrors", "make", options => + isProductionLikeMode(options) ); - const showWarnings = optionOrLocalFallback(options.warnings, true); - const warningsFilter = optionsOrFallback(options.warningsFilter, null); - const showPublicPath = optionOrLocalFallback( - options.publicPath, - !forToString + this.set("optimization.checkWasmTypes", "make", options => + isProductionLikeMode(options) ); - const showLogging = optionOrLocalFallback( - options.logging, - forToString ? "info" : true + this.set("optimization.mangleWasmImports", false); + // TODO webpack 5 remove optimization.namedModules + this.set( + "optimization.namedModules", + "make", + options => options.mode === "development" ); - const showLoggingTrace = optionOrLocalFallback( - options.loggingTrace, - !forToString + this.set("optimization.hashedModuleIds", false); + // TODO webpack 5 add `chunkIds: "named"` default for development + // TODO webpack 5 add `chunkIds: "size"` default for production + // TODO webpack 5 remove optimization.namedChunks + this.set( + "optimization.namedChunks", + "make", + options => options.mode === "development" ); - const loggingDebug = [] - .concat(optionsOrFallback(options.loggingDebug, [])) - .map(testAgainstGivenOption); - - const excludeModules = [] - .concat(optionsOrFallback(options.excludeModules, options.exclude, [])) - .map(testAgainstGivenOption); - const excludeAssets = [] - .concat(optionsOrFallback(options.excludeAssets, [])) - .map(testAgainstGivenOption); - const maxModules = optionsOrFallback( - options.maxModules, - forToString ? 15 : Infinity + this.set( + "optimization.portableRecords", + "make", + options => + !!( + options.recordsInputPath || + options.recordsOutputPath || + options.recordsPath + ) ); - const sortModules = optionsOrFallback(options.modulesSort, "id"); - const sortChunks = optionsOrFallback(options.chunksSort, "id"); - const sortAssets = optionsOrFallback(options.assetsSort, ""); - const showOutputPath = optionOrLocalFallback( - options.outputPath, - !forToString + this.set("optimization.minimize", "make", options => + isProductionLikeMode(options) ); - - if (!showCachedModules) { - excludeModules.push((ident, module) => !module.built); - } - - const createModuleFilter = () => { - let i = 0; - return module => { - if (excludeModules.length > 0) { - const ident = requestShortener.shorten(module.resource); - const excluded = excludeModules.some(fn => fn(ident, module)); - if (excluded) return false; - } - const result = i < maxModules; - i++; - return result; - }; - }; - - const createAssetFilter = () => { - return asset => { - if (excludeAssets.length > 0) { - const ident = asset.name; - const excluded = excludeAssets.some(fn => fn(ident, asset)); - if (excluded) return false; - } - return showCachedAssets || asset.emitted; - }; - }; - - const sortByFieldAndOrder = (fieldKey, a, b) => { - if (a[fieldKey] === null && b[fieldKey] === null) return 0; - if (a[fieldKey] === null) return 1; - if (b[fieldKey] === null) return -1; - if (a[fieldKey] === b[fieldKey]) return 0; - if (typeof a[fieldKey] !== typeof b[fieldKey]) - return typeof a[fieldKey] < typeof b[fieldKey] ? -1 : 1; - return a[fieldKey] < b[fieldKey] ? -1 : 1; - }; - - const sortByField = (field, originalArray) => { - const originalMap = originalArray.reduce((map, v, i) => { - map.set(v, i); - return map; - }, new Map()); - return (a, b) => { - if (field) { - const fieldKey = this.normalizeFieldKey(field); - - // if a field is prefixed with a "!" the sort is reversed! - const sortIsRegular = this.sortOrderRegular(field); - - const cmp = sortByFieldAndOrder( - fieldKey, - sortIsRegular ? a : b, - sortIsRegular ? b : a - ); - if (cmp) return cmp; + this.set("optimization.minimizer", "make", options => [ + { + apply: compiler => { + // Lazy load the Terser plugin + const TerserPlugin = __webpack_require__(89301); + const SourceMapDevToolPlugin = __webpack_require__(11851); + new TerserPlugin({ + cache: true, + parallel: true, + sourceMap: + (options.devtool && /source-?map/.test(options.devtool)) || + (options.plugins && + options.plugins.some(p => p instanceof SourceMapDevToolPlugin)) + }).apply(compiler); } - return originalMap.get(a) - originalMap.get(b); - }; - }; - - const formatError = e => { - let text = ""; - if (typeof e === "string") { - e = { message: e }; - } - if (e.chunk) { - text += `chunk ${e.chunk.name || e.chunk.id}${ - e.chunk.hasRuntime() - ? " [entry]" - : e.chunk.canBeInitial() - ? " [initial]" - : "" - }\n`; - } - if (e.file) { - text += `${e.file}\n`; } + ]); + this.set("optimization.nodeEnv", "make", options => { + // TODO: In webpack 5, it should return `false` when mode is `none` + return options.mode || "production"; + }); + + this.set("resolve", "call", value => Object.assign({}, value)); + this.set("resolve.unsafeCache", true); + this.set("resolve.modules", ["node_modules"]); + this.set("resolve.extensions", [".wasm", ".mjs", ".js", ".json"]); + this.set("resolve.mainFiles", ["index"]); + this.set("resolve.aliasFields", "make", options => { if ( - e.module && - e.module.readableIdentifier && - typeof e.module.readableIdentifier === "function" + options.target === "web" || + options.target === "webworker" || + options.target === "electron-renderer" ) { - text += this.formatFilePath( - e.module.readableIdentifier(requestShortener) - ); - if (typeof e.loc === "object") { - const locInfo = formatLocation(e.loc); - if (locInfo) text += ` ${locInfo}`; - } - text += "\n"; - } - text += e.message; - if (showErrorDetails && e.details) { - text += `\n${e.details}`; - } - if (showErrorDetails && e.missing) { - text += e.missing.map(item => `\n[${item}]`).join(""); + return ["browser"]; + } else { + return []; } - if (showModuleTrace && e.origin) { - text += `\n @ ${this.formatFilePath( - e.origin.readableIdentifier(requestShortener) - )}`; - if (typeof e.originLoc === "object") { - const locInfo = formatLocation(e.originLoc); - if (locInfo) text += ` ${locInfo}`; - } - if (e.dependencies) { - for (const dep of e.dependencies) { - if (!dep.loc) continue; - if (typeof dep.loc === "string") continue; - const locInfo = formatLocation(dep.loc); - if (!locInfo) continue; - text += ` ${locInfo}`; - } - } - let current = e.origin; - while (current.issuer) { - current = current.issuer; - text += `\n @ ${current.readableIdentifier(requestShortener)}`; - } + }); + this.set("resolve.mainFields", "make", options => { + if ( + options.target === "web" || + options.target === "webworker" || + options.target === "electron-renderer" + ) { + return ["browser", "module", "main"]; + } else { + return ["module", "main"]; } - return text; - }; - - const obj = { - errors: compilation.errors.map(formatError), - warnings: Stats.filterWarnings( - compilation.warnings.map(formatError), - warningsFilter - ) - }; - - //We just hint other renderers since actually omitting - //errors/warnings from the JSON would be kind of weird. - Object.defineProperty(obj, "_showWarnings", { - value: showWarnings, - enumerable: false }); - Object.defineProperty(obj, "_showErrors", { - value: showErrors, - enumerable: false + this.set("resolve.cacheWithContext", "make", options => { + return ( + Array.isArray(options.resolve.plugins) && + options.resolve.plugins.length > 0 + ); }); - if (showVersion) { - obj.version = __webpack_require__(71618)/* .version */ .i8; - } + this.set("resolveLoader", "call", value => Object.assign({}, value)); + this.set("resolveLoader.unsafeCache", true); + this.set("resolveLoader.mainFields", ["loader", "main"]); + this.set("resolveLoader.extensions", [".js", ".json"]); + this.set("resolveLoader.mainFiles", ["index"]); + this.set("resolveLoader.roots", "make", options => [options.context]); + this.set("resolveLoader.cacheWithContext", "make", options => { + return ( + Array.isArray(options.resolveLoader.plugins) && + options.resolveLoader.plugins.length > 0 + ); + }); - if (showHash) obj.hash = this.hash; - if (showTimings && this.startTime && this.endTime) { - obj.time = this.endTime - this.startTime; - } + this.set("infrastructureLogging", "call", value => + Object.assign({}, value) + ); + this.set("infrastructureLogging.level", "info"); + this.set("infrastructureLogging.debug", false); + } +} - if (showBuiltAt && this.endTime) { - obj.builtAt = this.endTime; - } +module.exports = WebpackOptionsDefaulter; - if (showEnv && options._env) { - obj.env = options._env; - } - if (compilation.needAdditionalPass) { - obj.needAdditionalPass = true; - } - if (showPublicPath) { - obj.publicPath = this.compilation.mainTemplate.getPublicPath({ - hash: this.compilation.hash - }); - } - if (showOutputPath) { - obj.outputPath = this.compilation.mainTemplate.outputOptions.path; - } - if (showAssets) { - const assetsByFile = {}; - const compilationAssets = compilation - .getAssets() - .sort((a, b) => (a.name < b.name ? -1 : 1)); - obj.assetsByChunkName = {}; - obj.assets = compilationAssets - .map(({ name, source, info }) => { - const obj = { - name, - size: source.size(), - chunks: [], - chunkNames: [], - info, - // TODO webpack 5: remove .emitted - emitted: source.emitted || compilation.emittedAssets.has(name) - }; +/***/ }), - if (showPerformance) { - obj.isOverSizeLimit = source.isOverSizeLimit; - } +/***/ 285: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - assetsByFile[name] = obj; - return obj; - }) - .filter(createAssetFilter()); - obj.filteredAssets = compilationAssets.length - obj.assets.length; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Gajus Kuizinas @gajus +*/ - for (const chunk of compilation.chunks) { - for (const asset of chunk.files) { - if (assetsByFile[asset]) { - for (const id of chunk.ids) { - assetsByFile[asset].chunks.push(id); - } - if (chunk.name) { - assetsByFile[asset].chunkNames.push(chunk.name); - if (obj.assetsByChunkName[chunk.name]) { - obj.assetsByChunkName[chunk.name] = [] - .concat(obj.assetsByChunkName[chunk.name]) - .concat([asset]); - } else { - obj.assetsByChunkName[chunk.name] = asset; - } - } - } - } - } - obj.assets.sort(sortByField(sortAssets, obj.assets)); - } - const fnChunkGroup = groupMap => { - const obj = {}; - for (const keyValuePair of groupMap) { - const name = keyValuePair[0]; - const cg = keyValuePair[1]; - const children = cg.getChildrenByOrders(); - obj[name] = { - chunks: cg.chunks.map(c => c.id), - assets: cg.chunks.reduce( - (array, c) => array.concat(c.files || []), - [] - ), - children: Object.keys(children).reduce((obj, key) => { - const groups = children[key]; - obj[key] = groups.map(group => ({ - name: group.name, - chunks: group.chunks.map(c => c.id), - assets: group.chunks.reduce( - (array, c) => array.concat(c.files || []), - [] - ) - })); - return obj; - }, Object.create(null)), - childAssets: Object.keys(children).reduce((obj, key) => { - const groups = children[key]; - obj[key] = Array.from( - groups.reduce((set, group) => { - for (const chunk of group.chunks) { - for (const asset of chunk.files) { - set.add(asset); - } - } - return set; - }, new Set()) - ); - return obj; - }, Object.create(null)) - }; - if (showPerformance) { - obj[name].isOverSizeLimit = cg.isOverSizeLimit; - } - } +const WebpackError = __webpack_require__(97391); +const webpackOptionsSchema = __webpack_require__(37863); - return obj; - }; +const getSchemaPart = (path, parents, additionalPath) => { + parents = parents || 0; + path = path.split("/"); + path = path.slice(0, path.length - parents); + if (additionalPath) { + additionalPath = additionalPath.split("/"); + path = path.concat(additionalPath); + } + let schemaPart = webpackOptionsSchema; + for (let i = 1; i < path.length; i++) { + const inner = schemaPart[path[i]]; + if (inner) schemaPart = inner; + } + return schemaPart; +}; - if (showEntrypoints) { - obj.entrypoints = fnChunkGroup(compilation.entrypoints); +const getSchemaPartText = (schemaPart, additionalPath) => { + if (additionalPath) { + for (let i = 0; i < additionalPath.length; i++) { + const inner = schemaPart[additionalPath[i]]; + if (inner) schemaPart = inner; } + } + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } + let schemaText = WebpackOptionsValidationError.formatSchema(schemaPart); + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } + return schemaText; +}; - if (showChunkGroups) { - obj.namedChunkGroups = fnChunkGroup(compilation.namedChunkGroups); - } +const getSchemaPartDescription = schemaPart => { + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } + if (schemaPart.description) { + return `\n-> ${schemaPart.description}`; + } + return ""; +}; - const fnModule = module => { - const path = []; - let current = module; - while (current.issuer) { - path.push((current = current.issuer)); - } - path.reverse(); - const obj = { - id: module.id, - identifier: module.identifier(), - name: module.readableIdentifier(requestShortener), - index: module.index, - index2: module.index2, - size: module.size(), - cacheable: module.buildInfo.cacheable, - built: !!module.built, - optional: module.optional, - prefetched: module.prefetched, - chunks: Array.from(module.chunksIterable, chunk => chunk.id), - issuer: module.issuer && module.issuer.identifier(), - issuerId: module.issuer && module.issuer.id, - issuerName: - module.issuer && module.issuer.readableIdentifier(requestShortener), - issuerPath: - module.issuer && - path.map(module => ({ - id: module.id, - identifier: module.identifier(), - name: module.readableIdentifier(requestShortener), - profile: module.profile - })), - profile: module.profile, - failed: !!module.error, - errors: module.errors ? module.errors.length : 0, - warnings: module.warnings ? module.warnings.length : 0 - }; - if (showModuleAssets) { - obj.assets = Object.keys(module.buildInfo.assets || {}); - } - if (showReasons) { - obj.reasons = module.reasons - .sort((a, b) => { - if (a.module && !b.module) return -1; - if (!a.module && b.module) return 1; - if (a.module && b.module) { - const cmp = compareId(a.module.id, b.module.id); - if (cmp) return cmp; - } - if (a.dependency && !b.dependency) return -1; - if (!a.dependency && b.dependency) return 1; - if (a.dependency && b.dependency) { - const cmp = compareLocations(a.dependency.loc, b.dependency.loc); - if (cmp) return cmp; - if (a.dependency.type < b.dependency.type) return -1; - if (a.dependency.type > b.dependency.type) return 1; - } - return 0; - }) - .map(reason => { - const obj = { - moduleId: reason.module ? reason.module.id : null, - moduleIdentifier: reason.module - ? reason.module.identifier() - : null, - module: reason.module - ? reason.module.readableIdentifier(requestShortener) - : null, - moduleName: reason.module - ? reason.module.readableIdentifier(requestShortener) - : null, - type: reason.dependency ? reason.dependency.type : null, - explanation: reason.explanation, - userRequest: reason.dependency - ? reason.dependency.userRequest - : null - }; - if (reason.dependency) { - const locInfo = formatLocation(reason.dependency.loc); - if (locInfo) { - obj.loc = locInfo; - } - } - return obj; - }); - } - if (showUsedExports) { - if (module.used === true) { - obj.usedExports = module.usedExports; - } else if (module.used === false) { - obj.usedExports = false; - } - } - if (showProvidedExports) { - obj.providedExports = Array.isArray(module.buildMeta.providedExports) - ? module.buildMeta.providedExports - : null; - } - if (showOptimizationBailout) { - obj.optimizationBailout = module.optimizationBailout.map(item => { - if (typeof item === "function") return item(requestShortener); - return item; - }); +const SPECIFICITY = { + type: 1, + oneOf: 1, + anyOf: 1, + allOf: 1, + additionalProperties: 2, + enum: 1, + instanceof: 1, + required: 2, + minimum: 2, + uniqueItems: 2, + minLength: 2, + minItems: 2, + minProperties: 2, + absolutePath: 2 +}; + +const filterMax = (array, fn) => { + const max = array.reduce((max, item) => Math.max(max, fn(item)), 0); + return array.filter(item => fn(item) === max); +}; + +const filterChildren = children => { + children = filterMax(children, err => + err.dataPath ? err.dataPath.length : 0 + ); + children = filterMax(children, err => SPECIFICITY[err.keyword] || 2); + return children; +}; + +const indent = (str, prefix, firstLine) => { + if (firstLine) { + return prefix + str.replace(/\n(?!$)/g, "\n" + prefix); + } else { + return str.replace(/\n(?!$)/g, `\n${prefix}`); + } +}; + +class WebpackOptionsValidationError extends WebpackError { + constructor(validationErrors) { + super( + "Invalid configuration object. " + + "Webpack has been initialised using a configuration object that does not match the API schema.\n" + + validationErrors + .map( + err => + " - " + + indent( + WebpackOptionsValidationError.formatValidationError(err), + " ", + false + ) + ) + .join("\n") + ); + + this.name = "WebpackOptionsValidationError"; + this.validationErrors = validationErrors; + + Error.captureStackTrace(this, this.constructor); + } + + static formatSchema(schema, prevSchemas) { + prevSchemas = prevSchemas || []; + + const formatInnerSchema = (innerSchema, addSelf) => { + if (!addSelf) { + return WebpackOptionsValidationError.formatSchema( + innerSchema, + prevSchemas + ); } - if (showDepth) { - obj.depth = module.depth; + if (prevSchemas.includes(innerSchema)) { + return "(recursive)"; } - if (showNestedModules) { - if (module.modules) { - const modules = module.modules; - obj.modules = modules - .sort(sortByField("depth", modules)) - .filter(createModuleFilter()) - .map(fnModule); - obj.filteredModules = modules.length - obj.modules.length; - obj.modules.sort(sortByField(sortModules, obj.modules)); - } + return WebpackOptionsValidationError.formatSchema( + innerSchema, + prevSchemas.concat(schema) + ); + }; + + if (schema.type === "string") { + if (schema.minLength === 1) { + return "non-empty string"; } - if (showSource && module._source) { - obj.source = module._source.source(); + if (schema.minLength > 1) { + return `string (min length ${schema.minLength})`; } - return obj; - }; - if (showChunks) { - obj.chunks = compilation.chunks.map(chunk => { - const parents = new Set(); - const children = new Set(); - const siblings = new Set(); - const childIdByOrder = chunk.getChildIdsByOrders(); - for (const chunkGroup of chunk.groupsIterable) { - for (const parentGroup of chunkGroup.parentsIterable) { - for (const chunk of parentGroup.chunks) { - parents.add(chunk.id); - } - } - for (const childGroup of chunkGroup.childrenIterable) { - for (const chunk of childGroup.chunks) { - children.add(chunk.id); - } - } - for (const sibling of chunkGroup.chunks) { - if (sibling !== chunk) siblings.add(sibling.id); - } - } - const obj = { - id: chunk.id, - rendered: chunk.rendered, - initial: chunk.canBeInitial(), - entry: chunk.hasRuntime(), - recorded: chunk.recorded, - reason: chunk.chunkReason, - size: chunk.modulesSize(), - names: chunk.name ? [chunk.name] : [], - files: chunk.files.slice(), - hash: chunk.renderedHash, - siblings: Array.from(siblings).sort(compareId), - parents: Array.from(parents).sort(compareId), - children: Array.from(children).sort(compareId), - childrenByOrder: childIdByOrder - }; - if (showChunkModules) { - const modules = chunk.getModules(); - obj.modules = modules - .slice() - .sort(sortByField("depth", modules)) - .filter(createModuleFilter()) - .map(fnModule); - obj.filteredModules = chunk.getNumberOfModules() - obj.modules.length; - obj.modules.sort(sortByField(sortModules, obj.modules)); - } - if (showChunkOrigins) { - obj.origins = Array.from(chunk.groupsIterable, g => g.origins) - .reduce((a, b) => a.concat(b), []) - .map(origin => ({ - moduleId: origin.module ? origin.module.id : undefined, - module: origin.module ? origin.module.identifier() : "", - moduleIdentifier: origin.module ? origin.module.identifier() : "", - moduleName: origin.module - ? origin.module.readableIdentifier(requestShortener) - : "", - loc: formatLocation(origin.loc), - request: origin.request, - reasons: origin.reasons || [] - })) - .sort((a, b) => { - const cmp1 = compareId(a.moduleId, b.moduleId); - if (cmp1) return cmp1; - const cmp2 = compareId(a.loc, b.loc); - if (cmp2) return cmp2; - const cmp3 = compareId(a.request, b.request); - if (cmp3) return cmp3; - return 0; - }); - } - return obj; - }); - obj.chunks.sort(sortByField(sortChunks, obj.chunks)); + return "string"; } - if (showModules) { - obj.modules = compilation.modules - .slice() - .sort(sortByField("depth", compilation.modules)) - .filter(createModuleFilter()) - .map(fnModule); - obj.filteredModules = compilation.modules.length - obj.modules.length; - obj.modules.sort(sortByField(sortModules, obj.modules)); + if (schema.type === "boolean") { + return "boolean"; } - if (showLogging) { - const util = __webpack_require__(31669); - obj.logging = {}; - let acceptedTypes; - let collapsedGroups = false; - switch (showLogging) { - case "none": - acceptedTypes = new Set([]); - break; - case "error": - acceptedTypes = new Set([LogType.error]); - break; - case "warn": - acceptedTypes = new Set([LogType.error, LogType.warn]); - break; - case "info": - acceptedTypes = new Set([LogType.error, LogType.warn, LogType.info]); - break; - case true: - case "log": - acceptedTypes = new Set([ - LogType.error, - LogType.warn, - LogType.info, - LogType.log, - LogType.group, - LogType.groupEnd, - LogType.groupCollapsed, - LogType.clear - ]); - break; - case "verbose": - acceptedTypes = new Set([ - LogType.error, - LogType.warn, - LogType.info, - LogType.log, - LogType.group, - LogType.groupEnd, - LogType.groupCollapsed, - LogType.profile, - LogType.profileEnd, - LogType.time, - LogType.status, - LogType.clear - ]); - collapsedGroups = true; - break; + if (schema.type === "number") { + return "number"; + } + if (schema.type === "object") { + if (schema.properties) { + const required = schema.required || []; + return `object { ${Object.keys(schema.properties) + .map(property => { + if (!required.includes(property)) return property + "?"; + return property; + }) + .concat(schema.additionalProperties ? ["…"] : []) + .join(", ")} }`; } - for (const [origin, logEntries] of compilation.logging) { - const debugMode = loggingDebug.some(fn => fn(origin)); - let collapseCounter = 0; - let processedLogEntries = logEntries; - if (!debugMode) { - processedLogEntries = processedLogEntries.filter(entry => { - if (!acceptedTypes.has(entry.type)) return false; - if (!collapsedGroups) { - switch (entry.type) { - case LogType.groupCollapsed: - collapseCounter++; - return collapseCounter === 1; - case LogType.group: - if (collapseCounter > 0) collapseCounter++; - return collapseCounter === 0; - case LogType.groupEnd: - if (collapseCounter > 0) { - collapseCounter--; - return false; - } - return true; - default: - return collapseCounter === 0; - } - } - return true; - }); - } - processedLogEntries = processedLogEntries.map(entry => { - let message = undefined; - if (entry.type === LogType.time) { - message = `${entry.args[0]}: ${entry.args[1] * 1000 + - entry.args[2] / 1000000}ms`; - } else if (entry.args && entry.args.length > 0) { - message = util.format(entry.args[0], ...entry.args.slice(1)); - } - return { - type: - (debugMode || collapsedGroups) && - entry.type === LogType.groupCollapsed - ? LogType.group - : entry.type, - message, - trace: showLoggingTrace && entry.trace ? entry.trace : undefined - }; - }); - let name = identifierUtils - .makePathsRelative(context, origin, compilation.cache) - .replace(/\|/g, " "); - if (name in obj.logging) { - let i = 1; - while (`${name}#${i}` in obj.logging) { - i++; - } - name = `${name}#${i}`; - } - obj.logging[name] = { - entries: processedLogEntries, - filteredEntries: logEntries.length - processedLogEntries.length, - debug: debugMode - }; + if (schema.additionalProperties) { + return `object { : ${formatInnerSchema( + schema.additionalProperties + )} }`; } + return "object"; } - if (showChildren) { - obj.children = compilation.children.map((child, idx) => { - const childOptions = Stats.getChildOptions(options, idx); - const obj = new Stats(child).toJson(childOptions, forToString); - delete obj.hash; - delete obj.version; - if (child.name) { - obj.name = identifierUtils.makePathsRelative( - context, - child.name, - compilation.cache - ); - } - return obj; - }); + if (schema.type === "array") { + return `[${formatInnerSchema(schema.items)}]`; } - return obj; - } - - toString(options) { - if (typeof options === "boolean" || typeof options === "string") { - options = Stats.presetToOptions(options); - } else if (!options) { - options = {}; + switch (schema.instanceof) { + case "Function": + return "function"; + case "RegExp": + return "RegExp"; } - const useColors = optionsOrFallback(options.colors, false); - - const obj = this.toJson(options, true); + if (schema.enum) { + return schema.enum.map(item => JSON.stringify(item)).join(" | "); + } - return Stats.jsonToString(obj, useColors); + if (schema.$ref) { + return formatInnerSchema(getSchemaPart(schema.$ref), true); + } + if (schema.allOf) { + return schema.allOf.map(formatInnerSchema).join(" & "); + } + if (schema.oneOf) { + return schema.oneOf.map(formatInnerSchema).join(" | "); + } + if (schema.anyOf) { + return schema.anyOf.map(formatInnerSchema).join(" | "); + } + return JSON.stringify(schema, null, 2); } - static jsonToString(obj, useColors) { - const buf = []; - - const defaultColors = { - bold: "\u001b[1m", - yellow: "\u001b[1m\u001b[33m", - red: "\u001b[1m\u001b[31m", - green: "\u001b[1m\u001b[32m", - cyan: "\u001b[1m\u001b[36m", - magenta: "\u001b[1m\u001b[35m" - }; - - const colors = Object.keys(defaultColors).reduce( - (obj, color) => { - obj[color] = str => { - if (useColors) { - buf.push( - useColors === true || useColors[color] === undefined - ? defaultColors[color] - : useColors[color] + static formatValidationError(err) { + const dataPath = `configuration${err.dataPath}`; + if (err.keyword === "additionalProperties") { + const baseMessage = `${dataPath} has an unknown property '${ + err.params.additionalProperty + }'. These properties are valid:\n${getSchemaPartText(err.parentSchema)}`; + if (!err.dataPath) { + switch (err.params.additionalProperty) { + case "debug": + return ( + `${baseMessage}\n` + + "The 'debug' property was removed in webpack 2.0.0.\n" + + "Loaders should be updated to allow passing this option via loader options in module.rules.\n" + + "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" + + "plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " debug: true\n" + + " })\n" + + "]" ); - } - buf.push(str); - if (useColors) { - buf.push("\u001b[39m\u001b[22m"); - } - }; - return obj; - }, - { - normal: str => buf.push(str) + } + return ( + `${baseMessage}\n` + + "For typos: please correct them.\n" + + "For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.\n" + + " Loaders should be updated to allow passing options via loader options in module.rules.\n" + + " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" + + " plugins: [\n" + + " new webpack.LoaderOptionsPlugin({\n" + + " // test: /\\.xxx$/, // may apply this only for some modules\n" + + " options: {\n" + + ` ${err.params.additionalProperty}: …\n` + + " }\n" + + " })\n" + + " ]" + ); } - ); - - const coloredTime = time => { - let times = [800, 400, 200, 100]; - if (obj.time) { - times = [obj.time / 2, obj.time / 4, obj.time / 8, obj.time / 16]; + return baseMessage; + } else if (err.keyword === "oneOf" || err.keyword === "anyOf") { + if (err.children && err.children.length > 0) { + if (err.schema.length === 1) { + const lastChild = err.children[err.children.length - 1]; + const remainingChildren = err.children.slice( + 0, + err.children.length - 1 + ); + return WebpackOptionsValidationError.formatValidationError( + Object.assign({}, lastChild, { + children: remainingChildren, + parentSchema: Object.assign( + {}, + err.parentSchema, + lastChild.parentSchema + ) + }) + ); + } + const children = filterChildren(err.children); + if (children.length === 1) { + return WebpackOptionsValidationError.formatValidationError( + children[0] + ); + } + return ( + `${dataPath} should be one of these:\n${getSchemaPartText( + err.parentSchema + )}\n` + + `Details:\n${children + .map( + err => + " * " + + indent( + WebpackOptionsValidationError.formatValidationError(err), + " ", + false + ) + ) + .join("\n")}` + ); } - if (time < times[3]) colors.normal(`${time}ms`); - else if (time < times[2]) colors.bold(`${time}ms`); - else if (time < times[1]) colors.green(`${time}ms`); - else if (time < times[0]) colors.yellow(`${time}ms`); - else colors.red(`${time}ms`); - }; - - const newline = () => buf.push("\n"); - - const getText = (arr, row, col) => { - return arr[row][col].value; - }; - - const table = (array, align, splitter) => { - const rows = array.length; - const cols = array[0].length; - const colSizes = new Array(cols); - for (let col = 0; col < cols; col++) { - colSizes[col] = 0; + return `${dataPath} should be one of these:\n${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "enum") { + if ( + err.parentSchema && + err.parentSchema.enum && + err.parentSchema.enum.length === 1 + ) { + return `${dataPath} should be ${getSchemaPartText(err.parentSchema)}`; } - for (let row = 0; row < rows; row++) { - for (let col = 0; col < cols; col++) { - const value = `${getText(array, row, col)}`; - if (value.length > colSizes[col]) { - colSizes[col] = value.length; - } - } + return `${dataPath} should be one of these:\n${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "allOf") { + return `${dataPath} should be:\n${getSchemaPartText(err.parentSchema)}`; + } else if (err.keyword === "type") { + switch (err.params.type) { + case "object": + return `${dataPath} should be an object.${getSchemaPartDescription( + err.parentSchema + )}`; + case "string": + return `${dataPath} should be a string.${getSchemaPartDescription( + err.parentSchema + )}`; + case "boolean": + return `${dataPath} should be a boolean.${getSchemaPartDescription( + err.parentSchema + )}`; + case "number": + return `${dataPath} should be a number.${getSchemaPartDescription( + err.parentSchema + )}`; + case "array": + return `${dataPath} should be an array:\n${getSchemaPartText( + err.parentSchema + )}`; } - for (let row = 0; row < rows; row++) { - for (let col = 0; col < cols; col++) { - const format = array[row][col].color; - const value = `${getText(array, row, col)}`; - let l = value.length; - if (align[col] === "l") { - format(value); - } - for (; l < colSizes[col] && col !== cols - 1; l++) { - colors.normal(" "); - } - if (align[col] === "r") { - format(value); - } - if (col + 1 < cols && colSizes[col] !== 0) { - colors.normal(splitter || " "); - } + return `${dataPath} should be ${err.params.type}:\n${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "instanceof") { + return `${dataPath} should be an instance of ${getSchemaPartText( + err.parentSchema + )}`; + } else if (err.keyword === "required") { + const missingProperty = err.params.missingProperty.replace(/^\./, ""); + return `${dataPath} misses the property '${missingProperty}'.\n${getSchemaPartText( + err.parentSchema, + ["properties", missingProperty] + )}`; + } else if (err.keyword === "minimum") { + return `${dataPath} ${err.message}.${getSchemaPartDescription( + err.parentSchema + )}`; + } else if (err.keyword === "uniqueItems") { + return `${dataPath} should not contain the item '${ + err.data[err.params.i] + }' twice.${getSchemaPartDescription(err.parentSchema)}`; + } else if ( + err.keyword === "minLength" || + err.keyword === "minItems" || + err.keyword === "minProperties" + ) { + if (err.params.limit === 1) { + switch (err.keyword) { + case "minLength": + return `${dataPath} should be an non-empty string.${getSchemaPartDescription( + err.parentSchema + )}`; + case "minItems": + return `${dataPath} should be an non-empty array.${getSchemaPartDescription( + err.parentSchema + )}`; + case "minProperties": + return `${dataPath} should be an non-empty object.${getSchemaPartDescription( + err.parentSchema + )}`; } - newline(); + return `${dataPath} should be not empty.${getSchemaPartDescription( + err.parentSchema + )}`; + } else { + return `${dataPath} ${err.message}${getSchemaPartDescription( + err.parentSchema + )}`; } - }; - - const getAssetColor = (asset, defaultColor) => { - if (asset.isOverSizeLimit) { - return colors.yellow; + } else if (err.keyword === "not") { + return `${dataPath} should not be ${getSchemaPartText( + err.schema + )}\n${getSchemaPartText(err.parentSchema)}`; + } else if (err.keyword === "absolutePath") { + const baseMessage = `${dataPath}: ${ + err.message + }${getSchemaPartDescription(err.parentSchema)}`; + if (dataPath === "configuration.output.filename") { + return ( + `${baseMessage}\n` + + "Please use output.path to specify absolute path and output.filename for the file name." + ); } + return baseMessage; + } else { + return `${dataPath} ${err.message} (${JSON.stringify( + err, + null, + 2 + )}).\n${getSchemaPartText(err.parentSchema)}`; + } + } +} - return defaultColor; - }; +module.exports = WebpackOptionsValidationError; - if (obj.hash) { - colors.normal("Hash: "); - colors.bold(obj.hash); - newline(); - } - if (obj.version) { - colors.normal("Version: webpack "); - colors.bold(obj.version); - newline(); - } - if (typeof obj.time === "number") { - colors.normal("Time: "); - colors.bold(obj.time); - colors.normal("ms"); - newline(); - } - if (typeof obj.builtAt === "number") { - const builtAtDate = new Date(obj.builtAt); - let timeZone = undefined; - try { - builtAtDate.toLocaleTimeString(); - } catch (err) { - // Force UTC if runtime timezone is unsupported - timeZone = "UTC"; - } +/***/ }), - colors.normal("Built at: "); - colors.normal( - builtAtDate.toLocaleDateString(undefined, { - day: "2-digit", - month: "2-digit", - year: "numeric", - timeZone - }) - ); - colors.normal(" "); - colors.bold(builtAtDate.toLocaleTimeString(undefined, { timeZone })); - newline(); - } - if (obj.env) { - colors.normal("Environment (--env): "); - colors.bold(JSON.stringify(obj.env, null, 2)); - newline(); - } - if (obj.publicPath) { - colors.normal("PublicPath: "); - colors.bold(obj.publicPath); - newline(); - } +/***/ 52337: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (obj.assets && obj.assets.length > 0) { - const t = [ - [ - { - value: "Asset", - color: colors.bold - }, - { - value: "Size", - color: colors.bold - }, - { - value: "Chunks", - color: colors.bold - }, - { - value: "", - color: colors.bold - }, - { - value: "", - color: colors.bold - }, - { - value: "Chunk Names", - color: colors.bold - } - ] - ]; - for (const asset of obj.assets) { - t.push([ - { - value: asset.name, - color: getAssetColor(asset, colors.green) - }, - { - value: SizeFormatHelpers.formatSize(asset.size), - color: getAssetColor(asset, colors.normal) - }, - { - value: asset.chunks.join(", "), - color: colors.bold - }, - { - value: [ - asset.emitted && "[emitted]", - asset.info.immutable && "[immutable]", - asset.info.development && "[dev]", - asset.info.hotModuleReplacement && "[hmr]" - ] - .filter(Boolean) - .join(" "), - color: colors.green - }, - { - value: asset.isOverSizeLimit ? "[big]" : "", - color: getAssetColor(asset, colors.normal) - }, - { - value: asset.chunkNames.join(", "), - color: colors.normal - } - ]); - } - table(t, "rrrlll"); - } - if (obj.filteredAssets > 0) { - colors.normal(" "); - if (obj.assets.length > 0) colors.normal("+ "); - colors.normal(obj.filteredAssets); - if (obj.assets.length > 0) colors.normal(" hidden"); - colors.normal(obj.filteredAssets !== 1 ? " assets" : " asset"); - newline(); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const processChunkGroups = (namedGroups, prefix) => { - for (const name of Object.keys(namedGroups)) { - const cg = namedGroups[name]; - colors.normal(`${prefix} `); - colors.bold(name); - if (cg.isOverSizeLimit) { - colors.normal(" "); - colors.yellow("[big]"); - } - colors.normal(" ="); - for (const asset of cg.assets) { - colors.normal(" "); - colors.green(asset); - } - for (const name of Object.keys(cg.childAssets)) { - const assets = cg.childAssets[name]; - if (assets && assets.length > 0) { - colors.normal(" "); - colors.magenta(`(${name}:`); - for (const asset of assets) { - colors.normal(" "); - colors.green(asset); - } - colors.magenta(")"); - } - } - newline(); - } - }; - if (obj.entrypoints) { - processChunkGroups(obj.entrypoints, "Entrypoint"); - } - if (obj.namedChunkGroups) { - let outputChunkGroups = obj.namedChunkGroups; - if (obj.entrypoints) { - outputChunkGroups = Object.keys(outputChunkGroups) - .filter(name => !obj.entrypoints[name]) - .reduce((result, name) => { - result[name] = obj.namedChunkGroups[name]; - return result; - }, {}); - } - processChunkGroups(outputChunkGroups, "Chunk Group"); - } +const AsyncDependencyToInitialChunkError = __webpack_require__(67089); +const GraphHelpers = __webpack_require__(32973); - const modulesByIdentifier = {}; - if (obj.modules) { - for (const module of obj.modules) { - modulesByIdentifier[`$${module.identifier}`] = module; - } - } else if (obj.chunks) { - for (const chunk of obj.chunks) { - if (chunk.modules) { - for (const module of chunk.modules) { - modulesByIdentifier[`$${module.identifier}`] = module; - } - } - } - } +/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ +/** @typedef {import("./Chunk")} Chunk */ +/** @typedef {import("./ChunkGroup")} ChunkGroup */ +/** @typedef {import("./Compilation")} Compilation */ +/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ +/** @typedef {import("./Dependency")} Dependency */ +/** @typedef {import("./Entrypoint")} Entrypoint */ +/** @typedef {import("./Module")} Module */ - const processModuleAttributes = module => { - colors.normal(" "); - colors.normal(SizeFormatHelpers.formatSize(module.size)); - if (module.chunks) { - for (const chunk of module.chunks) { - colors.normal(" {"); - colors.yellow(chunk); - colors.normal("}"); - } - } - if (typeof module.depth === "number") { - colors.normal(` [depth ${module.depth}]`); - } - if (module.cacheable === false) { - colors.red(" [not cacheable]"); - } - if (module.optional) { - colors.yellow(" [optional]"); - } - if (module.built) { - colors.green(" [built]"); - } - if (module.assets && module.assets.length) { - colors.magenta( - ` [${module.assets.length} asset${ - module.assets.length === 1 ? "" : "s" - }]` - ); +/** + * @typedef {Object} QueueItem + * @property {number} action + * @property {DependenciesBlock} block + * @property {Module} module + * @property {Chunk} chunk + * @property {ChunkGroup} chunkGroup + */ + +/** + * @typedef {Object} ChunkGroupInfo + * @property {ChunkGroup} chunkGroup the chunk group + * @property {Set} minAvailableModules current minimal set of modules available at this point + * @property {boolean} minAvailableModulesOwned true, if minAvailableModules is owned and can be modified + * @property {Set[]} availableModulesToBeMerged enqueued updates to the minimal set of available modules + * @property {QueueItem[]} skippedItems queue items that were skipped because module is already available in parent chunks (need to reconsider when minAvailableModules is shrinking) + * @property {Set} resultingAvailableModules set of modules available including modules from this chunk group + * @property {Set} children set of children chunk groups, that will be revisited when availableModules shrink + */ + +/** + * @typedef {Object} ChunkGroupDep + * @property {AsyncDependenciesBlock} block referencing block + * @property {ChunkGroup} chunkGroup referenced chunk group + */ + +/** + * @template T + * @param {Set} a first set + * @param {Set} b second set + * @returns {number} cmp + */ +const bySetSize = (a, b) => { + return b.size - a.size; +}; + +/** + * Extracts simplified info from the modules and their dependencies + * @param {Compilation} compilation the compilation + * @returns {Map, blocks: AsyncDependenciesBlock[]}>} the mapping block to modules and inner blocks + */ +const extraceBlockInfoMap = compilation => { + /** @type {Map, blocks: AsyncDependenciesBlock[]}>} */ + const blockInfoMap = new Map(); + + /** + * @param {Dependency} d dependency to iterate over + * @returns {void} + */ + const iteratorDependency = d => { + // We skip Dependencies without Reference + const ref = compilation.getDependencyReference(currentModule, d); + if (!ref) { + return; + } + // We skip Dependencies without Module pointer + const refModule = ref.module; + if (!refModule) { + return; + } + // We skip weak Dependencies + if (ref.weak) { + return; + } + + blockInfoModules.add(refModule); + }; + + /** + * @param {AsyncDependenciesBlock} b blocks to prepare + * @returns {void} + */ + const iteratorBlockPrepare = b => { + blockInfoBlocks.push(b); + blockQueue.push(b); + }; + + /** @type {Module} */ + let currentModule; + /** @type {DependenciesBlock} */ + let block; + /** @type {DependenciesBlock[]} */ + let blockQueue; + /** @type {Set} */ + let blockInfoModules; + /** @type {AsyncDependenciesBlock[]} */ + let blockInfoBlocks; + + for (const module of compilation.modules) { + blockQueue = [module]; + currentModule = module; + while (blockQueue.length > 0) { + block = blockQueue.pop(); + blockInfoModules = new Set(); + blockInfoBlocks = []; + + if (block.variables) { + for (const variable of block.variables) { + for (const dep of variable.dependencies) iteratorDependency(dep); + } } - if (module.prefetched) { - colors.magenta(" [prefetched]"); + + if (block.dependencies) { + for (const dep of block.dependencies) iteratorDependency(dep); } - if (module.failed) colors.red(" [failed]"); - if (module.warnings) { - colors.yellow( - ` [${module.warnings} warning${module.warnings === 1 ? "" : "s"}]` - ); + + if (block.blocks) { + for (const b of block.blocks) iteratorBlockPrepare(b); } - if (module.errors) { - colors.red( - ` [${module.errors} error${module.errors === 1 ? "" : "s"}]` + + const blockInfo = { + modules: blockInfoModules, + blocks: blockInfoBlocks + }; + blockInfoMap.set(block, blockInfo); + } + } + + return blockInfoMap; +}; + +/** + * + * @param {Compilation} compilation the compilation + * @param {Entrypoint[]} inputChunkGroups input groups + * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules + * @param {Map} chunkDependencies dependencies for chunk groups + * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks + * @param {Set} allCreatedChunkGroups filled with all chunk groups that are created here + */ +const visitModules = ( + compilation, + inputChunkGroups, + chunkGroupInfoMap, + chunkDependencies, + blocksWithNestedBlocks, + allCreatedChunkGroups +) => { + const logger = compilation.getLogger("webpack.buildChunkGraph.visitModules"); + const { namedChunkGroups } = compilation; + + logger.time("prepare"); + const blockInfoMap = extraceBlockInfoMap(compilation); + + /** @type {Map} */ + const chunkGroupCounters = new Map(); + for (const chunkGroup of inputChunkGroups) { + chunkGroupCounters.set(chunkGroup, { + index: 0, + index2: 0 + }); + } + + let nextFreeModuleIndex = 0; + let nextFreeModuleIndex2 = 0; + + /** @type {Map} */ + const blockChunkGroups = new Map(); + + const ADD_AND_ENTER_MODULE = 0; + const ENTER_MODULE = 1; + const PROCESS_BLOCK = 2; + const LEAVE_MODULE = 3; + + /** + * @param {QueueItem[]} queue the queue array (will be mutated) + * @param {ChunkGroup} chunkGroup chunk group + * @returns {QueueItem[]} the queue array again + */ + const reduceChunkGroupToQueueItem = (queue, chunkGroup) => { + for (const chunk of chunkGroup.chunks) { + const module = chunk.entryModule; + queue.push({ + action: ENTER_MODULE, + block: module, + module, + chunk, + chunkGroup + }); + } + chunkGroupInfoMap.set(chunkGroup, { + chunkGroup, + minAvailableModules: new Set(), + minAvailableModulesOwned: true, + availableModulesToBeMerged: [], + skippedItems: [], + resultingAvailableModules: undefined, + children: undefined + }); + return queue; + }; + + // Start with the provided modules/chunks + /** @type {QueueItem[]} */ + let queue = inputChunkGroups + .reduce(reduceChunkGroupToQueueItem, []) + .reverse(); + /** @type {Map>} */ + const queueConnect = new Map(); + /** @type {Set} */ + const outdatedChunkGroupInfo = new Set(); + /** @type {QueueItem[]} */ + let queueDelayed = []; + + logger.timeEnd("prepare"); + + /** @type {Module} */ + let module; + /** @type {Chunk} */ + let chunk; + /** @type {ChunkGroup} */ + let chunkGroup; + /** @type {DependenciesBlock} */ + let block; + /** @type {Set} */ + let minAvailableModules; + /** @type {QueueItem[]} */ + let skippedItems; + + // For each async Block in graph + /** + * @param {AsyncDependenciesBlock} b iterating over each Async DepBlock + * @returns {void} + */ + const iteratorBlock = b => { + // 1. We create a chunk for this Block + // but only once (blockChunkGroups map) + let c = blockChunkGroups.get(b); + if (c === undefined) { + c = namedChunkGroups.get(b.chunkName); + if (c && c.isInitial()) { + compilation.errors.push( + new AsyncDependencyToInitialChunkError(b.chunkName, module, b.loc) + ); + c = chunkGroup; + } else { + c = compilation.addChunkInGroup( + b.groupOptions || b.chunkName, + module, + b.loc, + b.request ); + chunkGroupCounters.set(c, { index: 0, index2: 0 }); + blockChunkGroups.set(b, c); + allCreatedChunkGroups.add(c); } - }; + } else { + // TODO webpack 5 remove addOptions check + if (c.addOptions) c.addOptions(b.groupOptions); + c.addOrigin(module, b.loc, b.request); + } - const processModuleContent = (module, prefix) => { - if (Array.isArray(module.providedExports)) { - colors.normal(prefix); - if (module.providedExports.length === 0) { - colors.cyan("[no exports]"); - } else { - colors.cyan(`[exports: ${module.providedExports.join(", ")}]`); - } - newline(); + // 2. We store the Block+Chunk mapping as dependency for the chunk + let deps = chunkDependencies.get(chunkGroup); + if (!deps) chunkDependencies.set(chunkGroup, (deps = [])); + deps.push({ + block: b, + chunkGroup: c + }); + + // 3. We create/update the chunk group info + let connectList = queueConnect.get(chunkGroup); + if (connectList === undefined) { + connectList = new Set(); + queueConnect.set(chunkGroup, connectList); + } + connectList.add(c); + + // 4. We enqueue the DependenciesBlock for traversal + queueDelayed.push({ + action: PROCESS_BLOCK, + block: b, + module: module, + chunk: c.chunks[0], + chunkGroup: c + }); + }; + + // Iterative traversal of the Module graph + // Recursive would be simpler to write but could result in Stack Overflows + while (queue.length) { + logger.time("visiting"); + while (queue.length) { + const queueItem = queue.pop(); + module = queueItem.module; + block = queueItem.block; + chunk = queueItem.chunk; + if (chunkGroup !== queueItem.chunkGroup) { + chunkGroup = queueItem.chunkGroup; + const chunkGroupInfo = chunkGroupInfoMap.get(chunkGroup); + minAvailableModules = chunkGroupInfo.minAvailableModules; + skippedItems = chunkGroupInfo.skippedItems; } - if (module.usedExports !== undefined) { - if (module.usedExports !== true) { - colors.normal(prefix); - if (module.usedExports === null) { - colors.cyan("[used exports unknown]"); - } else if (module.usedExports === false) { - colors.cyan("[no exports used]"); - } else if ( - Array.isArray(module.usedExports) && - module.usedExports.length === 0 - ) { - colors.cyan("[no exports used]"); - } else if (Array.isArray(module.usedExports)) { - const providedExportsCount = Array.isArray(module.providedExports) - ? module.providedExports.length - : null; - if ( - providedExportsCount !== null && - providedExportsCount === module.usedExports.length - ) { - colors.cyan("[all exports used]"); - } else { - colors.cyan( - `[only some exports used: ${module.usedExports.join(", ")}]` + + switch (queueItem.action) { + case ADD_AND_ENTER_MODULE: { + if (minAvailableModules.has(module)) { + // already in parent chunks + // skip it for now, but enqueue for rechecking when minAvailableModules shrinks + skippedItems.push(queueItem); + break; + } + // We connect Module and Chunk when not already done + if (chunk.addModule(module)) { + module.addChunk(chunk); + } else { + // already connected, skip it + break; + } + } + // fallthrough + case ENTER_MODULE: { + if (chunkGroup !== undefined) { + const index = chunkGroup.getModuleIndex(module); + if (index === undefined) { + chunkGroup.setModuleIndex( + module, + chunkGroupCounters.get(chunkGroup).index++ ); } } - newline(); - } - } - if (Array.isArray(module.optimizationBailout)) { - for (const item of module.optimizationBailout) { - colors.normal(prefix); - colors.yellow(item); - newline(); + + if (module.index === null) { + module.index = nextFreeModuleIndex++; + } + + queue.push({ + action: LEAVE_MODULE, + block, + module, + chunk, + chunkGroup + }); } - } - if (module.reasons) { - for (const reason of module.reasons) { - colors.normal(prefix); - if (reason.type) { - colors.normal(reason.type); - colors.normal(" "); + // fallthrough + case PROCESS_BLOCK: { + // get prepared block info + const blockInfo = blockInfoMap.get(block); + + // Buffer items because order need to be reverse to get indicies correct + const skipBuffer = []; + const queueBuffer = []; + // Traverse all referenced modules + for (const refModule of blockInfo.modules) { + if (chunk.containsModule(refModule)) { + // skip early if already connected + continue; + } + if (minAvailableModules.has(refModule)) { + // already in parent chunks, skip it for now + skipBuffer.push({ + action: ADD_AND_ENTER_MODULE, + block: refModule, + module: refModule, + chunk, + chunkGroup + }); + continue; + } + // enqueue the add and enter to enter in the correct order + // this is relevant with circular dependencies + queueBuffer.push({ + action: ADD_AND_ENTER_MODULE, + block: refModule, + module: refModule, + chunk, + chunkGroup + }); } - if (reason.userRequest) { - colors.cyan(reason.userRequest); - colors.normal(" "); + // Add buffered items in reversed order + for (let i = skipBuffer.length - 1; i >= 0; i--) { + skippedItems.push(skipBuffer[i]); } - if (reason.moduleId !== null) { - colors.normal("["); - colors.normal(reason.moduleId); - colors.normal("]"); + for (let i = queueBuffer.length - 1; i >= 0; i--) { + queue.push(queueBuffer[i]); } - if (reason.module && reason.module !== reason.moduleId) { - colors.normal(" "); - colors.magenta(reason.module); + + // Traverse all Blocks + for (const block of blockInfo.blocks) iteratorBlock(block); + + if (blockInfo.blocks.length > 0 && module !== block) { + blocksWithNestedBlocks.add(block); } - if (reason.loc) { - colors.normal(" "); - colors.normal(reason.loc); + break; + } + case LEAVE_MODULE: { + if (chunkGroup !== undefined) { + const index = chunkGroup.getModuleIndex2(module); + if (index === undefined) { + chunkGroup.setModuleIndex2( + module, + chunkGroupCounters.get(chunkGroup).index2++ + ); + } } - if (reason.explanation) { - colors.normal(" "); - colors.cyan(reason.explanation); + + if (module.index2 === null) { + module.index2 = nextFreeModuleIndex2++; } - newline(); + break; } } - if (module.profile) { - colors.normal(prefix); - let sum = 0; - if (module.issuerPath) { - for (const m of module.issuerPath) { - colors.normal("["); - colors.normal(m.id); - colors.normal("] "); - if (m.profile) { - const time = (m.profile.factory || 0) + (m.profile.building || 0); - coloredTime(time); - sum += time; - colors.normal(" "); - } - colors.normal("-> "); + } + logger.timeEnd("visiting"); + + while (queueConnect.size > 0) { + logger.time("calculating available modules"); + + // Figure out new parents for chunk groups + // to get new available modules for these children + for (const [chunkGroup, targets] of queueConnect) { + const info = chunkGroupInfoMap.get(chunkGroup); + let minAvailableModules = info.minAvailableModules; + + // 1. Create a new Set of available modules at this points + const resultingAvailableModules = new Set(minAvailableModules); + for (const chunk of chunkGroup.chunks) { + for (const m of chunk.modulesIterable) { + resultingAvailableModules.add(m); } } - for (const key of Object.keys(module.profile)) { - colors.normal(`${key}:`); - const time = module.profile[key]; - coloredTime(time); - colors.normal(" "); - sum += time; + info.resultingAvailableModules = resultingAvailableModules; + if (info.children === undefined) { + info.children = targets; + } else { + for (const target of targets) { + info.children.add(target); + } } - colors.normal("= "); - coloredTime(sum); - newline(); - } - if (module.modules) { - processModulesList(module, prefix + "| "); - } - }; - const processModulesList = (obj, prefix) => { - if (obj.modules) { - let maxModuleId = 0; - for (const module of obj.modules) { - if (typeof module.id === "number") { - if (maxModuleId < module.id) maxModuleId = module.id; - } - } - let contentPrefix = prefix + " "; - if (maxModuleId >= 10) contentPrefix += " "; - if (maxModuleId >= 100) contentPrefix += " "; - if (maxModuleId >= 1000) contentPrefix += " "; - for (const module of obj.modules) { - colors.normal(prefix); - const name = module.name || module.identifier; - if (typeof module.id === "string" || typeof module.id === "number") { - if (typeof module.id === "number") { - if (module.id < 1000 && maxModuleId >= 1000) colors.normal(" "); - if (module.id < 100 && maxModuleId >= 100) colors.normal(" "); - if (module.id < 10 && maxModuleId >= 10) colors.normal(" "); - } else { - if (maxModuleId >= 1000) colors.normal(" "); - if (maxModuleId >= 100) colors.normal(" "); - if (maxModuleId >= 10) colors.normal(" "); - } - if (name !== module.id) { - colors.normal("["); - colors.normal(module.id); - colors.normal("]"); - colors.normal(" "); - } else { - colors.normal("["); - colors.bold(module.id); - colors.normal("]"); - } - } - if (name !== module.id) { - colors.bold(name); + // 2. Update chunk group info + for (const target of targets) { + let chunkGroupInfo = chunkGroupInfoMap.get(target); + if (chunkGroupInfo === undefined) { + chunkGroupInfo = { + chunkGroup: target, + minAvailableModules: undefined, + minAvailableModulesOwned: undefined, + availableModulesToBeMerged: [], + skippedItems: [], + resultingAvailableModules: undefined, + children: undefined + }; + chunkGroupInfoMap.set(target, chunkGroupInfo); } - processModuleAttributes(module); - newline(); - processModuleContent(module, contentPrefix); - } - if (obj.filteredModules > 0) { - colors.normal(prefix); - colors.normal(" "); - if (obj.modules.length > 0) colors.normal(" + "); - colors.normal(obj.filteredModules); - if (obj.modules.length > 0) colors.normal(" hidden"); - colors.normal(obj.filteredModules !== 1 ? " modules" : " module"); - newline(); + chunkGroupInfo.availableModulesToBeMerged.push( + resultingAvailableModules + ); + outdatedChunkGroupInfo.add(chunkGroupInfo); } } - }; + queueConnect.clear(); + logger.timeEnd("calculating available modules"); - if (obj.chunks) { - for (const chunk of obj.chunks) { - colors.normal("chunk "); - if (chunk.id < 1000) colors.normal(" "); - if (chunk.id < 100) colors.normal(" "); - if (chunk.id < 10) colors.normal(" "); - colors.normal("{"); - colors.yellow(chunk.id); - colors.normal("} "); - colors.green(chunk.files.join(", ")); - if (chunk.names && chunk.names.length > 0) { - colors.normal(" ("); - colors.normal(chunk.names.join(", ")); - colors.normal(")"); - } - colors.normal(" "); - colors.normal(SizeFormatHelpers.formatSize(chunk.size)); - for (const id of chunk.parents) { - colors.normal(" <{"); - colors.yellow(id); - colors.normal("}>"); - } - for (const id of chunk.siblings) { - colors.normal(" ={"); - colors.yellow(id); - colors.normal("}="); - } - for (const id of chunk.children) { - colors.normal(" >{"); - colors.yellow(id); - colors.normal("}<"); - } - if (chunk.childrenByOrder) { - for (const name of Object.keys(chunk.childrenByOrder)) { - const children = chunk.childrenByOrder[name]; - colors.normal(" "); - colors.magenta(`(${name}:`); - for (const id of children) { - colors.normal(" {"); - colors.yellow(id); - colors.normal("}"); - } - colors.magenta(")"); + if (outdatedChunkGroupInfo.size > 0) { + logger.time("merging available modules"); + // Execute the merge + for (const info of outdatedChunkGroupInfo) { + const availableModulesToBeMerged = info.availableModulesToBeMerged; + let cachedMinAvailableModules = info.minAvailableModules; + + // 1. Get minimal available modules + // It doesn't make sense to traverse a chunk again with more available modules. + // This step calculates the minimal available modules and skips traversal when + // the list didn't shrink. + if (availableModulesToBeMerged.length > 1) { + availableModulesToBeMerged.sort(bySetSize); } - } - if (chunk.entry) { - colors.yellow(" [entry]"); - } else if (chunk.initial) { - colors.yellow(" [initial]"); - } - if (chunk.rendered) { - colors.green(" [rendered]"); - } - if (chunk.recorded) { - colors.green(" [recorded]"); - } - if (chunk.reason) { - colors.yellow(` ${chunk.reason}`); - } - newline(); - if (chunk.origins) { - for (const origin of chunk.origins) { - colors.normal(" > "); - if (origin.reasons && origin.reasons.length) { - colors.yellow(origin.reasons.join(" ")); - colors.normal(" "); - } - if (origin.request) { - colors.normal(origin.request); - colors.normal(" "); - } - if (origin.module) { - colors.normal("["); - colors.normal(origin.moduleId); - colors.normal("] "); - const module = modulesByIdentifier[`$${origin.module}`]; - if (module) { - colors.bold(module.name); - colors.normal(" "); + let changed = false; + for (const availableModules of availableModulesToBeMerged) { + if (cachedMinAvailableModules === undefined) { + cachedMinAvailableModules = availableModules; + info.minAvailableModules = cachedMinAvailableModules; + info.minAvailableModulesOwned = false; + changed = true; + } else { + if (info.minAvailableModulesOwned) { + // We own it and can modify it + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m)) { + cachedMinAvailableModules.delete(m); + changed = true; + } + } + } else { + for (const m of cachedMinAvailableModules) { + if (!availableModules.has(m)) { + // cachedMinAvailableModules need to be modified + // but we don't own it + // construct a new Set as intersection of cachedMinAvailableModules and availableModules + /** @type {Set} */ + const newSet = new Set(); + const iterator = cachedMinAvailableModules[ + Symbol.iterator + ](); + /** @type {IteratorResult} */ + let it; + while (!(it = iterator.next()).done) { + const module = it.value; + if (module === m) break; + newSet.add(module); + } + while (!(it = iterator.next()).done) { + const module = it.value; + if (availableModules.has(module)) { + newSet.add(module); + } + } + cachedMinAvailableModules = newSet; + info.minAvailableModulesOwned = true; + info.minAvailableModules = newSet; + + // Update the cache from the first queue + // if the chunkGroup is currently cached + if (chunkGroup === info.chunkGroup) { + minAvailableModules = cachedMinAvailableModules; + } + + changed = true; + break; + } + } } } - if (origin.loc) { - colors.normal(origin.loc); - } - newline(); } - } - processModulesList(chunk, " "); - } - } - - processModulesList(obj, ""); + availableModulesToBeMerged.length = 0; + if (!changed) continue; - if (obj.logging) { - for (const origin of Object.keys(obj.logging)) { - const logData = obj.logging[origin]; - if (logData.entries.length > 0) { - newline(); - if (logData.debug) { - colors.red("DEBUG "); + // 2. Reconsider skipped items + for (const queueItem of info.skippedItems) { + queue.push(queueItem); } - colors.bold("LOG from " + origin); - newline(); - let indent = ""; - for (const entry of logData.entries) { - let color = colors.normal; - let prefix = " "; - switch (entry.type) { - case LogType.clear: - colors.normal(`${indent}-------`); - newline(); - continue; - case LogType.error: - color = colors.red; - prefix = " "; - break; - case LogType.warn: - color = colors.yellow; - prefix = " "; - break; - case LogType.info: - color = colors.green; - prefix = " "; - break; - case LogType.log: - color = colors.bold; - break; - case LogType.trace: - case LogType.debug: - color = colors.normal; - break; - case LogType.status: - color = colors.magenta; - prefix = " "; - break; - case LogType.profile: - color = colors.magenta; - prefix = "

"; - break; - case LogType.profileEnd: - color = colors.magenta; - prefix = "

"; - break; - case LogType.time: - color = colors.magenta; - prefix = " "; - break; - case LogType.group: - color = colors.cyan; - prefix = "<-> "; - break; - case LogType.groupCollapsed: - color = colors.cyan; - prefix = "<+> "; - break; - case LogType.groupEnd: - if (indent.length >= 2) - indent = indent.slice(0, indent.length - 2); - continue; - } - if (entry.message) { - for (const line of entry.message.split("\n")) { - colors.normal(`${indent}${prefix}`); - color(line); - newline(); - } - } - if (entry.trace) { - for (const line of entry.trace) { - colors.normal(`${indent}| ${line}`); - newline(); + info.skippedItems.length = 0; + + // 3. Reconsider children chunk groups + if (info.children !== undefined) { + const chunkGroup = info.chunkGroup; + for (const c of info.children) { + let connectList = queueConnect.get(chunkGroup); + if (connectList === undefined) { + connectList = new Set(); + queueConnect.set(chunkGroup, connectList); } + connectList.add(c); } - switch (entry.type) { - case LogType.group: - indent += " "; - break; - } - } - if (logData.filteredEntries) { - colors.normal(`+ ${logData.filteredEntries} hidden lines`); - newline(); } } + outdatedChunkGroupInfo.clear(); + logger.timeEnd("merging available modules"); } } - if (obj._showWarnings && obj.warnings) { - for (const warning of obj.warnings) { - newline(); - colors.yellow(`WARNING in ${warning}`); - newline(); - } + // Run queueDelayed when all items of the queue are processed + // This is important to get the global indicing correct + // Async blocks should be processed after all sync blocks are processed + if (queue.length === 0) { + const tempQueue = queue; + queue = queueDelayed.reverse(); + queueDelayed = tempQueue; } - if (obj._showErrors && obj.errors) { - for (const error of obj.errors) { - newline(); - colors.red(`ERROR in ${error}`); - newline(); + } +}; + +/** + * + * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks + * @param {Map} chunkDependencies dependencies for chunk groups + * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules + */ +const connectChunkGroups = ( + blocksWithNestedBlocks, + chunkDependencies, + chunkGroupInfoMap +) => { + /** @type {Set} */ + let resultingAvailableModules; + + /** + * Helper function to check if all modules of a chunk are available + * + * @param {ChunkGroup} chunkGroup the chunkGroup to scan + * @param {Set} availableModules the comparitor set + * @returns {boolean} return true if all modules of a chunk are available + */ + const areModulesAvailable = (chunkGroup, availableModules) => { + for (const chunk of chunkGroup.chunks) { + for (const module of chunk.modulesIterable) { + if (!availableModules.has(module)) return false; } } - if (obj.children) { - for (const child of obj.children) { - const childString = Stats.jsonToString(child, useColors); - if (childString) { - if (child.name) { - colors.normal("Child "); - colors.bold(child.name); - colors.normal(":"); - } else { - colors.normal("Child"); - } - newline(); - buf.push(" "); - buf.push(childString.replace(/\n/g, "\n ")); - newline(); - } - } + return true; + }; + + // For each edge in the basic chunk graph + /** + * @param {ChunkGroupDep} dep the dependency used for filtering + * @returns {boolean} used to filter "edges" (aka Dependencies) that were pointing + * to modules that are already available. Also filters circular dependencies in the chunks graph + */ + const filterFn = dep => { + const depChunkGroup = dep.chunkGroup; + // TODO is this needed? + if (blocksWithNestedBlocks.has(dep.block)) return true; + if (areModulesAvailable(depChunkGroup, resultingAvailableModules)) { + return false; // break all modules are already available } - if (obj.needAdditionalPass) { - colors.yellow( - "Compilation needs an additional pass and will compile again." + return true; + }; + + // For all deps, check if chunk groups need to be connected + for (const [chunkGroup, deps] of chunkDependencies) { + if (deps.length === 0) continue; + + // 1. Get info from chunk group info map + const info = chunkGroupInfoMap.get(chunkGroup); + resultingAvailableModules = info.resultingAvailableModules; + + // 2. Foreach edge + for (let i = 0; i < deps.length; i++) { + const dep = deps[i]; + + // Filter inline, rather than creating a new array from `.filter()` + // TODO check if inlining filterFn makes sense here + if (!filterFn(dep)) { + continue; + } + const depChunkGroup = dep.chunkGroup; + const depBlock = dep.block; + + // 5. Connect block with chunk + GraphHelpers.connectDependenciesBlockAndChunkGroup( + depBlock, + depChunkGroup ); + + // 6. Connect chunk with parent + GraphHelpers.connectChunkGroupParentAndChild(chunkGroup, depChunkGroup); } + } +}; - while (buf[buf.length - 1] === "\n") { - buf.pop(); +/** + * Remove all unconnected chunk groups + * @param {Compilation} compilation the compilation + * @param {Iterable} allCreatedChunkGroups all chunk groups that where created before + */ +const cleanupUnconnectedGroups = (compilation, allCreatedChunkGroups) => { + for (const chunkGroup of allCreatedChunkGroups) { + if (chunkGroup.getNumberOfParents() === 0) { + for (const chunk of chunkGroup.chunks) { + const idx = compilation.chunks.indexOf(chunk); + if (idx >= 0) compilation.chunks.splice(idx, 1); + chunk.remove("unconnected"); + } + chunkGroup.remove("unconnected"); } - return buf.join(""); } - - static presetToOptions(name) { - // Accepted values: none, errors-only, minimal, normal, detailed, verbose - // Any other falsy value will behave as 'none', truthy values as 'normal' - const pn = - (typeof name === "string" && name.toLowerCase()) || name || "none"; - switch (pn) { - case "none": - return { - all: false - }; - case "verbose": - return { - entrypoints: true, - chunkGroups: true, - modules: false, - chunks: true, - chunkModules: true, - chunkOrigins: true, - depth: true, - env: true, - reasons: true, - usedExports: true, - providedExports: true, - optimizationBailout: true, - errorDetails: true, - publicPath: true, - logging: "verbose", - exclude: false, - maxModules: Infinity - }; - case "detailed": - return { - entrypoints: true, - chunkGroups: true, - chunks: true, - chunkModules: false, - chunkOrigins: true, - depth: true, - usedExports: true, - providedExports: true, - optimizationBailout: true, - errorDetails: true, - publicPath: true, - logging: true, - exclude: false, - maxModules: Infinity - }; - case "minimal": - return { - all: false, - modules: true, - maxModules: 0, - errors: true, - warnings: true, - logging: "warn" - }; - case "errors-only": - return { - all: false, - errors: true, - moduleTrace: true, - logging: "error" - }; - case "errors-warnings": - return { - all: false, - errors: true, - warnings: true, - logging: "warn" - }; - default: - return {}; - } - } - - static getChildOptions(options, idx) { - let innerOptions; - if (Array.isArray(options.children)) { - if (idx < options.children.length) { - innerOptions = options.children[idx]; - } - } else if (typeof options.children === "object" && options.children) { - innerOptions = options.children; - } - if (typeof innerOptions === "boolean" || typeof innerOptions === "string") { - innerOptions = Stats.presetToOptions(innerOptions); - } - if (!innerOptions) { - return options; - } - const childOptions = Object.assign({}, options); - delete childOptions.children; // do not inherit children - return Object.assign(childOptions, innerOptions); - } -} - -module.exports = Stats; - - -/***/ }), - -/***/ 97365: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Joel Denning @joeldenning - */ - - - -const { ConcatSource } = __webpack_require__(53665); -const Template = __webpack_require__(96066); - -/** @typedef {import("./Compilation")} Compilation */ +}; /** - * @typedef {Object} SystemMainTemplatePluginOptions - * @param {string=} name the library name + * This method creates the Chunk graph from the Module graph + * @param {Compilation} compilation the compilation + * @param {Entrypoint[]} inputChunkGroups chunk groups which are processed + * @returns {void} */ +const buildChunkGraph = (compilation, inputChunkGroups) => { + // SHARED STATE -class SystemMainTemplatePlugin { - /** - * @param {SystemMainTemplatePluginOptions} options the plugin options - */ - constructor(options) { - this.name = options.name; - } - - /** - * @param {Compilation} compilation the compilation instance - * @returns {void} - */ - apply(compilation) { - const { mainTemplate, chunkTemplate } = compilation; - - const onRenderWithEntry = (source, chunk, hash) => { - const externals = chunk.getModules().filter(m => m.external); - - // The name this bundle should be registered as with System - const name = this.name - ? `${JSON.stringify( - mainTemplate.getAssetPath(this.name, { hash, chunk }) - )}, ` - : ""; + /** @type {Map} */ + const chunkDependencies = new Map(); - // The array of dependencies that are external to webpack and will be provided by System - const systemDependencies = JSON.stringify( - externals.map(m => - typeof m.request === "object" ? m.request.amd : m.request - ) - ); + /** @type {Set} */ + const allCreatedChunkGroups = new Set(); - // The name of the variable provided by System for exporting - const dynamicExport = "__WEBPACK_DYNAMIC_EXPORT__"; + /** @type {Map} */ + const chunkGroupInfoMap = new Map(); - // An array of the internal variable names for the webpack externals - const externalWebpackNames = externals.map( - m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` - ); + /** @type {Set} */ + const blocksWithNestedBlocks = new Set(); - // Declaring variables for the internal variable names for the webpack externals - const externalVarDeclarations = - externalWebpackNames.length > 0 - ? `var ${externalWebpackNames.join(", ")};` - : ""; + // PART ONE - // The system.register format requires an array of setter functions for externals. - const setters = - externalWebpackNames.length === 0 - ? "" - : Template.asString([ - "setters: [", - Template.indent( - externalWebpackNames - .map(external => - Template.asString([ - "function(module) {", - Template.indent(`${external} = module;`), - "}" - ]) - ) - .join(",\n") - ), - "]," - ]); + visitModules( + compilation, + inputChunkGroups, + chunkGroupInfoMap, + chunkDependencies, + blocksWithNestedBlocks, + allCreatedChunkGroups + ); - return new ConcatSource( - Template.asString([ - `System.register(${name}${systemDependencies}, function(${dynamicExport}) {`, - Template.indent([ - externalVarDeclarations, - "return {", - Template.indent([ - setters, - "execute: function() {", - Template.indent(`${dynamicExport}(`) - ]) - ]) - ]) + "\n", - source, - "\n" + - Template.asString([ - Template.indent([ - Template.indent([Template.indent([");"]), "}"]), - "};" - ]), - "})" - ]) - ); - }; + // PART TWO - for (const template of [mainTemplate, chunkTemplate]) { - template.hooks.renderWithEntry.tap( - "SystemMainTemplatePlugin", - onRenderWithEntry - ); - } + connectChunkGroups( + blocksWithNestedBlocks, + chunkDependencies, + chunkGroupInfoMap + ); - mainTemplate.hooks.globalHashPaths.tap( - "SystemMainTemplatePlugin", - paths => { - if (this.name) { - paths.push(this.name); - } - return paths; - } - ); + // Cleaup work - mainTemplate.hooks.hash.tap("SystemMainTemplatePlugin", hash => { - hash.update("exports system"); - if (this.name) { - hash.update(this.name); - } - }); - } -} + cleanupUnconnectedGroups(compilation, allCreatedChunkGroups); +}; -module.exports = SystemMainTemplatePlugin; +module.exports = buildChunkGraph; /***/ }), -/***/ 96066: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 22562: +/***/ (function(module) { +"use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ModuleTemplate")} ModuleTemplate */ -/** @typedef {import("webpack-sources").ConcatSource} ConcatSource */ -const { ConcatSource } = __webpack_require__(53665); -const HotUpdateChunk = __webpack_require__(26782); - -const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0); -const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0); -const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1; -const FUNCTION_CONTENT_REGEX = /^function\s?\(\)\s?\{\r?\n?|\r?\n?\}$/g; -const INDENT_MULTILINE_REGEX = /^\t/gm; -const LINE_SEPARATOR_REGEX = /\r?\n/g; -const IDENTIFIER_NAME_REPLACE_REGEX = /^([^a-zA-Z$_])/; -const IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX = /[^a-zA-Z0-9$]+/g; -const COMMENT_END_REGEX = /\*\//g; -const PATH_NAME_NORMALIZE_REPLACE_REGEX = /[^a-zA-Z0-9_!§$()=\-^°]+/g; -const MATCH_PADDED_HYPHENS_REPLACE_REGEX = /^-|-$/g; -/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +// TODO webpack 5 remove string type from a and b /** - * @typedef {Object} HasId - * @property {number | string} id + * Compare two locations + * @param {string|DependencyLocation} a A location node + * @param {string|DependencyLocation} b A location node + * @returns {-1|0|1} sorting comparator value */ +module.exports = (a, b) => { + if (typeof a === "string") { + if (typeof b === "string") { + if (a < b) return -1; + if (a > b) return 1; + return 0; + } else if (typeof b === "object") { + return 1; + } else { + return 0; + } + } else if (typeof a === "object") { + if (typeof b === "string") { + return -1; + } else if (typeof b === "object") { + if ("start" in a && "start" in b) { + const ap = a.start; + const bp = b.start; + if (ap.line < bp.line) return -1; + if (ap.line > bp.line) return 1; + if (ap.column < bp.column) return -1; + if (ap.column > bp.column) return 1; + } + if ("name" in a && "name" in b) { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + } + if ("index" in a && "index" in b) { + if (a.index < b.index) return -1; + if (a.index > b.index) return 1; + } + return 0; + } else { + return 0; + } + } +}; -/** - * @typedef {function(Module, number): boolean} ModuleFilterPredicate - */ -/** - * @param {HasId} a first id object to be sorted - * @param {HasId} b second id object to be sorted against - * @returns {-1|0|1} the sort value - */ -const stringifyIdSortPredicate = (a, b) => { - const aId = a.id + ""; - const bId = b.id + ""; - if (aId < bId) return -1; - if (aId > bId) return 1; - return 0; -}; +/***/ }), -class Template { - /** - * - * @param {Function} fn a runtime function (.runtime.js) "template" - * @returns {string} the updated and normalized function string - */ - static getFunctionContent(fn) { - return fn - .toString() - .replace(FUNCTION_CONTENT_REGEX, "") - .replace(INDENT_MULTILINE_REGEX, "") - .replace(LINE_SEPARATOR_REGEX, "\n"); - } +/***/ 72890: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @param {string} str the string converted to identifier - * @returns {string} created identifier - */ - static toIdentifier(str) { - if (typeof str !== "string") return ""; - return str - .replace(IDENTIFIER_NAME_REPLACE_REGEX, "_$1") - .replace(IDENTIFIER_ALPHA_NUMERIC_NAME_REPLACE_REGEX, "_"); - } - /** - * - * @param {string} str string to be converted to commented in bundle code - * @returns {string} returns a commented version of string - */ - static toComment(str) { - if (!str) return ""; - return `/*! ${str.replace(COMMENT_END_REGEX, "* /")} */`; - } +const fs = __webpack_require__(35747); +const path = __webpack_require__(85622); +const mkdirp = __webpack_require__(50998); +const { Tracer } = __webpack_require__(92430); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(49049); - /** - * - * @param {string} str string to be converted to "normal comment" - * @returns {string} returns a commented version of string - */ - static toNormalComment(str) { - if (!str) return ""; - return `/* ${str.replace(COMMENT_END_REGEX, "* /")} */`; +/** @typedef {import("../../declarations/plugins/debug/ProfilingPlugin").ProfilingPluginOptions} ProfilingPluginOptions */ + +let inspector = undefined; + +try { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + inspector = __webpack_require__(57012); +} catch (e) { + console.log("Unable to CPU profile in < node 8.0"); +} + +class Profiler { + constructor(inspector) { + this.session = undefined; + this.inspector = inspector; } - /** - * @param {string} str string path to be normalized - * @returns {string} normalized bundle-safe path - */ - static toPath(str) { - if (typeof str !== "string") return ""; - return str - .replace(PATH_NAME_NORMALIZE_REPLACE_REGEX, "-") - .replace(MATCH_PADDED_HYPHENS_REPLACE_REGEX, ""); + hasSession() { + return this.session !== undefined; } - // map number to a single character a-z, A-Z or <_ + number> if number is too big - /** - * - * @param {number} n number to convert to ident - * @returns {string} returns single character ident - */ - static numberToIdentifer(n) { - // lower case - if (n < DELTA_A_TO_Z) { - return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); + startProfiling() { + if (this.inspector === undefined) { + return Promise.resolve(); } - // upper case - if (n < DELTA_A_TO_Z * 2) { - return String.fromCharCode( - START_UPPERCASE_ALPHABET_CODE + n - DELTA_A_TO_Z - ); + try { + this.session = new inspector.Session(); + this.session.connect(); + } catch (_) { + this.session = undefined; + return Promise.resolve(); } - // use multiple letters - return ( - Template.numberToIdentifer(n % (2 * DELTA_A_TO_Z)) + - Template.numberToIdentifer(Math.floor(n / (2 * DELTA_A_TO_Z))) - ); + return Promise.all([ + this.sendCommand("Profiler.setSamplingInterval", { + interval: 100 + }), + this.sendCommand("Profiler.enable"), + this.sendCommand("Profiler.start") + ]); } - /** - * - * @param {string | string[]} s string to convert to identity - * @returns {string} converted identity - */ - static indent(s) { - if (Array.isArray(s)) { - return s.map(Template.indent).join("\n"); + sendCommand(method, params) { + if (this.hasSession()) { + return new Promise((res, rej) => { + return this.session.post(method, params, (err, params) => { + if (err !== null) { + rej(err); + } else { + res(params); + } + }); + }); } else { - const str = s.trimRight(); - if (!str) return ""; - const ind = str[0] === "\n" ? "" : "\t"; - return ind + str.replace(/\n([^\n])/g, "\n\t$1"); + return Promise.resolve(); } } - /** - * - * @param {string|string[]} s string to create prefix for - * @param {string} prefix prefix to compose - * @returns {string} returns new prefix string - */ - static prefix(s, prefix) { - const str = Template.asString(s).trim(); - if (!str) return ""; - const ind = str[0] === "\n" ? "" : prefix; - return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); + destroy() { + if (this.hasSession()) { + this.session.disconnect(); + } + + return Promise.resolve(); } - /** - * - * @param {string|string[]} str string or string collection - * @returns {string} returns a single string from array - */ - static asString(str) { - if (Array.isArray(str)) { - return str.join("\n"); - } - return str; + stopProfiling() { + return this.sendCommand("Profiler.stop"); } +} - /** - * @typedef {Object} WithId - * @property {string|number} id - */ +/** + * an object that wraps Tracer and Profiler with a counter + * @typedef {Object} Trace + * @property {Tracer} trace instance of Tracer + * @property {number} counter Counter + * @property {Profiler} profiler instance of Profiler + * @property {Function} end the end function + */ - /** - * @param {WithId[]} modules a collection of modules to get array bounds for - * @returns {[number, number] | false} returns the upper and lower array bounds - * or false if not every module has a number based id - */ - static getModulesArrayBounds(modules) { - let maxId = -Infinity; - let minId = Infinity; - for (const module of modules) { - if (typeof module.id !== "number") return false; - if (maxId < module.id) maxId = /** @type {number} */ (module.id); - if (minId > module.id) minId = /** @type {number} */ (module.id); - } - if (minId < 16 + ("" + minId).length) { - // add minId x ',' instead of 'Array(minId).concat(…)' - minId = 0; - } - const objectOverhead = modules - .map(module => (module.id + "").length + 2) - .reduce((a, b) => a + b, -1); - const arrayOverhead = - minId === 0 ? maxId : 16 + ("" + minId).length + maxId; - return arrayOverhead < objectOverhead ? [minId, maxId] : false; +/** + * @param {string} outputPath The location where to write the log. + * @returns {Trace} The trace object + */ +const createTrace = outputPath => { + const trace = new Tracer({ + noStream: true + }); + const profiler = new Profiler(inspector); + if (/\/|\\/.test(outputPath)) { + const dirPath = path.dirname(outputPath); + mkdirp.sync(dirPath); } + const fsStream = fs.createWriteStream(outputPath); - /** - * @param {Chunk} chunk chunk whose modules will be rendered - * @param {ModuleFilterPredicate} filterFn function used to filter modules from chunk to render - * @param {ModuleTemplate} moduleTemplate ModuleTemplate instance used to render modules - * @param {TODO | TODO[]} dependencyTemplates templates needed for each module to render dependencies - * @param {string=} prefix applying prefix strings - * @returns {ConcatSource} rendered chunk modules in a Source object - */ - static renderChunkModules( - chunk, - filterFn, - moduleTemplate, - dependencyTemplates, - prefix = "" - ) { - const source = new ConcatSource(); - const modules = chunk.getModules().filter(filterFn); - let removedModules; - if (chunk instanceof HotUpdateChunk) { - removedModules = chunk.removedModules; - } - if ( - modules.length === 0 && - (!removedModules || removedModules.length === 0) - ) { - source.add("[]"); - return source; - } - /** @type {{id: string|number, source: Source|string}[]} */ - const allModules = modules.map(module => { - return { - id: module.id, - source: moduleTemplate.render(module, dependencyTemplates, { - chunk - }) - }; - }); - if (removedModules && removedModules.length > 0) { - for (const id of removedModules) { - allModules.push({ - id, - source: "false" - }); + let counter = 0; + + trace.pipe(fsStream); + // These are critical events that need to be inserted so that tools like + // chrome dev tools can load the profile. + trace.instantEvent({ + name: "TracingStartedInPage", + id: ++counter, + cat: ["disabled-by-default-devtools.timeline"], + args: { + data: { + sessionId: "-1", + page: "0xfff", + frames: [ + { + frame: "0xfff", + url: "webpack", + name: "" + } + ] } } - const bounds = Template.getModulesArrayBounds(allModules); - if (bounds) { - // Render a spare array - const minId = bounds[0]; - const maxId = bounds[1]; - if (minId !== 0) { - source.add(`Array(${minId}).concat(`); - } - source.add("[\n"); - /** @type {Map} */ - const modules = new Map(); - for (const module of allModules) { - modules.set(module.id, module); - } - for (let idx = minId; idx <= maxId; idx++) { - const module = modules.get(idx); - if (idx !== minId) { - source.add(",\n"); - } - source.add(`/* ${idx} */`); - if (module) { - source.add("\n"); - source.add(module.source); - } - } - source.add("\n" + prefix + "]"); - if (minId !== 0) { - source.add(")"); + }); + + trace.instantEvent({ + name: "TracingStartedInBrowser", + id: ++counter, + cat: ["disabled-by-default-devtools.timeline"], + args: { + data: { + sessionId: "-1" } - } else { - // Render an object - source.add("{\n"); - allModules.sort(stringifyIdSortPredicate).forEach((module, idx) => { - if (idx !== 0) { - source.add(",\n"); - } - source.add(`\n/***/ ${JSON.stringify(module.id)}:\n`); - source.add(module.source); - }); - source.add(`\n\n${prefix}}`); } - return source; - } -} - -module.exports = Template; - - -/***/ }), + }); -/***/ 76032: -/***/ (function(module) { + return { + trace, + counter, + profiler, + end: callback => { + // Wait until the write stream finishes. + fsStream.on("finish", () => { + callback(); + }); + // Tear down the readable trace stream. + trace.push(null); + } + }; +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Jason Anderson @diurnalist -*/ +const pluginName = "ProfilingPlugin"; +class ProfilingPlugin { + /** + * @param {ProfilingPluginOptions=} opts options object + */ + constructor(opts) { + validateOptions(schema, opts || {}, "Profiling plugin"); + opts = opts || {}; + this.outputPath = opts.outputPath || "events.json"; + } -const REGEXP_HASH = /\[hash(?::(\d+))?\]/gi, - REGEXP_CHUNKHASH = /\[chunkhash(?::(\d+))?\]/gi, - REGEXP_MODULEHASH = /\[modulehash(?::(\d+))?\]/gi, - REGEXP_CONTENTHASH = /\[contenthash(?::(\d+))?\]/gi, - REGEXP_NAME = /\[name\]/gi, - REGEXP_ID = /\[id\]/gi, - REGEXP_MODULEID = /\[moduleid\]/gi, - REGEXP_FILE = /\[file\]/gi, - REGEXP_QUERY = /\[query\]/gi, - REGEXP_FILEBASE = /\[filebase\]/gi, - REGEXP_URL = /\[url\]/gi; + apply(compiler) { + const tracer = createTrace(this.outputPath); + tracer.profiler.startProfiling(); -// Using global RegExp for .test is dangerous -// We use a normal RegExp instead of .test -const REGEXP_HASH_FOR_TEST = new RegExp(REGEXP_HASH.source, "i"), - REGEXP_CHUNKHASH_FOR_TEST = new RegExp(REGEXP_CHUNKHASH.source, "i"), - REGEXP_CONTENTHASH_FOR_TEST = new RegExp(REGEXP_CONTENTHASH.source, "i"), - REGEXP_NAME_FOR_TEST = new RegExp(REGEXP_NAME.source, "i"); + // Compiler Hooks + Object.keys(compiler.hooks).forEach(hookName => { + compiler.hooks[hookName].intercept( + makeInterceptorFor("Compiler", tracer)(hookName) + ); + }); -const withHashLength = (replacer, handlerFn, assetInfo) => { - const fn = (match, hashLength, ...args) => { - if (assetInfo) assetInfo.immutable = true; - const length = hashLength && parseInt(hashLength, 10); - if (length && handlerFn) { - return handlerFn(length); - } - const hash = replacer(match, hashLength, ...args); - return length ? hash.slice(0, length) : hash; - }; - return fn; -}; + Object.keys(compiler.resolverFactory.hooks).forEach(hookName => { + compiler.resolverFactory.hooks[hookName].intercept( + makeInterceptorFor("Resolver", tracer)(hookName) + ); + }); -const getReplacer = (value, allowEmpty) => { - const fn = (match, ...args) => { - // last argument in replacer is the entire input string - const input = args[args.length - 1]; - if (value === null || value === undefined) { - if (!allowEmpty) { - throw new Error( - `Path variable ${match} not implemented in this context: ${input}` + compiler.hooks.compilation.tap( + pluginName, + (compilation, { normalModuleFactory, contextModuleFactory }) => { + interceptAllHooksFor(compilation, tracer, "Compilation"); + interceptAllHooksFor( + normalModuleFactory, + tracer, + "Normal Module Factory" + ); + interceptAllHooksFor( + contextModuleFactory, + tracer, + "Context Module Factory" ); + interceptAllParserHooks(normalModuleFactory, tracer); + interceptTemplateInstancesFrom(compilation, tracer); } - return ""; - } else { - return `${escapePathVariables(value)}`; - } - }; - return fn; -}; + ); -const escapePathVariables = value => { - return typeof value === "string" - ? value.replace(/\[(\\*[\w:]+\\*)\]/gi, "[\\$1\\]") - : value; -}; + // We need to write out the CPU profile when we are all done. + compiler.hooks.done.tapAsync( + { + name: pluginName, + stage: Infinity + }, + (stats, callback) => { + tracer.profiler.stopProfiling().then(parsedResults => { + if (parsedResults === undefined) { + tracer.profiler.destroy(); + tracer.trace.flush(); + tracer.end(callback); + return; + } -const replacePathVariables = (path, data, assetInfo) => { - const chunk = data.chunk; - const chunkId = chunk && chunk.id; - const chunkName = chunk && (chunk.name || chunk.id); - const chunkHash = chunk && (chunk.renderedHash || chunk.hash); - const chunkHashWithLength = chunk && chunk.hashWithLength; - const contentHashType = data.contentHashType; - const contentHash = - (chunk && chunk.contentHash && chunk.contentHash[contentHashType]) || - data.contentHash; - const contentHashWithLength = - (chunk && - chunk.contentHashWithLength && - chunk.contentHashWithLength[contentHashType]) || - data.contentHashWithLength; - const module = data.module; - const moduleId = module && module.id; - const moduleHash = module && (module.renderedHash || module.hash); - const moduleHashWithLength = module && module.hashWithLength; + const cpuStartTime = parsedResults.profile.startTime; + const cpuEndTime = parsedResults.profile.endTime; - if (typeof path === "function") { - path = path(data); - } + tracer.trace.completeEvent({ + name: "TaskQueueManager::ProcessTaskFromWorkQueue", + id: ++tracer.counter, + cat: ["toplevel"], + ts: cpuStartTime, + args: { + src_file: "../../ipc/ipc_moji_bootstrap.cc", + src_func: "Accept" + } + }); - if ( - data.noChunkHash && - (REGEXP_CHUNKHASH_FOR_TEST.test(path) || - REGEXP_CONTENTHASH_FOR_TEST.test(path)) - ) { - throw new Error( - `Cannot use [chunkhash] or [contenthash] for chunk in '${path}' (use [hash] instead)` + tracer.trace.completeEvent({ + name: "EvaluateScript", + id: ++tracer.counter, + cat: ["devtools.timeline"], + ts: cpuStartTime, + dur: cpuEndTime - cpuStartTime, + args: { + data: { + url: "webpack", + lineNumber: 1, + columnNumber: 1, + frame: "0xFFF" + } + } + }); + + tracer.trace.instantEvent({ + name: "CpuProfile", + id: ++tracer.counter, + cat: ["disabled-by-default-devtools.timeline"], + ts: cpuEndTime, + args: { + data: { + cpuProfile: parsedResults.profile + } + } + }); + + tracer.profiler.destroy(); + tracer.trace.flush(); + tracer.end(callback); + }); + } ); } +} - return ( - path - .replace( - REGEXP_HASH, - withHashLength(getReplacer(data.hash), data.hashWithLength, assetInfo) - ) - .replace( - REGEXP_CHUNKHASH, - withHashLength(getReplacer(chunkHash), chunkHashWithLength, assetInfo) - ) - .replace( - REGEXP_CONTENTHASH, - withHashLength( - getReplacer(contentHash), - contentHashWithLength, - assetInfo - ) - ) - .replace( - REGEXP_MODULEHASH, - withHashLength(getReplacer(moduleHash), moduleHashWithLength, assetInfo) - ) - .replace(REGEXP_ID, getReplacer(chunkId)) - .replace(REGEXP_MODULEID, getReplacer(moduleId)) - .replace(REGEXP_NAME, getReplacer(chunkName)) - .replace(REGEXP_FILE, getReplacer(data.filename)) - .replace(REGEXP_FILEBASE, getReplacer(data.basename)) - // query is optional, it's OK if it's in a path but there's nothing to replace it with - .replace(REGEXP_QUERY, getReplacer(data.query, true)) - // only available in sourceMappingURLComment - .replace(REGEXP_URL, getReplacer(data.url)) - .replace(/\[\\(\\*[\w:]+\\*)\\\]/gi, "[$1]") - ); -}; - -class TemplatedPathPlugin { - apply(compiler) { - compiler.hooks.compilation.tap("TemplatedPathPlugin", compilation => { - const mainTemplate = compilation.mainTemplate; +const interceptTemplateInstancesFrom = (compilation, tracer) => { + const { + mainTemplate, + chunkTemplate, + hotUpdateChunkTemplate, + moduleTemplates + } = compilation; - mainTemplate.hooks.assetPath.tap( - "TemplatedPathPlugin", - replacePathVariables - ); + const { javascript, webassembly } = moduleTemplates; - mainTemplate.hooks.globalHash.tap( - "TemplatedPathPlugin", - (chunk, paths) => { - const outputOptions = mainTemplate.outputOptions; - const publicPath = outputOptions.publicPath || ""; - const filename = outputOptions.filename || ""; - const chunkFilename = - outputOptions.chunkFilename || outputOptions.filename; - if ( - REGEXP_HASH_FOR_TEST.test(publicPath) || - REGEXP_CHUNKHASH_FOR_TEST.test(publicPath) || - REGEXP_CONTENTHASH_FOR_TEST.test(publicPath) || - REGEXP_NAME_FOR_TEST.test(publicPath) - ) - return true; - if (REGEXP_HASH_FOR_TEST.test(filename)) return true; - if (REGEXP_HASH_FOR_TEST.test(chunkFilename)) return true; - if (REGEXP_HASH_FOR_TEST.test(paths.join("|"))) return true; - } + [ + { + instance: mainTemplate, + name: "MainTemplate" + }, + { + instance: chunkTemplate, + name: "ChunkTemplate" + }, + { + instance: hotUpdateChunkTemplate, + name: "HotUpdateChunkTemplate" + }, + { + instance: javascript, + name: "JavaScriptModuleTemplate" + }, + { + instance: webassembly, + name: "WebAssemblyModuleTemplate" + } + ].forEach(templateObject => { + Object.keys(templateObject.instance.hooks).forEach(hookName => { + templateObject.instance.hooks[hookName].intercept( + makeInterceptorFor(templateObject.name, tracer)(hookName) ); + }); + }); +}; - mainTemplate.hooks.hashForChunk.tap( - "TemplatedPathPlugin", - (hash, chunk) => { - const outputOptions = mainTemplate.outputOptions; - const chunkFilename = - outputOptions.chunkFilename || outputOptions.filename; - if (REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename)) { - hash.update(JSON.stringify(chunk.getChunkMaps(true).hash)); - } - if (REGEXP_CONTENTHASH_FOR_TEST.test(chunkFilename)) { - hash.update( - JSON.stringify( - chunk.getChunkMaps(true).contentHash.javascript || {} - ) - ); - } - if (REGEXP_NAME_FOR_TEST.test(chunkFilename)) { - hash.update(JSON.stringify(chunk.getChunkMaps(true).name)); - } - } +const interceptAllHooksFor = (instance, tracer, logLabel) => { + if (Reflect.has(instance, "hooks")) { + Object.keys(instance.hooks).forEach(hookName => { + instance.hooks[hookName].intercept( + makeInterceptorFor(logLabel, tracer)(hookName) ); }); } -} - -module.exports = TemplatedPathPlugin; - - -/***/ }), - -/***/ 75374: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const interceptAllParserHooks = (moduleFactory, tracer) => { + const moduleTypes = [ + "javascript/auto", + "javascript/dynamic", + "javascript/esm", + "json", + "webassembly/experimental" + ]; + moduleTypes.forEach(moduleType => { + moduleFactory.hooks.parser + .for(moduleType) + .tap("ProfilingPlugin", (parser, parserOpts) => { + interceptAllHooksFor(parser, tracer, "Parser"); + }); + }); +}; -const { ConcatSource, OriginalSource } = __webpack_require__(53665); -const Template = __webpack_require__(96066); +const makeInterceptorFor = (instance, tracer) => hookName => ({ + register: ({ name, type, context, fn }) => { + const newFn = makeNewProfiledTapFn(hookName, tracer, { + name, + type, + fn + }); + return { + name, + type, + context, + fn: newFn + }; + } +}); -/** @typedef {import("../declarations/WebpackOptions").LibraryCustomUmdObject} LibraryCustomUmdObject */ -/** @typedef {import("./Compilation")} Compilation */ +// TODO improve typing +/** @typedef {(...args: TODO[]) => void | Promise} PluginFunction */ /** - * @param {string[]} accessor the accessor to convert to path - * @returns {string} the path + * @param {string} hookName Name of the hook to profile. + * @param {Trace} tracer The trace object. + * @param {object} options Options for the profiled fn. + * @param {string} options.name Plugin name + * @param {string} options.type Plugin type (sync | async | promise) + * @param {PluginFunction} options.fn Plugin function + * @returns {PluginFunction} Chainable hooked function. */ -const accessorToObjectAccess = accessor => { - return accessor.map(a => `[${JSON.stringify(a)}]`).join(""); -}; +const makeNewProfiledTapFn = (hookName, tracer, { name, type, fn }) => { + const defaultCategory = ["blink.user_timing"]; -/** - * @param {string=} base the path prefix - * @param {string|string[]} accessor the accessor - * @param {string=} joinWith the element separator - * @returns {string} the path - */ -const accessorAccess = (base, accessor, joinWith = ", ") => { - const accessors = Array.isArray(accessor) ? accessor : [accessor]; - return accessors - .map((_, idx) => { - const a = base - ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) - : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); - if (idx === accessors.length - 1) return a; - if (idx === 0 && base === undefined) - return `${a} = typeof ${a} === "object" ? ${a} : {}`; - return `${a} = ${a} || {}`; - }) - .join(joinWith); -}; - -/** @typedef {string | string[] | LibraryCustomUmdObject} UmdMainTemplatePluginName */ - -/** - * @typedef {Object} AuxiliaryCommentObject - * @property {string} root - * @property {string} commonjs - * @property {string} commonjs2 - * @property {string} amd - */ - -/** - * @typedef {Object} UmdMainTemplatePluginOption - * @property {boolean=} optionalAmdExternalAsGlobal - * @property {boolean} namedDefine - * @property {string | AuxiliaryCommentObject} auxiliaryComment - */ - -class UmdMainTemplatePlugin { - /** - * @param {UmdMainTemplatePluginName} name the name of the UMD library - * @param {UmdMainTemplatePluginOption} options the plugin option - */ - constructor(name, options) { - if (typeof name === "object" && !Array.isArray(name)) { - this.name = name.root || name.amd || name.commonjs; - this.names = name; - } else { - this.name = name; - this.names = { - commonjs: name, - root: name, - amd: name - }; - } - this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal; - this.namedDefine = options.namedDefine; - this.auxiliaryComment = options.auxiliaryComment; - } - - /** - * @param {Compilation} compilation the compilation instance - * @returns {void} - */ - apply(compilation) { - const { mainTemplate, chunkTemplate, runtimeTemplate } = compilation; - - const onRenderWithEntry = (source, chunk, hash) => { - let externals = chunk - .getModules() - .filter( - m => - m.external && - (m.externalType === "umd" || m.externalType === "umd2") - ); - const optionalExternals = []; - let requiredExternals = []; - if (this.optionalAmdExternalAsGlobal) { - for (const m of externals) { - if (m.optional) { - optionalExternals.push(m); - } else { - requiredExternals.push(m); - } - } - externals = requiredExternals.concat(optionalExternals); - } else { - requiredExternals = externals; - } - - const replaceKeys = str => { - return mainTemplate.getAssetPath(str, { - hash, - chunk + switch (type) { + case "promise": + return (...args) => { + const id = ++tracer.counter; + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + const promise = /** @type {Promise<*>} */ (fn(...args)); + return promise.then(r => { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + return r; }); }; - - const externalsDepsArray = modules => { - return `[${replaceKeys( - modules - .map(m => - JSON.stringify( - typeof m.request === "object" ? m.request.amd : m.request - ) - ) - .join(", ") - )}]`; - }; - - const externalsRootArray = modules => { - return replaceKeys( - modules - .map(m => { - let request = m.request; - if (typeof request === "object") request = request.root; - return `root${accessorToObjectAccess([].concat(request))}`; - }) - .join(", ") - ); - }; - - const externalsRequireArray = type => { - return replaceKeys( - externals - .map(m => { - let expr; - let request = m.request; - if (typeof request === "object") { - request = request[type]; - } - if (request === undefined) { - throw new Error( - "Missing external configuration for type:" + type - ); - } - if (Array.isArray(request)) { - expr = `require(${JSON.stringify( - request[0] - )})${accessorToObjectAccess(request.slice(1))}`; - } else { - expr = `require(${JSON.stringify(request)})`; - } - if (m.optional) { - expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; - } - return expr; - }) - .join(", ") - ); - }; - - const externalsArguments = modules => { - return modules - .map( - m => - `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__` - ) - .join(", "); - }; - - const libraryName = library => { - return JSON.stringify(replaceKeys([].concat(library).pop())); + case "async": + return (...args) => { + const id = ++tracer.counter; + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + const callback = args.pop(); + fn(...args, (...r) => { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + callback(...r); + }); }; + case "sync": + return (...args) => { + const id = ++tracer.counter; + // Do not instrument ourself due to the CPU + // profile needing to be the last event in the trace. + if (name === pluginName) { + return fn(...args); + } - let amdFactory; - if (optionalExternals.length > 0) { - const wrapperArguments = externalsArguments(requiredExternals); - const factoryArguments = - requiredExternals.length > 0 - ? externalsArguments(requiredExternals) + - ", " + - externalsRootArray(optionalExternals) - : externalsRootArray(optionalExternals); - amdFactory = - `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` + - ` return factory(${factoryArguments});\n` + - " }"; - } else { - amdFactory = "factory"; - } - - const auxiliaryComment = this.auxiliaryComment; - - const getAuxilaryComment = type => { - if (auxiliaryComment) { - if (typeof auxiliaryComment === "string") - return "\t//" + auxiliaryComment + "\n"; - if (auxiliaryComment[type]) - return "\t//" + auxiliaryComment[type] + "\n"; + tracer.trace.begin({ + name, + id, + cat: defaultCategory + }); + let r; + try { + r = fn(...args); + } catch (error) { + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + throw error; } - return ""; + tracer.trace.end({ + name, + id, + cat: defaultCategory + }); + return r; }; - - return new ConcatSource( - new OriginalSource( - "(function webpackUniversalModuleDefinition(root, factory) {\n" + - getAuxilaryComment("commonjs2") + - " if(typeof exports === 'object' && typeof module === 'object')\n" + - " module.exports = factory(" + - externalsRequireArray("commonjs2") + - ");\n" + - getAuxilaryComment("amd") + - " else if(typeof define === 'function' && define.amd)\n" + - (requiredExternals.length > 0 - ? this.names.amd && this.namedDefine === true - ? " define(" + - libraryName(this.names.amd) + - ", " + - externalsDepsArray(requiredExternals) + - ", " + - amdFactory + - ");\n" - : " define(" + - externalsDepsArray(requiredExternals) + - ", " + - amdFactory + - ");\n" - : this.names.amd && this.namedDefine === true - ? " define(" + - libraryName(this.names.amd) + - ", [], " + - amdFactory + - ");\n" - : " define([], " + amdFactory + ");\n") + - (this.names.root || this.names.commonjs - ? getAuxilaryComment("commonjs") + - " else if(typeof exports === 'object')\n" + - " exports[" + - libraryName(this.names.commonjs || this.names.root) + - "] = factory(" + - externalsRequireArray("commonjs") + - ");\n" + - getAuxilaryComment("root") + - " else\n" + - " " + - replaceKeys( - accessorAccess("root", this.names.root || this.names.commonjs) - ) + - " = factory(" + - externalsRootArray(externals) + - ");\n" - : " else {\n" + - (externals.length > 0 - ? " var a = typeof exports === 'object' ? factory(" + - externalsRequireArray("commonjs") + - ") : factory(" + - externalsRootArray(externals) + - ");\n" - : " var a = factory();\n") + - " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" + - " }\n") + - `})(${ - runtimeTemplate.outputOptions.globalObject - }, function(${externalsArguments(externals)}) {\nreturn `, - "webpack/universalModuleDefinition" - ), - source, - ";\n})" - ); - }; - - for (const template of [mainTemplate, chunkTemplate]) { - template.hooks.renderWithEntry.tap( - "UmdMainTemplatePlugin", - onRenderWithEntry - ); - } - - mainTemplate.hooks.globalHashPaths.tap("UmdMainTemplatePlugin", paths => { - if (this.names.root) paths = paths.concat(this.names.root); - if (this.names.amd) paths = paths.concat(this.names.amd); - if (this.names.commonjs) paths = paths.concat(this.names.commonjs); - return paths; - }); - - mainTemplate.hooks.hash.tap("UmdMainTemplatePlugin", hash => { - hash.update("umd"); - hash.update(`${this.names.root}`); - hash.update(`${this.names.amd}`); - hash.update(`${this.names.commonjs}`); - }); + default: + break; } -} +}; -module.exports = UmdMainTemplatePlugin; +module.exports = ProfilingPlugin; +module.exports.Profiler = Profiler; /***/ }), -/***/ 99953: +/***/ 67045: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -93932,36 +93309,143 @@ module.exports = UmdMainTemplatePlugin; Author Tobias Koppers @sokra */ +const NullDependency = __webpack_require__(5088); -const WebpackError = __webpack_require__(97391); +class AMDDefineDependency extends NullDependency { + constructor(range, arrayRange, functionRange, objectRange, namedModule) { + super(); + this.range = range; + this.arrayRange = arrayRange; + this.functionRange = functionRange; + this.objectRange = objectRange; + this.namedModule = namedModule; + this.localModule = null; + } -/** @typedef {import("./Module")} Module */ -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ + get type() { + return "amd define"; + } +} -class UnsupportedFeatureWarning extends WebpackError { - /** - * @param {Module} module module relevant to warning - * @param {string} message description of warning - * @param {DependencyLocation} loc location start and end positions of the module - */ - constructor(module, message, loc) { - super(message); +AMDDefineDependency.Template = class AMDDefineDependencyTemplate { + get definitions() { + return { + f: [ + "var __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + o: ["", "!(module.exports = #)"], + of: [ + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + af: [ + "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + ao: ["", "!(#, module.exports = #)"], + aof: [ + "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", + `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` + ], + lf: [ + "var XXX, XXXmodule;", + "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = #.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))" + ], + lo: ["var XXX;", "!(XXX = #)"], + lof: [ + "var XXX, XXXfactory, XXXmodule;", + "!(XXXfactory = (#), (XXXmodule = { id: YYY, exports: {}, loaded: false }), XXX = (typeof XXXfactory === 'function' ? (XXXfactory.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule)) : XXXfactory), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports))" + ], + laf: [ + "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX;", + "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = ((#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)))" + ], + lao: ["var XXX;", "!(#, XXX = #)"], + laof: [ + "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_FACTORY__, XXX;", + `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), + XXX = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__))` + ] + }; + } - this.name = "UnsupportedFeatureWarning"; - this.module = module; - this.loc = loc; - this.hideStack = true; + apply(dependency, source) { + const branch = this.branch(dependency); + const defAndText = this.definitions[branch]; + const definitions = defAndText[0]; + const text = defAndText[1]; + this.replace(dependency, source, definitions, text); + } - Error.captureStackTrace(this, this.constructor); + localModuleVar(dependency) { + return ( + dependency.localModule && + dependency.localModule.used && + dependency.localModule.variableName() + ); } -} -module.exports = UnsupportedFeatureWarning; + branch(dependency) { + const localModuleVar = this.localModuleVar(dependency) ? "l" : ""; + const arrayRange = dependency.arrayRange ? "a" : ""; + const objectRange = dependency.objectRange ? "o" : ""; + const functionRange = dependency.functionRange ? "f" : ""; + return localModuleVar + arrayRange + objectRange + functionRange; + } + + replace(dependency, source, definition, text) { + const localModuleVar = this.localModuleVar(dependency); + if (localModuleVar) { + text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); + definition = definition.replace( + /XXX/g, + localModuleVar.replace(/\$/g, "$$$$") + ); + } + + if (dependency.namedModule) { + text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule)); + } + + const texts = text.split("#"); + + if (definition) source.insert(0, definition); + + let current = dependency.range[0]; + if (dependency.arrayRange) { + source.replace(current, dependency.arrayRange[0] - 1, texts.shift()); + current = dependency.arrayRange[1]; + } + + if (dependency.objectRange) { + source.replace(current, dependency.objectRange[0] - 1, texts.shift()); + current = dependency.objectRange[1]; + } else if (dependency.functionRange) { + source.replace(current, dependency.functionRange[0] - 1, texts.shift()); + current = dependency.functionRange[1]; + } + source.replace(current, dependency.range[1] - 1, texts.shift()); + if (texts.length > 0) throw new Error("Implementation error"); + } +}; + +module.exports = AMDDefineDependency; /***/ }), -/***/ 73554: +/***/ 27057: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -93971,104 +93455,341 @@ module.exports = UnsupportedFeatureWarning; */ +const AMDRequireItemDependency = __webpack_require__(34345); +const AMDRequireContextDependency = __webpack_require__(99890); const ConstDependency = __webpack_require__(71101); +const AMDDefineDependency = __webpack_require__(67045); +const AMDRequireArrayDependency = __webpack_require__(63960); +const LocalModuleDependency = __webpack_require__(56570); +const ContextDependencyHelpers = __webpack_require__(5594); +const LocalModulesHelpers = __webpack_require__(39658); -/** @typedef {import("./Compiler")} Compiler */ +const isBoundFunctionExpression = expr => { + if (expr.type !== "CallExpression") return false; + if (expr.callee.type !== "MemberExpression") return false; + if (expr.callee.computed) return false; + if (expr.callee.object.type !== "FunctionExpression") return false; + if (expr.callee.property.type !== "Identifier") return false; + if (expr.callee.property.name !== "bind") return false; + return true; +}; -class UseStrictPlugin { - /** - * @param {Compiler} compiler Webpack Compiler - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "UseStrictPlugin", - (compilation, { normalModuleFactory }) => { - const handler = parser => { - parser.hooks.program.tap("UseStrictPlugin", ast => { - const firstNode = ast.body[0]; - if ( - firstNode && - firstNode.type === "ExpressionStatement" && - firstNode.expression.type === "Literal" && - firstNode.expression.value === "use strict" - ) { - // Remove "use strict" expression. It will be added later by the renderer again. - // This is necessary in order to not break the strict mode when webpack prepends code. - // @see https://github.com/webpack/webpack/issues/1970 - const dep = new ConstDependency("", firstNode.range); - dep.loc = firstNode.loc; - parser.state.current.addDependency(dep); - parser.state.module.buildInfo.strict = true; - } - }); - }; - - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("UseStrictPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("UseStrictPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("UseStrictPlugin", handler); - } - ); - } -} - -module.exports = UseStrictPlugin; - - -/***/ }), +const isUnboundFunctionExpression = expr => { + if (expr.type === "FunctionExpression") return true; + if (expr.type === "ArrowFunctionExpression") return true; + return false; +}; -/***/ 40269: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const isCallable = expr => { + if (isUnboundFunctionExpression(expr)) return true; + if (isBoundFunctionExpression(expr)) return true; + return false; +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +class AMDDefineDependencyParserPlugin { + constructor(options) { + this.options = options; + } + apply(parser) { + parser.hooks.call + .for("define") + .tap( + "AMDDefineDependencyParserPlugin", + this.processCallDefine.bind(this, parser) + ); + } -const CaseSensitiveModulesWarning = __webpack_require__(8335); + processArray(parser, expr, param, identifiers, namedModule) { + if (param.isArray()) { + param.items.forEach((param, idx) => { + if ( + param.isString() && + ["require", "module", "exports"].includes(param.string) + ) + identifiers[idx] = param.string; + const result = this.processItem(parser, expr, param, namedModule); + if (result === undefined) { + this.processContext(parser, expr, param); + } + }); + return true; + } else if (param.isConstArray()) { + const deps = []; + param.array.forEach((request, idx) => { + let dep; + let localModule; + if (request === "require") { + identifiers[idx] = request; + dep = "__webpack_require__"; + } else if (["exports", "module"].includes(request)) { + identifiers[idx] = request; + dep = request; + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + request + )) + ) { + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + } + deps.push(dep); + }); + const dep = this.newRequireArrayDependency(deps, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + processItem(parser, expr, param, namedModule) { + if (param.isConditional()) { + param.options.forEach(param => { + const result = this.processItem(parser, expr, param); + if (result === undefined) { + this.processContext(parser, expr, param); + } + }); + return true; + } else if (param.isString()) { + let dep, localModule; + if (param.string === "require") { + dep = new ConstDependency("__webpack_require__", param.range); + } else if (["require", "exports", "module"].includes(param.string)) { + dep = new ConstDependency(param.string, param.range); + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + param.string, + namedModule + )) + ) { + dep = new LocalModuleDependency(localModule, param.range, false); + } else { + dep = this.newRequireItemDependency(param.string, param.range); + } + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + param.range, + param, + expr, + this.options, + {}, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } -class WarnCaseSensitiveModulesPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "WarnCaseSensitiveModulesPlugin", - compilation => { - compilation.hooks.seal.tap("WarnCaseSensitiveModulesPlugin", () => { - const moduleWithoutCase = new Map(); - for (const module of compilation.modules) { - const identifier = module.identifier().toLowerCase(); - const array = moduleWithoutCase.get(identifier); - if (array) { - array.push(module); - } else { - moduleWithoutCase.set(identifier, [module]); - } + processCallDefine(parser, expr) { + let array, fn, obj, namedModule; + switch (expr.arguments.length) { + case 1: + if (isCallable(expr.arguments[0])) { + // define(f() {…}) + fn = expr.arguments[0]; + } else if (expr.arguments[0].type === "ObjectExpression") { + // define({…}) + obj = expr.arguments[0]; + } else { + // define(expr) + // unclear if function or object + obj = fn = expr.arguments[0]; + } + break; + case 2: + if (expr.arguments[0].type === "Literal") { + namedModule = expr.arguments[0].value; + // define("…", …) + if (isCallable(expr.arguments[1])) { + // define("…", f() {…}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define("…", {…}) + obj = expr.arguments[1]; + } else { + // define("…", expr) + // unclear if function or object + obj = fn = expr.arguments[1]; } - for (const pair of moduleWithoutCase) { - const array = pair[1]; - if (array.length > 1) { - compilation.warnings.push(new CaseSensitiveModulesWarning(array)); - } + } else { + array = expr.arguments[0]; + if (isCallable(expr.arguments[1])) { + // define([…], f() {}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define([…], {…}) + obj = expr.arguments[1]; + } else { + // define([…], expr) + // unclear if function or object + obj = fn = expr.arguments[1]; + } + } + break; + case 3: + // define("…", […], f() {…}) + namedModule = expr.arguments[0].value; + array = expr.arguments[1]; + if (isCallable(expr.arguments[2])) { + // define("…", […], f() {}) + fn = expr.arguments[2]; + } else if (expr.arguments[2].type === "ObjectExpression") { + // define("…", […], {…}) + obj = expr.arguments[2]; + } else { + // define("…", […], expr) + // unclear if function or object + obj = fn = expr.arguments[2]; + } + break; + default: + return; + } + let fnParams = null; + let fnParamsOffset = 0; + if (fn) { + if (isUnboundFunctionExpression(fn)) { + fnParams = fn.params; + } else if (isBoundFunctionExpression(fn)) { + fnParams = fn.callee.object.params; + fnParamsOffset = fn.arguments.length - 1; + if (fnParamsOffset < 0) { + fnParamsOffset = 0; + } + } + } + let fnRenames = parser.scope.renames.createChild(); + if (array) { + const identifiers = {}; + const param = parser.evaluateExpression(array); + const result = this.processArray( + parser, + expr, + param, + identifiers, + namedModule + ); + if (!result) return; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, identifiers[idx]); + return false; + } + return true; + }); + } + } else { + const identifiers = ["require", "exports", "module"]; + if (fnParams) { + fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { + if (identifiers[idx]) { + fnRenames.set(param.name, identifiers[idx]); + return false; } + return true; }); } + } + let inTry; + if (fn && isUnboundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + parser.inScope(fnParams, () => { + parser.scope.renames = fnRenames; + parser.scope.inTry = inTry; + if (fn.body.type === "BlockStatement") { + parser.walkStatement(fn.body); + } else { + parser.walkExpression(fn.body); + } + }); + } else if (fn && isBoundFunctionExpression(fn)) { + inTry = parser.scope.inTry; + parser.inScope( + fn.callee.object.params.filter( + i => !["require", "module", "exports"].includes(i.name) + ), + () => { + parser.scope.renames = fnRenames; + parser.scope.inTry = inTry; + if (fn.callee.object.body.type === "BlockStatement") { + parser.walkStatement(fn.callee.object.body); + } else { + parser.walkExpression(fn.callee.object.body); + } + } + ); + if (fn.arguments) { + parser.walkExpressions(fn.arguments); + } + } else if (fn || obj) { + parser.walkExpression(fn || obj); + } + + const dep = this.newDefineDependency( + expr.range, + array ? array.range : null, + fn ? fn.range : null, + obj ? obj.range : null, + namedModule ? namedModule : null ); + dep.loc = expr.loc; + if (namedModule) { + dep.localModule = LocalModulesHelpers.addLocalModule( + parser.state, + namedModule + ); + } + parser.state.current.addDependency(dep); + return true; } -} -module.exports = WarnCaseSensitiveModulesPlugin; + newDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ) { + return new AMDDefineDependency( + range, + arrayRange, + functionRange, + objectRange, + namedModule + ); + } + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } +} +module.exports = AMDDefineDependencyParserPlugin; /***/ }), -/***/ 71245: +/***/ 85812: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -94078,136 +93799,236 @@ module.exports = WarnCaseSensitiveModulesPlugin; */ -const NoModeWarning = __webpack_require__(45759); - -class WarnNoModeSetPlugin { - apply(compiler) { - compiler.hooks.thisCompilation.tap("WarnNoModeSetPlugin", compilation => { - compilation.warnings.push(new NoModeWarning()); - }); - } -} - -module.exports = WarnNoModeSetPlugin; - - -/***/ }), - -/***/ 88015: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +const path = __webpack_require__(85622); +const AMDRequireDependency = __webpack_require__(73985); +const AMDRequireItemDependency = __webpack_require__(34345); +const AMDRequireArrayDependency = __webpack_require__(63960); +const AMDRequireContextDependency = __webpack_require__(99890); +const AMDDefineDependency = __webpack_require__(67045); +const UnsupportedDependency = __webpack_require__(15826); +const LocalModuleDependency = __webpack_require__(56570); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const NullFactory = __webpack_require__(40438); +const AMDRequireDependenciesBlockParserPlugin = __webpack_require__(9994); +const AMDDefineDependencyParserPlugin = __webpack_require__(27057); -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(97009); +const AliasPlugin = __webpack_require__(15005); -/** @typedef {import("../declarations/plugins/WatchIgnorePlugin").WatchIgnorePluginOptions} WatchIgnorePluginOptions */ +const ParserHelpers = __webpack_require__(23999); -class IgnoringWatchFileSystem { - constructor(wfs, paths) { - this.wfs = wfs; - this.paths = paths; +class AMDPlugin { + constructor(options, amdOptions) { + this.amdOptions = amdOptions; + this.options = options; } - watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { - const ignored = path => - this.paths.some(p => - p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0 - ); + apply(compiler) { + const options = this.options; + const amdOptions = this.amdOptions; + compiler.hooks.compilation.tap( + "AMDPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + AMDRequireDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + AMDRequireDependency, + new AMDRequireDependency.Template() + ); - const notIgnored = path => !ignored(path); + compilation.dependencyFactories.set( + AMDRequireItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireItemDependency, + new AMDRequireItemDependency.Template() + ); - const ignoredFiles = files.filter(ignored); - const ignoredDirs = dirs.filter(ignored); + compilation.dependencyFactories.set( + AMDRequireArrayDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + AMDRequireArrayDependency, + new AMDRequireArrayDependency.Template() + ); - const watcher = this.wfs.watch( - files.filter(notIgnored), - dirs.filter(notIgnored), - missing, - startTime, - options, - ( - err, - filesModified, - dirsModified, - missingModified, - fileTimestamps, - dirTimestamps, - removedFiles - ) => { - if (err) return callback(err); - for (const path of ignoredFiles) { - fileTimestamps.set(path, 1); - } + compilation.dependencyFactories.set( + AMDRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + AMDRequireContextDependency, + new AMDRequireContextDependency.Template() + ); - for (const path of ignoredDirs) { - dirTimestamps.set(path, 1); - } + compilation.dependencyFactories.set( + AMDDefineDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + AMDDefineDependency, + new AMDDefineDependency.Template() + ); - callback( - err, - filesModified, - dirsModified, - missingModified, - fileTimestamps, - dirTimestamps, - removedFiles + compilation.dependencyFactories.set( + UnsupportedDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + UnsupportedDependency, + new UnsupportedDependency.Template() ); - }, - callbackUndelayed - ); - return { - close: () => watcher.close(), - pause: () => watcher.pause(), - getContextTimestamps: () => { - const dirTimestamps = watcher.getContextTimestamps(); - for (const path of ignoredDirs) { - dirTimestamps.set(path, 1); - } - return dirTimestamps; - }, - getFileTimestamps: () => { - const fileTimestamps = watcher.getFileTimestamps(); - for (const path of ignoredFiles) { - fileTimestamps.set(path, 1); - } - return fileTimestamps; - } - }; - } -} + compilation.dependencyFactories.set( + LocalModuleDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + LocalModuleDependency, + new LocalModuleDependency.Template() + ); -class WatchIgnorePlugin { - /** - * @param {WatchIgnorePluginOptions} paths list of paths - */ - constructor(paths) { - validateOptions(schema, paths, "Watch Ignore Plugin"); - this.paths = paths; - } + const handler = (parser, parserOptions) => { + if (parserOptions.amd !== undefined && !parserOptions.amd) return; - apply(compiler) { - compiler.hooks.afterEnvironment.tap("WatchIgnorePlugin", () => { - compiler.watchFileSystem = new IgnoringWatchFileSystem( - compiler.watchFileSystem, - this.paths - ); + const setExpressionToModule = (outerExpr, module) => { + parser.hooks.expression.for(outerExpr).tap("AMDPlugin", expr => { + const dep = new AMDRequireItemDependency(module, expr.range); + dep.userRequest = outerExpr; + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }); + }; + + new AMDRequireDependenciesBlockParserPlugin(options).apply(parser); + new AMDDefineDependencyParserPlugin(options).apply(parser); + + setExpressionToModule("require.amd", "!!webpack amd options"); + setExpressionToModule("define.amd", "!!webpack amd options"); + setExpressionToModule("define", "!!webpack amd define"); + + parser.hooks.expression + .for("__webpack_amd_options__") + .tap("AMDPlugin", () => + parser.state.current.addVariable( + "__webpack_amd_options__", + JSON.stringify(amdOptions) + ) + ); + parser.hooks.evaluateTypeof + .for("define.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToString(typeof amdOptions) + ); + parser.hooks.evaluateTypeof + .for("require.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToString(typeof amdOptions) + ); + parser.hooks.evaluateIdentifier + .for("define.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToIdentifier("define.amd", true) + ); + parser.hooks.evaluateIdentifier + .for("require.amd") + .tap( + "AMDPlugin", + ParserHelpers.evaluateToIdentifier("require.amd", true) + ); + parser.hooks.typeof + .for("define") + .tap( + "AMDPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + parser.hooks.evaluateTypeof + .for("define") + .tap("AMDPlugin", ParserHelpers.evaluateToString("function")); + parser.hooks.canRename + .for("define") + .tap("AMDPlugin", ParserHelpers.approve); + parser.hooks.rename.for("define").tap("AMDPlugin", expr => { + const dep = new AMDRequireItemDependency( + "!!webpack amd define", + expr.range + ); + dep.userRequest = "define"; + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return false; + }); + parser.hooks.typeof + .for("require") + .tap( + "AMDPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + parser.hooks.evaluateTypeof + .for("require") + .tap("AMDPlugin", ParserHelpers.evaluateToString("function")); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("AMDPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("AMDPlugin", handler); + } + ); + compiler.hooks.afterResolvers.tap("AMDPlugin", () => { + compiler.resolverFactory.hooks.resolver + .for("normal") + .tap("AMDPlugin", resolver => { + new AliasPlugin( + "described-resolve", + { + name: "amdefine", + alias: __webpack_require__.ab + "amd-define.js" + }, + "resolve" + ).apply(resolver); + new AliasPlugin( + "described-resolve", + { + name: "webpack amd options", + alias: __webpack_require__.ab + "amd-options.js" + }, + "resolve" + ).apply(resolver); + new AliasPlugin( + "described-resolve", + { + name: "webpack amd define", + alias: __webpack_require__.ab + "amd-define.js" + }, + "resolve" + ).apply(resolver); + }); }); } } - -module.exports = WatchIgnorePlugin; +module.exports = AMDPlugin; /***/ }), -/***/ 29580: +/***/ 63960: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -94216,256 +94037,83 @@ module.exports = WatchIgnorePlugin; Author Tobias Koppers @sokra */ +const Dependency = __webpack_require__(57282); -const Stats = __webpack_require__(99977); - -class Watching { - constructor(compiler, watchOptions, handler) { - this.startTime = null; - this.invalid = false; - this.handler = handler; - this.callbacks = []; - this.closed = false; - this.suspended = false; - if (typeof watchOptions === "number") { - this.watchOptions = { - aggregateTimeout: watchOptions - }; - } else if (watchOptions && typeof watchOptions === "object") { - this.watchOptions = Object.assign({}, watchOptions); - } else { - this.watchOptions = {}; - } - this.watchOptions.aggregateTimeout = - this.watchOptions.aggregateTimeout || 200; - this.compiler = compiler; - this.running = true; - this.compiler.readRecords(err => { - if (err) return this._done(err); - - this._go(); - }); +class AMDRequireArrayDependency extends Dependency { + constructor(depsArray, range) { + super(); + this.depsArray = depsArray; + this.range = range; } - _go() { - this.startTime = Date.now(); - this.running = true; - this.invalid = false; - this.compiler.hooks.watchRun.callAsync(this.compiler, err => { - if (err) return this._done(err); - const onCompiled = (err, compilation) => { - if (err) return this._done(err); - if (this.invalid) return this._done(); - - if (this.compiler.hooks.shouldEmit.call(compilation) === false) { - return this._done(null, compilation); - } - - this.compiler.emitAssets(compilation, err => { - if (err) return this._done(err); - if (this.invalid) return this._done(); - this.compiler.emitRecords(err => { - if (err) return this._done(err); - - if (compilation.hooks.needAdditionalPass.call()) { - compilation.needAdditionalPass = true; - - const stats = new Stats(compilation); - stats.startTime = this.startTime; - stats.endTime = Date.now(); - this.compiler.hooks.done.callAsync(stats, err => { - if (err) return this._done(err); - - this.compiler.hooks.additionalPass.callAsync(err => { - if (err) return this._done(err); - this.compiler.compile(onCompiled); - }); - }); - return; - } - return this._done(null, compilation); - }); - }); - }; - this.compiler.compile(onCompiled); - }); + get type() { + return "amd require array"; } +} - _getStats(compilation) { - const stats = new Stats(compilation); - stats.startTime = this.startTime; - stats.endTime = Date.now(); - return stats; +AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate { + apply(dep, source, runtime) { + const content = this.getContent(dep, runtime); + source.replace(dep.range[0], dep.range[1] - 1, content); } - _done(err, compilation) { - this.running = false; - if (this.invalid) return this._go(); - - const stats = compilation ? this._getStats(compilation) : null; - if (err) { - this.compiler.hooks.failed.call(err); - this.handler(err, stats); - return; - } - this.compiler.hooks.done.callAsync(stats, () => { - this.handler(null, stats); - if (!this.closed) { - this.watch( - Array.from(compilation.fileDependencies), - Array.from(compilation.contextDependencies), - Array.from(compilation.missingDependencies) - ); - } - for (const cb of this.callbacks) cb(); - this.callbacks.length = 0; + getContent(dep, runtime) { + const requires = dep.depsArray.map(dependency => { + return this.contentForDependency(dependency, runtime); }); + return `[${requires.join(", ")}]`; } - watch(files, dirs, missing) { - this.pausedWatcher = null; - this.watcher = this.compiler.watchFileSystem.watch( - files, - dirs, - missing, - this.startTime, - this.watchOptions, - ( - err, - filesModified, - contextModified, - missingModified, - fileTimestamps, - contextTimestamps, - removedFiles - ) => { - this.pausedWatcher = this.watcher; - this.watcher = null; - if (err) { - return this.handler(err); - } - this.compiler.fileTimestamps = fileTimestamps; - this.compiler.contextTimestamps = contextTimestamps; - this.compiler.removedFiles = removedFiles; - if (!this.suspended) { - this._invalidate(); - } - }, - (fileName, changeTime) => { - this.compiler.hooks.invalid.call(fileName, changeTime); - } - ); - } - - invalidate(callback) { - if (callback) { - this.callbacks.push(callback); - } - if (this.watcher) { - this.compiler.fileTimestamps = this.watcher.getFileTimestamps(); - this.compiler.contextTimestamps = this.watcher.getContextTimestamps(); - } - return this._invalidate(); - } - - _invalidate() { - if (this.watcher) { - this.pausedWatcher = this.watcher; - this.watcher.pause(); - this.watcher = null; - } - - if (this.running) { - this.invalid = true; - return false; - } else { - this._go(); - } - } - - suspend() { - this.suspended = true; - this.invalid = false; - } - - resume() { - if (this.suspended) { - this.suspended = false; - this._invalidate(); + contentForDependency(dep, runtime) { + if (typeof dep === "string") { + return dep; } - } - - close(callback) { - const finalCallback = () => { - this.compiler.hooks.watchClose.call(); - this.compiler.running = false; - this.compiler.watchMode = false; - if (callback !== undefined) callback(); - }; - this.closed = true; - if (this.watcher) { - this.watcher.close(); - this.watcher = null; - } - if (this.pausedWatcher) { - this.pausedWatcher.close(); - this.pausedWatcher = null; - } - if (this.running) { - this.invalid = true; - this._done = finalCallback; + if (dep.localModule) { + return dep.localModule.variableName(); } else { - finalCallback(); + return runtime.moduleExports({ + module: dep.module, + request: dep.request + }); } } -} +}; -module.exports = Watching; +module.exports = AMDRequireArrayDependency; /***/ }), -/***/ 97391: +/***/ 99890: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Jarid Margolin @jaridmargolin + Author Tobias Koppers @sokra */ -const inspect = __webpack_require__(31669).inspect.custom; - -class WebpackError extends Error { - /** - * Creates an instance of WebpackError. - * @param {string=} message error message - */ - constructor(message) { - super(message); - - this.details = undefined; - this.missing = undefined; - this.origin = undefined; - this.dependencies = undefined; - this.module = undefined; - - Error.captureStackTrace(this, this.constructor); +const ContextDependency = __webpack_require__(11583); +class AMDRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; } - [inspect]() { - return this.stack + (this.details ? `\n${this.details}` : ""); + get type() { + return "amd require context"; } } - -module.exports = WebpackError; +AMDRequireContextDependency.Template = __webpack_require__(54380); +module.exports = AMDRequireContextDependency; /***/ }), -/***/ 2779: +/***/ 32894: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -94474,552 +94122,508 @@ module.exports = WebpackError; Author Tobias Koppers @sokra */ +const AsyncDependenciesBlock = __webpack_require__(22814); +const AMDRequireDependency = __webpack_require__(73985); -const OptionsApply = __webpack_require__(4428); - -const JavascriptModulesPlugin = __webpack_require__(10339); -const JsonModulesPlugin = __webpack_require__(2859); -const WebAssemblyModulesPlugin = __webpack_require__(99510); - -const LoaderTargetPlugin = __webpack_require__(95154); -const FunctionModulePlugin = __webpack_require__(31221); -const EvalDevToolModulePlugin = __webpack_require__(65200); -const SourceMapDevToolPlugin = __webpack_require__(11851); -const EvalSourceMapDevToolPlugin = __webpack_require__(99994); - -const EntryOptionPlugin = __webpack_require__(14604); -const RecordIdsPlugin = __webpack_require__(40355); +module.exports = class AMDRequireDependenciesBlock extends AsyncDependenciesBlock { + constructor( + expr, + arrayRange, + functionRange, + errorCallbackRange, + module, + loc, + request + ) { + super(null, module, loc, request); + this.expr = expr; + this.outerRange = expr.range; + this.arrayRange = arrayRange; + this.functionBindThis = false; + this.functionRange = functionRange; + this.errorCallbackBindThis = false; + this.errorCallbackRange = errorCallbackRange; + this.bindThis = true; + if (arrayRange && functionRange && errorCallbackRange) { + this.range = [arrayRange[0], errorCallbackRange[1]]; + } else if (arrayRange && functionRange) { + this.range = [arrayRange[0], functionRange[1]]; + } else if (arrayRange) { + this.range = arrayRange; + } else if (functionRange) { + this.range = functionRange; + } else { + this.range = expr.range; + } + const dep = this.newRequireDependency(); + dep.loc = loc; + this.addDependency(dep); + } -const APIPlugin = __webpack_require__(71118); -const ConstPlugin = __webpack_require__(84072); -const CommonJsStuffPlugin = __webpack_require__(85736); -const CompatibilityPlugin = __webpack_require__(85918); + newRequireDependency() { + return new AMDRequireDependency(this); + } +}; -const TemplatedPathPlugin = __webpack_require__(76032); -const WarnCaseSensitiveModulesPlugin = __webpack_require__(40269); -const UseStrictPlugin = __webpack_require__(73554); -const LoaderPlugin = __webpack_require__(31559); -const CommonJsPlugin = __webpack_require__(85358); -const HarmonyModulesPlugin = __webpack_require__(66792); -const SystemPlugin = __webpack_require__(68166); -const ImportPlugin = __webpack_require__(58839); -const RequireContextPlugin = __webpack_require__(89042); -const RequireEnsurePlugin = __webpack_require__(98655); -const RequireIncludePlugin = __webpack_require__(16522); +/***/ }), -const { cachedCleverMerge } = __webpack_require__(67916); +/***/ 9994: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ -/** @typedef {import("./Compiler")} Compiler */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -class WebpackOptionsApply extends OptionsApply { - constructor() { - super(); - } - /** - * @param {WebpackOptions} options options object - * @param {Compiler} compiler compiler object - * @returns {WebpackOptions} options object - */ - process(options, compiler) { - let ExternalsPlugin; - compiler.outputPath = options.output.path; - compiler.recordsInputPath = options.recordsInputPath || options.recordsPath; - compiler.recordsOutputPath = - options.recordsOutputPath || options.recordsPath; - compiler.name = options.name; - // TODO webpack 5 refactor this to MultiCompiler.setDependencies() with a WeakMap - // @ts-ignore TODO - compiler.dependencies = options.dependencies; - if (typeof options.target === "string") { - let JsonpTemplatePlugin; - let FetchCompileWasmTemplatePlugin; - let ReadFileCompileWasmTemplatePlugin; - let NodeSourcePlugin; - let NodeTargetPlugin; - let NodeTemplatePlugin; +const AMDRequireItemDependency = __webpack_require__(34345); +const AMDRequireArrayDependency = __webpack_require__(63960); +const AMDRequireContextDependency = __webpack_require__(99890); +const AMDRequireDependenciesBlock = __webpack_require__(32894); +const UnsupportedDependency = __webpack_require__(15826); +const LocalModuleDependency = __webpack_require__(56570); +const ContextDependencyHelpers = __webpack_require__(5594); +const LocalModulesHelpers = __webpack_require__(39658); +const ConstDependency = __webpack_require__(71101); +const getFunctionExpression = __webpack_require__(64197); +const UnsupportedFeatureWarning = __webpack_require__(99953); - switch (options.target) { - case "web": - JsonpTemplatePlugin = __webpack_require__(92764); - FetchCompileWasmTemplatePlugin = __webpack_require__(52669); - NodeSourcePlugin = __webpack_require__(9128); - new JsonpTemplatePlugin().apply(compiler); - new FetchCompileWasmTemplatePlugin({ - mangleImports: options.optimization.mangleWasmImports - }).apply(compiler); - new FunctionModulePlugin().apply(compiler); - new NodeSourcePlugin(options.node).apply(compiler); - new LoaderTargetPlugin(options.target).apply(compiler); - break; - case "webworker": { - let WebWorkerTemplatePlugin = __webpack_require__(21328); - FetchCompileWasmTemplatePlugin = __webpack_require__(52669); - NodeSourcePlugin = __webpack_require__(9128); - new WebWorkerTemplatePlugin().apply(compiler); - new FetchCompileWasmTemplatePlugin({ - mangleImports: options.optimization.mangleWasmImports - }).apply(compiler); - new FunctionModulePlugin().apply(compiler); - new NodeSourcePlugin(options.node).apply(compiler); - new LoaderTargetPlugin(options.target).apply(compiler); - break; - } - case "node": - case "async-node": - NodeTemplatePlugin = __webpack_require__(90010); - ReadFileCompileWasmTemplatePlugin = __webpack_require__(73839); - NodeTargetPlugin = __webpack_require__(59743); - new NodeTemplatePlugin({ - asyncChunkLoading: options.target === "async-node" - }).apply(compiler); - new ReadFileCompileWasmTemplatePlugin({ - mangleImports: options.optimization.mangleWasmImports - }).apply(compiler); - new FunctionModulePlugin().apply(compiler); - new NodeTargetPlugin().apply(compiler); - new LoaderTargetPlugin("node").apply(compiler); - break; - case "node-webkit": - JsonpTemplatePlugin = __webpack_require__(92764); - NodeTargetPlugin = __webpack_require__(59743); - ExternalsPlugin = __webpack_require__(75705); - new JsonpTemplatePlugin().apply(compiler); - new FunctionModulePlugin().apply(compiler); - new NodeTargetPlugin().apply(compiler); - new ExternalsPlugin("commonjs", "nw.gui").apply(compiler); - new LoaderTargetPlugin(options.target).apply(compiler); - break; - case "electron-main": - NodeTemplatePlugin = __webpack_require__(90010); - NodeTargetPlugin = __webpack_require__(59743); - ExternalsPlugin = __webpack_require__(75705); - new NodeTemplatePlugin({ - asyncChunkLoading: true - }).apply(compiler); - new FunctionModulePlugin().apply(compiler); - new NodeTargetPlugin().apply(compiler); - new ExternalsPlugin("commonjs", [ - "app", - "auto-updater", - "browser-window", - "clipboard", - "content-tracing", - "crash-reporter", - "dialog", - "electron", - "global-shortcut", - "ipc", - "ipc-main", - "menu", - "menu-item", - "native-image", - "original-fs", - "power-monitor", - "power-save-blocker", - "protocol", - "screen", - "session", - "shell", - "tray", - "web-contents" - ]).apply(compiler); - new LoaderTargetPlugin(options.target).apply(compiler); - break; - case "electron-renderer": - case "electron-preload": - FetchCompileWasmTemplatePlugin = __webpack_require__(52669); - NodeTargetPlugin = __webpack_require__(59743); - ExternalsPlugin = __webpack_require__(75705); - if (options.target === "electron-renderer") { - JsonpTemplatePlugin = __webpack_require__(92764); - new JsonpTemplatePlugin().apply(compiler); - } else if (options.target === "electron-preload") { - NodeTemplatePlugin = __webpack_require__(90010); - new NodeTemplatePlugin({ - asyncChunkLoading: true - }).apply(compiler); +class AMDRequireDependenciesBlockParserPlugin { + constructor(options) { + this.options = options; + } + + processFunctionArgument(parser, expression) { + let bindThis = true; + const fnData = getFunctionExpression(expression); + if (fnData) { + parser.inScope( + fnData.fn.params.filter(i => { + return !["require", "module", "exports"].includes(i.name); + }), + () => { + if (fnData.fn.body.type === "BlockStatement") { + parser.walkStatement(fnData.fn.body); + } else { + parser.walkExpression(fnData.fn.body); } - new FetchCompileWasmTemplatePlugin({ - mangleImports: options.optimization.mangleWasmImports - }).apply(compiler); - new FunctionModulePlugin().apply(compiler); - new NodeTargetPlugin().apply(compiler); - new ExternalsPlugin("commonjs", [ - "clipboard", - "crash-reporter", - "desktop-capturer", - "electron", - "ipc", - "ipc-renderer", - "native-image", - "original-fs", - "remote", - "screen", - "shell", - "web-frame" - ]).apply(compiler); - new LoaderTargetPlugin(options.target).apply(compiler); - break; - default: - throw new Error("Unsupported target '" + options.target + "'."); + } + ); + parser.walkExpressions(fnData.expressions); + if (fnData.needThis === false) { + bindThis = false; } - } - // @ts-ignore This is always true, which is good this way - else if (options.target !== false) { - options.target(compiler); } else { - throw new Error("Unsupported target '" + options.target + "'."); + parser.walkExpression(expression); } + return bindThis; + } - if (options.output.library || options.output.libraryTarget !== "var") { - const LibraryTemplatePlugin = __webpack_require__(65237); - new LibraryTemplatePlugin( - options.output.library, - options.output.libraryTarget, - options.output.umdNamedDefine, - options.output.auxiliaryComment || "", - options.output.libraryExport - ).apply(compiler); + apply(parser) { + parser.hooks.call + .for("require") + .tap( + "AMDRequireDependenciesBlockParserPlugin", + this.processCallRequire.bind(this, parser) + ); + } + + processArray(parser, expr, param) { + if (param.isArray()) { + for (const p of param.items) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); + } + } + return true; + } else if (param.isConstArray()) { + const deps = []; + for (const request of param.array) { + let dep, localModule; + if (request === "require") { + dep = "__webpack_require__"; + } else if (["exports", "module"].includes(request)) { + dep = request; + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + request + )) + ) { + dep = new LocalModuleDependency(localModule, undefined, false); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + } else { + dep = this.newRequireItemDependency(request); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + } + deps.push(dep); + } + const dep = this.newRequireArrayDependency(deps, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; } - if (options.externals) { - ExternalsPlugin = __webpack_require__(75705); - new ExternalsPlugin( - options.output.libraryTarget, - options.externals - ).apply(compiler); + } + processItem(parser, expr, param) { + if (param.isConditional()) { + for (const p of param.options) { + const result = this.processItem(parser, expr, p); + if (result === undefined) { + this.processContext(parser, expr, p); + } + } + return true; + } else if (param.isString()) { + let dep, localModule; + if (param.string === "require") { + dep = new ConstDependency("__webpack_require__", param.string); + } else if (param.string === "module") { + dep = new ConstDependency( + parser.state.module.buildInfo.moduleArgument, + param.range + ); + } else if (param.string === "exports") { + dep = new ConstDependency( + parser.state.module.buildInfo.exportsArgument, + param.range + ); + } else if ( + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + param.string + )) + ) { + dep = new LocalModuleDependency(localModule, param.range, false); + } else { + dep = this.newRequireItemDependency(param.string, param.range); + } + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; } + } + processContext(parser, expr, param) { + const dep = ContextDependencyHelpers.create( + AMDRequireContextDependency, + param.range, + param, + expr, + this.options, + {}, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } - let noSources; - let legacy; - let modern; - let comment; - if ( - options.devtool && - (options.devtool.includes("sourcemap") || - options.devtool.includes("source-map")) - ) { - const hidden = options.devtool.includes("hidden"); - const inline = options.devtool.includes("inline"); - const evalWrapped = options.devtool.includes("eval"); - const cheap = options.devtool.includes("cheap"); - const moduleMaps = options.devtool.includes("module"); - noSources = options.devtool.includes("nosources"); - legacy = options.devtool.includes("@"); - modern = options.devtool.includes("#"); - comment = - legacy && modern - ? "\n/*\n//@ source" + - "MappingURL=[url]\n//# source" + - "MappingURL=[url]\n*/" - : legacy - ? "\n/*\n//@ source" + "MappingURL=[url]\n*/" - : modern - ? "\n//# source" + "MappingURL=[url]" - : null; - const Plugin = evalWrapped - ? EvalSourceMapDevToolPlugin - : SourceMapDevToolPlugin; - new Plugin({ - filename: inline ? null : options.output.sourceMapFilename, - moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, - fallbackModuleFilenameTemplate: - options.output.devtoolFallbackModuleFilenameTemplate, - append: hidden ? false : comment, - module: moduleMaps ? true : cheap ? false : true, - columns: cheap ? false : true, - lineToLine: options.output.devtoolLineToLine, - noSources: noSources, - namespace: options.output.devtoolNamespace - }).apply(compiler); - } else if (options.devtool && options.devtool.includes("eval")) { - legacy = options.devtool.includes("@"); - modern = options.devtool.includes("#"); - comment = - legacy && modern - ? "\n//@ sourceURL=[url]\n//# sourceURL=[url]" - : legacy - ? "\n//@ sourceURL=[url]" - : modern - ? "\n//# sourceURL=[url]" - : null; - new EvalDevToolModulePlugin({ - sourceUrlComment: comment, - moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, - namespace: options.output.devtoolNamespace - }).apply(compiler); + processArrayForRequestString(param) { + if (param.isArray()) { + const result = param.items.map(item => + this.processItemForRequestString(item) + ); + if (result.every(Boolean)) return result.join(" "); + } else if (param.isConstArray()) { + return param.array.join(" "); } + } - new JavascriptModulesPlugin().apply(compiler); - new JsonModulesPlugin().apply(compiler); - new WebAssemblyModulesPlugin({ - mangleImports: options.optimization.mangleWasmImports - }).apply(compiler); + processItemForRequestString(param) { + if (param.isConditional()) { + const result = param.options.map(item => + this.processItemForRequestString(item) + ); + if (result.every(Boolean)) return result.join("|"); + } else if (param.isString()) { + return param.string; + } + } - new EntryOptionPlugin().apply(compiler); - compiler.hooks.entryOption.call(options.context, options.entry); + processCallRequire(parser, expr) { + let param; + let dep; + let result; - new CompatibilityPlugin().apply(compiler); - new HarmonyModulesPlugin(options.module).apply(compiler); - if (options.amd !== false) { - const AMDPlugin = __webpack_require__(85812); - const RequireJsStuffPlugin = __webpack_require__(88226); - new AMDPlugin(options.module, options.amd || {}).apply(compiler); - new RequireJsStuffPlugin().apply(compiler); - } - new CommonJsPlugin(options.module).apply(compiler); - new LoaderPlugin().apply(compiler); - if (options.node !== false) { - const NodeStuffPlugin = __webpack_require__(28386); - new NodeStuffPlugin(options.node).apply(compiler); - } - new CommonJsStuffPlugin().apply(compiler); - new APIPlugin().apply(compiler); - new ConstPlugin().apply(compiler); - new UseStrictPlugin().apply(compiler); - new RequireIncludePlugin().apply(compiler); - new RequireEnsurePlugin().apply(compiler); - new RequireContextPlugin( - options.resolve.modules, - options.resolve.extensions, - options.resolve.mainFiles - ).apply(compiler); - new ImportPlugin(options.module).apply(compiler); - new SystemPlugin(options.module).apply(compiler); + const old = parser.state.current; - if (typeof options.mode !== "string") { - const WarnNoModeSetPlugin = __webpack_require__(71245); - new WarnNoModeSetPlugin().apply(compiler); + if (expr.arguments.length >= 1) { + param = parser.evaluateExpression(expr.arguments[0]); + dep = this.newRequireDependenciesBlock( + expr, + param.range, + expr.arguments.length > 1 ? expr.arguments[1].range : null, + expr.arguments.length > 2 ? expr.arguments[2].range : null, + parser.state.module, + expr.loc, + this.processArrayForRequestString(param) + ); + parser.state.current = dep; } - const EnsureChunkConditionsPlugin = __webpack_require__(29720); - new EnsureChunkConditionsPlugin().apply(compiler); - if (options.optimization.removeAvailableModules) { - const RemoveParentModulesPlugin = __webpack_require__(58142); - new RemoveParentModulesPlugin().apply(compiler); - } - if (options.optimization.removeEmptyChunks) { - const RemoveEmptyChunksPlugin = __webpack_require__(78085); - new RemoveEmptyChunksPlugin().apply(compiler); - } - if (options.optimization.mergeDuplicateChunks) { - const MergeDuplicateChunksPlugin = __webpack_require__(46214); - new MergeDuplicateChunksPlugin().apply(compiler); - } - if (options.optimization.flagIncludedChunks) { - const FlagIncludedChunksPlugin = __webpack_require__(25850); - new FlagIncludedChunksPlugin().apply(compiler); - } - if (options.optimization.sideEffects) { - const SideEffectsFlagPlugin = __webpack_require__(83654); - new SideEffectsFlagPlugin().apply(compiler); - } - if (options.optimization.providedExports) { - const FlagDependencyExportsPlugin = __webpack_require__(73599); - new FlagDependencyExportsPlugin().apply(compiler); + if (expr.arguments.length === 1) { + parser.inScope([], () => { + result = this.processArray(parser, expr, param); + }); + parser.state.current = old; + if (!result) return; + parser.state.current.addBlock(dep); + return true; } - if (options.optimization.usedExports) { - const FlagDependencyUsagePlugin = __webpack_require__(33632); - new FlagDependencyUsagePlugin().apply(compiler); + + if (expr.arguments.length === 2 || expr.arguments.length === 3) { + try { + parser.inScope([], () => { + result = this.processArray(parser, expr, param); + }); + if (!result) { + dep = new UnsupportedDependency("unsupported", expr.range); + old.addDependency(dep); + if (parser.state.module) { + parser.state.module.errors.push( + new UnsupportedFeatureWarning( + parser.state.module, + "Cannot statically analyse 'require(…, …)' in line " + + expr.loc.start.line, + expr.loc + ) + ); + } + dep = null; + return true; + } + dep.functionBindThis = this.processFunctionArgument( + parser, + expr.arguments[1] + ); + if (expr.arguments.length === 3) { + dep.errorCallbackBindThis = this.processFunctionArgument( + parser, + expr.arguments[2] + ); + } + } finally { + parser.state.current = old; + if (dep) parser.state.current.addBlock(dep); + } + return true; } - if (options.optimization.concatenateModules) { - const ModuleConcatenationPlugin = __webpack_require__(45184); - new ModuleConcatenationPlugin().apply(compiler); - } - if (options.optimization.splitChunks) { - const SplitChunksPlugin = __webpack_require__(60474); - new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler); - } - if (options.optimization.runtimeChunk) { - const RuntimeChunkPlugin = __webpack_require__(76894); - new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler); - } - if (options.optimization.noEmitOnErrors) { - const NoEmitOnErrorsPlugin = __webpack_require__(22615); - new NoEmitOnErrorsPlugin().apply(compiler); - } - if (options.optimization.checkWasmTypes) { - const WasmFinalizeExportsPlugin = __webpack_require__(10557); - new WasmFinalizeExportsPlugin().apply(compiler); - } - let moduleIds = options.optimization.moduleIds; - if (moduleIds === undefined) { - // TODO webpack 5 remove all these options - if (options.optimization.occurrenceOrder) { - moduleIds = "size"; - } - if (options.optimization.namedModules) { - moduleIds = "named"; - } - if (options.optimization.hashedModuleIds) { - moduleIds = "hashed"; - } - if (moduleIds === undefined) { - moduleIds = "natural"; - } - } - if (moduleIds) { - const NamedModulesPlugin = __webpack_require__(86707); - const HashedModuleIdsPlugin = __webpack_require__(50268); - const OccurrenceModuleOrderPlugin = __webpack_require__(62000); - switch (moduleIds) { - case "natural": - // TODO webpack 5: see hint in Compilation.sortModules - break; - case "named": - new NamedModulesPlugin().apply(compiler); - break; - case "hashed": - new HashedModuleIdsPlugin().apply(compiler); - break; - case "size": - new OccurrenceModuleOrderPlugin({ - prioritiseInitial: true - }).apply(compiler); - break; - case "total-size": - new OccurrenceModuleOrderPlugin({ - prioritiseInitial: false - }).apply(compiler); - break; - default: - throw new Error( - `webpack bug: moduleIds: ${moduleIds} is not implemented` - ); - } - } - let chunkIds = options.optimization.chunkIds; - if (chunkIds === undefined) { - // TODO webpack 5 remove all these options - if (options.optimization.occurrenceOrder) { - // This looks weird but it's for backward-compat - // This bug already existed before adding this feature - chunkIds = "total-size"; - } - if (options.optimization.namedChunks) { - chunkIds = "named"; - } - if (chunkIds === undefined) { - chunkIds = "natural"; - } - } - if (chunkIds) { - const NaturalChunkOrderPlugin = __webpack_require__(68053); - const NamedChunksPlugin = __webpack_require__(70419); - const OccurrenceChunkOrderPlugin = __webpack_require__(83741); - switch (chunkIds) { - case "natural": - new NaturalChunkOrderPlugin().apply(compiler); - break; - case "named": - // TODO webapck 5: for backward-compat this need to have OccurrenceChunkOrderPlugin too - // The NamedChunksPlugin doesn't give every chunk a name - // This should be fixed, and the OccurrenceChunkOrderPlugin should be removed here. - new OccurrenceChunkOrderPlugin({ - prioritiseInitial: false - }).apply(compiler); - new NamedChunksPlugin().apply(compiler); - break; - case "size": - new OccurrenceChunkOrderPlugin({ - prioritiseInitial: true - }).apply(compiler); - break; - case "total-size": - new OccurrenceChunkOrderPlugin({ - prioritiseInitial: false - }).apply(compiler); - break; - default: - throw new Error( - `webpack bug: chunkIds: ${chunkIds} is not implemented` - ); - } + } + + newRequireDependenciesBlock( + expr, + arrayRange, + functionRange, + errorCallbackRange, + module, + loc, + request + ) { + return new AMDRequireDependenciesBlock( + expr, + arrayRange, + functionRange, + errorCallbackRange, + module, + loc, + request + ); + } + newRequireItemDependency(request, range) { + return new AMDRequireItemDependency(request, range); + } + newRequireArrayDependency(depsArray, range) { + return new AMDRequireArrayDependency(depsArray, range); + } +} +module.exports = AMDRequireDependenciesBlockParserPlugin; + + +/***/ }), + +/***/ 73985: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class AMDRequireDependency extends NullDependency { + constructor(block) { + super(); + this.block = block; + } +} + +AMDRequireDependency.Template = class AMDRequireDependencyTemplate { + apply(dep, source, runtime) { + const depBlock = dep.block; + const promise = runtime.blockPromise({ + block: depBlock, + message: "AMD require" + }); + + // has array range but no function range + if (depBlock.arrayRange && !depBlock.functionRange) { + const startBlock = `${promise}.then(function() {`; + const endBlock = `;}).catch(${runtime.onError()})`; + source.replace( + depBlock.outerRange[0], + depBlock.arrayRange[0] - 1, + startBlock + ); + source.replace( + depBlock.arrayRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); + return; } - if (options.optimization.nodeEnv) { - const DefinePlugin = __webpack_require__(97374); - new DefinePlugin({ - "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv) - }).apply(compiler); + + // has function range but no array range + if (depBlock.functionRange && !depBlock.arrayRange) { + const startBlock = `${promise}.then((`; + const endBlock = `).bind(exports, __webpack_require__, exports, module)).catch(${runtime.onError()})`; + source.replace( + depBlock.outerRange[0], + depBlock.functionRange[0] - 1, + startBlock + ); + source.replace( + depBlock.functionRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); + return; } - if (options.optimization.minimize) { - for (const minimizer of options.optimization.minimizer) { - if (typeof minimizer === "function") { - minimizer.call(compiler, compiler); - } else { - minimizer.apply(compiler); - } - } + + // has array range, function range, and errorCallbackRange + if ( + depBlock.arrayRange && + depBlock.functionRange && + depBlock.errorCallbackRange + ) { + const startBlock = `${promise}.then(function() { `; + const errorRangeBlock = `}${ + depBlock.functionBindThis ? ".bind(this)" : "" + }).catch(`; + const endBlock = `${ + depBlock.errorCallbackBindThis ? ".bind(this)" : "" + })`; + + source.replace( + depBlock.outerRange[0], + depBlock.arrayRange[0] - 1, + startBlock + ); + source.insert( + depBlock.arrayRange[0] + 0.9, + "var __WEBPACK_AMD_REQUIRE_ARRAY__ = " + ); + source.replace( + depBlock.arrayRange[1], + depBlock.functionRange[0] - 1, + "; (" + ); + source.insert( + depBlock.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); + source.replace( + depBlock.functionRange[1], + depBlock.errorCallbackRange[0] - 1, + errorRangeBlock + ); + source.replace( + depBlock.errorCallbackRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); + return; } - if (options.performance) { - const SizeLimitsPlugin = __webpack_require__(68310); - new SizeLimitsPlugin(options.performance).apply(compiler); + // has array range, function range, but no errorCallbackRange + if (depBlock.arrayRange && depBlock.functionRange) { + const startBlock = `${promise}.then(function() { `; + const endBlock = `}${ + depBlock.functionBindThis ? ".bind(this)" : "" + }).catch(${runtime.onError()})`; + source.replace( + depBlock.outerRange[0], + depBlock.arrayRange[0] - 1, + startBlock + ); + source.insert( + depBlock.arrayRange[0] + 0.9, + "var __WEBPACK_AMD_REQUIRE_ARRAY__ = " + ); + source.replace( + depBlock.arrayRange[1], + depBlock.functionRange[0] - 1, + "; (" + ); + source.insert( + depBlock.functionRange[1], + ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" + ); + source.replace( + depBlock.functionRange[1], + depBlock.outerRange[1] - 1, + endBlock + ); } + } +}; - new TemplatedPathPlugin().apply(compiler); +module.exports = AMDRequireDependency; - new RecordIdsPlugin({ - portableIds: options.optimization.portableRecords - }).apply(compiler); - new WarnCaseSensitiveModulesPlugin().apply(compiler); +/***/ }), - if (options.cache) { - const CachePlugin = __webpack_require__(6465); - new CachePlugin( - typeof options.cache === "object" ? options.cache : null - ).apply(compiler); - } +/***/ 34345: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - compiler.hooks.afterPlugins.call(compiler); - if (!compiler.inputFileSystem) { - throw new Error("No input filesystem provided"); - } - compiler.resolverFactory.hooks.resolveOptions - .for("normal") - .tap("WebpackOptionsApply", resolveOptions => { - return Object.assign( - { - fileSystem: compiler.inputFileSystem - }, - cachedCleverMerge(options.resolve, resolveOptions) - ); - }); - compiler.resolverFactory.hooks.resolveOptions - .for("context") - .tap("WebpackOptionsApply", resolveOptions => { - return Object.assign( - { - fileSystem: compiler.inputFileSystem, - resolveToContext: true - }, - cachedCleverMerge(options.resolve, resolveOptions) - ); - }); - compiler.resolverFactory.hooks.resolveOptions - .for("loader") - .tap("WebpackOptionsApply", resolveOptions => { - return Object.assign( - { - fileSystem: compiler.inputFileSystem - }, - cachedCleverMerge(options.resolveLoader, resolveOptions) - ); - }); - compiler.hooks.afterResolvers.call(compiler); - return options; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const ModuleDependency = __webpack_require__(90865); +const ModuleDependencyTemplateAsRequireId = __webpack_require__(60441); + +class AMDRequireItemDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + } + + get type() { + return "amd require"; } } -module.exports = WebpackOptionsApply; +AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; + +module.exports = AMDRequireItemDependency; /***/ }), -/***/ 60016: +/***/ 85358: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95028,785 +94632,371 @@ module.exports = WebpackOptionsApply; Author Tobias Koppers @sokra */ +const ConstDependency = __webpack_require__(71101); +const CommonJsRequireDependency = __webpack_require__(37504); +const CommonJsRequireContextDependency = __webpack_require__(26791); +const RequireResolveDependency = __webpack_require__(43519); +const RequireResolveContextDependency = __webpack_require__(83309); +const RequireResolveHeaderDependency = __webpack_require__(69647); +const RequireHeaderDependency = __webpack_require__(22928); -const path = __webpack_require__(85622); - -const OptionsDefaulter = __webpack_require__(3414); -const Template = __webpack_require__(96066); +const NullFactory = __webpack_require__(40438); -const isProductionLikeMode = options => { - return options.mode === "production" || !options.mode; -}; +const RequireResolveDependencyParserPlugin = __webpack_require__(68349); +const CommonJsRequireDependencyParserPlugin = __webpack_require__(37278); -const isWebLikeTarget = options => { - return options.target === "web" || options.target === "webworker"; -}; +const ParserHelpers = __webpack_require__(23999); -const getDevtoolNamespace = library => { - // if options.output.library is a string - if (Array.isArray(library)) { - return library.join("."); - } else if (typeof library === "object") { - return getDevtoolNamespace(library.root); +class CommonJsPlugin { + constructor(options) { + this.options = options; } - return library || ""; -}; - -class WebpackOptionsDefaulter extends OptionsDefaulter { - constructor() { - super(); - this.set("entry", "./src"); + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "CommonJsPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + CommonJsRequireDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireDependency, + new CommonJsRequireDependency.Template() + ); - this.set("devtool", "make", options => - options.mode === "development" ? "eval" : false - ); - this.set("cache", "make", options => options.mode === "development"); + compilation.dependencyFactories.set( + CommonJsRequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + CommonJsRequireContextDependency, + new CommonJsRequireContextDependency.Template() + ); - this.set("context", process.cwd()); - this.set("target", "web"); + compilation.dependencyFactories.set( + RequireResolveDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveDependency, + new RequireResolveDependency.Template() + ); - this.set("module", "call", value => Object.assign({}, value)); - this.set("module.unknownContextRequest", "."); - this.set("module.unknownContextRegExp", false); - this.set("module.unknownContextRecursive", true); - this.set("module.unknownContextCritical", true); - this.set("module.exprContextRequest", "."); - this.set("module.exprContextRegExp", false); - this.set("module.exprContextRecursive", true); - this.set("module.exprContextCritical", true); - this.set("module.wrappedContextRegExp", /.*/); - this.set("module.wrappedContextRecursive", true); - this.set("module.wrappedContextCritical", false); - this.set("module.strictExportPresence", false); - this.set("module.strictThisContextOnImports", false); - this.set("module.unsafeCache", "make", options => !!options.cache); - this.set("module.rules", []); - this.set("module.defaultRules", "make", options => [ - { - type: "javascript/auto", - resolve: {} - }, - { - test: /\.mjs$/i, - type: "javascript/esm", - resolve: { - mainFields: - options.target === "web" || - options.target === "webworker" || - options.target === "electron-renderer" - ? ["browser", "main"] - : ["main"] - } - }, - { - test: /\.json$/i, - type: "json" - }, - { - test: /\.wasm$/i, - type: "webassembly/experimental" - } - ]); + compilation.dependencyFactories.set( + RequireResolveContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireResolveContextDependency, + new RequireResolveContextDependency.Template() + ); - this.set("output", "call", (value, options) => { - if (typeof value === "string") { - return { - filename: value - }; - } else if (typeof value !== "object") { - return {}; - } else { - return Object.assign({}, value); - } - }); + compilation.dependencyFactories.set( + RequireResolveHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + RequireResolveHeaderDependency, + new RequireResolveHeaderDependency.Template() + ); - this.set("output.filename", "[name].js"); - this.set("output.chunkFilename", "make", options => { - const filename = options.output.filename; - if (typeof filename !== "function") { - const hasName = filename.includes("[name]"); - const hasId = filename.includes("[id]"); - const hasChunkHash = filename.includes("[chunkhash]"); - // Anything changing depending on chunk is fine - if (hasChunkHash || hasName || hasId) return filename; - // Elsewise prefix "[id]." in front of the basename to make it changing - return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2"); - } - return "[id].js"; - }); - this.set("output.webassemblyModuleFilename", "[modulehash].module.wasm"); - this.set("output.library", ""); - this.set("output.hotUpdateFunction", "make", options => { - return Template.toIdentifier( - "webpackHotUpdate" + Template.toIdentifier(options.output.library) - ); - }); - this.set("output.jsonpFunction", "make", options => { - return Template.toIdentifier( - "webpackJsonp" + Template.toIdentifier(options.output.library) - ); - }); - this.set("output.chunkCallbackName", "make", options => { - return Template.toIdentifier( - "webpackChunk" + Template.toIdentifier(options.output.library) - ); - }); - this.set("output.globalObject", "make", options => { - switch (options.target) { - case "web": - case "electron-renderer": - case "node-webkit": - return "window"; - case "webworker": - return "self"; - case "node": - case "async-node": - case "electron-main": - return "global"; - default: - return "self"; - } - }); - this.set("output.devtoolNamespace", "make", options => { - return getDevtoolNamespace(options.output.library); - }); - this.set("output.libraryTarget", "var"); - this.set("output.path", path.join(process.cwd(), "dist")); - this.set( - "output.pathinfo", - "make", - options => options.mode === "development" - ); - this.set("output.sourceMapFilename", "[file].map[query]"); - this.set("output.hotUpdateChunkFilename", "[id].[hash].hot-update.js"); - this.set("output.hotUpdateMainFilename", "[hash].hot-update.json"); - this.set("output.crossOriginLoading", false); - this.set("output.jsonpScriptType", false); - this.set("output.chunkLoadTimeout", 120000); - this.set("output.hashFunction", "md4"); - this.set("output.hashDigest", "hex"); - this.set("output.hashDigestLength", 20); - this.set("output.devtoolLineToLine", false); - this.set("output.strictModuleExceptionHandling", false); + compilation.dependencyFactories.set( + RequireHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + RequireHeaderDependency, + new RequireHeaderDependency.Template() + ); - this.set("node", "call", value => { - if (typeof value === "boolean") { - return value; - } else { - return Object.assign({}, value); - } - }); - this.set("node.console", false); - this.set("node.process", true); - this.set("node.global", true); - this.set("node.Buffer", true); - this.set("node.setImmediate", true); - this.set("node.__filename", "mock"); - this.set("node.__dirname", "mock"); + const handler = (parser, parserOptions) => { + if (parserOptions.commonjs !== undefined && !parserOptions.commonjs) + return; - this.set("performance", "call", (value, options) => { - if (value === false) return false; - if ( - value === undefined && - (!isProductionLikeMode(options) || !isWebLikeTarget(options)) - ) - return false; - return Object.assign({}, value); - }); - this.set("performance.maxAssetSize", 250000); - this.set("performance.maxEntrypointSize", 250000); - this.set("performance.hints", "make", options => - isProductionLikeMode(options) ? "warning" : false - ); + const requireExpressions = [ + "require", + "require.resolve", + "require.resolveWeak" + ]; + for (let expression of requireExpressions) { + parser.hooks.typeof + .for(expression) + .tap( + "CommonJsPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + parser.hooks.evaluateTypeof + .for(expression) + .tap( + "CommonJsPlugin", + ParserHelpers.evaluateToString("function") + ); + parser.hooks.evaluateIdentifier + .for(expression) + .tap( + "CommonJsPlugin", + ParserHelpers.evaluateToIdentifier(expression, true) + ); + } - this.set("optimization", "call", value => Object.assign({}, value)); - // TODO webpack 5: Disable by default in a modes - this.set( - "optimization.removeAvailableModules", - "make", - options => options.mode !== "development" - ); - this.set("optimization.removeEmptyChunks", true); - this.set("optimization.mergeDuplicateChunks", true); - this.set("optimization.flagIncludedChunks", "make", options => - isProductionLikeMode(options) - ); - // TODO webpack 5 add `moduleIds: "named"` default for development - // TODO webpack 5 add `moduleIds: "size"` default for production - // TODO webpack 5 remove optimization.occurrenceOrder - this.set("optimization.occurrenceOrder", "make", options => - isProductionLikeMode(options) - ); - this.set("optimization.sideEffects", "make", options => - isProductionLikeMode(options) - ); - this.set("optimization.providedExports", true); - this.set("optimization.usedExports", "make", options => - isProductionLikeMode(options) - ); - this.set("optimization.concatenateModules", "make", options => - isProductionLikeMode(options) - ); - this.set("optimization.splitChunks", {}); - this.set("optimization.splitChunks.hidePathInfo", "make", options => { - return isProductionLikeMode(options); - }); - this.set("optimization.splitChunks.chunks", "async"); - this.set("optimization.splitChunks.minSize", "make", options => { - return isProductionLikeMode(options) ? 30000 : 10000; - }); - this.set("optimization.splitChunks.minChunks", 1); - this.set("optimization.splitChunks.maxAsyncRequests", "make", options => { - return isProductionLikeMode(options) ? 5 : Infinity; - }); - this.set("optimization.splitChunks.automaticNameDelimiter", "~"); - this.set("optimization.splitChunks.automaticNameMaxLength", 109); - this.set("optimization.splitChunks.maxInitialRequests", "make", options => { - return isProductionLikeMode(options) ? 3 : Infinity; - }); - this.set("optimization.splitChunks.name", true); - this.set("optimization.splitChunks.cacheGroups", {}); - this.set("optimization.splitChunks.cacheGroups.default", { - automaticNamePrefix: "", - reuseExistingChunk: true, - minChunks: 2, - priority: -20 - }); - this.set("optimization.splitChunks.cacheGroups.vendors", { - automaticNamePrefix: "vendors", - test: /[\\/]node_modules[\\/]/, - priority: -10 - }); - this.set("optimization.runtimeChunk", "call", value => { - if (value === "single") { - return { - name: "runtime" - }; - } - if (value === true || value === "multiple") { - return { - name: entrypoint => `runtime~${entrypoint.name}` + parser.hooks.evaluateTypeof + .for("module") + .tap("CommonJsPlugin", ParserHelpers.evaluateToString("object")); + parser.hooks.assign.for("require").tap("CommonJsPlugin", expr => { + // to not leak to global "require", we need to define a local require here. + const dep = new ConstDependency("var require;", 0); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + parser.scope.definitions.add("require"); + return true; + }); + parser.hooks.canRename + .for("require") + .tap("CommonJsPlugin", () => true); + parser.hooks.rename.for("require").tap("CommonJsPlugin", expr => { + // define the require variable. It's still undefined, but not "not defined". + const dep = new ConstDependency("var require;", 0); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return false; + }); + parser.hooks.typeof.for("module").tap("CommonJsPlugin", () => true); + parser.hooks.evaluateTypeof + .for("exports") + .tap("CommonJsPlugin", ParserHelpers.evaluateToString("object")); + + new CommonJsRequireDependencyParserPlugin(options).apply(parser); + new RequireResolveDependencyParserPlugin(options).apply(parser); }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("CommonJsPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("CommonJsPlugin", handler); } - return value; - }); - this.set("optimization.noEmitOnErrors", "make", options => - isProductionLikeMode(options) - ); - this.set("optimization.checkWasmTypes", "make", options => - isProductionLikeMode(options) - ); - this.set("optimization.mangleWasmImports", false); - // TODO webpack 5 remove optimization.namedModules - this.set( - "optimization.namedModules", - "make", - options => options.mode === "development" - ); - this.set("optimization.hashedModuleIds", false); - // TODO webpack 5 add `chunkIds: "named"` default for development - // TODO webpack 5 add `chunkIds: "size"` default for production - // TODO webpack 5 remove optimization.namedChunks - this.set( - "optimization.namedChunks", - "make", - options => options.mode === "development" - ); - this.set( - "optimization.portableRecords", - "make", - options => - !!( - options.recordsInputPath || - options.recordsOutputPath || - options.recordsPath - ) - ); - this.set("optimization.minimize", "make", options => - isProductionLikeMode(options) ); - this.set("optimization.minimizer", "make", options => [ - { - apply: compiler => { - // Lazy load the Terser plugin - const TerserPlugin = __webpack_require__(89301); - const SourceMapDevToolPlugin = __webpack_require__(11851); - new TerserPlugin({ - cache: true, - parallel: true, - sourceMap: - (options.devtool && /source-?map/.test(options.devtool)) || - (options.plugins && - options.plugins.some(p => p instanceof SourceMapDevToolPlugin)) - }).apply(compiler); - } - } - ]); - this.set("optimization.nodeEnv", "make", options => { - // TODO: In webpack 5, it should return `false` when mode is `none` - return options.mode || "production"; - }); + } +} +module.exports = CommonJsPlugin; - this.set("resolve", "call", value => Object.assign({}, value)); - this.set("resolve.unsafeCache", true); - this.set("resolve.modules", ["node_modules"]); - this.set("resolve.extensions", [".wasm", ".mjs", ".js", ".json"]); - this.set("resolve.mainFiles", ["index"]); - this.set("resolve.aliasFields", "make", options => { - if ( - options.target === "web" || - options.target === "webworker" || - options.target === "electron-renderer" - ) { - return ["browser"]; - } else { - return []; - } - }); - this.set("resolve.mainFields", "make", options => { - if ( - options.target === "web" || - options.target === "webworker" || - options.target === "electron-renderer" - ) { - return ["browser", "module", "main"]; - } else { - return ["module", "main"]; - } - }); - this.set("resolve.cacheWithContext", "make", options => { - return ( - Array.isArray(options.resolve.plugins) && - options.resolve.plugins.length > 0 - ); - }); - this.set("resolveLoader", "call", value => Object.assign({}, value)); - this.set("resolveLoader.unsafeCache", true); - this.set("resolveLoader.mainFields", ["loader", "main"]); - this.set("resolveLoader.extensions", [".js", ".json"]); - this.set("resolveLoader.mainFiles", ["index"]); - this.set("resolveLoader.roots", "make", options => [options.context]); - this.set("resolveLoader.cacheWithContext", "make", options => { - return ( - Array.isArray(options.resolveLoader.plugins) && - options.resolveLoader.plugins.length > 0 - ); - }); +/***/ }), - this.set("infrastructureLogging", "call", value => - Object.assign({}, value) - ); - this.set("infrastructureLogging.level", "info"); - this.set("infrastructureLogging.debug", false); +/***/ 26791: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const ContextDependency = __webpack_require__(11583); +const ContextDependencyTemplateAsRequireCall = __webpack_require__(54380); + +class CommonJsRequireContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } + + get type() { + return "cjs require context"; } } -module.exports = WebpackOptionsDefaulter; +CommonJsRequireContextDependency.Template = ContextDependencyTemplateAsRequireCall; + +module.exports = CommonJsRequireContextDependency; /***/ }), -/***/ 285: +/***/ 37504: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Gajus Kuizinas @gajus + Author Tobias Koppers @sokra */ +const ModuleDependency = __webpack_require__(90865); +const ModuleDependencyTemplateAsId = __webpack_require__(63708); -const WebpackError = __webpack_require__(97391); -const webpackOptionsSchema = __webpack_require__(37863); - -const getSchemaPart = (path, parents, additionalPath) => { - parents = parents || 0; - path = path.split("/"); - path = path.slice(0, path.length - parents); - if (additionalPath) { - additionalPath = additionalPath.split("/"); - path = path.concat(additionalPath); - } - let schemaPart = webpackOptionsSchema; - for (let i = 1; i < path.length; i++) { - const inner = schemaPart[path[i]]; - if (inner) schemaPart = inner; +class CommonJsRequireDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; } - return schemaPart; -}; -const getSchemaPartText = (schemaPart, additionalPath) => { - if (additionalPath) { - for (let i = 0; i < additionalPath.length; i++) { - const inner = schemaPart[additionalPath[i]]; - if (inner) schemaPart = inner; - } - } - while (schemaPart.$ref) { - schemaPart = getSchemaPart(schemaPart.$ref); - } - let schemaText = WebpackOptionsValidationError.formatSchema(schemaPart); - if (schemaPart.description) { - schemaText += `\n-> ${schemaPart.description}`; + get type() { + return "cjs require"; } - return schemaText; -}; +} -const getSchemaPartDescription = schemaPart => { - while (schemaPart.$ref) { - schemaPart = getSchemaPart(schemaPart.$ref); - } - if (schemaPart.description) { - return `\n-> ${schemaPart.description}`; - } - return ""; -}; +CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; -const SPECIFICITY = { - type: 1, - oneOf: 1, - anyOf: 1, - allOf: 1, - additionalProperties: 2, - enum: 1, - instanceof: 1, - required: 2, - minimum: 2, - uniqueItems: 2, - minLength: 2, - minItems: 2, - minProperties: 2, - absolutePath: 2 -}; +module.exports = CommonJsRequireDependency; -const filterMax = (array, fn) => { - const max = array.reduce((max, item) => Math.max(max, fn(item)), 0); - return array.filter(item => fn(item) === max); -}; -const filterChildren = children => { - children = filterMax(children, err => - err.dataPath ? err.dataPath.length : 0 - ); - children = filterMax(children, err => SPECIFICITY[err.keyword] || 2); - return children; -}; +/***/ }), -const indent = (str, prefix, firstLine) => { - if (firstLine) { - return prefix + str.replace(/\n(?!$)/g, "\n" + prefix); - } else { - return str.replace(/\n(?!$)/g, `\n${prefix}`); - } -}; +/***/ 37278: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -class WebpackOptionsValidationError extends WebpackError { - constructor(validationErrors) { - super( - "Invalid configuration object. " + - "Webpack has been initialised using a configuration object that does not match the API schema.\n" + - validationErrors - .map( - err => - " - " + - indent( - WebpackOptionsValidationError.formatValidationError(err), - " ", - false - ) - ) - .join("\n") - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - this.name = "WebpackOptionsValidationError"; - this.validationErrors = validationErrors; - Error.captureStackTrace(this, this.constructor); +const CommonJsRequireDependency = __webpack_require__(37504); +const CommonJsRequireContextDependency = __webpack_require__(26791); +const RequireHeaderDependency = __webpack_require__(22928); +const LocalModuleDependency = __webpack_require__(56570); +const ContextDependencyHelpers = __webpack_require__(5594); +const LocalModulesHelpers = __webpack_require__(39658); +const ParserHelpers = __webpack_require__(23999); + +class CommonJsRequireDependencyParserPlugin { + constructor(options) { + this.options = options; } - static formatSchema(schema, prevSchemas) { - prevSchemas = prevSchemas || []; + apply(parser) { + const options = this.options; - const formatInnerSchema = (innerSchema, addSelf) => { - if (!addSelf) { - return WebpackOptionsValidationError.formatSchema( - innerSchema, - prevSchemas - ); - } - if (prevSchemas.includes(innerSchema)) { - return "(recursive)"; - } - return WebpackOptionsValidationError.formatSchema( - innerSchema, - prevSchemas.concat(schema) + const processItem = (expr, param) => { + if (param.isString()) { + const dep = new CommonJsRequireDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + }; + const processContext = (expr, param) => { + const dep = ContextDependencyHelpers.create( + CommonJsRequireContextDependency, + expr.range, + param, + expr, + options, + {}, + parser ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; }; - if (schema.type === "string") { - if (schema.minLength === 1) { - return "non-empty string"; - } - if (schema.minLength > 1) { - return `string (min length ${schema.minLength})`; - } - return "string"; - } - if (schema.type === "boolean") { - return "boolean"; - } - if (schema.type === "number") { - return "number"; - } - if (schema.type === "object") { - if (schema.properties) { - const required = schema.required || []; - return `object { ${Object.keys(schema.properties) - .map(property => { - if (!required.includes(property)) return property + "?"; - return property; - }) - .concat(schema.additionalProperties ? ["…"] : []) - .join(", ")} }`; - } - if (schema.additionalProperties) { - return `object { : ${formatInnerSchema( - schema.additionalProperties - )} }`; - } - return "object"; - } - if (schema.type === "array") { - return `[${formatInnerSchema(schema.items)}]`; - } - - switch (schema.instanceof) { - case "Function": - return "function"; - case "RegExp": - return "RegExp"; - } - - if (schema.enum) { - return schema.enum.map(item => JSON.stringify(item)).join(" | "); - } - - if (schema.$ref) { - return formatInnerSchema(getSchemaPart(schema.$ref), true); - } - if (schema.allOf) { - return schema.allOf.map(formatInnerSchema).join(" & "); - } - if (schema.oneOf) { - return schema.oneOf.map(formatInnerSchema).join(" | "); - } - if (schema.anyOf) { - return schema.anyOf.map(formatInnerSchema).join(" | "); - } - return JSON.stringify(schema, null, 2); - } - - static formatValidationError(err) { - const dataPath = `configuration${err.dataPath}`; - if (err.keyword === "additionalProperties") { - const baseMessage = `${dataPath} has an unknown property '${ - err.params.additionalProperty - }'. These properties are valid:\n${getSchemaPartText(err.parentSchema)}`; - if (!err.dataPath) { - switch (err.params.additionalProperty) { - case "debug": - return ( - `${baseMessage}\n` + - "The 'debug' property was removed in webpack 2.0.0.\n" + - "Loaders should be updated to allow passing this option via loader options in module.rules.\n" + - "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" + - "plugins: [\n" + - " new webpack.LoaderOptionsPlugin({\n" + - " debug: true\n" + - " })\n" + - "]" - ); - } - return ( - `${baseMessage}\n` + - "For typos: please correct them.\n" + - "For loader options: webpack >= v2.0.0 no longer allows custom properties in configuration.\n" + - " Loaders should be updated to allow passing options via loader options in module.rules.\n" + - " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" + - " plugins: [\n" + - " new webpack.LoaderOptionsPlugin({\n" + - " // test: /\\.xxx$/, // may apply this only for some modules\n" + - " options: {\n" + - ` ${err.params.additionalProperty}: …\n` + - " }\n" + - " })\n" + - " ]" + parser.hooks.expression + .for("require.cache") + .tap( + "CommonJsRequireDependencyParserPlugin", + ParserHelpers.toConstantDependencyWithWebpackRequire( + parser, + "__webpack_require__.c" + ) + ); + parser.hooks.expression + .for("require") + .tap("CommonJsRequireDependencyParserPlugin", expr => { + const dep = new CommonJsRequireContextDependency( + { + request: options.unknownContextRequest, + recursive: options.unknownContextRecursive, + regExp: options.unknownContextRegExp, + mode: "sync" + }, + expr.range ); - } - return baseMessage; - } else if (err.keyword === "oneOf" || err.keyword === "anyOf") { - if (err.children && err.children.length > 0) { - if (err.schema.length === 1) { - const lastChild = err.children[err.children.length - 1]; - const remainingChildren = err.children.slice( - 0, - err.children.length - 1 - ); - return WebpackOptionsValidationError.formatValidationError( - Object.assign({}, lastChild, { - children: remainingChildren, - parentSchema: Object.assign( - {}, - err.parentSchema, - lastChild.parentSchema - ) - }) - ); + dep.critical = + options.unknownContextCritical && + "require function is used in a way in which dependencies cannot be statically extracted"; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }); + + const createHandler = callNew => expr => { + if (expr.arguments.length !== 1) return; + let localModule; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + let isExpression = false; + const prevLength = parser.state.current.dependencies.length; + const dep = new RequireHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + for (const p of param.options) { + const result = processItem(expr, p); + if (result === undefined) { + isExpression = true; + } } - const children = filterChildren(err.children); - if (children.length === 1) { - return WebpackOptionsValidationError.formatValidationError( - children[0] - ); + if (isExpression) { + parser.state.current.dependencies.length = prevLength; + } else { + return true; } - return ( - `${dataPath} should be one of these:\n${getSchemaPartText( - err.parentSchema - )}\n` + - `Details:\n${children - .map( - err => - " * " + - indent( - WebpackOptionsValidationError.formatValidationError(err), - " ", - false - ) - ) - .join("\n")}` - ); } - return `${dataPath} should be one of these:\n${getSchemaPartText( - err.parentSchema - )}`; - } else if (err.keyword === "enum") { if ( - err.parentSchema && - err.parentSchema.enum && - err.parentSchema.enum.length === 1 + param.isString() && + (localModule = LocalModulesHelpers.getLocalModule( + parser.state, + param.string + )) ) { - return `${dataPath} should be ${getSchemaPartText(err.parentSchema)}`; - } - return `${dataPath} should be one of these:\n${getSchemaPartText( - err.parentSchema - )}`; - } else if (err.keyword === "allOf") { - return `${dataPath} should be:\n${getSchemaPartText(err.parentSchema)}`; - } else if (err.keyword === "type") { - switch (err.params.type) { - case "object": - return `${dataPath} should be an object.${getSchemaPartDescription( - err.parentSchema - )}`; - case "string": - return `${dataPath} should be a string.${getSchemaPartDescription( - err.parentSchema - )}`; - case "boolean": - return `${dataPath} should be a boolean.${getSchemaPartDescription( - err.parentSchema - )}`; - case "number": - return `${dataPath} should be a number.${getSchemaPartDescription( - err.parentSchema - )}`; - case "array": - return `${dataPath} should be an array:\n${getSchemaPartText( - err.parentSchema - )}`; - } - return `${dataPath} should be ${err.params.type}:\n${getSchemaPartText( - err.parentSchema - )}`; - } else if (err.keyword === "instanceof") { - return `${dataPath} should be an instance of ${getSchemaPartText( - err.parentSchema - )}`; - } else if (err.keyword === "required") { - const missingProperty = err.params.missingProperty.replace(/^\./, ""); - return `${dataPath} misses the property '${missingProperty}'.\n${getSchemaPartText( - err.parentSchema, - ["properties", missingProperty] - )}`; - } else if (err.keyword === "minimum") { - return `${dataPath} ${err.message}.${getSchemaPartDescription( - err.parentSchema - )}`; - } else if (err.keyword === "uniqueItems") { - return `${dataPath} should not contain the item '${ - err.data[err.params.i] - }' twice.${getSchemaPartDescription(err.parentSchema)}`; - } else if ( - err.keyword === "minLength" || - err.keyword === "minItems" || - err.keyword === "minProperties" - ) { - if (err.params.limit === 1) { - switch (err.keyword) { - case "minLength": - return `${dataPath} should be an non-empty string.${getSchemaPartDescription( - err.parentSchema - )}`; - case "minItems": - return `${dataPath} should be an non-empty array.${getSchemaPartDescription( - err.parentSchema - )}`; - case "minProperties": - return `${dataPath} should be an non-empty object.${getSchemaPartDescription( - err.parentSchema - )}`; - } - return `${dataPath} should be not empty.${getSchemaPartDescription( - err.parentSchema - )}`; + const dep = new LocalModuleDependency(localModule, expr.range, callNew); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; } else { - return `${dataPath} ${err.message}${getSchemaPartDescription( - err.parentSchema - )}`; - } - } else if (err.keyword === "not") { - return `${dataPath} should not be ${getSchemaPartText( - err.schema - )}\n${getSchemaPartText(err.parentSchema)}`; - } else if (err.keyword === "absolutePath") { - const baseMessage = `${dataPath}: ${ - err.message - }${getSchemaPartDescription(err.parentSchema)}`; - if (dataPath === "configuration.output.filename") { - return ( - `${baseMessage}\n` + - "Please use output.path to specify absolute path and output.filename for the file name." - ); + const result = processItem(expr, param); + if (result === undefined) { + processContext(expr, param); + } else { + const dep = new RequireHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + } + return true; } - return baseMessage; - } else { - return `${dataPath} ${err.message} (${JSON.stringify( - err, - null, - 2 - )}).\n${getSchemaPartText(err.parentSchema)}`; - } + }; + parser.hooks.call + .for("require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(false)); + parser.hooks.new + .for("require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(true)); + parser.hooks.call + .for("module.require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(false)); + parser.hooks.new + .for("module.require") + .tap("CommonJsRequireDependencyParserPlugin", createHandler(true)); } } - -module.exports = WebpackOptionsValidationError; +module.exports = CommonJsRequireDependencyParserPlugin; /***/ }), -/***/ 52337: +/***/ 71101: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -95815,1239 +95005,1069 @@ module.exports = WebpackOptionsValidationError; Author Tobias Koppers @sokra */ +const NullDependency = __webpack_require__(5088); +class ConstDependency extends NullDependency { + constructor(expression, range, requireWebpackRequire) { + super(); + this.expression = expression; + this.range = range; + this.requireWebpackRequire = requireWebpackRequire; + } -const AsyncDependencyToInitialChunkError = __webpack_require__(67089); -const GraphHelpers = __webpack_require__(32973); - -/** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */ -/** @typedef {import("./Chunk")} Chunk */ -/** @typedef {import("./ChunkGroup")} ChunkGroup */ -/** @typedef {import("./Compilation")} Compilation */ -/** @typedef {import("./DependenciesBlock")} DependenciesBlock */ -/** @typedef {import("./Dependency")} Dependency */ -/** @typedef {import("./Entrypoint")} Entrypoint */ -/** @typedef {import("./Module")} Module */ - -/** - * @typedef {Object} QueueItem - * @property {number} action - * @property {DependenciesBlock} block - * @property {Module} module - * @property {Chunk} chunk - * @property {ChunkGroup} chunkGroup - */ - -/** - * @typedef {Object} ChunkGroupInfo - * @property {ChunkGroup} chunkGroup the chunk group - * @property {Set} minAvailableModules current minimal set of modules available at this point - * @property {boolean} minAvailableModulesOwned true, if minAvailableModules is owned and can be modified - * @property {Set[]} availableModulesToBeMerged enqueued updates to the minimal set of available modules - * @property {QueueItem[]} skippedItems queue items that were skipped because module is already available in parent chunks (need to reconsider when minAvailableModules is shrinking) - * @property {Set} resultingAvailableModules set of modules available including modules from this chunk group - * @property {Set} children set of children chunk groups, that will be revisited when availableModules shrink - */ - -/** - * @typedef {Object} ChunkGroupDep - * @property {AsyncDependenciesBlock} block referencing block - * @property {ChunkGroup} chunkGroup referenced chunk group - */ - -/** - * @template T - * @param {Set} a first set - * @param {Set} b second set - * @returns {number} cmp - */ -const bySetSize = (a, b) => { - return b.size - a.size; -}; - -/** - * Extracts simplified info from the modules and their dependencies - * @param {Compilation} compilation the compilation - * @returns {Map, blocks: AsyncDependenciesBlock[]}>} the mapping block to modules and inner blocks - */ -const extraceBlockInfoMap = compilation => { - /** @type {Map, blocks: AsyncDependenciesBlock[]}>} */ - const blockInfoMap = new Map(); + updateHash(hash) { + hash.update(this.range + ""); + hash.update(this.expression + ""); + } +} - /** - * @param {Dependency} d dependency to iterate over - * @returns {void} - */ - const iteratorDependency = d => { - // We skip Dependencies without Reference - const ref = compilation.getDependencyReference(currentModule, d); - if (!ref) { - return; - } - // We skip Dependencies without Module pointer - const refModule = ref.module; - if (!refModule) { - return; - } - // We skip weak Dependencies - if (ref.weak) { +ConstDependency.Template = class ConstDependencyTemplate { + apply(dep, source) { + if (typeof dep.range === "number") { + source.insert(dep.range, dep.expression); return; } - blockInfoModules.add(refModule); - }; - - /** - * @param {AsyncDependenciesBlock} b blocks to prepare - * @returns {void} - */ - const iteratorBlockPrepare = b => { - blockInfoBlocks.push(b); - blockQueue.push(b); - }; + source.replace(dep.range[0], dep.range[1] - 1, dep.expression); + } +}; - /** @type {Module} */ - let currentModule; - /** @type {DependenciesBlock} */ - let block; - /** @type {DependenciesBlock[]} */ - let blockQueue; - /** @type {Set} */ - let blockInfoModules; - /** @type {AsyncDependenciesBlock[]} */ - let blockInfoBlocks; +module.exports = ConstDependency; - for (const module of compilation.modules) { - blockQueue = [module]; - currentModule = module; - while (blockQueue.length > 0) { - block = blockQueue.pop(); - blockInfoModules = new Set(); - blockInfoBlocks = []; - if (block.variables) { - for (const variable of block.variables) { - for (const dep of variable.dependencies) iteratorDependency(dep); - } - } +/***/ }), - if (block.dependencies) { - for (const dep of block.dependencies) iteratorDependency(dep); - } +/***/ 11583: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (block.blocks) { - for (const b of block.blocks) iteratorBlockPrepare(b); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const blockInfo = { - modules: blockInfoModules, - blocks: blockInfoBlocks - }; - blockInfoMap.set(block, blockInfo); - } - } +const Dependency = __webpack_require__(57282); +const CriticalDependencyWarning = __webpack_require__(54983); - return blockInfoMap; -}; +const regExpToString = r => (r ? r + "" : ""); -/** - * - * @param {Compilation} compilation the compilation - * @param {Entrypoint[]} inputChunkGroups input groups - * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules - * @param {Map} chunkDependencies dependencies for chunk groups - * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks - * @param {Set} allCreatedChunkGroups filled with all chunk groups that are created here +class ContextDependency extends Dependency { + // options: { request, recursive, regExp, include, exclude, mode, chunkName, groupOptions } + constructor(options) { + super(); + this.options = options; + this.userRequest = this.options.request; + /** @type {false | string} */ + this.critical = false; + this.hadGlobalOrStickyRegExp = false; + if (this.options.regExp.global || this.options.regExp.sticky) { + this.options.regExp = null; + this.hadGlobalOrStickyRegExp = true; + } + } + + getResourceIdentifier() { + return ( + `context${this.options.request} ${this.options.recursive} ` + + `${regExpToString(this.options.regExp)} ${regExpToString( + this.options.include + )} ${regExpToString(this.options.exclude)} ` + + `${this.options.mode} ${this.options.chunkName} ` + + `${JSON.stringify(this.options.groupOptions)}` + ); + } + + getWarnings() { + let warnings = super.getWarnings() || []; + if (this.critical) { + warnings.push(new CriticalDependencyWarning(this.critical)); + } + if (this.hadGlobalOrStickyRegExp) { + warnings.push( + new CriticalDependencyWarning( + "Contexts can't use RegExps with the 'g' or 'y' flags." + ) + ); + } + return warnings; + } +} + +// TODO remove in webpack 5 +Object.defineProperty(ContextDependency.prototype, "async", { + configurable: false, + get() { + throw new Error( + "ContextDependency.async was removed. Use ContextDependency.options.mode instead." + ); + }, + set() { + throw new Error( + "ContextDependency.async was removed. Pass options.mode to constructor instead" + ); + } +}); + +module.exports = ContextDependency; + + +/***/ }), + +/***/ 5594: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const ContextDependencyHelpers = exports; + +/** + * Escapes regular expression metacharacters + * @param {string} str String to quote + * @returns {string} Escaped string */ -const visitModules = ( - compilation, - inputChunkGroups, - chunkGroupInfoMap, - chunkDependencies, - blocksWithNestedBlocks, - allCreatedChunkGroups -) => { - const logger = compilation.getLogger("webpack.buildChunkGraph.visitModules"); - const { namedChunkGroups } = compilation; +const quotemeta = str => { + return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); +}; - logger.time("prepare"); - const blockInfoMap = extraceBlockInfoMap(compilation); +const splitContextFromPrefix = prefix => { + const idx = prefix.lastIndexOf("/"); + let context = "."; + if (idx >= 0) { + context = prefix.substr(0, idx); + prefix = `.${prefix.substr(idx)}`; + } + return { + context, + prefix + }; +}; - /** @type {Map} */ - const chunkGroupCounters = new Map(); - for (const chunkGroup of inputChunkGroups) { - chunkGroupCounters.set(chunkGroup, { - index: 0, - index2: 0 - }); +const splitQueryFromPostfix = postfix => { + const idx = postfix.indexOf("?"); + let query = ""; + if (idx >= 0) { + query = postfix.substr(idx); + postfix = postfix.substr(0, idx); } + return { + postfix, + query + }; +}; - let nextFreeModuleIndex = 0; - let nextFreeModuleIndex2 = 0; +ContextDependencyHelpers.create = ( + Dep, + range, + param, + expr, + options, + contextOptions, + // when parser is not passed in, expressions won't be walked + parser = null +) => { + if (param.isTemplateString()) { + let prefixRaw = param.quasis[0].string; + let postfixRaw = + param.quasis.length > 1 + ? param.quasis[param.quasis.length - 1].string + : ""; - /** @type {Map} */ - const blockChunkGroups = new Map(); + const valueRange = param.range; + const { context, prefix } = splitContextFromPrefix(prefixRaw); + const { postfix, query } = splitQueryFromPostfix(postfixRaw); - const ADD_AND_ENTER_MODULE = 0; - const ENTER_MODULE = 1; - const PROCESS_BLOCK = 2; - const LEAVE_MODULE = 3; + // When there are more than two quasis, the generated RegExp can be more precise + // We join the quasis with the expression regexp + const innerQuasis = param.quasis.slice(1, param.quasis.length - 1); + const innerRegExp = + options.wrappedContextRegExp.source + + innerQuasis + .map(q => quotemeta(q.string) + options.wrappedContextRegExp.source) + .join(""); - /** - * @param {QueueItem[]} queue the queue array (will be mutated) - * @param {ChunkGroup} chunkGroup chunk group - * @returns {QueueItem[]} the queue array again - */ - const reduceChunkGroupToQueueItem = (queue, chunkGroup) => { - for (const chunk of chunkGroup.chunks) { - const module = chunk.entryModule; - queue.push({ - action: ENTER_MODULE, - block: module, - module, - chunk, - chunkGroup + // Example: `./context/pre${e}inner${e}inner2${e}post?query` + // context: "./context" + // prefix: "./pre" + // innerQuasis: [BEE("inner"), BEE("inner2")] + // (BEE = BasicEvaluatedExpression) + // postfix: "post" + // query: "?query" + // regExp: /^\.\/pre.*inner.*inner2.*post$/ + const regExp = new RegExp( + `^${quotemeta(prefix)}${innerRegExp}${quotemeta(postfix)}$` + ); + const dep = new Dep( + Object.assign( + { + request: context + query, + recursive: options.wrappedContextRecursive, + regExp, + mode: "sync" + }, + contextOptions + ), + range, + valueRange + ); + dep.loc = expr.loc; + const replaces = []; + + param.parts.forEach((part, i) => { + if (i % 2 === 0) { + // Quasis or merged quasi + let range = part.range; + let value = part.string; + if (param.templateStringKind === "cooked") { + value = JSON.stringify(value); + value = value.slice(1, value.length - 1); + } + if (i === 0) { + // prefix + value = prefix; + range = [param.range[0], part.range[1]]; + value = + (param.templateStringKind === "cooked" ? "`" : "String.raw`") + + value; + } else if (i === param.parts.length - 1) { + // postfix + value = postfix; + range = [part.range[0], param.range[1]]; + value = value + "`"; + } else if ( + part.expression && + part.expression.type === "TemplateElement" && + part.expression.value.raw === value + ) { + // Shortcut when it's a single quasi and doesn't need to be replaced + return; + } + replaces.push({ + range, + value + }); + } else { + // Expression + if (parser) { + parser.walkExpression(part.expression); + } + } + }); + + dep.replaces = replaces; + dep.critical = + options.wrappedContextCritical && + "a part of the request of a dependency is an expression"; + return dep; + } else if ( + param.isWrapped() && + ((param.prefix && param.prefix.isString()) || + (param.postfix && param.postfix.isString())) + ) { + let prefixRaw = + param.prefix && param.prefix.isString() ? param.prefix.string : ""; + let postfixRaw = + param.postfix && param.postfix.isString() ? param.postfix.string : ""; + const prefixRange = + param.prefix && param.prefix.isString() ? param.prefix.range : null; + const postfixRange = + param.postfix && param.postfix.isString() ? param.postfix.range : null; + const valueRange = param.range; + const { context, prefix } = splitContextFromPrefix(prefixRaw); + const { postfix, query } = splitQueryFromPostfix(postfixRaw); + const regExp = new RegExp( + `^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta( + postfix + )}$` + ); + const dep = new Dep( + Object.assign( + { + request: context + query, + recursive: options.wrappedContextRecursive, + regExp, + mode: "sync" + }, + contextOptions + ), + range, + valueRange + ); + dep.loc = expr.loc; + const replaces = []; + if (prefixRange) { + replaces.push({ + range: prefixRange, + value: JSON.stringify(prefix) }); } - chunkGroupInfoMap.set(chunkGroup, { - chunkGroup, - minAvailableModules: new Set(), - minAvailableModulesOwned: true, - availableModulesToBeMerged: [], - skippedItems: [], - resultingAvailableModules: undefined, - children: undefined - }); - return queue; - }; + if (postfixRange) { + replaces.push({ + range: postfixRange, + value: JSON.stringify(postfix) + }); + } + dep.replaces = replaces; + dep.critical = + options.wrappedContextCritical && + "a part of the request of a dependency is an expression"; - // Start with the provided modules/chunks - /** @type {QueueItem[]} */ - let queue = inputChunkGroups - .reduce(reduceChunkGroupToQueueItem, []) - .reverse(); - /** @type {Map>} */ - const queueConnect = new Map(); - /** @type {Set} */ - const outdatedChunkGroupInfo = new Set(); - /** @type {QueueItem[]} */ - let queueDelayed = []; + if (parser && param.wrappedInnerExpressions) { + for (const part of param.wrappedInnerExpressions) { + if (part.expression) parser.walkExpression(part.expression); + } + } - logger.timeEnd("prepare"); + return dep; + } else { + const dep = new Dep( + Object.assign( + { + request: options.exprContextRequest, + recursive: options.exprContextRecursive, + regExp: options.exprContextRegExp, + mode: "sync" + }, + contextOptions + ), + range, + param.range + ); + dep.loc = expr.loc; + dep.critical = + options.exprContextCritical && + "the request of a dependency is an expression"; - /** @type {Module} */ - let module; - /** @type {Chunk} */ - let chunk; - /** @type {ChunkGroup} */ - let chunkGroup; - /** @type {DependenciesBlock} */ - let block; - /** @type {Set} */ - let minAvailableModules; - /** @type {QueueItem[]} */ - let skippedItems; + if (parser) { + parser.walkExpression(param.expression); + } - // For each async Block in graph - /** - * @param {AsyncDependenciesBlock} b iterating over each Async DepBlock - * @returns {void} - */ - const iteratorBlock = b => { - // 1. We create a chunk for this Block - // but only once (blockChunkGroups map) - let c = blockChunkGroups.get(b); - if (c === undefined) { - c = namedChunkGroups.get(b.chunkName); - if (c && c.isInitial()) { - compilation.errors.push( - new AsyncDependencyToInitialChunkError(b.chunkName, module, b.loc) + return dep; + } +}; + + +/***/ }), + +/***/ 6174: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class ContextDependencyTemplateAsId { + apply(dep, source, runtime) { + const moduleExports = runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + + if (dep.module) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); + } + } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + // TODO webpack 5 remove `prepend` it's no longer used + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}.resolve(${ + typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "" + }` ); - c = chunkGroup; } else { - c = compilation.addChunkInGroup( - b.groupOptions || b.chunkName, - module, - b.loc, - b.request + source.replace( + dep.range[0], + dep.range[1] - 1, + `${moduleExports}.resolve` ); - chunkGroupCounters.set(c, { index: 0, index2: 0 }); - blockChunkGroups.set(b, c); - allCreatedChunkGroups.add(c); } } else { - // TODO webpack 5 remove addOptions check - if (c.addOptions) c.addOptions(b.groupOptions); - c.addOrigin(module, b.loc, b.request); + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); } + } +} +module.exports = ContextDependencyTemplateAsId; - // 2. We store the Block+Chunk mapping as dependency for the chunk - let deps = chunkDependencies.get(chunkGroup); - if (!deps) chunkDependencies.set(chunkGroup, (deps = [])); - deps.push({ - block: b, - chunkGroup: c - }); - // 3. We create/update the chunk group info - let connectList = queueConnect.get(chunkGroup); - if (connectList === undefined) { - connectList = new Set(); - queueConnect.set(chunkGroup, connectList); - } - connectList.add(c); +/***/ }), - // 4. We enqueue the DependenciesBlock for traversal - queueDelayed.push({ - action: PROCESS_BLOCK, - block: b, - module: module, - chunk: c.chunks[0], - chunkGroup: c - }); - }; +/***/ 54380: +/***/ (function(module) { - // Iterative traversal of the Module graph - // Recursive would be simpler to write but could result in Stack Overflows - while (queue.length) { - logger.time("visiting"); - while (queue.length) { - const queueItem = queue.pop(); - module = queueItem.module; - block = queueItem.block; - chunk = queueItem.chunk; - if (chunkGroup !== queueItem.chunkGroup) { - chunkGroup = queueItem.chunkGroup; - const chunkGroupInfo = chunkGroupInfoMap.get(chunkGroup); - minAvailableModules = chunkGroupInfo.minAvailableModules; - skippedItems = chunkGroupInfo.skippedItems; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - switch (queueItem.action) { - case ADD_AND_ENTER_MODULE: { - if (minAvailableModules.has(module)) { - // already in parent chunks - // skip it for now, but enqueue for rechecking when minAvailableModules shrinks - skippedItems.push(queueItem); - break; - } - // We connect Module and Chunk when not already done - if (chunk.addModule(module)) { - module.addChunk(chunk); - } else { - // already connected, skip it - break; + +class ContextDependencyTemplateAsRequireCall { + apply(dep, source, runtime) { + const moduleExports = runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + + if (dep.module) { + if (dep.valueRange) { + if (Array.isArray(dep.replaces)) { + for (let i = 0; i < dep.replaces.length; i++) { + const rep = dep.replaces[i]; + source.replace(rep.range[0], rep.range[1] - 1, rep.value); } } - // fallthrough - case ENTER_MODULE: { - if (chunkGroup !== undefined) { - const index = chunkGroup.getModuleIndex(module); - if (index === undefined) { - chunkGroup.setModuleIndex( - module, - chunkGroupCounters.get(chunkGroup).index++ - ); - } - } + source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); + // TODO webpack 5 remove `prepend` it's no longer used + source.replace( + dep.range[0], + dep.valueRange[0] - 1, + `${moduleExports}(${ + typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "" + }` + ); + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } else { + source.replace(dep.range[0], dep.range[1] - 1, moduleExports); + } + } +} +module.exports = ContextDependencyTemplateAsRequireCall; - if (module.index === null) { - module.index = nextFreeModuleIndex++; - } - queue.push({ - action: LEAVE_MODULE, - block, - module, - chunk, - chunkGroup - }); - } - // fallthrough - case PROCESS_BLOCK: { - // get prepared block info - const blockInfo = blockInfoMap.get(block); +/***/ }), - // Buffer items because order need to be reverse to get indicies correct - const skipBuffer = []; - const queueBuffer = []; - // Traverse all referenced modules - for (const refModule of blockInfo.modules) { - if (chunk.containsModule(refModule)) { - // skip early if already connected - continue; - } - if (minAvailableModules.has(refModule)) { - // already in parent chunks, skip it for now - skipBuffer.push({ - action: ADD_AND_ENTER_MODULE, - block: refModule, - module: refModule, - chunk, - chunkGroup - }); - continue; - } - // enqueue the add and enter to enter in the correct order - // this is relevant with circular dependencies - queueBuffer.push({ - action: ADD_AND_ENTER_MODULE, - block: refModule, - module: refModule, - chunk, - chunkGroup - }); - } - // Add buffered items in reversed order - for (let i = skipBuffer.length - 1; i >= 0; i--) { - skippedItems.push(skipBuffer[i]); - } - for (let i = queueBuffer.length - 1; i >= 0; i--) { - queue.push(queueBuffer[i]); - } +/***/ 89079: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Traverse all Blocks - for (const block of blockInfo.blocks) iteratorBlock(block); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (blockInfo.blocks.length > 0 && module !== block) { - blocksWithNestedBlocks.add(block); - } - break; - } - case LEAVE_MODULE: { - if (chunkGroup !== undefined) { - const index = chunkGroup.getModuleIndex2(module); - if (index === undefined) { - chunkGroup.setModuleIndex2( - module, - chunkGroupCounters.get(chunkGroup).index2++ - ); - } - } +const ModuleDependency = __webpack_require__(90865); - if (module.index2 === null) { - module.index2 = nextFreeModuleIndex2++; - } - break; - } - } +class ContextElementDependency extends ModuleDependency { + constructor(request, userRequest) { + super(request); + if (userRequest) { + this.userRequest = userRequest; } - logger.timeEnd("visiting"); + } - while (queueConnect.size > 0) { - logger.time("calculating available modules"); + get type() { + return "context element"; + } +} - // Figure out new parents for chunk groups - // to get new available modules for these children - for (const [chunkGroup, targets] of queueConnect) { - const info = chunkGroupInfoMap.get(chunkGroup); - let minAvailableModules = info.minAvailableModules; +module.exports = ContextElementDependency; - // 1. Create a new Set of available modules at this points - const resultingAvailableModules = new Set(minAvailableModules); - for (const chunk of chunkGroup.chunks) { - for (const m of chunk.modulesIterable) { - resultingAvailableModules.add(m); - } - } - info.resultingAvailableModules = resultingAvailableModules; - if (info.children === undefined) { - info.children = targets; - } else { - for (const target of targets) { - info.children.add(target); - } - } - // 2. Update chunk group info - for (const target of targets) { - let chunkGroupInfo = chunkGroupInfoMap.get(target); - if (chunkGroupInfo === undefined) { - chunkGroupInfo = { - chunkGroup: target, - minAvailableModules: undefined, - minAvailableModulesOwned: undefined, - availableModulesToBeMerged: [], - skippedItems: [], - resultingAvailableModules: undefined, - children: undefined - }; - chunkGroupInfoMap.set(target, chunkGroupInfo); - } - chunkGroupInfo.availableModulesToBeMerged.push( - resultingAvailableModules - ); - outdatedChunkGroupInfo.add(chunkGroupInfo); - } - } - queueConnect.clear(); - logger.timeEnd("calculating available modules"); +/***/ }), - if (outdatedChunkGroupInfo.size > 0) { - logger.time("merging available modules"); - // Execute the merge - for (const info of outdatedChunkGroupInfo) { - const availableModulesToBeMerged = info.availableModulesToBeMerged; - let cachedMinAvailableModules = info.minAvailableModules; +/***/ 54983: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // 1. Get minimal available modules - // It doesn't make sense to traverse a chunk again with more available modules. - // This step calculates the minimal available modules and skips traversal when - // the list didn't shrink. - if (availableModulesToBeMerged.length > 1) { - availableModulesToBeMerged.sort(bySetSize); - } - let changed = false; - for (const availableModules of availableModulesToBeMerged) { - if (cachedMinAvailableModules === undefined) { - cachedMinAvailableModules = availableModules; - info.minAvailableModules = cachedMinAvailableModules; - info.minAvailableModulesOwned = false; - changed = true; - } else { - if (info.minAvailableModulesOwned) { - // We own it and can modify it - for (const m of cachedMinAvailableModules) { - if (!availableModules.has(m)) { - cachedMinAvailableModules.delete(m); - changed = true; - } - } - } else { - for (const m of cachedMinAvailableModules) { - if (!availableModules.has(m)) { - // cachedMinAvailableModules need to be modified - // but we don't own it - // construct a new Set as intersection of cachedMinAvailableModules and availableModules - /** @type {Set} */ - const newSet = new Set(); - const iterator = cachedMinAvailableModules[ - Symbol.iterator - ](); - /** @type {IteratorResult} */ - let it; - while (!(it = iterator.next()).done) { - const module = it.value; - if (module === m) break; - newSet.add(module); - } - while (!(it = iterator.next()).done) { - const module = it.value; - if (availableModules.has(module)) { - newSet.add(module); - } - } - cachedMinAvailableModules = newSet; - info.minAvailableModulesOwned = true; - info.minAvailableModules = newSet; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Update the cache from the first queue - // if the chunkGroup is currently cached - if (chunkGroup === info.chunkGroup) { - minAvailableModules = cachedMinAvailableModules; - } - changed = true; - break; - } - } - } - } - } - availableModulesToBeMerged.length = 0; - if (!changed) continue; +const WebpackError = __webpack_require__(97391); - // 2. Reconsider skipped items - for (const queueItem of info.skippedItems) { - queue.push(queueItem); - } - info.skippedItems.length = 0; +class CriticalDependencyWarning extends WebpackError { + constructor(message) { + super(); - // 3. Reconsider children chunk groups - if (info.children !== undefined) { - const chunkGroup = info.chunkGroup; - for (const c of info.children) { - let connectList = queueConnect.get(chunkGroup); - if (connectList === undefined) { - connectList = new Set(); - queueConnect.set(chunkGroup, connectList); - } - connectList.add(c); - } - } - } - outdatedChunkGroupInfo.clear(); - logger.timeEnd("merging available modules"); - } - } + this.name = "CriticalDependencyWarning"; + this.message = "Critical dependency: " + message; - // Run queueDelayed when all items of the queue are processed - // This is important to get the global indicing correct - // Async blocks should be processed after all sync blocks are processed - if (queue.length === 0) { - const tempQueue = queue; - queue = queueDelayed.reverse(); - queueDelayed = tempQueue; - } + Error.captureStackTrace(this, this.constructor); } -}; - -/** - * - * @param {Set} blocksWithNestedBlocks flag for blocks that have nested blocks - * @param {Map} chunkDependencies dependencies for chunk groups - * @param {Map} chunkGroupInfoMap mapping from chunk group to available modules - */ -const connectChunkGroups = ( - blocksWithNestedBlocks, - chunkDependencies, - chunkGroupInfoMap -) => { - /** @type {Set} */ - let resultingAvailableModules; +} - /** - * Helper function to check if all modules of a chunk are available - * - * @param {ChunkGroup} chunkGroup the chunkGroup to scan - * @param {Set} availableModules the comparitor set - * @returns {boolean} return true if all modules of a chunk are available - */ - const areModulesAvailable = (chunkGroup, availableModules) => { - for (const chunk of chunkGroup.chunks) { - for (const module of chunk.modulesIterable) { - if (!availableModules.has(module)) return false; - } - } - return true; - }; +module.exports = CriticalDependencyWarning; - // For each edge in the basic chunk graph - /** - * @param {ChunkGroupDep} dep the dependency used for filtering - * @returns {boolean} used to filter "edges" (aka Dependencies) that were pointing - * to modules that are already available. Also filters circular dependencies in the chunks graph - */ - const filterFn = dep => { - const depChunkGroup = dep.chunkGroup; - // TODO is this needed? - if (blocksWithNestedBlocks.has(dep.block)) return true; - if (areModulesAvailable(depChunkGroup, resultingAvailableModules)) { - return false; // break all modules are already available - } - return true; - }; - // For all deps, check if chunk groups need to be connected - for (const [chunkGroup, deps] of chunkDependencies) { - if (deps.length === 0) continue; +/***/ }), - // 1. Get info from chunk group info map - const info = chunkGroupInfoMap.get(chunkGroup); - resultingAvailableModules = info.resultingAvailableModules; +/***/ 53104: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // 2. Foreach edge - for (let i = 0; i < deps.length; i++) { - const dep = deps[i]; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Filter inline, rather than creating a new array from `.filter()` - // TODO check if inlining filterFn makes sense here - if (!filterFn(dep)) { - continue; - } - const depChunkGroup = dep.chunkGroup; - const depBlock = dep.block; - // 5. Connect block with chunk - GraphHelpers.connectDependenciesBlockAndChunkGroup( - depBlock, - depChunkGroup - ); +const DependencyReference = __webpack_require__(71722); +const NullDependency = __webpack_require__(5088); - // 6. Connect chunk with parent - GraphHelpers.connectChunkGroupParentAndChild(chunkGroup, depChunkGroup); - } +class DelegatedExportsDependency extends NullDependency { + constructor(originModule, exports) { + super(); + this.originModule = originModule; + this.exports = exports; } -}; -/** - * Remove all unconnected chunk groups - * @param {Compilation} compilation the compilation - * @param {Iterable} allCreatedChunkGroups all chunk groups that where created before - */ -const cleanupUnconnectedGroups = (compilation, allCreatedChunkGroups) => { - for (const chunkGroup of allCreatedChunkGroups) { - if (chunkGroup.getNumberOfParents() === 0) { - for (const chunk of chunkGroup.chunks) { - const idx = compilation.chunks.indexOf(chunk); - if (idx >= 0) compilation.chunks.splice(idx, 1); - chunk.remove("unconnected"); - } - chunkGroup.remove("unconnected"); - } + get type() { + return "delegated exports"; } -}; - -/** - * This method creates the Chunk graph from the Module graph - * @param {Compilation} compilation the compilation - * @param {Entrypoint[]} inputChunkGroups chunk groups which are processed - * @returns {void} - */ -const buildChunkGraph = (compilation, inputChunkGroups) => { - // SHARED STATE - /** @type {Map} */ - const chunkDependencies = new Map(); + getReference() { + return new DependencyReference(this.originModule, true, false); + } - /** @type {Set} */ - const allCreatedChunkGroups = new Set(); + getExports() { + return { + exports: this.exports, + dependencies: undefined + }; + } +} - /** @type {Map} */ - const chunkGroupInfoMap = new Map(); +module.exports = DelegatedExportsDependency; - /** @type {Set} */ - const blocksWithNestedBlocks = new Set(); - // PART ONE +/***/ }), - visitModules( - compilation, - inputChunkGroups, - chunkGroupInfoMap, - chunkDependencies, - blocksWithNestedBlocks, - allCreatedChunkGroups - ); +/***/ 25930: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // PART TWO +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - connectChunkGroups( - blocksWithNestedBlocks, - chunkDependencies, - chunkGroupInfoMap - ); +const ModuleDependency = __webpack_require__(90865); - // Cleaup work +class DelegatedSourceDependency extends ModuleDependency { + constructor(request) { + super(request); + } - cleanupUnconnectedGroups(compilation, allCreatedChunkGroups); -}; + get type() { + return "delegated source"; + } +} -module.exports = buildChunkGraph; +module.exports = DelegatedSourceDependency; /***/ }), -/***/ 22562: +/***/ 71722: /***/ (function(module) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Florent Cailhol @ooflorent */ -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("../Module")} Module */ -// TODO webpack 5 remove string type from a and b -/** - * Compare two locations - * @param {string|DependencyLocation} a A location node - * @param {string|DependencyLocation} b A location node - * @returns {-1|0|1} sorting comparator value - */ -module.exports = (a, b) => { - if (typeof a === "string") { - if (typeof b === "string") { - if (a < b) return -1; - if (a > b) return 1; - return 0; - } else if (typeof b === "object") { - return 1; - } else { - return 0; +class DependencyReference { + // TODO webpack 5: module must be dynamic, you must pass a function returning a module + // This is needed to remove the hack in ConcatenatedModule + // The problem is that the `module` in Dependency could be replaced i. e. because of Scope Hoisting + /** + * + * @param {Module} module the referenced module + * @param {string[] | boolean} importedNames imported named from the module + * @param {boolean=} weak if this is a weak reference + * @param {number} order the order information or NaN if don't care + */ + constructor(module, importedNames, weak = false, order = NaN) { + // TODO webpack 5: make it a getter + this.module = module; + // true: full object + // false: only sideeffects/no export + // array of strings: the exports with this names + this.importedNames = importedNames; + this.weak = !!weak; + this.order = order; + } + + /** + * @param {DependencyReference[]} array an array (will be modified) + * @returns {DependencyReference[]} the array again + */ + static sort(array) { + /** @type {WeakMap} */ + const originalOrder = new WeakMap(); + let i = 0; + for (const ref of array) { + originalOrder.set(ref, i++); } - } else if (typeof a === "object") { - if (typeof b === "string") { - return -1; - } else if (typeof b === "object") { - if ("start" in a && "start" in b) { - const ap = a.start; - const bp = b.start; - if (ap.line < bp.line) return -1; - if (ap.line > bp.line) return 1; - if (ap.column < bp.column) return -1; - if (ap.column > bp.column) return 1; - } - if ("name" in a && "name" in b) { - if (a.name < b.name) return -1; - if (a.name > b.name) return 1; - } - if ("index" in a && "index" in b) { - if (a.index < b.index) return -1; - if (a.index > b.index) return 1; + return array.sort((a, b) => { + const aOrder = a.order; + const bOrder = b.order; + if (isNaN(aOrder)) { + if (!isNaN(bOrder)) { + return 1; + } + } else { + if (isNaN(bOrder)) { + return -1; + } + if (aOrder !== bOrder) { + return aOrder - bOrder; + } } - return 0; - } else { - return 0; - } + const aOrg = originalOrder.get(a); + const bOrg = originalOrder.get(b); + return aOrg - bOrg; + }); } -}; +} + +module.exports = DependencyReference; /***/ }), -/***/ 72890: +/***/ 66279: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const fs = __webpack_require__(35747); -const path = __webpack_require__(85622); -const mkdirp = __webpack_require__(50998); -const { Tracer } = __webpack_require__(92430); -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(49049); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** @typedef {import("../../declarations/plugins/debug/ProfilingPlugin").ProfilingPluginOptions} ProfilingPluginOptions */ +const Dependency = __webpack_require__(57282); -let inspector = undefined; +class DllEntryDependency extends Dependency { + constructor(dependencies, name) { + super(); + this.dependencies = dependencies; + this.name = name; + } -try { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - inspector = __webpack_require__(57012); -} catch (e) { - console.log("Unable to CPU profile in < node 8.0"); + get type() { + return "dll entry"; + } } -class Profiler { - constructor(inspector) { - this.session = undefined; - this.inspector = inspector; - } +module.exports = DllEntryDependency; - hasSession() { - return this.session !== undefined; - } - startProfiling() { - if (this.inspector === undefined) { - return Promise.resolve(); - } +/***/ }), - try { - this.session = new inspector.Session(); - this.session.connect(); - } catch (_) { - this.session = undefined; - return Promise.resolve(); - } +/***/ 75159: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return Promise.all([ - this.sendCommand("Profiler.setSamplingInterval", { - interval: 100 - }), - this.sendCommand("Profiler.enable"), - this.sendCommand("Profiler.start") - ]); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - sendCommand(method, params) { - if (this.hasSession()) { - return new Promise((res, rej) => { - return this.session.post(method, params, (err, params) => { - if (err !== null) { - rej(err); - } else { - res(params); - } - }); - }); - } else { - return Promise.resolve(); - } - } - destroy() { - if (this.hasSession()) { - this.session.disconnect(); - } +const NullDependency = __webpack_require__(5088); +const HarmonyImportDependency = __webpack_require__(81599); - return Promise.resolve(); +class HarmonyAcceptDependency extends NullDependency { + constructor(range, dependencies, hasCallback) { + super(); + this.range = range; + this.dependencies = dependencies; + this.hasCallback = hasCallback; } - stopProfiling() { - return this.sendCommand("Profiler.stop"); + get type() { + return "accepted harmony modules"; } } -/** - * an object that wraps Tracer and Profiler with a counter - * @typedef {Object} Trace - * @property {Tracer} trace instance of Tracer - * @property {number} counter Counter - * @property {Profiler} profiler instance of Profiler - * @property {Function} end the end function - */ +HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate { + apply(dep, source, runtime) { + const content = dep.dependencies + .filter(dependency => + HarmonyImportDependency.Template.isImportEmitted(dependency, source) + ) + .map(dependency => dependency.getImportStatement(true, runtime)) + .join(""); -/** - * @param {string} outputPath The location where to write the log. - * @returns {Trace} The trace object - */ -const createTrace = outputPath => { - const trace = new Tracer({ - noStream: true - }); - const profiler = new Profiler(inspector); - if (/\/|\\/.test(outputPath)) { - const dirPath = path.dirname(outputPath); - mkdirp.sync(dirPath); + if (dep.hasCallback) { + source.insert( + dep.range[0], + `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(` + ); + source.insert( + dep.range[1], + ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }.bind(this)" + ); + return; + } + + source.insert(dep.range[1] - 0.5, `, function() { ${content} }`); } - const fsStream = fs.createWriteStream(outputPath); +}; - let counter = 0; +module.exports = HarmonyAcceptDependency; - trace.pipe(fsStream); - // These are critical events that need to be inserted so that tools like - // chrome dev tools can load the profile. - trace.instantEvent({ - name: "TracingStartedInPage", - id: ++counter, - cat: ["disabled-by-default-devtools.timeline"], - args: { - data: { - sessionId: "-1", - page: "0xfff", - frames: [ - { - frame: "0xfff", - url: "webpack", - name: "" - } - ] - } - } - }); - trace.instantEvent({ - name: "TracingStartedInBrowser", - id: ++counter, - cat: ["disabled-by-default-devtools.timeline"], - args: { - data: { - sessionId: "-1" - } - } - }); +/***/ }), - return { - trace, - counter, - profiler, - end: callback => { - // Wait until the write stream finishes. - fsStream.on("finish", () => { - callback(); - }); - // Tear down the readable trace stream. - trace.push(null); - } - }; -}; +/***/ 66136: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const pluginName = "ProfilingPlugin"; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -class ProfilingPlugin { - /** - * @param {ProfilingPluginOptions=} opts options object - */ - constructor(opts) { - validateOptions(schema, opts || {}, "Profiling plugin"); - opts = opts || {}; - this.outputPath = opts.outputPath || "events.json"; +const HarmonyImportDependency = __webpack_require__(81599); + +class HarmonyAcceptImportDependency extends HarmonyImportDependency { + constructor(request, originModule, parserScope) { + super(request, originModule, NaN, parserScope); + this.weak = true; } - apply(compiler) { - const tracer = createTrace(this.outputPath); - tracer.profiler.startProfiling(); + get type() { + return "harmony accept"; + } +} - // Compiler Hooks - Object.keys(compiler.hooks).forEach(hookName => { - compiler.hooks[hookName].intercept( - makeInterceptorFor("Compiler", tracer)(hookName) - ); - }); +HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate extends HarmonyImportDependency.Template { + apply(dep, source, runtime) {} +}; - Object.keys(compiler.resolverFactory.hooks).forEach(hookName => { - compiler.resolverFactory.hooks[hookName].intercept( - makeInterceptorFor("Resolver", tracer)(hookName) - ); - }); +module.exports = HarmonyAcceptImportDependency; - compiler.hooks.compilation.tap( - pluginName, - (compilation, { normalModuleFactory, contextModuleFactory }) => { - interceptAllHooksFor(compilation, tracer, "Compilation"); - interceptAllHooksFor( - normalModuleFactory, - tracer, - "Normal Module Factory" - ); - interceptAllHooksFor( - contextModuleFactory, - tracer, - "Context Module Factory" - ); - interceptAllParserHooks(normalModuleFactory, tracer); - interceptTemplateInstancesFrom(compilation, tracer); - } - ); - // We need to write out the CPU profile when we are all done. - compiler.hooks.done.tapAsync( - { - name: pluginName, - stage: Infinity - }, - (stats, callback) => { - tracer.profiler.stopProfiling().then(parsedResults => { - if (parsedResults === undefined) { - tracer.profiler.destroy(); - tracer.trace.flush(); - tracer.end(callback); - return; - } +/***/ }), - const cpuStartTime = parsedResults.profile.startTime; - const cpuEndTime = parsedResults.profile.endTime; +/***/ 1533: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - tracer.trace.completeEvent({ - name: "TaskQueueManager::ProcessTaskFromWorkQueue", - id: ++tracer.counter, - cat: ["toplevel"], - ts: cpuStartTime, - args: { - src_file: "../../ipc/ipc_moji_bootstrap.cc", - src_func: "Accept" - } - }); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - tracer.trace.completeEvent({ - name: "EvaluateScript", - id: ++tracer.counter, - cat: ["devtools.timeline"], - ts: cpuStartTime, - dur: cpuEndTime - cpuStartTime, - args: { - data: { - url: "webpack", - lineNumber: 1, - columnNumber: 1, - frame: "0xFFF" - } - } - }); +const NullDependency = __webpack_require__(5088); - tracer.trace.instantEvent({ - name: "CpuProfile", - id: ++tracer.counter, - cat: ["disabled-by-default-devtools.timeline"], - ts: cpuEndTime, - args: { - data: { - cpuProfile: parsedResults.profile - } - } - }); +class HarmonyCompatibilityDependency extends NullDependency { + constructor(originModule) { + super(); + this.originModule = originModule; + } - tracer.profiler.destroy(); - tracer.trace.flush(); - tracer.end(callback); - }); - } - ); + get type() { + return "harmony export header"; } } -const interceptTemplateInstancesFrom = (compilation, tracer) => { - const { - mainTemplate, - chunkTemplate, - hotUpdateChunkTemplate, - moduleTemplates - } = compilation; - - const { javascript, webassembly } = moduleTemplates; - - [ - { - instance: mainTemplate, - name: "MainTemplate" - }, - { - instance: chunkTemplate, - name: "ChunkTemplate" - }, - { - instance: hotUpdateChunkTemplate, - name: "HotUpdateChunkTemplate" - }, - { - instance: javascript, - name: "JavaScriptModuleTemplate" - }, - { - instance: webassembly, - name: "WebAssemblyModuleTemplate" +HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate { + apply(dep, source, runtime) { + const usedExports = dep.originModule.usedExports; + if (usedExports !== false && !Array.isArray(usedExports)) { + const content = runtime.defineEsModuleFlagStatement({ + exportsArgument: dep.originModule.exportsArgument + }); + source.insert(-10, content); } - ].forEach(templateObject => { - Object.keys(templateObject.instance.hooks).forEach(hookName => { - templateObject.instance.hooks[hookName].intercept( - makeInterceptorFor(templateObject.name, tracer)(hookName) - ); - }); - }); -}; - -const interceptAllHooksFor = (instance, tracer, logLabel) => { - if (Reflect.has(instance, "hooks")) { - Object.keys(instance.hooks).forEach(hookName => { - instance.hooks[hookName].intercept( - makeInterceptorFor(logLabel, tracer)(hookName) - ); - }); } }; -const interceptAllParserHooks = (moduleFactory, tracer) => { - const moduleTypes = [ - "javascript/auto", - "javascript/dynamic", - "javascript/esm", - "json", - "webassembly/experimental" - ]; +module.exports = HarmonyCompatibilityDependency; - moduleTypes.forEach(moduleType => { - moduleFactory.hooks.parser - .for(moduleType) - .tap("ProfilingPlugin", (parser, parserOpts) => { - interceptAllHooksFor(parser, tracer, "Parser"); - }); - }); -}; -const makeInterceptorFor = (instance, tracer) => hookName => ({ - register: ({ name, type, context, fn }) => { - const newFn = makeNewProfiledTapFn(hookName, tracer, { - name, - type, - fn - }); - return { - name, - type, - context, - fn: newFn - }; - } -}); +/***/ }), -// TODO improve typing -/** @typedef {(...args: TODO[]) => void | Promise} PluginFunction */ +/***/ 59310: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * @param {string} hookName Name of the hook to profile. - * @param {Trace} tracer The trace object. - * @param {object} options Options for the profiled fn. - * @param {string} options.name Plugin name - * @param {string} options.type Plugin type (sync | async | promise) - * @param {PluginFunction} options.fn Plugin function - * @returns {PluginFunction} Chainable hooked function. - */ -const makeNewProfiledTapFn = (hookName, tracer, { name, type, fn }) => { - const defaultCategory = ["blink.user_timing"]; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - switch (type) { - case "promise": - return (...args) => { - const id = ++tracer.counter; - tracer.trace.begin({ - name, - id, - cat: defaultCategory - }); - const promise = /** @type {Promise<*>} */ (fn(...args)); - return promise.then(r => { - tracer.trace.end({ - name, - id, - cat: defaultCategory - }); - return r; - }); - }; - case "async": - return (...args) => { - const id = ++tracer.counter; - tracer.trace.begin({ - name, - id, - cat: defaultCategory - }); - const callback = args.pop(); - fn(...args, (...r) => { - tracer.trace.end({ - name, - id, - cat: defaultCategory - }); - callback(...r); - }); - }; - case "sync": - return (...args) => { - const id = ++tracer.counter; - // Do not instrument ourself due to the CPU - // profile needing to be the last event in the trace. - if (name === pluginName) { - return fn(...args); + +const HarmonyCompatibilityDependency = __webpack_require__(1533); +const HarmonyInitDependency = __webpack_require__(27204); + +module.exports = class HarmonyDetectionParserPlugin { + apply(parser) { + parser.hooks.program.tap("HarmonyDetectionParserPlugin", ast => { + const isStrictHarmony = parser.state.module.type === "javascript/esm"; + const isHarmony = + isStrictHarmony || + ast.body.some( + statement => + statement.type === "ImportDeclaration" || + statement.type === "ExportDefaultDeclaration" || + statement.type === "ExportNamedDeclaration" || + statement.type === "ExportAllDeclaration" + ); + if (isHarmony) { + const module = parser.state.module; + const compatDep = new HarmonyCompatibilityDependency(module); + compatDep.loc = { + start: { + line: -1, + column: 0 + }, + end: { + line: -1, + column: 0 + }, + index: -3 + }; + module.addDependency(compatDep); + const initDep = new HarmonyInitDependency(module); + initDep.loc = { + start: { + line: -1, + column: 0 + }, + end: { + line: -1, + column: 0 + }, + index: -2 + }; + module.addDependency(initDep); + parser.state.harmonyParserScope = parser.state.harmonyParserScope || {}; + parser.scope.isStrict = true; + module.buildMeta.exportsType = "namespace"; + module.buildInfo.strict = true; + module.buildInfo.exportsArgument = "__webpack_exports__"; + if (isStrictHarmony) { + module.buildMeta.strictHarmonyModule = true; + module.buildInfo.moduleArgument = "__webpack_module__"; } + } + }); - tracer.trace.begin({ - name, - id, - cat: defaultCategory - }); - let r; - try { - r = fn(...args); - } catch (error) { - tracer.trace.end({ + const skipInHarmony = () => { + const module = parser.state.module; + if (module && module.buildMeta && module.buildMeta.exportsType) { + return true; + } + }; + + const nullInHarmony = () => { + const module = parser.state.module; + if (module && module.buildMeta && module.buildMeta.exportsType) { + return null; + } + }; + + const nonHarmonyIdentifiers = ["define", "exports"]; + for (const identifer of nonHarmonyIdentifiers) { + parser.hooks.evaluateTypeof + .for(identifer) + .tap("HarmonyDetectionParserPlugin", nullInHarmony); + parser.hooks.typeof + .for(identifer) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + parser.hooks.evaluate + .for(identifer) + .tap("HarmonyDetectionParserPlugin", nullInHarmony); + parser.hooks.expression + .for(identifer) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + parser.hooks.call + .for(identifer) + .tap("HarmonyDetectionParserPlugin", skipInHarmony); + } + } +}; + + +/***/ }), + +/***/ 49180: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const HarmonyExportExpressionDependency = __webpack_require__(84245); +const HarmonyImportSideEffectDependency = __webpack_require__(79171); +const HarmonyExportHeaderDependency = __webpack_require__(21320); +const HarmonyExportSpecifierDependency = __webpack_require__(34834); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); +const ConstDependency = __webpack_require__(71101); + +module.exports = class HarmonyExportDependencyParserPlugin { + constructor(moduleOptions) { + this.strictExportPresence = moduleOptions.strictExportPresence; + } + + apply(parser) { + parser.hooks.export.tap( + "HarmonyExportDependencyParserPlugin", + statement => { + const dep = new HarmonyExportHeaderDependency( + statement.declaration && statement.declaration.range, + statement.range + ); + dep.loc = Object.create(statement.loc); + dep.loc.index = -1; + parser.state.current.addDependency(dep); + return true; + } + ); + parser.hooks.exportImport.tap( + "HarmonyExportDependencyParserPlugin", + (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency("", statement.range); + clearDep.loc = Object.create(statement.loc); + clearDep.loc.index = -1; + parser.state.current.addDependency(clearDep); + const sideEffectDep = new HarmonyImportSideEffectDependency( + source, + parser.state.module, + parser.state.lastHarmonyImportOrder, + parser.state.harmonyParserScope + ); + sideEffectDep.loc = Object.create(statement.loc); + sideEffectDep.loc.index = -1; + parser.state.current.addDependency(sideEffectDep); + return true; + } + ); + parser.hooks.exportExpression.tap( + "HarmonyExportDependencyParserPlugin", + (statement, expr) => { + const comments = parser.getComments([ + statement.range[0], + expr.range[0] + ]); + const dep = new HarmonyExportExpressionDependency( + parser.state.module, + expr.range, + statement.range, + comments + .map(c => { + switch (c.type) { + case "Block": + return `/*${c.value}*/`; + case "Line": + return `//${c.value}\n`; + } + return ""; + }) + .join("") + ); + dep.loc = Object.create(statement.loc); + dep.loc.index = -1; + parser.state.current.addDependency(dep); + return true; + } + ); + parser.hooks.exportDeclaration.tap( + "HarmonyExportDependencyParserPlugin", + statement => {} + ); + parser.hooks.exportSpecifier.tap( + "HarmonyExportDependencyParserPlugin", + (statement, id, name, idx) => { + const rename = parser.scope.renames.get(id); + let dep; + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + harmonyNamedExports.add(name); + if (rename === "imported var") { + const settings = parser.state.harmonySpecifier.get(id); + dep = new HarmonyExportImportedSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + settings.id, name, + harmonyNamedExports, + null, + this.strictExportPresence + ); + } else { + dep = new HarmonyExportSpecifierDependency( + parser.state.module, id, - cat: defaultCategory - }); - throw error; + name + ); } - tracer.trace.end({ - name, + dep.loc = Object.create(statement.loc); + dep.loc.index = idx; + parser.state.current.addDependency(dep); + return true; + } + ); + parser.hooks.exportImportSpecifier.tap( + "HarmonyExportDependencyParserPlugin", + (statement, source, id, name, idx) => { + const harmonyNamedExports = (parser.state.harmonyNamedExports = + parser.state.harmonyNamedExports || new Set()); + let harmonyStarExports = null; + if (name) { + harmonyNamedExports.add(name); + } else { + harmonyStarExports = parser.state.harmonyStarExports = + parser.state.harmonyStarExports || []; + } + const dep = new HarmonyExportImportedSpecifierDependency( + source, + parser.state.module, + parser.state.lastHarmonyImportOrder, + parser.state.harmonyParserScope, id, - cat: defaultCategory - }); - return r; - }; - default: - break; + name, + harmonyNamedExports, + harmonyStarExports && harmonyStarExports.slice(), + this.strictExportPresence + ); + if (harmonyStarExports) { + harmonyStarExports.push(dep); + } + dep.loc = Object.create(statement.loc); + dep.loc.index = idx; + parser.state.current.addDependency(dep); + return true; + } + ); } }; -module.exports = ProfilingPlugin; -module.exports.Profiler = Profiler; - /***/ }), -/***/ 67045: +/***/ 84245: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -97058,141 +96078,100 @@ module.exports.Profiler = Profiler; const NullDependency = __webpack_require__(5088); -class AMDDefineDependency extends NullDependency { - constructor(range, arrayRange, functionRange, objectRange, namedModule) { +class HarmonyExportExpressionDependency extends NullDependency { + constructor(originModule, range, rangeStatement, prefix) { super(); + this.originModule = originModule; this.range = range; - this.arrayRange = arrayRange; - this.functionRange = functionRange; - this.objectRange = objectRange; - this.namedModule = namedModule; - this.localModule = null; + this.rangeStatement = rangeStatement; + this.prefix = prefix; } get type() { - return "amd define"; + return "harmony export expression"; } -} -AMDDefineDependency.Template = class AMDDefineDependencyTemplate { - get definitions() { + getExports() { return { - f: [ - "var __WEBPACK_AMD_DEFINE_RESULT__;", - `!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` - ], - o: ["", "!(module.exports = #)"], - of: [ - "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;", - `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : - __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` - ], - af: [ - "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", - `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` - ], - ao: ["", "!(#, module.exports = #)"], - aof: [ - "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", - `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` - ], - lf: [ - "var XXX, XXXmodule;", - "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = #.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))" - ], - lo: ["var XXX;", "!(XXX = #)"], - lof: [ - "var XXX, XXXfactory, XXXmodule;", - "!(XXXfactory = (#), (XXXmodule = { id: YYY, exports: {}, loaded: false }), XXX = (typeof XXXfactory === 'function' ? (XXXfactory.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule)) : XXXfactory), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports))" - ], - laf: [ - "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX;", - "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = ((#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)))" - ], - lao: ["var XXX;", "!(#, XXX = #)"], - laof: [ - "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_FACTORY__, XXX;", - `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), - XXX = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__))` - ] + exports: ["default"], + dependencies: undefined }; } +} - apply(dependency, source) { - const branch = this.branch(dependency); - const defAndText = this.definitions[branch]; - const definitions = defAndText[0]; - const text = defAndText[1]; - this.replace(dependency, source, definitions, text); - } +HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTemplate { + apply(dep, source) { + const used = dep.originModule.isUsed("default"); + const content = this.getContent(dep.originModule, used); - localModuleVar(dependency) { - return ( - dependency.localModule && - dependency.localModule.used && - dependency.localModule.variableName() - ); - } + if (dep.range) { + source.replace( + dep.rangeStatement[0], + dep.range[0] - 1, + content + "(" + dep.prefix + ); + source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); + return; + } - branch(dependency) { - const localModuleVar = this.localModuleVar(dependency) ? "l" : ""; - const arrayRange = dependency.arrayRange ? "a" : ""; - const objectRange = dependency.objectRange ? "o" : ""; - const functionRange = dependency.functionRange ? "f" : ""; - return localModuleVar + arrayRange + objectRange + functionRange; + source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); } - replace(dependency, source, definition, text) { - const localModuleVar = this.localModuleVar(dependency); - if (localModuleVar) { - text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); - definition = definition.replace( - /XXX/g, - localModuleVar.replace(/\$/g, "$$$$") - ); + getContent(module, used) { + const exportsName = module.exportsArgument; + if (used) { + return `/* harmony default export */ ${exportsName}[${JSON.stringify( + used + )}] = `; } + return "/* unused harmony default export */ var _unused_webpack_default_export = "; + } +}; - if (dependency.namedModule) { - text = text.replace(/YYY/g, JSON.stringify(dependency.namedModule)); - } +module.exports = HarmonyExportExpressionDependency; - const texts = text.split("#"); - if (definition) source.insert(0, definition); +/***/ }), - let current = dependency.range[0]; - if (dependency.arrayRange) { - source.replace(current, dependency.arrayRange[0] - 1, texts.shift()); - current = dependency.arrayRange[1]; - } +/***/ 21320: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (dependency.objectRange) { - source.replace(current, dependency.objectRange[0] - 1, texts.shift()); - current = dependency.objectRange[1]; - } else if (dependency.functionRange) { - source.replace(current, dependency.functionRange[0] - 1, texts.shift()); - current = dependency.functionRange[1]; - } - source.replace(current, dependency.range[1] - 1, texts.shift()); - if (texts.length > 0) throw new Error("Implementation error"); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const NullDependency = __webpack_require__(5088); + +class HarmonyExportHeaderDependency extends NullDependency { + constructor(range, rangeStatement) { + super(); + this.range = range; + this.rangeStatement = rangeStatement; + } + + get type() { + return "harmony export header"; + } +} + +HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate { + apply(dep, source) { + const content = ""; + const replaceUntil = dep.range + ? dep.range[0] - 1 + : dep.rangeStatement[1] - 1; + source.replace(dep.rangeStatement[0], replaceUntil, content); } }; -module.exports = AMDDefineDependency; +module.exports = HarmonyExportHeaderDependency; /***/ }), -/***/ 27057: +/***/ 22864: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -97202,1002 +96181,664 @@ module.exports = AMDDefineDependency; */ -const AMDRequireItemDependency = __webpack_require__(34345); -const AMDRequireContextDependency = __webpack_require__(99890); -const ConstDependency = __webpack_require__(71101); -const AMDDefineDependency = __webpack_require__(67045); -const AMDRequireArrayDependency = __webpack_require__(63960); -const LocalModuleDependency = __webpack_require__(56570); -const ContextDependencyHelpers = __webpack_require__(5594); -const LocalModulesHelpers = __webpack_require__(39658); +const DependencyReference = __webpack_require__(71722); +const HarmonyImportDependency = __webpack_require__(81599); +const Template = __webpack_require__(96066); +const HarmonyLinkingError = __webpack_require__(30327); -const isBoundFunctionExpression = expr => { - if (expr.type !== "CallExpression") return false; - if (expr.callee.type !== "MemberExpression") return false; - if (expr.callee.computed) return false; - if (expr.callee.object.type !== "FunctionExpression") return false; - if (expr.callee.property.type !== "Identifier") return false; - if (expr.callee.property.name !== "bind") return false; - return true; -}; +/** @typedef {import("../Module")} Module */ -const isUnboundFunctionExpression = expr => { - if (expr.type === "FunctionExpression") return true; - if (expr.type === "ArrowFunctionExpression") return true; - return false; -}; +/** @typedef {"missing"|"unused"|"empty-star"|"reexport-non-harmony-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-non-harmony-default-strict"|"reexport-fake-namespace-object"|"rexport-non-harmony-undefined"|"safe-reexport"|"checked-reexport"|"dynamic-reexport"} ExportModeType */ -const isCallable = expr => { - if (isUnboundFunctionExpression(expr)) return true; - if (isBoundFunctionExpression(expr)) return true; - return false; -}; +/** @type {Map} */ +const EMPTY_MAP = new Map(); -class AMDDefineDependencyParserPlugin { - constructor(options) { - this.options = options; +class ExportMode { + /** + * @param {ExportModeType} type type of the mode + */ + constructor(type) { + /** @type {ExportModeType} */ + this.type = type; + /** @type {string|null} */ + this.name = null; + /** @type {Map} */ + this.map = EMPTY_MAP; + /** @type {Set|null} */ + this.ignored = null; + /** @type {Module|null} */ + this.module = null; + /** @type {string|null} */ + this.userRequest = null; } +} - apply(parser) { - parser.hooks.call - .for("define") - .tap( - "AMDDefineDependencyParserPlugin", - this.processCallDefine.bind(this, parser) - ); - } +const EMPTY_STAR_MODE = new ExportMode("empty-star"); - processArray(parser, expr, param, identifiers, namedModule) { - if (param.isArray()) { - param.items.forEach((param, idx) => { - if ( - param.isString() && - ["require", "module", "exports"].includes(param.string) - ) - identifiers[idx] = param.string; - const result = this.processItem(parser, expr, param, namedModule); - if (result === undefined) { - this.processContext(parser, expr, param); - } - }); - return true; - } else if (param.isConstArray()) { - const deps = []; - param.array.forEach((request, idx) => { - let dep; - let localModule; - if (request === "require") { - identifiers[idx] = request; - dep = "__webpack_require__"; - } else if (["exports", "module"].includes(request)) { - identifiers[idx] = request; - dep = request; - } else if ( - (localModule = LocalModulesHelpers.getLocalModule( - parser.state, - request - )) - ) { - dep = new LocalModuleDependency(localModule, undefined, false); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - } else { - dep = this.newRequireItemDependency(request); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - } - deps.push(dep); - }); - const dep = this.newRequireArrayDependency(deps, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } +class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { + constructor( + request, + originModule, + sourceOrder, + parserScope, + id, + name, + activeExports, + otherStarExports, + strictExportPresence + ) { + super(request, originModule, sourceOrder, parserScope); + this.id = id; + this.redirectedId = undefined; + this.name = name; + this.activeExports = activeExports; + this.otherStarExports = otherStarExports; + this.strictExportPresence = strictExportPresence; } - processItem(parser, expr, param, namedModule) { - if (param.isConditional()) { - param.options.forEach(param => { - const result = this.processItem(parser, expr, param); - if (result === undefined) { - this.processContext(parser, expr, param); - } - }); - return true; - } else if (param.isString()) { - let dep, localModule; - if (param.string === "require") { - dep = new ConstDependency("__webpack_require__", param.range); - } else if (["require", "exports", "module"].includes(param.string)) { - dep = new ConstDependency(param.string, param.range); - } else if ( - (localModule = LocalModulesHelpers.getLocalModule( - parser.state, - param.string, - namedModule - )) - ) { - dep = new LocalModuleDependency(localModule, param.range, false); - } else { - dep = this.newRequireItemDependency(param.string, param.range); - } - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } + + get type() { + return "harmony export imported specifier"; } - processContext(parser, expr, param) { - const dep = ContextDependencyHelpers.create( - AMDRequireContextDependency, - param.range, - param, - expr, - this.options, - {}, - parser - ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; + + get _id() { + return this.redirectedId || this.id; } - processCallDefine(parser, expr) { - let array, fn, obj, namedModule; - switch (expr.arguments.length) { - case 1: - if (isCallable(expr.arguments[0])) { - // define(f() {…}) - fn = expr.arguments[0]; - } else if (expr.arguments[0].type === "ObjectExpression") { - // define({…}) - obj = expr.arguments[0]; - } else { - // define(expr) - // unclear if function or object - obj = fn = expr.arguments[0]; - } - break; - case 2: - if (expr.arguments[0].type === "Literal") { - namedModule = expr.arguments[0].value; - // define("…", …) - if (isCallable(expr.arguments[1])) { - // define("…", f() {…}) - fn = expr.arguments[1]; - } else if (expr.arguments[1].type === "ObjectExpression") { - // define("…", {…}) - obj = expr.arguments[1]; - } else { - // define("…", expr) - // unclear if function or object - obj = fn = expr.arguments[1]; - } - } else { - array = expr.arguments[0]; - if (isCallable(expr.arguments[1])) { - // define([…], f() {}) - fn = expr.arguments[1]; - } else if (expr.arguments[1].type === "ObjectExpression") { - // define([…], {…}) - obj = expr.arguments[1]; - } else { - // define([…], expr) - // unclear if function or object - obj = fn = expr.arguments[1]; - } - } - break; - case 3: - // define("…", […], f() {…}) - namedModule = expr.arguments[0].value; - array = expr.arguments[1]; - if (isCallable(expr.arguments[2])) { - // define("…", […], f() {}) - fn = expr.arguments[2]; - } else if (expr.arguments[2].type === "ObjectExpression") { - // define("…", […], {…}) - obj = expr.arguments[2]; - } else { - // define("…", […], expr) - // unclear if function or object - obj = fn = expr.arguments[2]; - } - break; - default: - return; + getMode(ignoreUnused) { + const name = this.name; + const id = this._id; + const used = this.originModule.isUsed(name); + const importedModule = this._module; + + if (!importedModule) { + const mode = new ExportMode("missing"); + mode.userRequest = this.userRequest; + return mode; } - let fnParams = null; - let fnParamsOffset = 0; - if (fn) { - if (isUnboundFunctionExpression(fn)) { - fnParams = fn.params; - } else if (isBoundFunctionExpression(fn)) { - fnParams = fn.callee.object.params; - fnParamsOffset = fn.arguments.length - 1; - if (fnParamsOffset < 0) { - fnParamsOffset = 0; - } - } + + if ( + !ignoreUnused && + (name ? !used : this.originModule.usedExports === false) + ) { + const mode = new ExportMode("unused"); + mode.name = name || "*"; + return mode; } - let fnRenames = parser.scope.renames.createChild(); - if (array) { - const identifiers = {}; - const param = parser.evaluateExpression(array); - const result = this.processArray( - parser, - expr, - param, - identifiers, - namedModule - ); - if (!result) return; - if (fnParams) { - fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { - if (identifiers[idx]) { - fnRenames.set(param.name, identifiers[idx]); - return false; - } - return true; - }); - } - } else { - const identifiers = ["require", "exports", "module"]; - if (fnParams) { - fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { - if (identifiers[idx]) { - fnRenames.set(param.name, identifiers[idx]); - return false; - } - return true; - }); + + const strictHarmonyModule = this.originModule.buildMeta.strictHarmonyModule; + if (name && id === "default" && importedModule.buildMeta) { + if (!importedModule.buildMeta.exportsType) { + const mode = new ExportMode( + strictHarmonyModule + ? "reexport-non-harmony-default-strict" + : "reexport-non-harmony-default" + ); + mode.name = name; + mode.module = importedModule; + return mode; + } else if (importedModule.buildMeta.exportsType === "named") { + const mode = new ExportMode("reexport-named-default"); + mode.name = name; + mode.module = importedModule; + return mode; } } - let inTry; - if (fn && isUnboundFunctionExpression(fn)) { - inTry = parser.scope.inTry; - parser.inScope(fnParams, () => { - parser.scope.renames = fnRenames; - parser.scope.inTry = inTry; - if (fn.body.type === "BlockStatement") { - parser.walkStatement(fn.body); + + const isNotAHarmonyModule = + importedModule.buildMeta && !importedModule.buildMeta.exportsType; + if (name) { + let mode; + if (id) { + // export { name as name } + if (isNotAHarmonyModule && strictHarmonyModule) { + mode = new ExportMode("rexport-non-harmony-undefined"); + mode.name = name; } else { - parser.walkExpression(fn.body); + mode = new ExportMode("safe-reexport"); + mode.map = new Map([[name, id]]); } - }); - } else if (fn && isBoundFunctionExpression(fn)) { - inTry = parser.scope.inTry; - parser.inScope( - fn.callee.object.params.filter( - i => !["require", "module", "exports"].includes(i.name) - ), - () => { - parser.scope.renames = fnRenames; - parser.scope.inTry = inTry; - if (fn.callee.object.body.type === "BlockStatement") { - parser.walkStatement(fn.callee.object.body); - } else { - parser.walkExpression(fn.callee.object.body); - } + } else { + // export { * as name } + if (isNotAHarmonyModule && strictHarmonyModule) { + mode = new ExportMode("reexport-fake-namespace-object"); + mode.name = name; + } else { + mode = new ExportMode("reexport-namespace-object"); + mode.name = name; } - ); - if (fn.arguments) { - parser.walkExpressions(fn.arguments); } - } else if (fn || obj) { - parser.walkExpression(fn || obj); + mode.module = importedModule; + return mode; } - const dep = this.newDefineDependency( - expr.range, - array ? array.range : null, - fn ? fn.range : null, - obj ? obj.range : null, - namedModule ? namedModule : null + const hasUsedExports = Array.isArray(this.originModule.usedExports); + const hasProvidedExports = Array.isArray( + importedModule.buildMeta.providedExports ); - dep.loc = expr.loc; - if (namedModule) { - dep.localModule = LocalModulesHelpers.addLocalModule( - parser.state, - namedModule - ); - } - parser.state.current.addDependency(dep); - return true; - } + const activeFromOtherStarExports = this._discoverActiveExportsFromOtherStartExports(); - newDefineDependency( - range, - arrayRange, - functionRange, - objectRange, - namedModule - ) { - return new AMDDefineDependency( - range, - arrayRange, - functionRange, - objectRange, - namedModule - ); - } - newRequireArrayDependency(depsArray, range) { - return new AMDRequireArrayDependency(depsArray, range); - } - newRequireItemDependency(request, range) { - return new AMDRequireItemDependency(request, range); - } -} -module.exports = AMDDefineDependencyParserPlugin; + // export * + if (hasUsedExports) { + // reexport * with known used exports + if (hasProvidedExports) { + const map = new Map( + this.originModule.usedExports + .filter(id => { + if (id === "default") return false; + if (this.activeExports.has(id)) return false; + if (activeFromOtherStarExports.has(id)) return false; + if (!importedModule.buildMeta.providedExports.includes(id)) + return false; + return true; + }) + .map(item => [item, item]) + ); + if (map.size === 0) { + return EMPTY_STAR_MODE; + } -/***/ }), + const mode = new ExportMode("safe-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } -/***/ 85812: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const map = new Map( + this.originModule.usedExports + .filter(id => { + if (id === "default") return false; + if (this.activeExports.has(id)) return false; + if (activeFromOtherStarExports.has(id)) return false; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return true; + }) + .map(item => [item, item]) + ); + if (map.size === 0) { + return EMPTY_STAR_MODE; + } -const path = __webpack_require__(85622); -const AMDRequireDependency = __webpack_require__(73985); -const AMDRequireItemDependency = __webpack_require__(34345); -const AMDRequireArrayDependency = __webpack_require__(63960); -const AMDRequireContextDependency = __webpack_require__(99890); -const AMDDefineDependency = __webpack_require__(67045); -const UnsupportedDependency = __webpack_require__(15826); -const LocalModuleDependency = __webpack_require__(56570); + const mode = new ExportMode("checked-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } -const NullFactory = __webpack_require__(40438); + if (hasProvidedExports) { + const map = new Map( + importedModule.buildMeta.providedExports + .filter(id => { + if (id === "default") return false; + if (this.activeExports.has(id)) return false; + if (activeFromOtherStarExports.has(id)) return false; -const AMDRequireDependenciesBlockParserPlugin = __webpack_require__(9994); -const AMDDefineDependencyParserPlugin = __webpack_require__(27057); + return true; + }) + .map(item => [item, item]) + ); -const AliasPlugin = __webpack_require__(15005); + if (map.size === 0) { + return EMPTY_STAR_MODE; + } -const ParserHelpers = __webpack_require__(23999); + const mode = new ExportMode("safe-reexport"); + mode.module = importedModule; + mode.map = map; + return mode; + } -class AMDPlugin { - constructor(options, amdOptions) { - this.amdOptions = amdOptions; - this.options = options; + const mode = new ExportMode("dynamic-reexport"); + mode.module = importedModule; + mode.ignored = new Set([ + "default", + ...this.activeExports, + ...activeFromOtherStarExports + ]); + return mode; } - apply(compiler) { - const options = this.options; - const amdOptions = this.amdOptions; - compiler.hooks.compilation.tap( - "AMDPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { - compilation.dependencyFactories.set( - AMDRequireDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - AMDRequireDependency, - new AMDRequireDependency.Template() - ); + getReference() { + const mode = this.getMode(false); - compilation.dependencyFactories.set( - AMDRequireItemDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - AMDRequireItemDependency, - new AMDRequireItemDependency.Template() - ); + switch (mode.type) { + case "missing": + case "unused": + case "empty-star": + return null; - compilation.dependencyFactories.set( - AMDRequireArrayDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - AMDRequireArrayDependency, - new AMDRequireArrayDependency.Template() + case "reexport-non-harmony-default": + case "reexport-named-default": + return new DependencyReference( + mode.module, + ["default"], + false, + this.sourceOrder ); - compilation.dependencyFactories.set( - AMDRequireContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - AMDRequireContextDependency, - new AMDRequireContextDependency.Template() + case "reexport-namespace-object": + case "reexport-non-harmony-default-strict": + case "reexport-fake-namespace-object": + case "rexport-non-harmony-undefined": + return new DependencyReference( + mode.module, + true, + false, + this.sourceOrder ); - compilation.dependencyFactories.set( - AMDDefineDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - AMDDefineDependency, - new AMDDefineDependency.Template() - ); - - compilation.dependencyFactories.set( - UnsupportedDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - UnsupportedDependency, - new UnsupportedDependency.Template() + case "safe-reexport": + case "checked-reexport": + return new DependencyReference( + mode.module, + Array.from(mode.map.values()), + false, + this.sourceOrder ); - compilation.dependencyFactories.set( - LocalModuleDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - LocalModuleDependency, - new LocalModuleDependency.Template() + case "dynamic-reexport": + return new DependencyReference( + mode.module, + true, + false, + this.sourceOrder ); - const handler = (parser, parserOptions) => { - if (parserOptions.amd !== undefined && !parserOptions.amd) return; - - const setExpressionToModule = (outerExpr, module) => { - parser.hooks.expression.for(outerExpr).tap("AMDPlugin", expr => { - const dep = new AMDRequireItemDependency(module, expr.range); - dep.userRequest = outerExpr; - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return true; - }); - }; - - new AMDRequireDependenciesBlockParserPlugin(options).apply(parser); - new AMDDefineDependencyParserPlugin(options).apply(parser); - - setExpressionToModule("require.amd", "!!webpack amd options"); - setExpressionToModule("define.amd", "!!webpack amd options"); - setExpressionToModule("define", "!!webpack amd define"); - - parser.hooks.expression - .for("__webpack_amd_options__") - .tap("AMDPlugin", () => - parser.state.current.addVariable( - "__webpack_amd_options__", - JSON.stringify(amdOptions) - ) - ); - parser.hooks.evaluateTypeof - .for("define.amd") - .tap( - "AMDPlugin", - ParserHelpers.evaluateToString(typeof amdOptions) - ); - parser.hooks.evaluateTypeof - .for("require.amd") - .tap( - "AMDPlugin", - ParserHelpers.evaluateToString(typeof amdOptions) - ); - parser.hooks.evaluateIdentifier - .for("define.amd") - .tap( - "AMDPlugin", - ParserHelpers.evaluateToIdentifier("define.amd", true) - ); - parser.hooks.evaluateIdentifier - .for("require.amd") - .tap( - "AMDPlugin", - ParserHelpers.evaluateToIdentifier("require.amd", true) - ); - parser.hooks.typeof - .for("define") - .tap( - "AMDPlugin", - ParserHelpers.toConstantDependency( - parser, - JSON.stringify("function") - ) - ); - parser.hooks.evaluateTypeof - .for("define") - .tap("AMDPlugin", ParserHelpers.evaluateToString("function")); - parser.hooks.canRename - .for("define") - .tap("AMDPlugin", ParserHelpers.approve); - parser.hooks.rename.for("define").tap("AMDPlugin", expr => { - const dep = new AMDRequireItemDependency( - "!!webpack amd define", - expr.range - ); - dep.userRequest = "define"; - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return false; - }); - parser.hooks.typeof - .for("require") - .tap( - "AMDPlugin", - ParserHelpers.toConstantDependency( - parser, - JSON.stringify("function") - ) - ); - parser.hooks.evaluateTypeof - .for("require") - .tap("AMDPlugin", ParserHelpers.evaluateToString("function")); - }; + default: + throw new Error(`Unknown mode ${mode.type}`); + } + } - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("AMDPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("AMDPlugin", handler); + _discoverActiveExportsFromOtherStartExports() { + if (!this.otherStarExports) return new Set(); + const result = new Set(); + // try to learn impossible exports from other star exports with provided exports + for (const otherStarExport of this.otherStarExports) { + const otherImportedModule = otherStarExport._module; + if ( + otherImportedModule && + Array.isArray(otherImportedModule.buildMeta.providedExports) + ) { + for (const exportName of otherImportedModule.buildMeta + .providedExports) { + result.add(exportName); + } } - ); - compiler.hooks.afterResolvers.tap("AMDPlugin", () => { - compiler.resolverFactory.hooks.resolver - .for("normal") - .tap("AMDPlugin", resolver => { - new AliasPlugin( - "described-resolve", - { - name: "amdefine", - alias: __webpack_require__.ab + "amd-define.js" - }, - "resolve" - ).apply(resolver); - new AliasPlugin( - "described-resolve", - { - name: "webpack amd options", - alias: __webpack_require__.ab + "amd-options.js" - }, - "resolve" - ).apply(resolver); - new AliasPlugin( - "described-resolve", - { - name: "webpack amd define", - alias: __webpack_require__.ab + "amd-define.js" - }, - "resolve" - ).apply(resolver); - }); - }); + } + return result; } -} -module.exports = AMDPlugin; - -/***/ }), + getExports() { + if (this.name) { + return { + exports: [this.name], + dependencies: undefined + }; + } -/***/ 63960: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const importedModule = this._module; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (!importedModule) { + // no imported module available + return { + exports: null, + dependencies: undefined + }; + } -const Dependency = __webpack_require__(57282); + if (Array.isArray(importedModule.buildMeta.providedExports)) { + const activeFromOtherStarExports = this._discoverActiveExportsFromOtherStartExports(); + return { + exports: importedModule.buildMeta.providedExports.filter( + id => + id !== "default" && + !activeFromOtherStarExports.has(id) && + !this.activeExports.has(id) + ), + dependencies: [importedModule] + }; + } -class AMDRequireArrayDependency extends Dependency { - constructor(depsArray, range) { - super(); - this.depsArray = depsArray; - this.range = range; - } + if (importedModule.buildMeta.providedExports) { + return { + exports: true, + dependencies: undefined + }; + } - get type() { - return "amd require array"; + return { + exports: null, + dependencies: [importedModule] + }; } -} -AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate { - apply(dep, source, runtime) { - const content = this.getContent(dep, runtime); - source.replace(dep.range[0], dep.range[1] - 1, content); + getWarnings() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return []; + } + return this._getErrors(); } - getContent(dep, runtime) { - const requires = dep.depsArray.map(dependency => { - return this.contentForDependency(dependency, runtime); - }); - return `[${requires.join(", ")}]`; + getErrors() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return this._getErrors(); + } + return []; } - contentForDependency(dep, runtime) { - if (typeof dep === "string") { - return dep; + _getErrors() { + const importedModule = this._module; + if (!importedModule) { + return; } - if (dep.localModule) { - return dep.localModule.variableName(); - } else { - return runtime.moduleExports({ - module: dep.module, - request: dep.request - }); + if (!importedModule.buildMeta || !importedModule.buildMeta.exportsType) { + // It's not an harmony module + if ( + this.originModule.buildMeta.strictHarmonyModule && + this._id && + this._id !== "default" + ) { + // In strict harmony modules we only support the default export + return [ + new HarmonyLinkingError( + `Can't reexport the named export '${this._id}' from non EcmaScript module (only default export is available)` + ) + ]; + } + return; } - } -}; - -module.exports = AMDRequireArrayDependency; + if (!this._id) { + return; + } -/***/ }), + if (importedModule.isProvided(this._id) !== false) { + // It's provided or we are not sure + return; + } -/***/ 99890: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // We are sure that it's not provided + const idIsNotNameMessage = + this._id !== this.name ? ` (reexported as '${this.name}')` : ""; + const errorMessage = `"export '${this._id}'${idIsNotNameMessage} was not found in '${this.userRequest}'`; + return [new HarmonyLinkingError(errorMessage)]; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + updateHash(hash) { + super.updateHash(hash); + const hashValue = this.getHashValue(this._module); + hash.update(hashValue); + } + getHashValue(importedModule) { + if (!importedModule) { + return ""; + } -const ContextDependency = __webpack_require__(11583); -class AMDRequireContextDependency extends ContextDependency { - constructor(options, range, valueRange) { - super(options); - this.range = range; - this.valueRange = valueRange; + const stringifiedUsedExport = JSON.stringify(importedModule.usedExports); + const stringifiedProvidedExport = JSON.stringify( + importedModule.buildMeta.providedExports + ); + return ( + importedModule.used + stringifiedUsedExport + stringifiedProvidedExport + ); } - get type() { - return "amd require context"; + disconnect() { + super.disconnect(); + this.redirectedId = undefined; } } -AMDRequireContextDependency.Template = __webpack_require__(54380); -module.exports = AMDRequireContextDependency; +module.exports = HarmonyExportImportedSpecifierDependency; -/***/ }), +HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate extends HarmonyImportDependency.Template { + harmonyInit(dep, source, runtime, dependencyTemplates) { + super.harmonyInit(dep, source, runtime, dependencyTemplates); + const content = this.getContent(dep); + source.insert(-1, content); + } -/***/ 32894: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + getHarmonyInitOrder(dep) { + if (dep.name) { + const used = dep.originModule.isUsed(dep.name); + if (!used) return NaN; + } else { + const importedModule = dep._module; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const activeFromOtherStarExports = dep._discoverActiveExportsFromOtherStartExports(); -const AsyncDependenciesBlock = __webpack_require__(22814); -const AMDRequireDependency = __webpack_require__(73985); + if (Array.isArray(dep.originModule.usedExports)) { + // we know which exports are used -module.exports = class AMDRequireDependenciesBlock extends AsyncDependenciesBlock { - constructor( - expr, - arrayRange, - functionRange, - errorCallbackRange, - module, - loc, - request - ) { - super(null, module, loc, request); - this.expr = expr; - this.outerRange = expr.range; - this.arrayRange = arrayRange; - this.functionBindThis = false; - this.functionRange = functionRange; - this.errorCallbackBindThis = false; - this.errorCallbackRange = errorCallbackRange; - this.bindThis = true; - if (arrayRange && functionRange && errorCallbackRange) { - this.range = [arrayRange[0], errorCallbackRange[1]]; - } else if (arrayRange && functionRange) { - this.range = [arrayRange[0], functionRange[1]]; - } else if (arrayRange) { - this.range = arrayRange; - } else if (functionRange) { - this.range = functionRange; - } else { - this.range = expr.range; - } - const dep = this.newRequireDependency(); - dep.loc = loc; - this.addDependency(dep); - } + const unused = dep.originModule.usedExports.every(id => { + if (id === "default") return true; + if (dep.activeExports.has(id)) return true; + if (importedModule.isProvided(id) === false) return true; + if (activeFromOtherStarExports.has(id)) return true; + return false; + }); + if (unused) return NaN; + } else if ( + dep.originModule.usedExports && + importedModule && + Array.isArray(importedModule.buildMeta.providedExports) + ) { + // not sure which exports are used, but we know which are provided - newRequireDependency() { - return new AMDRequireDependency(this); + const unused = importedModule.buildMeta.providedExports.every(id => { + if (id === "default") return true; + if (dep.activeExports.has(id)) return true; + if (activeFromOtherStarExports.has(id)) return true; + return false; + }); + if (unused) return NaN; + } + } + return super.getHarmonyInitOrder(dep); } -}; + getContent(dep) { + const mode = dep.getMode(false); + const module = dep.originModule; + const importedModule = dep._module; + const importVar = dep.getImportVar(); -/***/ }), + switch (mode.type) { + case "missing": + return `throw new Error(${JSON.stringify( + `Cannot find module '${mode.userRequest}'` + )});\n`; -/***/ 9994: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + case "unused": + return `${Template.toNormalComment( + `unused harmony reexport ${mode.name}` + )}\n`; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + case "reexport-non-harmony-default": + return ( + "/* harmony reexport (default from non-harmony) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + null + ) + ); + case "reexport-named-default": + return ( + "/* harmony reexport (default from named exports) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + "" + ) + ); -const AMDRequireItemDependency = __webpack_require__(34345); -const AMDRequireArrayDependency = __webpack_require__(63960); -const AMDRequireContextDependency = __webpack_require__(99890); -const AMDRequireDependenciesBlock = __webpack_require__(32894); -const UnsupportedDependency = __webpack_require__(15826); -const LocalModuleDependency = __webpack_require__(56570); -const ContextDependencyHelpers = __webpack_require__(5594); -const LocalModulesHelpers = __webpack_require__(39658); -const ConstDependency = __webpack_require__(71101); -const getFunctionExpression = __webpack_require__(64197); -const UnsupportedFeatureWarning = __webpack_require__(99953); + case "reexport-fake-namespace-object": + return ( + "/* harmony reexport (fake namespace object from non-harmony) */ " + + this.getReexportFakeNamespaceObjectStatement( + module, + module.isUsed(mode.name), + importVar + ) + ); -class AMDRequireDependenciesBlockParserPlugin { - constructor(options) { - this.options = options; - } + case "rexport-non-harmony-undefined": + return ( + "/* harmony reexport (non default export from non-harmony) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + "undefined", + "" + ) + ); - processFunctionArgument(parser, expression) { - let bindThis = true; - const fnData = getFunctionExpression(expression); - if (fnData) { - parser.inScope( - fnData.fn.params.filter(i => { - return !["require", "module", "exports"].includes(i.name); - }), - () => { - if (fnData.fn.body.type === "BlockStatement") { - parser.walkStatement(fnData.fn.body); - } else { - parser.walkExpression(fnData.fn.body); - } - } - ); - parser.walkExpressions(fnData.expressions); - if (fnData.needThis === false) { - bindThis = false; - } - } else { - parser.walkExpression(expression); - } - return bindThis; - } + case "reexport-non-harmony-default-strict": + return ( + "/* harmony reexport (default from non-harmony) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + "" + ) + ); - apply(parser) { - parser.hooks.call - .for("require") - .tap( - "AMDRequireDependenciesBlockParserPlugin", - this.processCallRequire.bind(this, parser) - ); - } + case "reexport-namespace-object": + return ( + "/* harmony reexport (module object) */ " + + this.getReexportStatement( + module, + module.isUsed(mode.name), + importVar, + "" + ) + ); - processArray(parser, expr, param) { - if (param.isArray()) { - for (const p of param.items) { - const result = this.processItem(parser, expr, p); - if (result === undefined) { - this.processContext(parser, expr, p); - } - } - return true; - } else if (param.isConstArray()) { - const deps = []; - for (const request of param.array) { - let dep, localModule; - if (request === "require") { - dep = "__webpack_require__"; - } else if (["exports", "module"].includes(request)) { - dep = request; - } else if ( - (localModule = LocalModulesHelpers.getLocalModule( - parser.state, - request - )) - ) { - dep = new LocalModuleDependency(localModule, undefined, false); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); + case "empty-star": + return "/* empty/unused harmony star reexport */"; + + case "safe-reexport": + return Array.from(mode.map.entries()) + .map(item => { + return ( + "/* harmony reexport (safe) */ " + + this.getReexportStatement( + module, + module.isUsed(item[0]), + importVar, + importedModule.isUsed(item[1]) + ) + + "\n" + ); + }) + .join(""); + + case "checked-reexport": + return Array.from(mode.map.entries()) + .map(item => { + return ( + "/* harmony reexport (checked) */ " + + this.getConditionalReexportStatement( + module, + item[0], + importVar, + item[1] + ) + + "\n" + ); + }) + .join(""); + + case "dynamic-reexport": { + const ignoredExports = mode.ignored; + let content = + "/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in " + + importVar + + ") "; + + // Filter out exports which are defined by other exports + // and filter out default export because it cannot be reexported with * + if (ignoredExports.size > 0) { + content += + "if(" + + JSON.stringify(Array.from(ignoredExports)) + + ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; } else { - dep = this.newRequireItemDependency(request); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - } - deps.push(dep); - } - const dep = this.newRequireArrayDependency(deps, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - } - processItem(parser, expr, param) { - if (param.isConditional()) { - for (const p of param.options) { - const result = this.processItem(parser, expr, p); - if (result === undefined) { - this.processContext(parser, expr, p); + content += "if(__WEBPACK_IMPORT_KEY__ !== 'default') "; } - } - return true; - } else if (param.isString()) { - let dep, localModule; - if (param.string === "require") { - dep = new ConstDependency("__webpack_require__", param.string); - } else if (param.string === "module") { - dep = new ConstDependency( - parser.state.module.buildInfo.moduleArgument, - param.range - ); - } else if (param.string === "exports") { - dep = new ConstDependency( - parser.state.module.buildInfo.exportsArgument, - param.range + const exportsName = dep.originModule.exportsArgument; + return ( + content + + `(function(key) { __webpack_require__.d(${exportsName}, key, function() { return ${importVar}[key]; }) }(__WEBPACK_IMPORT_KEY__));\n` ); - } else if ( - (localModule = LocalModulesHelpers.getLocalModule( - parser.state, - param.string - )) - ) { - dep = new LocalModuleDependency(localModule, param.range, false); - } else { - dep = this.newRequireItemDependency(param.string, param.range); } - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; + + default: + throw new Error(`Unknown mode ${mode.type}`); } } - processContext(parser, expr, param) { - const dep = ContextDependencyHelpers.create( - AMDRequireContextDependency, - param.range, - param, - expr, - this.options, - {}, - parser - ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; + + getReexportStatement(module, key, name, valueKey) { + const exportsName = module.exportsArgument; + const returnValue = this.getReturnValue(name, valueKey); + return `__webpack_require__.d(${exportsName}, ${JSON.stringify( + key + )}, function() { return ${returnValue}; });\n`; } - processArrayForRequestString(param) { - if (param.isArray()) { - const result = param.items.map(item => - this.processItemForRequestString(item) - ); - if (result.every(Boolean)) return result.join(" "); - } else if (param.isConstArray()) { - return param.array.join(" "); - } + getReexportFakeNamespaceObjectStatement(module, key, name) { + const exportsName = module.exportsArgument; + return `__webpack_require__.d(${exportsName}, ${JSON.stringify( + key + )}, function() { return __webpack_require__.t(${name}); });\n`; } - processItemForRequestString(param) { - if (param.isConditional()) { - const result = param.options.map(item => - this.processItemForRequestString(item) - ); - if (result.every(Boolean)) return result.join("|"); - } else if (param.isString()) { - return param.string; + getConditionalReexportStatement(module, key, name, valueKey) { + if (valueKey === false) { + return "/* unused export */\n"; } + const exportsName = module.exportsArgument; + const returnValue = this.getReturnValue(name, valueKey); + return `if(__webpack_require__.o(${name}, ${JSON.stringify( + valueKey + )})) __webpack_require__.d(${exportsName}, ${JSON.stringify( + key + )}, function() { return ${returnValue}; });\n`; } - processCallRequire(parser, expr) { - let param; - let dep; - let result; - - const old = parser.state.current; - - if (expr.arguments.length >= 1) { - param = parser.evaluateExpression(expr.arguments[0]); - dep = this.newRequireDependenciesBlock( - expr, - param.range, - expr.arguments.length > 1 ? expr.arguments[1].range : null, - expr.arguments.length > 2 ? expr.arguments[2].range : null, - parser.state.module, - expr.loc, - this.processArrayForRequestString(param) - ); - parser.state.current = dep; + getReturnValue(name, valueKey) { + if (valueKey === null) { + return `${name}_default.a`; } - - if (expr.arguments.length === 1) { - parser.inScope([], () => { - result = this.processArray(parser, expr, param); - }); - parser.state.current = old; - if (!result) return; - parser.state.current.addBlock(dep); - return true; + if (valueKey === "") { + return name; } - - if (expr.arguments.length === 2 || expr.arguments.length === 3) { - try { - parser.inScope([], () => { - result = this.processArray(parser, expr, param); - }); - if (!result) { - dep = new UnsupportedDependency("unsupported", expr.range); - old.addDependency(dep); - if (parser.state.module) { - parser.state.module.errors.push( - new UnsupportedFeatureWarning( - parser.state.module, - "Cannot statically analyse 'require(…, …)' in line " + - expr.loc.start.line, - expr.loc - ) - ); - } - dep = null; - return true; - } - dep.functionBindThis = this.processFunctionArgument( - parser, - expr.arguments[1] - ); - if (expr.arguments.length === 3) { - dep.errorCallbackBindThis = this.processFunctionArgument( - parser, - expr.arguments[2] - ); - } - } finally { - parser.state.current = old; - if (dep) parser.state.current.addBlock(dep); - } - return true; + if (valueKey === false) { + return "/* unused export */ undefined"; } - } - newRequireDependenciesBlock( - expr, - arrayRange, - functionRange, - errorCallbackRange, - module, - loc, - request - ) { - return new AMDRequireDependenciesBlock( - expr, - arrayRange, - functionRange, - errorCallbackRange, - module, - loc, - request - ); - } - newRequireItemDependency(request, range) { - return new AMDRequireItemDependency(request, range); - } - newRequireArrayDependency(depsArray, range) { - return new AMDRequireArrayDependency(depsArray, range); + return `${name}[${JSON.stringify(valueKey)}]`; } -} -module.exports = AMDRequireDependenciesBlockParserPlugin; +}; /***/ }), -/***/ 73985: +/***/ 34834: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98208,139 +96849,58 @@ module.exports = AMDRequireDependenciesBlockParserPlugin; const NullDependency = __webpack_require__(5088); -class AMDRequireDependency extends NullDependency { - constructor(block) { +class HarmonyExportSpecifierDependency extends NullDependency { + constructor(originModule, id, name) { super(); - this.block = block; + this.originModule = originModule; + this.id = id; + this.name = name; } -} -AMDRequireDependency.Template = class AMDRequireDependencyTemplate { - apply(dep, source, runtime) { - const depBlock = dep.block; - const promise = runtime.blockPromise({ - block: depBlock, - message: "AMD require" - }); + get type() { + return "harmony export specifier"; + } - // has array range but no function range - if (depBlock.arrayRange && !depBlock.functionRange) { - const startBlock = `${promise}.then(function() {`; - const endBlock = `;}).catch(${runtime.onError()})`; - source.replace( - depBlock.outerRange[0], - depBlock.arrayRange[0] - 1, - startBlock - ); - source.replace( - depBlock.arrayRange[1], - depBlock.outerRange[1] - 1, - endBlock - ); - return; - } + getExports() { + return { + exports: [this.name], + dependencies: undefined + }; + } +} - // has function range but no array range - if (depBlock.functionRange && !depBlock.arrayRange) { - const startBlock = `${promise}.then((`; - const endBlock = `).bind(exports, __webpack_require__, exports, module)).catch(${runtime.onError()})`; - source.replace( - depBlock.outerRange[0], - depBlock.functionRange[0] - 1, - startBlock - ); - source.replace( - depBlock.functionRange[1], - depBlock.outerRange[1] - 1, - endBlock - ); - return; - } +HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate { + apply(dep, source) {} - // has array range, function range, and errorCallbackRange - if ( - depBlock.arrayRange && - depBlock.functionRange && - depBlock.errorCallbackRange - ) { - const startBlock = `${promise}.then(function() { `; - const errorRangeBlock = `}${ - depBlock.functionBindThis ? ".bind(this)" : "" - }).catch(`; - const endBlock = `${ - depBlock.errorCallbackBindThis ? ".bind(this)" : "" - })`; + getHarmonyInitOrder(dep) { + return 0; + } - source.replace( - depBlock.outerRange[0], - depBlock.arrayRange[0] - 1, - startBlock - ); - source.insert( - depBlock.arrayRange[0] + 0.9, - "var __WEBPACK_AMD_REQUIRE_ARRAY__ = " - ); - source.replace( - depBlock.arrayRange[1], - depBlock.functionRange[0] - 1, - "; (" - ); - source.insert( - depBlock.functionRange[1], - ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" - ); - source.replace( - depBlock.functionRange[1], - depBlock.errorCallbackRange[0] - 1, - errorRangeBlock - ); - source.replace( - depBlock.errorCallbackRange[1], - depBlock.outerRange[1] - 1, - endBlock - ); - return; - } + harmonyInit(dep, source, runtime) { + const content = this.getContent(dep); + source.insert(-1, content); + } - // has array range, function range, but no errorCallbackRange - if (depBlock.arrayRange && depBlock.functionRange) { - const startBlock = `${promise}.then(function() { `; - const endBlock = `}${ - depBlock.functionBindThis ? ".bind(this)" : "" - }).catch(${runtime.onError()})`; - source.replace( - depBlock.outerRange[0], - depBlock.arrayRange[0] - 1, - startBlock - ); - source.insert( - depBlock.arrayRange[0] + 0.9, - "var __WEBPACK_AMD_REQUIRE_ARRAY__ = " - ); - source.replace( - depBlock.arrayRange[1], - depBlock.functionRange[0] - 1, - "; (" - ); - source.insert( - depBlock.functionRange[1], - ").apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__);" - ); - source.replace( - depBlock.functionRange[1], - depBlock.outerRange[1] - 1, - endBlock - ); + getContent(dep) { + const used = dep.originModule.isUsed(dep.name); + if (!used) { + return `/* unused harmony export ${dep.name || "namespace"} */\n`; } + + const exportsName = dep.originModule.exportsArgument; + + return `/* harmony export (binding) */ __webpack_require__.d(${exportsName}, ${JSON.stringify( + used + )}, function() { return ${dep.id}; });\n`; } }; -module.exports = AMDRequireDependency; +module.exports = HarmonyExportSpecifierDependency; /***/ }), -/***/ 34345: +/***/ 81599: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98349,194 +96909,115 @@ module.exports = AMDRequireDependency; Author Tobias Koppers @sokra */ + +const DependencyReference = __webpack_require__(71722); const ModuleDependency = __webpack_require__(90865); -const ModuleDependencyTemplateAsRequireId = __webpack_require__(60441); +const Template = __webpack_require__(96066); -class AMDRequireItemDependency extends ModuleDependency { - constructor(request, range) { +class HarmonyImportDependency extends ModuleDependency { + constructor(request, originModule, sourceOrder, parserScope) { super(request); - this.range = range; + this.redirectedModule = undefined; + this.originModule = originModule; + this.sourceOrder = sourceOrder; + this.parserScope = parserScope; } - get type() { - return "amd require"; + get _module() { + return this.redirectedModule || this.module; } -} - -AMDRequireItemDependency.Template = ModuleDependencyTemplateAsRequireId; - -module.exports = AMDRequireItemDependency; - -/***/ }), - -/***/ 85358: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const ConstDependency = __webpack_require__(71101); -const CommonJsRequireDependency = __webpack_require__(37504); -const CommonJsRequireContextDependency = __webpack_require__(26791); -const RequireResolveDependency = __webpack_require__(43519); -const RequireResolveContextDependency = __webpack_require__(83309); -const RequireResolveHeaderDependency = __webpack_require__(69647); -const RequireHeaderDependency = __webpack_require__(22928); - -const NullFactory = __webpack_require__(40438); - -const RequireResolveDependencyParserPlugin = __webpack_require__(68349); -const CommonJsRequireDependencyParserPlugin = __webpack_require__(37278); - -const ParserHelpers = __webpack_require__(23999); - -class CommonJsPlugin { - constructor(options) { - this.options = options; + getReference() { + if (!this._module) return null; + return new DependencyReference( + this._module, + false, + this.weak, + this.sourceOrder + ); } - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap( - "CommonJsPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { - compilation.dependencyFactories.set( - CommonJsRequireDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - CommonJsRequireDependency, - new CommonJsRequireDependency.Template() - ); - - compilation.dependencyFactories.set( - CommonJsRequireContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - CommonJsRequireContextDependency, - new CommonJsRequireContextDependency.Template() - ); + getImportVar() { + let importVarMap = this.parserScope.importVarMap; + if (!importVarMap) this.parserScope.importVarMap = importVarMap = new Map(); + let importVar = importVarMap.get(this._module); + if (importVar) return importVar; + importVar = `${Template.toIdentifier( + `${this.userRequest}` + )}__WEBPACK_IMPORTED_MODULE_${importVarMap.size}__`; + importVarMap.set(this._module, importVar); + return importVar; + } - compilation.dependencyFactories.set( - RequireResolveDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - RequireResolveDependency, - new RequireResolveDependency.Template() - ); + getImportStatement(update, runtime) { + return runtime.importStatement({ + update, + module: this._module, + importVar: this.getImportVar(), + request: this.request, + originModule: this.originModule + }); + } - compilation.dependencyFactories.set( - RequireResolveContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - RequireResolveContextDependency, - new RequireResolveContextDependency.Template() - ); + updateHash(hash) { + super.updateHash(hash); + const importedModule = this._module; + hash.update( + (importedModule && + (!importedModule.buildMeta || importedModule.buildMeta.exportsType)) + + "" + ); + hash.update((importedModule && importedModule.id) + ""); + } - compilation.dependencyFactories.set( - RequireResolveHeaderDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - RequireResolveHeaderDependency, - new RequireResolveHeaderDependency.Template() - ); + disconnect() { + super.disconnect(); + this.redirectedModule = undefined; + } +} - compilation.dependencyFactories.set( - RequireHeaderDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - RequireHeaderDependency, - new RequireHeaderDependency.Template() - ); +module.exports = HarmonyImportDependency; - const handler = (parser, parserOptions) => { - if (parserOptions.commonjs !== undefined && !parserOptions.commonjs) - return; +const importEmittedMap = new WeakMap(); - const requireExpressions = [ - "require", - "require.resolve", - "require.resolveWeak" - ]; - for (let expression of requireExpressions) { - parser.hooks.typeof - .for(expression) - .tap( - "CommonJsPlugin", - ParserHelpers.toConstantDependency( - parser, - JSON.stringify("function") - ) - ); - parser.hooks.evaluateTypeof - .for(expression) - .tap( - "CommonJsPlugin", - ParserHelpers.evaluateToString("function") - ); - parser.hooks.evaluateIdentifier - .for(expression) - .tap( - "CommonJsPlugin", - ParserHelpers.evaluateToIdentifier(expression, true) - ); - } +HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate { + apply(dep, source, runtime) { + // no-op + } - parser.hooks.evaluateTypeof - .for("module") - .tap("CommonJsPlugin", ParserHelpers.evaluateToString("object")); - parser.hooks.assign.for("require").tap("CommonJsPlugin", expr => { - // to not leak to global "require", we need to define a local require here. - const dep = new ConstDependency("var require;", 0); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - parser.scope.definitions.add("require"); - return true; - }); - parser.hooks.canRename - .for("require") - .tap("CommonJsPlugin", () => true); - parser.hooks.rename.for("require").tap("CommonJsPlugin", expr => { - // define the require variable. It's still undefined, but not "not defined". - const dep = new ConstDependency("var require;", 0); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return false; - }); - parser.hooks.typeof.for("module").tap("CommonJsPlugin", () => true); - parser.hooks.evaluateTypeof - .for("exports") - .tap("CommonJsPlugin", ParserHelpers.evaluateToString("object")); + getHarmonyInitOrder(dep) { + return dep.sourceOrder; + } - new CommonJsRequireDependencyParserPlugin(options).apply(parser); - new RequireResolveDependencyParserPlugin(options).apply(parser); - }; + static isImportEmitted(dep, source) { + let sourceInfo = importEmittedMap.get(source); + if (!sourceInfo) return false; + const key = dep._module || dep.request; + return key && sourceInfo.emittedImports.get(key); + } - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("CommonJsPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("CommonJsPlugin", handler); - } - ); + harmonyInit(dep, source, runtime, dependencyTemplates) { + let sourceInfo = importEmittedMap.get(source); + if (!sourceInfo) { + importEmittedMap.set( + source, + (sourceInfo = { + emittedImports: new Map() + }) + ); + } + const key = dep._module || dep.request; + if (key && sourceInfo.emittedImports.get(key)) return; + sourceInfo.emittedImports.set(key, true); + const content = dep.getImportStatement(false, runtime); + source.insert(-1, content); } -} -module.exports = CommonJsPlugin; +}; /***/ }), -/***/ 26791: +/***/ 99433: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98545,29 +97026,228 @@ module.exports = CommonJsPlugin; Author Tobias Koppers @sokra */ -const ContextDependency = __webpack_require__(11583); -const ContextDependencyTemplateAsRequireCall = __webpack_require__(54380); -class CommonJsRequireContextDependency extends ContextDependency { - constructor(options, range, valueRange) { - super(options); - this.range = range; - this.valueRange = valueRange; - } +const { SyncBailHook } = __webpack_require__(56758); +const HarmonyImportSideEffectDependency = __webpack_require__(79171); +const HarmonyImportSpecifierDependency = __webpack_require__(95966); +const HarmonyAcceptImportDependency = __webpack_require__(66136); +const HarmonyAcceptDependency = __webpack_require__(75159); +const ConstDependency = __webpack_require__(71101); - get type() { - return "cjs require context"; +module.exports = class HarmonyImportDependencyParserPlugin { + constructor(moduleOptions) { + this.strictExportPresence = moduleOptions.strictExportPresence; + this.strictThisContextOnImports = moduleOptions.strictThisContextOnImports; } -} - -CommonJsRequireContextDependency.Template = ContextDependencyTemplateAsRequireCall; -module.exports = CommonJsRequireContextDependency; + apply(parser) { + parser.hooks.import.tap( + "HarmonyImportDependencyParserPlugin", + (statement, source) => { + parser.state.lastHarmonyImportOrder = + (parser.state.lastHarmonyImportOrder || 0) + 1; + const clearDep = new ConstDependency("", statement.range); + clearDep.loc = statement.loc; + parser.state.module.addDependency(clearDep); + const sideEffectDep = new HarmonyImportSideEffectDependency( + source, + parser.state.module, + parser.state.lastHarmonyImportOrder, + parser.state.harmonyParserScope + ); + sideEffectDep.loc = statement.loc; + parser.state.module.addDependency(sideEffectDep); + return true; + } + ); + parser.hooks.importSpecifier.tap( + "HarmonyImportDependencyParserPlugin", + (statement, source, id, name) => { + parser.scope.definitions.delete(name); + parser.scope.renames.set(name, "imported var"); + if (!parser.state.harmonySpecifier) { + parser.state.harmonySpecifier = new Map(); + } + parser.state.harmonySpecifier.set(name, { + source, + id, + sourceOrder: parser.state.lastHarmonyImportOrder + }); + return true; + } + ); + parser.hooks.expression + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + const name = expr.name; + const settings = parser.state.harmonySpecifier.get(name); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + settings.id, + name, + expr.range, + this.strictExportPresence + ); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = true; + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); + parser.hooks.expressionAnyMember + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + const name = expr.object.name; + const settings = parser.state.harmonySpecifier.get(name); + if (settings.id !== null) return false; + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + expr.property.name || expr.property.value, + name, + expr.range, + this.strictExportPresence + ); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = false; + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return true; + }); + if (this.strictThisContextOnImports) { + // only in case when we strictly follow the spec we need a special case here + parser.hooks.callAnyMember + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + if (expr.callee.type !== "MemberExpression") return; + if (expr.callee.object.type !== "Identifier") return; + const name = expr.callee.object.name; + const settings = parser.state.harmonySpecifier.get(name); + if (settings.id !== null) return false; + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + expr.callee.property.name || expr.callee.property.value, + name, + expr.callee.range, + this.strictExportPresence + ); + dep.shorthand = parser.scope.inShorthand; + dep.directImport = false; + dep.namespaceObjectAsContext = true; + dep.loc = expr.callee.loc; + parser.state.module.addDependency(dep); + if (expr.arguments) parser.walkExpressions(expr.arguments); + return true; + }); + } + parser.hooks.call + .for("imported var") + .tap("HarmonyImportDependencyParserPlugin", expr => { + const args = expr.arguments; + const fullExpr = expr; + expr = expr.callee; + if (expr.type !== "Identifier") return; + const name = expr.name; + const settings = parser.state.harmonySpecifier.get(name); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + parser.state.module, + settings.sourceOrder, + parser.state.harmonyParserScope, + settings.id, + name, + expr.range, + this.strictExportPresence + ); + dep.directImport = true; + dep.callArgs = args; + dep.call = fullExpr; + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + if (args) parser.walkExpressions(args); + return true; + }); + // TODO webpack 5: refactor this, no custom hooks + if (!parser.hooks.hotAcceptCallback) { + parser.hooks.hotAcceptCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + if (!parser.hooks.hotAcceptWithoutCallback) { + parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ + "expression", + "requests" + ]); + } + parser.hooks.hotAcceptCallback.tap( + "HarmonyImportDependencyParserPlugin", + (expr, requests) => { + const harmonyParserScope = parser.state.harmonyParserScope; + if (!harmonyParserScope) { + // This is not a harmony module, skip it + return; + } + const dependencies = requests.map(request => { + const dep = new HarmonyAcceptImportDependency( + request, + parser.state.module, + harmonyParserScope + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + expr.range, + dependencies, + true + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + } + } + ); + parser.hooks.hotAcceptWithoutCallback.tap( + "HarmonyImportDependencyParserPlugin", + (expr, requests) => { + const dependencies = requests.map(request => { + const dep = new HarmonyAcceptImportDependency( + request, + parser.state.module, + parser.state.harmonyParserScope + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + return dep; + }); + if (dependencies.length > 0) { + const dep = new HarmonyAcceptDependency( + expr.range, + dependencies, + false + ); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + } + } + ); + } +}; /***/ }), -/***/ 37504: +/***/ 79171: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98576,28 +97256,37 @@ module.exports = CommonJsRequireContextDependency; Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(90865); -const ModuleDependencyTemplateAsId = __webpack_require__(63708); +const HarmonyImportDependency = __webpack_require__(81599); -class CommonJsRequireDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; +class HarmonyImportSideEffectDependency extends HarmonyImportDependency { + constructor(request, originModule, sourceOrder, parserScope) { + super(request, originModule, sourceOrder, parserScope); + } + + getReference() { + if (this._module && this._module.factoryMeta.sideEffectFree) return null; + + return super.getReference(); } get type() { - return "cjs require"; + return "harmony side effect evaluation"; } } -CommonJsRequireDependency.Template = ModuleDependencyTemplateAsId; +HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends HarmonyImportDependency.Template { + getHarmonyInitOrder(dep) { + if (dep._module && dep._module.factoryMeta.sideEffectFree) return NaN; + return super.getHarmonyInitOrder(dep); + } +}; -module.exports = CommonJsRequireDependency; +module.exports = HarmonyImportSideEffectDependency; /***/ }), -/***/ 37278: +/***/ 95966: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98607,143 +97296,168 @@ module.exports = CommonJsRequireDependency; */ -const CommonJsRequireDependency = __webpack_require__(37504); -const CommonJsRequireContextDependency = __webpack_require__(26791); -const RequireHeaderDependency = __webpack_require__(22928); -const LocalModuleDependency = __webpack_require__(56570); -const ContextDependencyHelpers = __webpack_require__(5594); -const LocalModulesHelpers = __webpack_require__(39658); -const ParserHelpers = __webpack_require__(23999); - -class CommonJsRequireDependencyParserPlugin { - constructor(options) { - this.options = options; - } - - apply(parser) { - const options = this.options; +const DependencyReference = __webpack_require__(71722); +const HarmonyImportDependency = __webpack_require__(81599); +const HarmonyLinkingError = __webpack_require__(30327); - const processItem = (expr, param) => { - if (param.isString()) { - const dep = new CommonJsRequireDependency(param.string, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - }; - const processContext = (expr, param) => { - const dep = ContextDependencyHelpers.create( - CommonJsRequireContextDependency, - expr.range, - param, - expr, - options, - {}, - parser - ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - }; +class HarmonyImportSpecifierDependency extends HarmonyImportDependency { + constructor( + request, + originModule, + sourceOrder, + parserScope, + id, + name, + range, + strictExportPresence + ) { + super(request, originModule, sourceOrder, parserScope); + this.id = id === null ? null : `${id}`; + this.redirectedId = undefined; + this.name = name; + this.range = range; + this.strictExportPresence = strictExportPresence; + this.namespaceObjectAsContext = false; + this.callArgs = undefined; + this.call = undefined; + this.directImport = undefined; + this.shorthand = undefined; + } - parser.hooks.expression - .for("require.cache") - .tap( - "CommonJsRequireDependencyParserPlugin", - ParserHelpers.toConstantDependencyWithWebpackRequire( - parser, - "__webpack_require__.c" - ) - ); - parser.hooks.expression - .for("require") - .tap("CommonJsRequireDependencyParserPlugin", expr => { - const dep = new CommonJsRequireContextDependency( - { - request: options.unknownContextRequest, - recursive: options.unknownContextRecursive, - regExp: options.unknownContextRegExp, - mode: "sync" - }, - expr.range - ); - dep.critical = - options.unknownContextCritical && - "require function is used in a way in which dependencies cannot be statically extracted"; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - }); + get type() { + return "harmony import specifier"; + } - const createHandler = callNew => expr => { - if (expr.arguments.length !== 1) return; - let localModule; - const param = parser.evaluateExpression(expr.arguments[0]); - if (param.isConditional()) { - let isExpression = false; - const prevLength = parser.state.current.dependencies.length; - const dep = new RequireHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - for (const p of param.options) { - const result = processItem(expr, p); - if (result === undefined) { - isExpression = true; - } - } - if (isExpression) { - parser.state.current.dependencies.length = prevLength; - } else { - return true; - } - } + get _id() { + return this.redirectedId || this.id; + } + + getReference() { + if (!this._module) return null; + return new DependencyReference( + this._module, + this._id && !this.namespaceObjectAsContext ? [this._id] : true, + false, + this.sourceOrder + ); + } + + getWarnings() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return []; + } + return this._getErrors(); + } + + getErrors() { + if ( + this.strictExportPresence || + this.originModule.buildMeta.strictHarmonyModule + ) { + return this._getErrors(); + } + return []; + } + + _getErrors() { + const importedModule = this._module; + if (!importedModule) { + return; + } + + if (!importedModule.buildMeta || !importedModule.buildMeta.exportsType) { + // It's not an harmony module if ( - param.isString() && - (localModule = LocalModulesHelpers.getLocalModule( - parser.state, - param.string - )) + this.originModule.buildMeta.strictHarmonyModule && + this._id && + this._id !== "default" ) { - const dep = new LocalModuleDependency(localModule, expr.range, callNew); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return true; - } else { - const result = processItem(expr, param); - if (result === undefined) { - processContext(expr, param); - } else { - const dep = new RequireHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - } - return true; + // In strict harmony modules we only support the default export + return [ + new HarmonyLinkingError( + `Can't import the named export '${this._id}' from non EcmaScript module (only default export is available)` + ) + ]; } - }; - parser.hooks.call - .for("require") - .tap("CommonJsRequireDependencyParserPlugin", createHandler(false)); - parser.hooks.new - .for("require") - .tap("CommonJsRequireDependencyParserPlugin", createHandler(true)); - parser.hooks.call - .for("module.require") - .tap("CommonJsRequireDependencyParserPlugin", createHandler(false)); - parser.hooks.new - .for("module.require") - .tap("CommonJsRequireDependencyParserPlugin", createHandler(true)); + return; + } + + if (!this._id) { + return; + } + + if (importedModule.isProvided(this._id) !== false) { + // It's provided or we are not sure + return; + } + + // We are sure that it's not provided + const idIsNotNameMessage = + this._id !== this.name ? ` (imported as '${this.name}')` : ""; + const errorMessage = `"export '${this._id}'${idIsNotNameMessage} was not found in '${this.userRequest}'`; + return [new HarmonyLinkingError(errorMessage)]; + } + + // implement this method to allow the occurrence order plugin to count correctly + getNumberOfIdOccurrences() { + return 0; + } + + updateHash(hash) { + super.updateHash(hash); + const importedModule = this._module; + hash.update((importedModule && this._id) + ""); + hash.update( + (importedModule && this._id && importedModule.isUsed(this._id)) + "" + ); + hash.update( + (importedModule && + (!importedModule.buildMeta || importedModule.buildMeta.exportsType)) + + "" + ); + hash.update( + (importedModule && + importedModule.used + JSON.stringify(importedModule.usedExports)) + "" + ); + } + + disconnect() { + super.disconnect(); + this.redirectedId = undefined; } } -module.exports = CommonJsRequireDependencyParserPlugin; + +HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate extends HarmonyImportDependency.Template { + apply(dep, source, runtime) { + super.apply(dep, source, runtime); + const content = this.getContent(dep, runtime); + source.replace(dep.range[0], dep.range[1] - 1, content); + } + + getContent(dep, runtime) { + const exportExpr = runtime.exportFromImport({ + module: dep._module, + request: dep.request, + exportName: dep._id, + originModule: dep.originModule, + asiSafe: dep.shorthand, + isCall: dep.call, + callContext: !dep.directImport, + importVar: dep.getImportVar() + }); + return dep.shorthand ? `${dep.name}: ${exportExpr}` : exportExpr; + } +}; + +module.exports = HarmonyImportSpecifierDependency; /***/ }), -/***/ 71101: +/***/ 27204: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98752,39 +97466,66 @@ module.exports = CommonJsRequireDependencyParserPlugin; Author Tobias Koppers @sokra */ + const NullDependency = __webpack_require__(5088); -class ConstDependency extends NullDependency { - constructor(expression, range, requireWebpackRequire) { +class HarmonyInitDependency extends NullDependency { + constructor(originModule) { super(); - this.expression = expression; - this.range = range; - this.requireWebpackRequire = requireWebpackRequire; + this.originModule = originModule; } - updateHash(hash) { - hash.update(this.range + ""); - hash.update(this.expression + ""); + get type() { + return "harmony init"; } } -ConstDependency.Template = class ConstDependencyTemplate { - apply(dep, source) { - if (typeof dep.range === "number") { - source.insert(dep.range, dep.expression); - return; +module.exports = HarmonyInitDependency; + +HarmonyInitDependency.Template = class HarmonyInitDependencyTemplate { + apply(dep, source, runtime, dependencyTemplates) { + const module = dep.originModule; + const list = []; + for (const dependency of module.dependencies) { + const template = dependencyTemplates.get(dependency.constructor); + if ( + template && + typeof template.harmonyInit === "function" && + typeof template.getHarmonyInitOrder === "function" + ) { + const order = template.getHarmonyInitOrder(dependency); + if (!isNaN(order)) { + list.push({ + order, + listOrder: list.length, + dependency, + template + }); + } + } } - source.replace(dep.range[0], dep.range[1] - 1, dep.expression); + list.sort((a, b) => { + const x = a.order - b.order; + if (x) return x; + return a.listOrder - b.listOrder; + }); + + for (const item of list) { + item.template.harmonyInit( + item.dependency, + source, + runtime, + dependencyTemplates + ); + } } }; -module.exports = ConstDependency; - /***/ }), -/***/ 11583: +/***/ 66792: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -98793,412 +97534,183 @@ module.exports = ConstDependency; Author Tobias Koppers @sokra */ -const Dependency = __webpack_require__(57282); -const CriticalDependencyWarning = __webpack_require__(54983); +const HarmonyCompatibilityDependency = __webpack_require__(1533); +const HarmonyInitDependency = __webpack_require__(27204); +const HarmonyImportSpecifierDependency = __webpack_require__(95966); +const HarmonyImportSideEffectDependency = __webpack_require__(79171); +const HarmonyExportHeaderDependency = __webpack_require__(21320); +const HarmonyExportExpressionDependency = __webpack_require__(84245); +const HarmonyExportSpecifierDependency = __webpack_require__(34834); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); +const HarmonyAcceptDependency = __webpack_require__(75159); +const HarmonyAcceptImportDependency = __webpack_require__(66136); -const regExpToString = r => (r ? r + "" : ""); +const NullFactory = __webpack_require__(40438); -class ContextDependency extends Dependency { - // options: { request, recursive, regExp, include, exclude, mode, chunkName, groupOptions } +const HarmonyDetectionParserPlugin = __webpack_require__(59310); +const HarmonyImportDependencyParserPlugin = __webpack_require__(99433); +const HarmonyExportDependencyParserPlugin = __webpack_require__(49180); +const HarmonyTopLevelThisParserPlugin = __webpack_require__(58215); + +class HarmonyModulesPlugin { constructor(options) { - super(); this.options = options; - this.userRequest = this.options.request; - /** @type {false | string} */ - this.critical = false; - this.hadGlobalOrStickyRegExp = false; - if (this.options.regExp.global || this.options.regExp.sticky) { - this.options.regExp = null; - this.hadGlobalOrStickyRegExp = true; - } } - getResourceIdentifier() { - return ( - `context${this.options.request} ${this.options.recursive} ` + - `${regExpToString(this.options.regExp)} ${regExpToString( - this.options.include - )} ${regExpToString(this.options.exclude)} ` + - `${this.options.mode} ${this.options.chunkName} ` + - `${JSON.stringify(this.options.groupOptions)}` - ); - } + apply(compiler) { + compiler.hooks.compilation.tap( + "HarmonyModulesPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + HarmonyCompatibilityDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyCompatibilityDependency, + new HarmonyCompatibilityDependency.Template() + ); - getWarnings() { - let warnings = super.getWarnings() || []; - if (this.critical) { - warnings.push(new CriticalDependencyWarning(this.critical)); - } - if (this.hadGlobalOrStickyRegExp) { - warnings.push( - new CriticalDependencyWarning( - "Contexts can't use RegExps with the 'g' or 'y' flags." - ) - ); - } - return warnings; - } -} + compilation.dependencyFactories.set( + HarmonyInitDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyInitDependency, + new HarmonyInitDependency.Template() + ); -// TODO remove in webpack 5 -Object.defineProperty(ContextDependency.prototype, "async", { - configurable: false, - get() { - throw new Error( - "ContextDependency.async was removed. Use ContextDependency.options.mode instead." - ); - }, - set() { - throw new Error( - "ContextDependency.async was removed. Pass options.mode to constructor instead" + compilation.dependencyFactories.set( + HarmonyImportSideEffectDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSideEffectDependency, + new HarmonyImportSideEffectDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyImportSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyImportSpecifierDependency, + new HarmonyImportSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportHeaderDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportHeaderDependency, + new HarmonyExportHeaderDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportExpressionDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportExpressionDependency, + new HarmonyExportExpressionDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportSpecifierDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyExportSpecifierDependency, + new HarmonyExportSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyExportImportedSpecifierDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyExportImportedSpecifierDependency, + new HarmonyExportImportedSpecifierDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyAcceptDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + HarmonyAcceptDependency, + new HarmonyAcceptDependency.Template() + ); + + compilation.dependencyFactories.set( + HarmonyAcceptImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + HarmonyAcceptImportDependency, + new HarmonyAcceptImportDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if (parserOptions.harmony !== undefined && !parserOptions.harmony) + return; + + new HarmonyDetectionParserPlugin().apply(parser); + new HarmonyImportDependencyParserPlugin(this.options).apply(parser); + new HarmonyExportDependencyParserPlugin(this.options).apply(parser); + new HarmonyTopLevelThisParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("HarmonyModulesPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("HarmonyModulesPlugin", handler); + } ); } -}); - -module.exports = ContextDependency; +} +module.exports = HarmonyModulesPlugin; /***/ }), -/***/ 5594: -/***/ (function(__unused_webpack_module, exports) { +/***/ 58215: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Florent Cailhol @ooflorent */ -const ContextDependencyHelpers = exports; - -/** - * Escapes regular expression metacharacters - * @param {string} str String to quote - * @returns {string} Escaped string - */ -const quotemeta = str => { - return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&"); -}; +const ConstDependency = __webpack_require__(71101); -const splitContextFromPrefix = prefix => { - const idx = prefix.lastIndexOf("/"); - let context = "."; - if (idx >= 0) { - context = prefix.substr(0, idx); - prefix = `.${prefix.substr(idx)}`; - } - return { - context, - prefix - }; -}; - -const splitQueryFromPostfix = postfix => { - const idx = postfix.indexOf("?"); - let query = ""; - if (idx >= 0) { - query = postfix.substr(idx); - postfix = postfix.substr(0, idx); - } - return { - postfix, - query - }; -}; - -ContextDependencyHelpers.create = ( - Dep, - range, - param, - expr, - options, - contextOptions, - // when parser is not passed in, expressions won't be walked - parser = null -) => { - if (param.isTemplateString()) { - let prefixRaw = param.quasis[0].string; - let postfixRaw = - param.quasis.length > 1 - ? param.quasis[param.quasis.length - 1].string - : ""; - - const valueRange = param.range; - const { context, prefix } = splitContextFromPrefix(prefixRaw); - const { postfix, query } = splitQueryFromPostfix(postfixRaw); - - // When there are more than two quasis, the generated RegExp can be more precise - // We join the quasis with the expression regexp - const innerQuasis = param.quasis.slice(1, param.quasis.length - 1); - const innerRegExp = - options.wrappedContextRegExp.source + - innerQuasis - .map(q => quotemeta(q.string) + options.wrappedContextRegExp.source) - .join(""); - - // Example: `./context/pre${e}inner${e}inner2${e}post?query` - // context: "./context" - // prefix: "./pre" - // innerQuasis: [BEE("inner"), BEE("inner2")] - // (BEE = BasicEvaluatedExpression) - // postfix: "post" - // query: "?query" - // regExp: /^\.\/pre.*inner.*inner2.*post$/ - const regExp = new RegExp( - `^${quotemeta(prefix)}${innerRegExp}${quotemeta(postfix)}$` - ); - const dep = new Dep( - Object.assign( - { - request: context + query, - recursive: options.wrappedContextRecursive, - regExp, - mode: "sync" - }, - contextOptions - ), - range, - valueRange - ); - dep.loc = expr.loc; - const replaces = []; - - param.parts.forEach((part, i) => { - if (i % 2 === 0) { - // Quasis or merged quasi - let range = part.range; - let value = part.string; - if (param.templateStringKind === "cooked") { - value = JSON.stringify(value); - value = value.slice(1, value.length - 1); - } - if (i === 0) { - // prefix - value = prefix; - range = [param.range[0], part.range[1]]; - value = - (param.templateStringKind === "cooked" ? "`" : "String.raw`") + - value; - } else if (i === param.parts.length - 1) { - // postfix - value = postfix; - range = [part.range[0], param.range[1]]; - value = value + "`"; - } else if ( - part.expression && - part.expression.type === "TemplateElement" && - part.expression.value.raw === value - ) { - // Shortcut when it's a single quasi and doesn't need to be replaced - return; - } - replaces.push({ - range, - value - }); - } else { - // Expression - if (parser) { - parser.walkExpression(part.expression); +class HarmonyTopLevelThisParserPlugin { + apply(parser) { + parser.hooks.expression + .for("this") + .tap("HarmonyTopLevelThisParserPlugin", node => { + if (!parser.scope.topLevelScope) return; + const module = parser.state.module; + const isHarmony = !!(module.buildMeta && module.buildMeta.exportsType); + if (isHarmony) { + const dep = new ConstDependency("undefined", node.range, false); + dep.loc = node.loc; + parser.state.current.addDependency(dep); } - } - }); - - dep.replaces = replaces; - dep.critical = - options.wrappedContextCritical && - "a part of the request of a dependency is an expression"; - return dep; - } else if ( - param.isWrapped() && - ((param.prefix && param.prefix.isString()) || - (param.postfix && param.postfix.isString())) - ) { - let prefixRaw = - param.prefix && param.prefix.isString() ? param.prefix.string : ""; - let postfixRaw = - param.postfix && param.postfix.isString() ? param.postfix.string : ""; - const prefixRange = - param.prefix && param.prefix.isString() ? param.prefix.range : null; - const postfixRange = - param.postfix && param.postfix.isString() ? param.postfix.range : null; - const valueRange = param.range; - const { context, prefix } = splitContextFromPrefix(prefixRaw); - const { postfix, query } = splitQueryFromPostfix(postfixRaw); - const regExp = new RegExp( - `^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta( - postfix - )}$` - ); - const dep = new Dep( - Object.assign( - { - request: context + query, - recursive: options.wrappedContextRecursive, - regExp, - mode: "sync" - }, - contextOptions - ), - range, - valueRange - ); - dep.loc = expr.loc; - const replaces = []; - if (prefixRange) { - replaces.push({ - range: prefixRange, - value: JSON.stringify(prefix) - }); - } - if (postfixRange) { - replaces.push({ - range: postfixRange, - value: JSON.stringify(postfix) }); - } - dep.replaces = replaces; - dep.critical = - options.wrappedContextCritical && - "a part of the request of a dependency is an expression"; - - if (parser && param.wrappedInnerExpressions) { - for (const part of param.wrappedInnerExpressions) { - if (part.expression) parser.walkExpression(part.expression); - } - } - - return dep; - } else { - const dep = new Dep( - Object.assign( - { - request: options.exprContextRequest, - recursive: options.exprContextRecursive, - regExp: options.exprContextRegExp, - mode: "sync" - }, - contextOptions - ), - range, - param.range - ); - dep.loc = expr.loc; - dep.critical = - options.exprContextCritical && - "the request of a dependency is an expression"; - - if (parser) { - parser.walkExpression(param.expression); - } - - return dep; - } -}; - - -/***/ }), - -/***/ 6174: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -class ContextDependencyTemplateAsId { - apply(dep, source, runtime) { - const moduleExports = runtime.moduleExports({ - module: dep.module, - request: dep.request - }); - - if (dep.module) { - if (dep.valueRange) { - if (Array.isArray(dep.replaces)) { - for (let i = 0; i < dep.replaces.length; i++) { - const rep = dep.replaces[i]; - source.replace(rep.range[0], rep.range[1] - 1, rep.value); - } - } - source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); - // TODO webpack 5 remove `prepend` it's no longer used - source.replace( - dep.range[0], - dep.valueRange[0] - 1, - `${moduleExports}.resolve(${ - typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "" - }` - ); - } else { - source.replace( - dep.range[0], - dep.range[1] - 1, - `${moduleExports}.resolve` - ); - } - } else { - source.replace(dep.range[0], dep.range[1] - 1, moduleExports); - } } } -module.exports = ContextDependencyTemplateAsId; - - -/***/ }), - -/***/ 54380: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -class ContextDependencyTemplateAsRequireCall { - apply(dep, source, runtime) { - const moduleExports = runtime.moduleExports({ - module: dep.module, - request: dep.request - }); - if (dep.module) { - if (dep.valueRange) { - if (Array.isArray(dep.replaces)) { - for (let i = 0; i < dep.replaces.length; i++) { - const rep = dep.replaces[i]; - source.replace(rep.range[0], rep.range[1] - 1, rep.value); - } - } - source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); - // TODO webpack 5 remove `prepend` it's no longer used - source.replace( - dep.range[0], - dep.valueRange[0] - 1, - `${moduleExports}(${ - typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "" - }` - ); - } else { - source.replace(dep.range[0], dep.range[1] - 1, moduleExports); - } - } else { - source.replace(dep.range[0], dep.range[1] - 1, moduleExports); - } - } -} -module.exports = ContextDependencyTemplateAsRequireCall; +module.exports = HarmonyTopLevelThisParserPlugin; /***/ }), -/***/ 89079: +/***/ 20417: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99207,27 +97719,29 @@ module.exports = ContextDependencyTemplateAsRequireCall; Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(90865); +const ContextDependency = __webpack_require__(11583); +const ContextDependencyTemplateAsRequireCall = __webpack_require__(54380); -class ContextElementDependency extends ModuleDependency { - constructor(request, userRequest) { - super(request); - if (userRequest) { - this.userRequest = userRequest; - } +class ImportContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; } get type() { - return "context element"; + return `import() context ${this.options.mode}`; } } -module.exports = ContextElementDependency; +ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; + +module.exports = ImportContextDependency; /***/ }), -/***/ 54983: +/***/ 38875: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99236,26 +97750,24 @@ module.exports = ContextElementDependency; Author Tobias Koppers @sokra */ +const AsyncDependenciesBlock = __webpack_require__(22814); +const ImportDependency = __webpack_require__(50883); -const WebpackError = __webpack_require__(97391); - -class CriticalDependencyWarning extends WebpackError { - constructor(message) { - super(); - - this.name = "CriticalDependencyWarning"; - this.message = "Critical dependency: " + message; - - Error.captureStackTrace(this, this.constructor); +module.exports = class ImportDependenciesBlock extends AsyncDependenciesBlock { + // TODO webpack 5 reorganize arguments + constructor(request, range, groupOptions, module, loc, originModule) { + super(groupOptions, module, loc, request); + this.range = range; + const dep = new ImportDependency(request, originModule, this); + dep.loc = loc; + this.addDependency(dep); } -} - -module.exports = CriticalDependencyWarning; +}; /***/ }), -/***/ 53104: +/***/ 50883: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99264,39 +97776,40 @@ module.exports = CriticalDependencyWarning; Author Tobias Koppers @sokra */ +const ModuleDependency = __webpack_require__(90865); -const DependencyReference = __webpack_require__(71722); -const NullDependency = __webpack_require__(5088); - -class DelegatedExportsDependency extends NullDependency { - constructor(originModule, exports) { - super(); +class ImportDependency extends ModuleDependency { + constructor(request, originModule, block) { + super(request); this.originModule = originModule; - this.exports = exports; + this.block = block; } get type() { - return "delegated exports"; + return "import()"; } +} - getReference() { - return new DependencyReference(this.originModule, true, false); - } +ImportDependency.Template = class ImportDependencyTemplate { + apply(dep, source, runtime) { + const content = runtime.moduleNamespacePromise({ + block: dep.block, + module: dep.module, + request: dep.request, + strict: dep.originModule.buildMeta.strictHarmonyModule, + message: "import()" + }); - getExports() { - return { - exports: this.exports, - dependencies: undefined - }; + source.replace(dep.block.range[0], dep.block.range[1] - 1, content); } -} +}; -module.exports = DelegatedExportsDependency; +module.exports = ImportDependency; /***/ }), -/***/ 25930: +/***/ 25552: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99307,122 +97820,292 @@ module.exports = DelegatedExportsDependency; const ModuleDependency = __webpack_require__(90865); -class DelegatedSourceDependency extends ModuleDependency { - constructor(request) { +class ImportEagerDependency extends ModuleDependency { + constructor(request, originModule, range) { super(request); + this.originModule = originModule; + this.range = range; } get type() { - return "delegated source"; + return "import() eager"; } } -module.exports = DelegatedSourceDependency; +ImportEagerDependency.Template = class ImportEagerDependencyTemplate { + apply(dep, source, runtime) { + const content = runtime.moduleNamespacePromise({ + module: dep.module, + request: dep.request, + strict: dep.originModule.buildMeta.strictHarmonyModule, + message: "import() eager" + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +}; + +module.exports = ImportEagerDependency; /***/ }), -/***/ 71722: -/***/ (function(module) { +/***/ 93382: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent + Author Tobias Koppers @sokra */ -/** @typedef {import("../Module")} Module */ +const ImportContextDependency = __webpack_require__(20417); +const ImportWeakDependency = __webpack_require__(86817); +const ImportDependenciesBlock = __webpack_require__(38875); +const ImportEagerDependency = __webpack_require__(25552); +const ContextDependencyHelpers = __webpack_require__(5594); +const UnsupportedFeatureWarning = __webpack_require__(99953); +const CommentCompilationWarning = __webpack_require__(51760); -class DependencyReference { - // TODO webpack 5: module must be dynamic, you must pass a function returning a module - // This is needed to remove the hack in ConcatenatedModule - // The problem is that the `module` in Dependency could be replaced i. e. because of Scope Hoisting - /** - * - * @param {Module} module the referenced module - * @param {string[] | boolean} importedNames imported named from the module - * @param {boolean=} weak if this is a weak reference - * @param {number} order the order information or NaN if don't care - */ - constructor(module, importedNames, weak = false, order = NaN) { - // TODO webpack 5: make it a getter - this.module = module; - // true: full object - // false: only sideeffects/no export - // array of strings: the exports with this names - this.importedNames = importedNames; - this.weak = !!weak; - this.order = order; +class ImportParserPlugin { + constructor(options) { + this.options = options; } - /** - * @param {DependencyReference[]} array an array (will be modified) - * @returns {DependencyReference[]} the array again - */ - static sort(array) { - /** @type {WeakMap} */ - const originalOrder = new WeakMap(); - let i = 0; - for (const ref of array) { - originalOrder.set(ref, i++); - } - return array.sort((a, b) => { - const aOrder = a.order; - const bOrder = b.order; - if (isNaN(aOrder)) { - if (!isNaN(bOrder)) { - return 1; - } - } else { - if (isNaN(bOrder)) { - return -1; - } - if (aOrder !== bOrder) { - return aOrder - bOrder; - } + apply(parser) { + parser.hooks.importCall.tap("ImportParserPlugin", expr => { + if (expr.arguments.length !== 1) { + throw new Error( + "Incorrect number of arguments provided to 'import(module: string) -> Promise'." + ); } - const aOrg = originalOrder.get(a); - const bOrg = originalOrder.get(b); - return aOrg - bOrg; - }); - } -} - -module.exports = DependencyReference; + const param = parser.evaluateExpression(expr.arguments[0]); -/***/ }), + let chunkName = null; + let mode = "lazy"; + let include = null; + let exclude = null; + const groupOptions = {}; -/***/ 66279: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const { + options: importOptions, + errors: commentErrors + } = parser.parseCommentOptions(expr.range); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (commentErrors) { + for (const e of commentErrors) { + const { comment } = e; + parser.state.module.warnings.push( + new CommentCompilationWarning( + `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, + parser.state.module, + comment.loc + ) + ); + } + } -const Dependency = __webpack_require__(57282); + if (importOptions) { + if (importOptions.webpackIgnore !== undefined) { + if (typeof importOptions.webpackIgnore !== "boolean") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, + expr.loc + ) + ); + } else { + // Do not instrument `import()` if `webpackIgnore` is `true` + if (importOptions.webpackIgnore) { + return false; + } + } + } + if (importOptions.webpackChunkName !== undefined) { + if (typeof importOptions.webpackChunkName !== "string") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, + expr.loc + ) + ); + } else { + chunkName = importOptions.webpackChunkName; + } + } + if (importOptions.webpackMode !== undefined) { + if (typeof importOptions.webpackMode !== "string") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackMode\` expected a string, but received: ${importOptions.webpackMode}.`, + expr.loc + ) + ); + } else { + mode = importOptions.webpackMode; + } + } + if (importOptions.webpackPrefetch !== undefined) { + if (importOptions.webpackPrefetch === true) { + groupOptions.prefetchOrder = 0; + } else if (typeof importOptions.webpackPrefetch === "number") { + groupOptions.prefetchOrder = importOptions.webpackPrefetch; + } else { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackPrefetch\` expected true or a number, but received: ${importOptions.webpackPrefetch}.`, + expr.loc + ) + ); + } + } + if (importOptions.webpackPreload !== undefined) { + if (importOptions.webpackPreload === true) { + groupOptions.preloadOrder = 0; + } else if (typeof importOptions.webpackPreload === "number") { + groupOptions.preloadOrder = importOptions.webpackPreload; + } else { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackPreload\` expected true or a number, but received: ${importOptions.webpackPreload}.`, + expr.loc + ) + ); + } + } + if (importOptions.webpackInclude !== undefined) { + if ( + !importOptions.webpackInclude || + importOptions.webpackInclude.constructor.name !== "RegExp" + ) { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackInclude\` expected a regular expression, but received: ${importOptions.webpackInclude}.`, + expr.loc + ) + ); + } else { + include = new RegExp(importOptions.webpackInclude); + } + } + if (importOptions.webpackExclude !== undefined) { + if ( + !importOptions.webpackExclude || + importOptions.webpackExclude.constructor.name !== "RegExp" + ) { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackExclude\` expected a regular expression, but received: ${importOptions.webpackExclude}.`, + expr.loc + ) + ); + } else { + exclude = new RegExp(importOptions.webpackExclude); + } + } + } -class DllEntryDependency extends Dependency { - constructor(dependencies, name) { - super(); - this.dependencies = dependencies; - this.name = name; - } + if (param.isString()) { + if (mode !== "lazy" && mode !== "eager" && mode !== "weak") { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackMode\` expected 'lazy', 'eager' or 'weak', but received: ${mode}.`, + expr.loc + ) + ); + } - get type() { - return "dll entry"; + if (mode === "eager") { + const dep = new ImportEagerDependency( + param.string, + parser.state.module, + expr.range + ); + parser.state.current.addDependency(dep); + } else if (mode === "weak") { + const dep = new ImportWeakDependency( + param.string, + parser.state.module, + expr.range + ); + parser.state.current.addDependency(dep); + } else { + const depBlock = new ImportDependenciesBlock( + param.string, + expr.range, + Object.assign(groupOptions, { + name: chunkName + }), + parser.state.module, + expr.loc, + parser.state.module + ); + parser.state.current.addBlock(depBlock); + } + return true; + } else { + if ( + mode !== "lazy" && + mode !== "lazy-once" && + mode !== "eager" && + mode !== "weak" + ) { + parser.state.module.warnings.push( + new UnsupportedFeatureWarning( + parser.state.module, + `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`, + expr.loc + ) + ); + mode = "lazy"; + } + + if (mode === "weak") { + mode = "async-weak"; + } + const dep = ContextDependencyHelpers.create( + ImportContextDependency, + expr.range, + param, + expr, + this.options, + { + chunkName, + groupOptions, + include, + exclude, + mode, + namespaceObject: parser.state.module.buildMeta.strictHarmonyModule + ? "strict" + : true + }, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + }); } } -module.exports = DllEntryDependency; +module.exports = ImportParserPlugin; /***/ }), -/***/ 75159: +/***/ 58839: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99432,53 +98115,84 @@ module.exports = DllEntryDependency; */ -const NullDependency = __webpack_require__(5088); -const HarmonyImportDependency = __webpack_require__(81599); +const ImportDependency = __webpack_require__(50883); +const ImportEagerDependency = __webpack_require__(25552); +const ImportWeakDependency = __webpack_require__(86817); +const ImportContextDependency = __webpack_require__(20417); +const ImportParserPlugin = __webpack_require__(93382); -class HarmonyAcceptDependency extends NullDependency { - constructor(range, dependencies, hasCallback) { - super(); - this.range = range; - this.dependencies = dependencies; - this.hasCallback = hasCallback; +class ImportPlugin { + constructor(options) { + this.options = options; } - get type() { - return "accepted harmony modules"; - } -} + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap( + "ImportPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + ImportDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportDependency, + new ImportDependency.Template() + ); -HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate { - apply(dep, source, runtime) { - const content = dep.dependencies - .filter(dependency => - HarmonyImportDependency.Template.isImportEmitted(dependency, source) - ) - .map(dependency => dependency.getImportStatement(true, runtime)) - .join(""); + compilation.dependencyFactories.set( + ImportEagerDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportEagerDependency, + new ImportEagerDependency.Template() + ); - if (dep.hasCallback) { - source.insert( - dep.range[0], - `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(` - ); - source.insert( - dep.range[1], - ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }.bind(this)" - ); - return; - } + compilation.dependencyFactories.set( + ImportWeakDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + ImportWeakDependency, + new ImportWeakDependency.Template() + ); - source.insert(dep.range[1] - 0.5, `, function() { ${content} }`); - } -}; + compilation.dependencyFactories.set( + ImportContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + ImportContextDependency, + new ImportContextDependency.Template() + ); -module.exports = HarmonyAcceptDependency; + const handler = (parser, parserOptions) => { + if (parserOptions.import !== undefined && !parserOptions.import) + return; + + new ImportParserPlugin(options).apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ImportPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ImportPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ImportPlugin", handler); + } + ); + } +} +module.exports = ImportPlugin; /***/ }), -/***/ 66136: +/***/ 86817: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99487,29 +98201,40 @@ module.exports = HarmonyAcceptDependency; Author Tobias Koppers @sokra */ -const HarmonyImportDependency = __webpack_require__(81599); +const ModuleDependency = __webpack_require__(90865); -class HarmonyAcceptImportDependency extends HarmonyImportDependency { - constructor(request, originModule, parserScope) { - super(request, originModule, NaN, parserScope); +class ImportWeakDependency extends ModuleDependency { + constructor(request, originModule, range) { + super(request); + this.originModule = originModule; + this.range = range; this.weak = true; } get type() { - return "harmony accept"; + return "import() weak"; } } -HarmonyAcceptImportDependency.Template = class HarmonyAcceptImportDependencyTemplate extends HarmonyImportDependency.Template { - apply(dep, source, runtime) {} +ImportWeakDependency.Template = class ImportDependencyTemplate { + apply(dep, source, runtime) { + const content = runtime.moduleNamespacePromise({ + module: dep.module, + request: dep.request, + strict: dep.originModule.buildMeta.strictHarmonyModule, + message: "import() weak", + weak: true + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } }; -module.exports = HarmonyAcceptImportDependency; +module.exports = ImportWeakDependency; /***/ }), -/***/ 1533: +/***/ 54396: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99520,35 +98245,30 @@ module.exports = HarmonyAcceptImportDependency; const NullDependency = __webpack_require__(5088); -class HarmonyCompatibilityDependency extends NullDependency { - constructor(originModule) { +class JsonExportsDependency extends NullDependency { + constructor(exports) { super(); - this.originModule = originModule; + this.exports = exports; } get type() { - return "harmony export header"; + return "json exports"; } -} -HarmonyCompatibilityDependency.Template = class HarmonyExportDependencyTemplate { - apply(dep, source, runtime) { - const usedExports = dep.originModule.usedExports; - if (usedExports !== false && !Array.isArray(usedExports)) { - const content = runtime.defineEsModuleFlagStatement({ - exportsArgument: dep.originModule.exportsArgument - }); - source.insert(-10, content); - } + getExports() { + return { + exports: this.exports, + dependencies: undefined + }; } -}; +} -module.exports = HarmonyCompatibilityDependency; +module.exports = JsonExportsDependency; /***/ }), -/***/ 59310: +/***/ 1129: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99557,102 +98277,27 @@ module.exports = HarmonyCompatibilityDependency; Author Tobias Koppers @sokra */ +const ModuleDependency = __webpack_require__(90865); -const HarmonyCompatibilityDependency = __webpack_require__(1533); -const HarmonyInitDependency = __webpack_require__(27204); - -module.exports = class HarmonyDetectionParserPlugin { - apply(parser) { - parser.hooks.program.tap("HarmonyDetectionParserPlugin", ast => { - const isStrictHarmony = parser.state.module.type === "javascript/esm"; - const isHarmony = - isStrictHarmony || - ast.body.some( - statement => - statement.type === "ImportDeclaration" || - statement.type === "ExportDefaultDeclaration" || - statement.type === "ExportNamedDeclaration" || - statement.type === "ExportAllDeclaration" - ); - if (isHarmony) { - const module = parser.state.module; - const compatDep = new HarmonyCompatibilityDependency(module); - compatDep.loc = { - start: { - line: -1, - column: 0 - }, - end: { - line: -1, - column: 0 - }, - index: -3 - }; - module.addDependency(compatDep); - const initDep = new HarmonyInitDependency(module); - initDep.loc = { - start: { - line: -1, - column: 0 - }, - end: { - line: -1, - column: 0 - }, - index: -2 - }; - module.addDependency(initDep); - parser.state.harmonyParserScope = parser.state.harmonyParserScope || {}; - parser.scope.isStrict = true; - module.buildMeta.exportsType = "namespace"; - module.buildInfo.strict = true; - module.buildInfo.exportsArgument = "__webpack_exports__"; - if (isStrictHarmony) { - module.buildMeta.strictHarmonyModule = true; - module.buildInfo.moduleArgument = "__webpack_module__"; - } - } - }); - - const skipInHarmony = () => { - const module = parser.state.module; - if (module && module.buildMeta && module.buildMeta.exportsType) { - return true; - } - }; - - const nullInHarmony = () => { - const module = parser.state.module; - if (module && module.buildMeta && module.buildMeta.exportsType) { - return null; - } - }; +class LoaderDependency extends ModuleDependency { + /** + * @param {string} request request string + */ + constructor(request) { + super(request); + } - const nonHarmonyIdentifiers = ["define", "exports"]; - for (const identifer of nonHarmonyIdentifiers) { - parser.hooks.evaluateTypeof - .for(identifer) - .tap("HarmonyDetectionParserPlugin", nullInHarmony); - parser.hooks.typeof - .for(identifer) - .tap("HarmonyDetectionParserPlugin", skipInHarmony); - parser.hooks.evaluate - .for(identifer) - .tap("HarmonyDetectionParserPlugin", nullInHarmony); - parser.hooks.expression - .for(identifer) - .tap("HarmonyDetectionParserPlugin", skipInHarmony); - parser.hooks.call - .for(identifer) - .tap("HarmonyDetectionParserPlugin", skipInHarmony); - } + get type() { + return "loader"; } -}; +} + +module.exports = LoaderDependency; /***/ }), -/***/ 49180: +/***/ 31559: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99662,159 +98307,151 @@ module.exports = class HarmonyDetectionParserPlugin { */ -const HarmonyExportExpressionDependency = __webpack_require__(84245); -const HarmonyImportSideEffectDependency = __webpack_require__(79171); -const HarmonyExportHeaderDependency = __webpack_require__(21320); -const HarmonyExportSpecifierDependency = __webpack_require__(34834); -const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); -const ConstDependency = __webpack_require__(71101); +const LoaderDependency = __webpack_require__(1129); +const NormalModule = __webpack_require__(25963); -module.exports = class HarmonyExportDependencyParserPlugin { - constructor(moduleOptions) { - this.strictExportPresence = moduleOptions.strictExportPresence; - } +/** @typedef {import("../Module")} Module */ - apply(parser) { - parser.hooks.export.tap( - "HarmonyExportDependencyParserPlugin", - statement => { - const dep = new HarmonyExportHeaderDependency( - statement.declaration && statement.declaration.range, - statement.range - ); - dep.loc = Object.create(statement.loc); - dep.loc.index = -1; - parser.state.current.addDependency(dep); - return true; - } - ); - parser.hooks.exportImport.tap( - "HarmonyExportDependencyParserPlugin", - (statement, source) => { - parser.state.lastHarmonyImportOrder = - (parser.state.lastHarmonyImportOrder || 0) + 1; - const clearDep = new ConstDependency("", statement.range); - clearDep.loc = Object.create(statement.loc); - clearDep.loc.index = -1; - parser.state.current.addDependency(clearDep); - const sideEffectDep = new HarmonyImportSideEffectDependency( - source, - parser.state.module, - parser.state.lastHarmonyImportOrder, - parser.state.harmonyParserScope +/** + * @callback LoadModuleCallback + * @param {Error=} err error object + * @param {string=} source source code + * @param {object=} map source map + * @param {Module=} module loaded module if successful + */ + +class LoaderPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "LoaderPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + LoaderDependency, + normalModuleFactory ); - sideEffectDep.loc = Object.create(statement.loc); - sideEffectDep.loc.index = -1; - parser.state.current.addDependency(sideEffectDep); - return true; } ); - parser.hooks.exportExpression.tap( - "HarmonyExportDependencyParserPlugin", - (statement, expr) => { - const comments = parser.getComments([ - statement.range[0], - expr.range[0] - ]); - const dep = new HarmonyExportExpressionDependency( - parser.state.module, - expr.range, - statement.range, - comments - .map(c => { - switch (c.type) { - case "Block": - return `/*${c.value}*/`; - case "Line": - return `//${c.value}\n`; + + compiler.hooks.compilation.tap("LoaderPlugin", compilation => { + compilation.hooks.normalModuleLoader.tap( + "LoaderPlugin", + (loaderContext, module) => { + /** + * @param {string} request the request string to load the module from + * @param {LoadModuleCallback} callback callback returning the loaded module or error + * @returns {void} + */ + loaderContext.loadModule = (request, callback) => { + const dep = new LoaderDependency(request); + dep.loc = { + name: request + }; + const factory = compilation.dependencyFactories.get( + dep.constructor + ); + if (factory === undefined) { + return callback( + new Error( + `No module factory available for dependency type: ${dep.constructor.name}` + ) + ); + } + compilation.semaphore.release(); + compilation.addModuleDependencies( + module, + [ + { + factory, + dependencies: [dep] + } + ], + true, + "lm", + true, + err => { + compilation.semaphore.acquire(() => { + if (err) { + return callback(err); + } + if (!dep.module) { + return callback(new Error("Cannot load the module")); + } + // TODO consider removing this in webpack 5 + if (dep.module instanceof NormalModule && dep.module.error) { + return callback(dep.module.error); + } + if (!dep.module._source) { + throw new Error( + "The module created for a LoaderDependency must have a property _source" + ); + } + let source, map; + const moduleSource = dep.module._source; + if (moduleSource.sourceAndMap) { + const sourceAndMap = moduleSource.sourceAndMap(); + map = sourceAndMap.map; + source = sourceAndMap.source; + } else { + map = moduleSource.map(); + source = moduleSource.source(); + } + if (dep.module.buildInfo.fileDependencies) { + for (const d of dep.module.buildInfo.fileDependencies) { + loaderContext.addDependency(d); + } + } + if (dep.module.buildInfo.contextDependencies) { + for (const d of dep.module.buildInfo.contextDependencies) { + loaderContext.addContextDependency(d); + } + } + return callback(null, source, map, dep.module); + }); } - return ""; - }) - .join("") - ); - dep.loc = Object.create(statement.loc); - dep.loc.index = -1; - parser.state.current.addDependency(dep); - return true; - } - ); - parser.hooks.exportDeclaration.tap( - "HarmonyExportDependencyParserPlugin", - statement => {} - ); - parser.hooks.exportSpecifier.tap( - "HarmonyExportDependencyParserPlugin", - (statement, id, name, idx) => { - const rename = parser.scope.renames.get(id); - let dep; - const harmonyNamedExports = (parser.state.harmonyNamedExports = - parser.state.harmonyNamedExports || new Set()); - harmonyNamedExports.add(name); - if (rename === "imported var") { - const settings = parser.state.harmonySpecifier.get(id); - dep = new HarmonyExportImportedSpecifierDependency( - settings.source, - parser.state.module, - settings.sourceOrder, - parser.state.harmonyParserScope, - settings.id, - name, - harmonyNamedExports, - null, - this.strictExportPresence - ); - } else { - dep = new HarmonyExportSpecifierDependency( - parser.state.module, - id, - name - ); - } - dep.loc = Object.create(statement.loc); - dep.loc.index = idx; - parser.state.current.addDependency(dep); - return true; - } - ); - parser.hooks.exportImportSpecifier.tap( - "HarmonyExportDependencyParserPlugin", - (statement, source, id, name, idx) => { - const harmonyNamedExports = (parser.state.harmonyNamedExports = - parser.state.harmonyNamedExports || new Set()); - let harmonyStarExports = null; - if (name) { - harmonyNamedExports.add(name); - } else { - harmonyStarExports = parser.state.harmonyStarExports = - parser.state.harmonyStarExports || []; - } - const dep = new HarmonyExportImportedSpecifierDependency( - source, - parser.state.module, - parser.state.lastHarmonyImportOrder, - parser.state.harmonyParserScope, - id, - name, - harmonyNamedExports, - harmonyStarExports && harmonyStarExports.slice(), - this.strictExportPresence - ); - if (harmonyStarExports) { - harmonyStarExports.push(dep); + ); + }; } - dep.loc = Object.create(statement.loc); - dep.loc.index = idx; - parser.state.current.addDependency(dep); - return true; - } - ); + ); + }); } -}; +} +module.exports = LoaderPlugin; /***/ }), -/***/ 84245: +/***/ 17356: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class LocalModule { + constructor(module, name, idx) { + this.module = module; + this.name = name; + this.idx = idx; + this.used = false; + } + + flagUsed() { + this.used = true; + } + + variableName() { + return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; + } +} +module.exports = LocalModule; + + +/***/ }), + +/***/ 56570: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99825,62 +98462,92 @@ module.exports = class HarmonyExportDependencyParserPlugin { const NullDependency = __webpack_require__(5088); -class HarmonyExportExpressionDependency extends NullDependency { - constructor(originModule, range, rangeStatement, prefix) { +class LocalModuleDependency extends NullDependency { + constructor(localModule, range, callNew) { super(); - this.originModule = originModule; + localModule.flagUsed(); + this.localModule = localModule; this.range = range; - this.rangeStatement = rangeStatement; - this.prefix = prefix; + this.callNew = callNew; } +} - get type() { - return "harmony export expression"; +LocalModuleDependency.Template = class LocalModuleDependencyTemplate { + apply(dep, source) { + if (!dep.range) return; + const moduleInstance = dep.callNew + ? `new (function () { return ${dep.localModule.variableName()}; })()` + : dep.localModule.variableName(); + source.replace(dep.range[0], dep.range[1] - 1, moduleInstance); } +}; - getExports() { - return { - exports: ["default"], - dependencies: undefined - }; - } -} +module.exports = LocalModuleDependency; -HarmonyExportExpressionDependency.Template = class HarmonyExportDependencyTemplate { - apply(dep, source) { - const used = dep.originModule.isUsed("default"); - const content = this.getContent(dep.originModule, used); - if (dep.range) { - source.replace( - dep.rangeStatement[0], - dep.range[0] - 1, - content + "(" + dep.prefix - ); - source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); - return; +/***/ }), + +/***/ 39658: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const LocalModule = __webpack_require__(17356); +const LocalModulesHelpers = exports; + +const lookup = (parent, mod) => { + if (mod.charAt(0) !== ".") return mod; + + var path = parent.split("/"); + var segs = mod.split("/"); + path.pop(); + + for (let i = 0; i < segs.length; i++) { + const seg = segs[i]; + if (seg === "..") { + path.pop(); + } else if (seg !== ".") { + path.push(seg); } + } - source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); + return path.join("/"); +}; + +LocalModulesHelpers.addLocalModule = (state, name) => { + if (!state.localModules) { + state.localModules = []; } + const m = new LocalModule(state.module, name, state.localModules.length); + state.localModules.push(m); + return m; +}; - getContent(module, used) { - const exportsName = module.exportsArgument; - if (used) { - return `/* harmony default export */ ${exportsName}[${JSON.stringify( - used - )}] = `; +LocalModulesHelpers.getLocalModule = (state, name, namedModule) => { + if (!state.localModules) return null; + if (namedModule) { + // resolve dependency name relative to the defining named module + name = lookup(namedModule, name); + } + for (let i = 0; i < state.localModules.length; i++) { + if (state.localModules[i].name === name) { + return state.localModules[i]; } - return "/* unused harmony default export */ var _unused_webpack_default_export = "; } + return null; }; -module.exports = HarmonyExportExpressionDependency; +module.exports = LocalModulesHelpers; /***/ }), -/***/ 21320: +/***/ 90865: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -99889,37 +98556,30 @@ module.exports = HarmonyExportExpressionDependency; Author Tobias Koppers @sokra */ -const NullDependency = __webpack_require__(5088); +const Dependency = __webpack_require__(57282); -class HarmonyExportHeaderDependency extends NullDependency { - constructor(range, rangeStatement) { +class ModuleDependency extends Dependency { + /** + * @param {string} request request path which needs resolving + */ + constructor(request) { super(); - this.range = range; - this.rangeStatement = rangeStatement; + this.request = request; + this.userRequest = request; } - get type() { - return "harmony export header"; + getResourceIdentifier() { + return `module${this.request}`; } } -HarmonyExportHeaderDependency.Template = class HarmonyExportDependencyTemplate { - apply(dep, source) { - const content = ""; - const replaceUntil = dep.range - ? dep.range[0] - 1 - : dep.rangeStatement[1] - 1; - source.replace(dep.rangeStatement[0], replaceUntil, content); - } -}; - -module.exports = HarmonyExportHeaderDependency; +module.exports = ModuleDependency; /***/ }), -/***/ 22864: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 63708: +/***/ (function(module) { "use strict"; /* @@ -99928,664 +98588,606 @@ module.exports = HarmonyExportHeaderDependency; */ -const DependencyReference = __webpack_require__(71722); -const HarmonyImportDependency = __webpack_require__(81599); -const Template = __webpack_require__(96066); -const HarmonyLinkingError = __webpack_require__(30327); +class ModuleDependencyTemplateAsId { + apply(dep, source, runtime) { + if (!dep.range) return; + const content = runtime.moduleId({ + module: dep.module, + request: dep.request + }); + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} +module.exports = ModuleDependencyTemplateAsId; -/** @typedef {import("../Module")} Module */ -/** @typedef {"missing"|"unused"|"empty-star"|"reexport-non-harmony-default"|"reexport-named-default"|"reexport-namespace-object"|"reexport-non-harmony-default-strict"|"reexport-fake-namespace-object"|"rexport-non-harmony-undefined"|"safe-reexport"|"checked-reexport"|"dynamic-reexport"} ExportModeType */ +/***/ }), -/** @type {Map} */ -const EMPTY_MAP = new Map(); +/***/ 60441: +/***/ (function(module) { -class ExportMode { - /** - * @param {ExportModeType} type type of the mode - */ - constructor(type) { - /** @type {ExportModeType} */ - this.type = type; - /** @type {string|null} */ - this.name = null; - /** @type {Map} */ - this.map = EMPTY_MAP; - /** @type {Set|null} */ - this.ignored = null; - /** @type {Module|null} */ - this.module = null; - /** @type {string|null} */ - this.userRequest = null; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +class ModuleDependencyTemplateAsRequireId { + apply(dep, source, runtime) { + if (!dep.range) return; + const content = runtime.moduleExports({ + module: dep.module, + request: dep.request + }); + source.replace(dep.range[0], dep.range[1] - 1, content); } } +module.exports = ModuleDependencyTemplateAsRequireId; -const EMPTY_STAR_MODE = new ExportMode("empty-star"); -class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { - constructor( - request, - originModule, - sourceOrder, - parserScope, - id, - name, - activeExports, - otherStarExports, - strictExportPresence - ) { - super(request, originModule, sourceOrder, parserScope); - this.id = id; - this.redirectedId = undefined; - this.name = name; - this.activeExports = activeExports; - this.otherStarExports = otherStarExports; - this.strictExportPresence = strictExportPresence; +/***/ }), + +/***/ 29018: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +const ModuleDependency = __webpack_require__(90865); +const ModuleDependencyTemplateAsId = __webpack_require__(63708); + +class ModuleHotAcceptDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; } get type() { - return "harmony export imported specifier"; + return "module.hot.accept"; } +} - get _id() { - return this.redirectedId || this.id; - } +ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; - getMode(ignoreUnused) { - const name = this.name; - const id = this._id; - const used = this.originModule.isUsed(name); - const importedModule = this._module; +module.exports = ModuleHotAcceptDependency; - if (!importedModule) { - const mode = new ExportMode("missing"); - mode.userRequest = this.userRequest; - return mode; - } - if ( - !ignoreUnused && - (name ? !used : this.originModule.usedExports === false) - ) { - const mode = new ExportMode("unused"); - mode.name = name || "*"; - return mode; - } +/***/ }), - const strictHarmonyModule = this.originModule.buildMeta.strictHarmonyModule; - if (name && id === "default" && importedModule.buildMeta) { - if (!importedModule.buildMeta.exportsType) { - const mode = new ExportMode( - strictHarmonyModule - ? "reexport-non-harmony-default-strict" - : "reexport-non-harmony-default" - ); - mode.name = name; - mode.module = importedModule; - return mode; - } else if (importedModule.buildMeta.exportsType === "named") { - const mode = new ExportMode("reexport-named-default"); - mode.name = name; - mode.module = importedModule; - return mode; - } - } - - const isNotAHarmonyModule = - importedModule.buildMeta && !importedModule.buildMeta.exportsType; - if (name) { - let mode; - if (id) { - // export { name as name } - if (isNotAHarmonyModule && strictHarmonyModule) { - mode = new ExportMode("rexport-non-harmony-undefined"); - mode.name = name; - } else { - mode = new ExportMode("safe-reexport"); - mode.map = new Map([[name, id]]); - } - } else { - // export { * as name } - if (isNotAHarmonyModule && strictHarmonyModule) { - mode = new ExportMode("reexport-fake-namespace-object"); - mode.name = name; - } else { - mode = new ExportMode("reexport-namespace-object"); - mode.name = name; - } - } - mode.module = importedModule; - return mode; - } +/***/ 60482: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const hasUsedExports = Array.isArray(this.originModule.usedExports); - const hasProvidedExports = Array.isArray( - importedModule.buildMeta.providedExports - ); - const activeFromOtherStarExports = this._discoverActiveExportsFromOtherStartExports(); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // export * - if (hasUsedExports) { - // reexport * with known used exports - if (hasProvidedExports) { - const map = new Map( - this.originModule.usedExports - .filter(id => { - if (id === "default") return false; - if (this.activeExports.has(id)) return false; - if (activeFromOtherStarExports.has(id)) return false; - if (!importedModule.buildMeta.providedExports.includes(id)) - return false; - return true; - }) - .map(item => [item, item]) - ); +const ModuleDependency = __webpack_require__(90865); +const ModuleDependencyTemplateAsId = __webpack_require__(63708); - if (map.size === 0) { - return EMPTY_STAR_MODE; - } +class ModuleHotDeclineDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; + this.weak = true; + } - const mode = new ExportMode("safe-reexport"); - mode.module = importedModule; - mode.map = map; - return mode; - } + get type() { + return "module.hot.decline"; + } +} - const map = new Map( - this.originModule.usedExports - .filter(id => { - if (id === "default") return false; - if (this.activeExports.has(id)) return false; - if (activeFromOtherStarExports.has(id)) return false; +ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; - return true; - }) - .map(item => [item, item]) - ); +module.exports = ModuleHotDeclineDependency; - if (map.size === 0) { - return EMPTY_STAR_MODE; - } - const mode = new ExportMode("checked-reexport"); - mode.module = importedModule; - mode.map = map; - return mode; - } +/***/ }), - if (hasProvidedExports) { - const map = new Map( - importedModule.buildMeta.providedExports - .filter(id => { - if (id === "default") return false; - if (this.activeExports.has(id)) return false; - if (activeFromOtherStarExports.has(id)) return false; +/***/ 7791: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return true; - }) - .map(item => [item, item]) - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - if (map.size === 0) { - return EMPTY_STAR_MODE; - } +/** @typedef {import("./SingleEntryDependency")} SingleEntryDependency */ +const Dependency = __webpack_require__(57282); - const mode = new ExportMode("safe-reexport"); - mode.module = importedModule; - mode.map = map; - return mode; - } +class MultiEntryDependency extends Dependency { + /** + * @param {SingleEntryDependency[]} dependencies an array of SingleEntryDependencies + * @param {string} name entry name + */ + constructor(dependencies, name) { + super(); + this.dependencies = dependencies; + this.name = name; + } - const mode = new ExportMode("dynamic-reexport"); - mode.module = importedModule; - mode.ignored = new Set([ - "default", - ...this.activeExports, - ...activeFromOtherStarExports - ]); - return mode; + get type() { + return "multi entry"; } +} - getReference() { - const mode = this.getMode(false); +module.exports = MultiEntryDependency; - switch (mode.type) { - case "missing": - case "unused": - case "empty-star": - return null; - case "reexport-non-harmony-default": - case "reexport-named-default": - return new DependencyReference( - mode.module, - ["default"], - false, - this.sourceOrder - ); +/***/ }), - case "reexport-namespace-object": - case "reexport-non-harmony-default-strict": - case "reexport-fake-namespace-object": - case "rexport-non-harmony-undefined": - return new DependencyReference( - mode.module, - true, - false, - this.sourceOrder - ); +/***/ 5088: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - case "safe-reexport": - case "checked-reexport": - return new DependencyReference( - mode.module, - Array.from(mode.map.values()), - false, - this.sourceOrder - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - case "dynamic-reexport": - return new DependencyReference( - mode.module, - true, - false, - this.sourceOrder - ); +const Dependency = __webpack_require__(57282); - default: - throw new Error(`Unknown mode ${mode.type}`); - } +class NullDependency extends Dependency { + get type() { + return "null"; } - _discoverActiveExportsFromOtherStartExports() { - if (!this.otherStarExports) return new Set(); - const result = new Set(); - // try to learn impossible exports from other star exports with provided exports - for (const otherStarExport of this.otherStarExports) { - const otherImportedModule = otherStarExport._module; - if ( - otherImportedModule && - Array.isArray(otherImportedModule.buildMeta.providedExports) - ) { - for (const exportName of otherImportedModule.buildMeta - .providedExports) { - result.add(exportName); - } - } - } - return result; - } + updateHash() {} +} - getExports() { - if (this.name) { - return { - exports: [this.name], - dependencies: undefined - }; - } +NullDependency.Template = class NullDependencyTemplate { + apply() {} +}; - const importedModule = this._module; +module.exports = NullDependency; - if (!importedModule) { - // no imported module available - return { - exports: null, - dependencies: undefined - }; - } - if (Array.isArray(importedModule.buildMeta.providedExports)) { - const activeFromOtherStarExports = this._discoverActiveExportsFromOtherStartExports(); - return { - exports: importedModule.buildMeta.providedExports.filter( - id => - id !== "default" && - !activeFromOtherStarExports.has(id) && - !this.activeExports.has(id) - ), - dependencies: [importedModule] - }; - } +/***/ }), - if (importedModule.buildMeta.providedExports) { - return { - exports: true, - dependencies: undefined - }; - } +/***/ 14237: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return { - exports: null, - dependencies: [importedModule] - }; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - getWarnings() { - if ( - this.strictExportPresence || - this.originModule.buildMeta.strictHarmonyModule - ) { - return []; - } - return this._getErrors(); - } +const ModuleDependency = __webpack_require__(90865); - getErrors() { - if ( - this.strictExportPresence || - this.originModule.buildMeta.strictHarmonyModule - ) { - return this._getErrors(); - } - return []; +class PrefetchDependency extends ModuleDependency { + constructor(request) { + super(request); } - _getErrors() { - const importedModule = this._module; - if (!importedModule) { - return; - } + get type() { + return "prefetch"; + } +} - if (!importedModule.buildMeta || !importedModule.buildMeta.exportsType) { - // It's not an harmony module - if ( - this.originModule.buildMeta.strictHarmonyModule && - this._id && - this._id !== "default" - ) { - // In strict harmony modules we only support the default export - return [ - new HarmonyLinkingError( - `Can't reexport the named export '${this._id}' from non EcmaScript module (only default export is available)` - ) - ]; - } - return; - } +module.exports = PrefetchDependency; - if (!this._id) { - return; - } - if (importedModule.isProvided(this._id) !== false) { - // It's provided or we are not sure - return; - } +/***/ }), - // We are sure that it's not provided - const idIsNotNameMessage = - this._id !== this.name ? ` (reexported as '${this.name}')` : ""; - const errorMessage = `"export '${this._id}'${idIsNotNameMessage} was not found in '${this.userRequest}'`; - return [new HarmonyLinkingError(errorMessage)]; - } +/***/ 79142: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - updateHash(hash) { - super.updateHash(hash); - const hashValue = this.getHashValue(this._module); - hash.update(hashValue); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - getHashValue(importedModule) { - if (!importedModule) { - return ""; - } +const ContextDependency = __webpack_require__(11583); +const ModuleDependencyTemplateAsRequireId = __webpack_require__(60441); - const stringifiedUsedExport = JSON.stringify(importedModule.usedExports); - const stringifiedProvidedExport = JSON.stringify( - importedModule.buildMeta.providedExports - ); - return ( - importedModule.used + stringifiedUsedExport + stringifiedProvidedExport - ); +class RequireContextDependency extends ContextDependency { + constructor(options, range) { + super(options); + this.range = range; } - disconnect() { - super.disconnect(); - this.redirectedId = undefined; + get type() { + return "require.context"; } } -module.exports = HarmonyExportImportedSpecifierDependency; +RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; -HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedSpecifierDependencyTemplate extends HarmonyImportDependency.Template { - harmonyInit(dep, source, runtime, dependencyTemplates) { - super.harmonyInit(dep, source, runtime, dependencyTemplates); - const content = this.getContent(dep); - source.insert(-1, content); - } +module.exports = RequireContextDependency; - getHarmonyInitOrder(dep) { - if (dep.name) { - const used = dep.originModule.isUsed(dep.name); - if (!used) return NaN; - } else { - const importedModule = dep._module; - const activeFromOtherStarExports = dep._discoverActiveExportsFromOtherStartExports(); +/***/ }), - if (Array.isArray(dep.originModule.usedExports)) { - // we know which exports are used +/***/ 10566: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const unused = dep.originModule.usedExports.every(id => { - if (id === "default") return true; - if (dep.activeExports.has(id)) return true; - if (importedModule.isProvided(id) === false) return true; - if (activeFromOtherStarExports.has(id)) return true; - return false; - }); - if (unused) return NaN; - } else if ( - dep.originModule.usedExports && - importedModule && - Array.isArray(importedModule.buildMeta.providedExports) - ) { - // not sure which exports are used, but we know which are provided +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const unused = importedModule.buildMeta.providedExports.every(id => { - if (id === "default") return true; - if (dep.activeExports.has(id)) return true; - if (activeFromOtherStarExports.has(id)) return true; - return false; - }); - if (unused) return NaN; - } - } - return super.getHarmonyInitOrder(dep); + +const RequireContextDependency = __webpack_require__(79142); + +module.exports = class RequireContextDependencyParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.context") + .tap("RequireContextDependencyParserPlugin", expr => { + let regExp = /^\.\/.*$/; + let recursive = true; + let mode = "sync"; + switch (expr.arguments.length) { + case 4: { + const modeExpr = parser.evaluateExpression(expr.arguments[3]); + if (!modeExpr.isString()) return; + mode = modeExpr.string; + } + // falls through + case 3: { + const regExpExpr = parser.evaluateExpression(expr.arguments[2]); + if (!regExpExpr.isRegExp()) return; + regExp = regExpExpr.regExp; + } + // falls through + case 2: { + const recursiveExpr = parser.evaluateExpression(expr.arguments[1]); + if (!recursiveExpr.isBoolean()) return; + recursive = recursiveExpr.bool; + } + // falls through + case 1: { + const requestExpr = parser.evaluateExpression(expr.arguments[0]); + if (!requestExpr.isString()) return; + const dep = new RequireContextDependency( + { + request: requestExpr.string, + recursive, + regExp, + mode + }, + expr.range + ); + dep.loc = expr.loc; + dep.optional = parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + } + } + }); } +}; - getContent(dep) { - const mode = dep.getMode(false); - const module = dep.originModule; - const importedModule = dep._module; - const importVar = dep.getImportVar(); - switch (mode.type) { - case "missing": - return `throw new Error(${JSON.stringify( - `Cannot find module '${mode.userRequest}'` - )});\n`; +/***/ }), - case "unused": - return `${Template.toNormalComment( - `unused harmony reexport ${mode.name}` - )}\n`; +/***/ 89042: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - case "reexport-non-harmony-default": - return ( - "/* harmony reexport (default from non-harmony) */ " + - this.getReexportStatement( - module, - module.isUsed(mode.name), - importVar, - null - ) - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - case "reexport-named-default": - return ( - "/* harmony reexport (default from named exports) */ " + - this.getReexportStatement( - module, - module.isUsed(mode.name), - importVar, - "" - ) + +const RequireContextDependency = __webpack_require__(79142); +const ContextElementDependency = __webpack_require__(89079); + +const RequireContextDependencyParserPlugin = __webpack_require__(10566); + +class RequireContextPlugin { + constructor(modulesDirectories, extensions, mainFiles) { + if (!Array.isArray(modulesDirectories)) { + throw new Error("modulesDirectories must be an array"); + } + if (!Array.isArray(extensions)) { + throw new Error("extensions must be an array"); + } + this.modulesDirectories = modulesDirectories; + this.extensions = extensions; + this.mainFiles = mainFiles; + } + + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireContextPlugin", + (compilation, { contextModuleFactory, normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireContextDependency, + contextModuleFactory + ); + compilation.dependencyTemplates.set( + RequireContextDependency, + new RequireContextDependency.Template() ); - case "reexport-fake-namespace-object": - return ( - "/* harmony reexport (fake namespace object from non-harmony) */ " + - this.getReexportFakeNamespaceObjectStatement( - module, - module.isUsed(mode.name), - importVar - ) + compilation.dependencyFactories.set( + ContextElementDependency, + normalModuleFactory ); - case "rexport-non-harmony-undefined": - return ( - "/* harmony reexport (non default export from non-harmony) */ " + - this.getReexportStatement( - module, - module.isUsed(mode.name), - "undefined", - "" + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireContext !== undefined && + !parserOptions.requireContext ) + return; + + new RequireContextDependencyParserPlugin().apply(parser); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireContextPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireContextPlugin", handler); + + contextModuleFactory.hooks.alternatives.tap( + "RequireContextPlugin", + items => { + if (items.length === 0) return items; + return items + .map(obj => { + return this.extensions + .filter(ext => { + const l = obj.request.length; + return ( + l > ext.length && + obj.request.substr(l - ext.length, l) === ext + ); + }) + .map(ext => { + const l = obj.request.length; + return { + context: obj.context, + request: obj.request.substr(0, l - ext.length) + }; + }) + .concat(obj); + }) + .reduce((a, b) => a.concat(b), []); + } ); - case "reexport-non-harmony-default-strict": - return ( - "/* harmony reexport (default from non-harmony) */ " + - this.getReexportStatement( - module, - module.isUsed(mode.name), - importVar, - "" - ) + contextModuleFactory.hooks.alternatives.tap( + "RequireContextPlugin", + items => { + if (items.length === 0) return items; + return items + .map(obj => { + return this.mainFiles + .filter(mainFile => { + const l = obj.request.length; + return ( + l > mainFile.length + 1 && + obj.request.substr(l - mainFile.length - 1, l) === + "/" + mainFile + ); + }) + .map(mainFile => { + const l = obj.request.length; + return [ + { + context: obj.context, + request: obj.request.substr(0, l - mainFile.length) + }, + { + context: obj.context, + request: obj.request.substr(0, l - mainFile.length - 1) + } + ]; + }) + .reduce((a, b) => a.concat(b), []) + .concat(obj); + }) + .reduce((a, b) => a.concat(b), []); + } ); - case "reexport-namespace-object": - return ( - "/* harmony reexport (module object) */ " + - this.getReexportStatement( - module, - module.isUsed(mode.name), - importVar, - "" - ) + contextModuleFactory.hooks.alternatives.tap( + "RequireContextPlugin", + items => { + if (items.length === 0) return items; + return items.map(obj => { + for (let i = 0; i < this.modulesDirectories.length; i++) { + const dir = this.modulesDirectories[i]; + const idx = obj.request.indexOf("./" + dir + "/"); + if (idx === 0) { + obj.request = obj.request.slice(dir.length + 3); + break; + } + } + return obj; + }); + } ); + } + ); + } +} +module.exports = RequireContextPlugin; - case "empty-star": - return "/* empty/unused harmony star reexport */"; - case "safe-reexport": - return Array.from(mode.map.entries()) - .map(item => { - return ( - "/* harmony reexport (safe) */ " + - this.getReexportStatement( - module, - module.isUsed(item[0]), - importVar, - importedModule.isUsed(item[1]) - ) + - "\n" - ); - }) - .join(""); +/***/ }), - case "checked-reexport": - return Array.from(mode.map.entries()) - .map(item => { - return ( - "/* harmony reexport (checked) */ " + - this.getConditionalReexportStatement( - module, - item[0], - importVar, - item[1] - ) + - "\n" - ); - }) - .join(""); +/***/ 49105: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - case "dynamic-reexport": { - const ignoredExports = mode.ignored; - let content = - "/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in " + - importVar + - ") "; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Filter out exports which are defined by other exports - // and filter out default export because it cannot be reexported with * - if (ignoredExports.size > 0) { - content += - "if(" + - JSON.stringify(Array.from(ignoredExports)) + - ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; - } else { - content += "if(__WEBPACK_IMPORT_KEY__ !== 'default') "; - } - const exportsName = dep.originModule.exportsArgument; - return ( - content + - `(function(key) { __webpack_require__.d(${exportsName}, key, function() { return ${importVar}[key]; }) }(__WEBPACK_IMPORT_KEY__));\n` - ); - } +const AsyncDependenciesBlock = __webpack_require__(22814); +const RequireEnsureDependency = __webpack_require__(75830); - default: - throw new Error(`Unknown mode ${mode.type}`); +module.exports = class RequireEnsureDependenciesBlock extends AsyncDependenciesBlock { + constructor( + expr, + successExpression, + errorExpression, + chunkName, + chunkNameRange, + module, + loc + ) { + super(chunkName, module, loc, null); + this.expr = expr; + const successBodyRange = + successExpression && + successExpression.body && + successExpression.body.range; + if (successBodyRange) { + this.range = [successBodyRange[0] + 1, successBodyRange[1] - 1]; } + this.chunkNameRange = chunkNameRange; + const dep = new RequireEnsureDependency(this); + dep.loc = loc; + this.addDependency(dep); } +}; - getReexportStatement(module, key, name, valueKey) { - const exportsName = module.exportsArgument; - const returnValue = this.getReturnValue(name, valueKey); - return `__webpack_require__.d(${exportsName}, ${JSON.stringify( - key - )}, function() { return ${returnValue}; });\n`; - } - getReexportFakeNamespaceObjectStatement(module, key, name) { - const exportsName = module.exportsArgument; - return `__webpack_require__.d(${exportsName}, ${JSON.stringify( - key - )}, function() { return __webpack_require__.t(${name}); });\n`; - } +/***/ }), - getConditionalReexportStatement(module, key, name, valueKey) { - if (valueKey === false) { - return "/* unused export */\n"; - } - const exportsName = module.exportsArgument; - const returnValue = this.getReturnValue(name, valueKey); - return `if(__webpack_require__.o(${name}, ${JSON.stringify( - valueKey - )})) __webpack_require__.d(${exportsName}, ${JSON.stringify( - key - )}, function() { return ${returnValue}; });\n`; - } +/***/ 24620: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - getReturnValue(name, valueKey) { - if (valueKey === null) { - return `${name}_default.a`; - } - if (valueKey === "") { - return name; - } - if (valueKey === false) { - return "/* unused export */ undefined"; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - return `${name}[${JSON.stringify(valueKey)}]`; + +const RequireEnsureDependenciesBlock = __webpack_require__(49105); +const RequireEnsureItemDependency = __webpack_require__(5511); +const getFunctionExpression = __webpack_require__(64197); + +module.exports = class RequireEnsureDependenciesBlockParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.ensure") + .tap("RequireEnsureDependenciesBlockParserPlugin", expr => { + let chunkName = null; + let chunkNameRange = null; + let errorExpressionArg = null; + let errorExpression = null; + switch (expr.arguments.length) { + case 4: { + const chunkNameExpr = parser.evaluateExpression(expr.arguments[3]); + if (!chunkNameExpr.isString()) return; + chunkNameRange = chunkNameExpr.range; + chunkName = chunkNameExpr.string; + } + // falls through + case 3: { + errorExpressionArg = expr.arguments[2]; + errorExpression = getFunctionExpression(errorExpressionArg); + + if (!errorExpression && !chunkName) { + const chunkNameExpr = parser.evaluateExpression( + expr.arguments[2] + ); + if (!chunkNameExpr.isString()) return; + chunkNameRange = chunkNameExpr.range; + chunkName = chunkNameExpr.string; + } + } + // falls through + case 2: { + const dependenciesExpr = parser.evaluateExpression( + expr.arguments[0] + ); + const dependenciesItems = dependenciesExpr.isArray() + ? dependenciesExpr.items + : [dependenciesExpr]; + const successExpressionArg = expr.arguments[1]; + const successExpression = getFunctionExpression( + successExpressionArg + ); + + if (successExpression) { + parser.walkExpressions(successExpression.expressions); + } + if (errorExpression) { + parser.walkExpressions(errorExpression.expressions); + } + + const dep = new RequireEnsureDependenciesBlock( + expr, + successExpression ? successExpression.fn : successExpressionArg, + errorExpression ? errorExpression.fn : errorExpressionArg, + chunkName, + chunkNameRange, + parser.state.module, + expr.loc + ); + const old = parser.state.current; + parser.state.current = dep; + try { + let failed = false; + parser.inScope([], () => { + for (const ee of dependenciesItems) { + if (ee.isString()) { + const edep = new RequireEnsureItemDependency(ee.string); + edep.loc = dep.loc; + dep.addDependency(edep); + } else { + failed = true; + } + } + }); + if (failed) { + return; + } + if (successExpression) { + if (successExpression.fn.body.type === "BlockStatement") { + parser.walkStatement(successExpression.fn.body); + } else { + parser.walkExpression(successExpression.fn.body); + } + } + old.addBlock(dep); + } finally { + parser.state.current = old; + } + if (!successExpression) { + parser.walkExpression(successExpressionArg); + } + if (errorExpression) { + if (errorExpression.fn.body.type === "BlockStatement") { + parser.walkStatement(errorExpression.fn.body); + } else { + parser.walkExpression(errorExpression.fn.body); + } + } else if (errorExpressionArg) { + parser.walkExpression(errorExpressionArg); + } + return true; + } + } + }); } }; /***/ }), -/***/ 34834: +/***/ 75830: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -100596,58 +99198,62 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS const NullDependency = __webpack_require__(5088); -class HarmonyExportSpecifierDependency extends NullDependency { - constructor(originModule, id, name) { +class RequireEnsureDependency extends NullDependency { + constructor(block) { super(); - this.originModule = originModule; - this.id = id; - this.name = name; + this.block = block; } get type() { - return "harmony export specifier"; - } - - getExports() { - return { - exports: [this.name], - dependencies: undefined - }; + return "require.ensure"; } } -HarmonyExportSpecifierDependency.Template = class HarmonyExportSpecifierDependencyTemplate { - apply(dep, source) {} - - getHarmonyInitOrder(dep) { - return 0; - } - - harmonyInit(dep, source, runtime) { - const content = this.getContent(dep); - source.insert(-1, content); - } - - getContent(dep) { - const used = dep.originModule.isUsed(dep.name); - if (!used) { - return `/* unused harmony export ${dep.name || "namespace"} */\n`; +RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate { + apply(dep, source, runtime) { + const depBlock = dep.block; + const promise = runtime.blockPromise({ + block: depBlock, + message: "require.ensure" + }); + const errorCallbackExists = + depBlock.expr.arguments.length === 4 || + (!depBlock.chunkName && depBlock.expr.arguments.length === 3); + const startBlock = `${promise}.then((`; + const middleBlock = ").bind(null, __webpack_require__)).catch("; + const endBlock = `).bind(null, __webpack_require__)).catch(${runtime.onError()})`; + source.replace( + depBlock.expr.range[0], + depBlock.expr.arguments[1].range[0] - 1, + startBlock + ); + if (errorCallbackExists) { + source.replace( + depBlock.expr.arguments[1].range[1], + depBlock.expr.arguments[2].range[0] - 1, + middleBlock + ); + source.replace( + depBlock.expr.arguments[2].range[1], + depBlock.expr.range[1] - 1, + ")" + ); + } else { + source.replace( + depBlock.expr.arguments[1].range[1], + depBlock.expr.range[1] - 1, + endBlock + ); } - - const exportsName = dep.originModule.exportsArgument; - - return `/* harmony export (binding) */ __webpack_require__.d(${exportsName}, ${JSON.stringify( - used - )}, function() { return ${dep.id}; });\n`; } }; -module.exports = HarmonyExportSpecifierDependency; +module.exports = RequireEnsureDependency; /***/ }), -/***/ 81599: +/***/ 5511: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -100656,115 +99262,109 @@ module.exports = HarmonyExportSpecifierDependency; Author Tobias Koppers @sokra */ - -const DependencyReference = __webpack_require__(71722); const ModuleDependency = __webpack_require__(90865); -const Template = __webpack_require__(96066); +const NullDependency = __webpack_require__(5088); -class HarmonyImportDependency extends ModuleDependency { - constructor(request, originModule, sourceOrder, parserScope) { +class RequireEnsureItemDependency extends ModuleDependency { + constructor(request) { super(request); - this.redirectedModule = undefined; - this.originModule = originModule; - this.sourceOrder = sourceOrder; - this.parserScope = parserScope; } - get _module() { - return this.redirectedModule || this.module; + get type() { + return "require.ensure item"; } +} - getReference() { - if (!this._module) return null; - return new DependencyReference( - this._module, - false, - this.weak, - this.sourceOrder - ); - } +RequireEnsureItemDependency.Template = NullDependency.Template; - getImportVar() { - let importVarMap = this.parserScope.importVarMap; - if (!importVarMap) this.parserScope.importVarMap = importVarMap = new Map(); - let importVar = importVarMap.get(this._module); - if (importVar) return importVar; - importVar = `${Template.toIdentifier( - `${this.userRequest}` - )}__WEBPACK_IMPORTED_MODULE_${importVarMap.size}__`; - importVarMap.set(this._module, importVar); - return importVar; - } +module.exports = RequireEnsureItemDependency; - getImportStatement(update, runtime) { - return runtime.importStatement({ - update, - module: this._module, - importVar: this.getImportVar(), - request: this.request, - originModule: this.originModule - }); - } - updateHash(hash) { - super.updateHash(hash); - const importedModule = this._module; - hash.update( - (importedModule && - (!importedModule.buildMeta || importedModule.buildMeta.exportsType)) + - "" - ); - hash.update((importedModule && importedModule.id) + ""); - } +/***/ }), - disconnect() { - super.disconnect(); - this.redirectedModule = undefined; - } -} +/***/ 98655: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -module.exports = HarmonyImportDependency; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -const importEmittedMap = new WeakMap(); -HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate { - apply(dep, source, runtime) { - // no-op - } +const RequireEnsureItemDependency = __webpack_require__(5511); +const RequireEnsureDependency = __webpack_require__(75830); - getHarmonyInitOrder(dep) { - return dep.sourceOrder; - } +const NullFactory = __webpack_require__(40438); - static isImportEmitted(dep, source) { - let sourceInfo = importEmittedMap.get(source); - if (!sourceInfo) return false; - const key = dep._module || dep.request; - return key && sourceInfo.emittedImports.get(key); - } +const RequireEnsureDependenciesBlockParserPlugin = __webpack_require__(24620); - harmonyInit(dep, source, runtime, dependencyTemplates) { - let sourceInfo = importEmittedMap.get(source); - if (!sourceInfo) { - importEmittedMap.set( - source, - (sourceInfo = { - emittedImports: new Map() - }) - ); - } - const key = dep._module || dep.request; - if (key && sourceInfo.emittedImports.get(key)) return; - sourceInfo.emittedImports.set(key, true); - const content = dep.getImportStatement(false, runtime); - source.insert(-1, content); +const ParserHelpers = __webpack_require__(23999); + +class RequireEnsurePlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "RequireEnsurePlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + RequireEnsureItemDependency, + normalModuleFactory + ); + compilation.dependencyTemplates.set( + RequireEnsureItemDependency, + new RequireEnsureItemDependency.Template() + ); + + compilation.dependencyFactories.set( + RequireEnsureDependency, + new NullFactory() + ); + compilation.dependencyTemplates.set( + RequireEnsureDependency, + new RequireEnsureDependency.Template() + ); + + const handler = (parser, parserOptions) => { + if ( + parserOptions.requireEnsure !== undefined && + !parserOptions.requireEnsure + ) + return; + + new RequireEnsureDependenciesBlockParserPlugin().apply(parser); + parser.hooks.evaluateTypeof + .for("require.ensure") + .tap( + "RequireEnsurePlugin", + ParserHelpers.evaluateToString("function") + ); + parser.hooks.typeof + .for("require.ensure") + .tap( + "RequireEnsurePlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); + }; + + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("RequireEnsurePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("RequireEnsurePlugin", handler); + } + ); } -}; +} +module.exports = RequireEnsurePlugin; /***/ }), -/***/ 99433: +/***/ 22928: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -100773,228 +99373,32 @@ HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate { Author Tobias Koppers @sokra */ +const NullDependency = __webpack_require__(5088); -const { SyncBailHook } = __webpack_require__(56758); -const HarmonyImportSideEffectDependency = __webpack_require__(79171); -const HarmonyImportSpecifierDependency = __webpack_require__(95966); -const HarmonyAcceptImportDependency = __webpack_require__(66136); -const HarmonyAcceptDependency = __webpack_require__(75159); -const ConstDependency = __webpack_require__(71101); +class RequireHeaderDependency extends NullDependency { + constructor(range) { + super(); + if (!Array.isArray(range)) throw new Error("range must be valid"); + this.range = range; + } +} -module.exports = class HarmonyImportDependencyParserPlugin { - constructor(moduleOptions) { - this.strictExportPresence = moduleOptions.strictExportPresence; - this.strictThisContextOnImports = moduleOptions.strictThisContextOnImports; +RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate { + apply(dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__"); } - apply(parser) { - parser.hooks.import.tap( - "HarmonyImportDependencyParserPlugin", - (statement, source) => { - parser.state.lastHarmonyImportOrder = - (parser.state.lastHarmonyImportOrder || 0) + 1; - const clearDep = new ConstDependency("", statement.range); - clearDep.loc = statement.loc; - parser.state.module.addDependency(clearDep); - const sideEffectDep = new HarmonyImportSideEffectDependency( - source, - parser.state.module, - parser.state.lastHarmonyImportOrder, - parser.state.harmonyParserScope - ); - sideEffectDep.loc = statement.loc; - parser.state.module.addDependency(sideEffectDep); - return true; - } - ); - parser.hooks.importSpecifier.tap( - "HarmonyImportDependencyParserPlugin", - (statement, source, id, name) => { - parser.scope.definitions.delete(name); - parser.scope.renames.set(name, "imported var"); - if (!parser.state.harmonySpecifier) { - parser.state.harmonySpecifier = new Map(); - } - parser.state.harmonySpecifier.set(name, { - source, - id, - sourceOrder: parser.state.lastHarmonyImportOrder - }); - return true; - } - ); - parser.hooks.expression - .for("imported var") - .tap("HarmonyImportDependencyParserPlugin", expr => { - const name = expr.name; - const settings = parser.state.harmonySpecifier.get(name); - const dep = new HarmonyImportSpecifierDependency( - settings.source, - parser.state.module, - settings.sourceOrder, - parser.state.harmonyParserScope, - settings.id, - name, - expr.range, - this.strictExportPresence - ); - dep.shorthand = parser.scope.inShorthand; - dep.directImport = true; - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return true; - }); - parser.hooks.expressionAnyMember - .for("imported var") - .tap("HarmonyImportDependencyParserPlugin", expr => { - const name = expr.object.name; - const settings = parser.state.harmonySpecifier.get(name); - if (settings.id !== null) return false; - const dep = new HarmonyImportSpecifierDependency( - settings.source, - parser.state.module, - settings.sourceOrder, - parser.state.harmonyParserScope, - expr.property.name || expr.property.value, - name, - expr.range, - this.strictExportPresence - ); - dep.shorthand = parser.scope.inShorthand; - dep.directImport = false; - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return true; - }); - if (this.strictThisContextOnImports) { - // only in case when we strictly follow the spec we need a special case here - parser.hooks.callAnyMember - .for("imported var") - .tap("HarmonyImportDependencyParserPlugin", expr => { - if (expr.callee.type !== "MemberExpression") return; - if (expr.callee.object.type !== "Identifier") return; - const name = expr.callee.object.name; - const settings = parser.state.harmonySpecifier.get(name); - if (settings.id !== null) return false; - const dep = new HarmonyImportSpecifierDependency( - settings.source, - parser.state.module, - settings.sourceOrder, - parser.state.harmonyParserScope, - expr.callee.property.name || expr.callee.property.value, - name, - expr.callee.range, - this.strictExportPresence - ); - dep.shorthand = parser.scope.inShorthand; - dep.directImport = false; - dep.namespaceObjectAsContext = true; - dep.loc = expr.callee.loc; - parser.state.module.addDependency(dep); - if (expr.arguments) parser.walkExpressions(expr.arguments); - return true; - }); - } - parser.hooks.call - .for("imported var") - .tap("HarmonyImportDependencyParserPlugin", expr => { - const args = expr.arguments; - const fullExpr = expr; - expr = expr.callee; - if (expr.type !== "Identifier") return; - const name = expr.name; - const settings = parser.state.harmonySpecifier.get(name); - const dep = new HarmonyImportSpecifierDependency( - settings.source, - parser.state.module, - settings.sourceOrder, - parser.state.harmonyParserScope, - settings.id, - name, - expr.range, - this.strictExportPresence - ); - dep.directImport = true; - dep.callArgs = args; - dep.call = fullExpr; - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - if (args) parser.walkExpressions(args); - return true; - }); - // TODO webpack 5: refactor this, no custom hooks - if (!parser.hooks.hotAcceptCallback) { - parser.hooks.hotAcceptCallback = new SyncBailHook([ - "expression", - "requests" - ]); - } - if (!parser.hooks.hotAcceptWithoutCallback) { - parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ - "expression", - "requests" - ]); - } - parser.hooks.hotAcceptCallback.tap( - "HarmonyImportDependencyParserPlugin", - (expr, requests) => { - const harmonyParserScope = parser.state.harmonyParserScope; - if (!harmonyParserScope) { - // This is not a harmony module, skip it - return; - } - const dependencies = requests.map(request => { - const dep = new HarmonyAcceptImportDependency( - request, - parser.state.module, - harmonyParserScope - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return dep; - }); - if (dependencies.length > 0) { - const dep = new HarmonyAcceptDependency( - expr.range, - dependencies, - true - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - } - } - ); - parser.hooks.hotAcceptWithoutCallback.tap( - "HarmonyImportDependencyParserPlugin", - (expr, requests) => { - const dependencies = requests.map(request => { - const dep = new HarmonyAcceptImportDependency( - request, - parser.state.module, - parser.state.harmonyParserScope - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - return dep; - }); - if (dependencies.length > 0) { - const dep = new HarmonyAcceptDependency( - expr.range, - dependencies, - false - ); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - } - } - ); + applyAsTemplateArgument(name, dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "require"); } }; +module.exports = RequireHeaderDependency; + /***/ }), -/***/ 79171: +/***/ 58045: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -101003,37 +99407,45 @@ module.exports = class HarmonyImportDependencyParserPlugin { Author Tobias Koppers @sokra */ -const HarmonyImportDependency = __webpack_require__(81599); -class HarmonyImportSideEffectDependency extends HarmonyImportDependency { - constructor(request, originModule, sourceOrder, parserScope) { - super(request, originModule, sourceOrder, parserScope); +const DependencyReference = __webpack_require__(71722); +const ModuleDependency = __webpack_require__(90865); +const Template = __webpack_require__(96066); + +class RequireIncludeDependency extends ModuleDependency { + constructor(request, range) { + super(request); + this.range = range; } getReference() { - if (this._module && this._module.factoryMeta.sideEffectFree) return null; - - return super.getReference(); + if (!this.module) return null; + // This doesn't use any export + return new DependencyReference(this.module, [], false); } get type() { - return "harmony side effect evaluation"; + return "require.include"; } } -HarmonyImportSideEffectDependency.Template = class HarmonyImportSideEffectDependencyTemplate extends HarmonyImportDependency.Template { - getHarmonyInitOrder(dep) { - if (dep._module && dep._module.factoryMeta.sideEffectFree) return NaN; - return super.getHarmonyInitOrder(dep); +RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate { + apply(dep, source, runtime) { + const comment = runtime.outputOptions.pathinfo + ? Template.toComment( + `require.include ${runtime.requestShortener.shorten(dep.request)}` + ) + : ""; + source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); } }; -module.exports = HarmonyImportSideEffectDependency; +module.exports = RequireIncludeDependency; /***/ }), -/***/ 95966: +/***/ 36330: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -101043,421 +99455,128 @@ module.exports = HarmonyImportSideEffectDependency; */ -const DependencyReference = __webpack_require__(71722); -const HarmonyImportDependency = __webpack_require__(81599); -const HarmonyLinkingError = __webpack_require__(30327); +const RequireIncludeDependency = __webpack_require__(58045); -class HarmonyImportSpecifierDependency extends HarmonyImportDependency { - constructor( - request, - originModule, - sourceOrder, - parserScope, - id, - name, - range, - strictExportPresence - ) { - super(request, originModule, sourceOrder, parserScope); - this.id = id === null ? null : `${id}`; - this.redirectedId = undefined; - this.name = name; - this.range = range; - this.strictExportPresence = strictExportPresence; - this.namespaceObjectAsContext = false; - this.callArgs = undefined; - this.call = undefined; - this.directImport = undefined; - this.shorthand = undefined; +module.exports = class RequireIncludeDependencyParserPlugin { + apply(parser) { + parser.hooks.call + .for("require.include") + .tap("RequireIncludeDependencyParserPlugin", expr => { + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (!param.isString()) return; + const dep = new RequireIncludeDependency(param.string, expr.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + }); } +}; - get type() { - return "harmony import specifier"; - } - get _id() { - return this.redirectedId || this.id; - } +/***/ }), - getReference() { - if (!this._module) return null; - return new DependencyReference( - this._module, - this._id && !this.namespaceObjectAsContext ? [this._id] : true, - false, - this.sourceOrder - ); - } +/***/ 16522: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - getWarnings() { - if ( - this.strictExportPresence || - this.originModule.buildMeta.strictHarmonyModule - ) { - return []; - } - return this._getErrors(); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - getErrors() { - if ( - this.strictExportPresence || - this.originModule.buildMeta.strictHarmonyModule - ) { - return this._getErrors(); - } - return []; - } - _getErrors() { - const importedModule = this._module; - if (!importedModule) { - return; - } +const RequireIncludeDependency = __webpack_require__(58045); +const RequireIncludeDependencyParserPlugin = __webpack_require__(36330); - if (!importedModule.buildMeta || !importedModule.buildMeta.exportsType) { - // It's not an harmony module - if ( - this.originModule.buildMeta.strictHarmonyModule && - this._id && - this._id !== "default" - ) { - // In strict harmony modules we only support the default export - return [ - new HarmonyLinkingError( - `Can't import the named export '${this._id}' from non EcmaScript module (only default export is available)` - ) - ]; - } - return; - } - - if (!this._id) { - return; - } - - if (importedModule.isProvided(this._id) !== false) { - // It's provided or we are not sure - return; - } - - // We are sure that it's not provided - const idIsNotNameMessage = - this._id !== this.name ? ` (imported as '${this.name}')` : ""; - const errorMessage = `"export '${this._id}'${idIsNotNameMessage} was not found in '${this.userRequest}'`; - return [new HarmonyLinkingError(errorMessage)]; - } - - // implement this method to allow the occurrence order plugin to count correctly - getNumberOfIdOccurrences() { - return 0; - } - - updateHash(hash) { - super.updateHash(hash); - const importedModule = this._module; - hash.update((importedModule && this._id) + ""); - hash.update( - (importedModule && this._id && importedModule.isUsed(this._id)) + "" - ); - hash.update( - (importedModule && - (!importedModule.buildMeta || importedModule.buildMeta.exportsType)) + - "" - ); - hash.update( - (importedModule && - importedModule.used + JSON.stringify(importedModule.usedExports)) + "" - ); - } - - disconnect() { - super.disconnect(); - this.redirectedId = undefined; - } -} - -HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependencyTemplate extends HarmonyImportDependency.Template { - apply(dep, source, runtime) { - super.apply(dep, source, runtime); - const content = this.getContent(dep, runtime); - source.replace(dep.range[0], dep.range[1] - 1, content); - } - - getContent(dep, runtime) { - const exportExpr = runtime.exportFromImport({ - module: dep._module, - request: dep.request, - exportName: dep._id, - originModule: dep.originModule, - asiSafe: dep.shorthand, - isCall: dep.call, - callContext: !dep.directImport, - importVar: dep.getImportVar() - }); - return dep.shorthand ? `${dep.name}: ${exportExpr}` : exportExpr; - } -}; - -module.exports = HarmonyImportSpecifierDependency; - - -/***/ }), - -/***/ 27204: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const NullDependency = __webpack_require__(5088); - -class HarmonyInitDependency extends NullDependency { - constructor(originModule) { - super(); - this.originModule = originModule; - } - - get type() { - return "harmony init"; - } -} - -module.exports = HarmonyInitDependency; - -HarmonyInitDependency.Template = class HarmonyInitDependencyTemplate { - apply(dep, source, runtime, dependencyTemplates) { - const module = dep.originModule; - const list = []; - for (const dependency of module.dependencies) { - const template = dependencyTemplates.get(dependency.constructor); - if ( - template && - typeof template.harmonyInit === "function" && - typeof template.getHarmonyInitOrder === "function" - ) { - const order = template.getHarmonyInitOrder(dependency); - if (!isNaN(order)) { - list.push({ - order, - listOrder: list.length, - dependency, - template - }); - } - } - } - - list.sort((a, b) => { - const x = a.order - b.order; - if (x) return x; - return a.listOrder - b.listOrder; - }); - - for (const item of list) { - item.template.harmonyInit( - item.dependency, - source, - runtime, - dependencyTemplates - ); - } - } -}; - - -/***/ }), - -/***/ 66792: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const HarmonyCompatibilityDependency = __webpack_require__(1533); -const HarmonyInitDependency = __webpack_require__(27204); -const HarmonyImportSpecifierDependency = __webpack_require__(95966); -const HarmonyImportSideEffectDependency = __webpack_require__(79171); -const HarmonyExportHeaderDependency = __webpack_require__(21320); -const HarmonyExportExpressionDependency = __webpack_require__(84245); -const HarmonyExportSpecifierDependency = __webpack_require__(34834); -const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); -const HarmonyAcceptDependency = __webpack_require__(75159); -const HarmonyAcceptImportDependency = __webpack_require__(66136); - -const NullFactory = __webpack_require__(40438); - -const HarmonyDetectionParserPlugin = __webpack_require__(59310); -const HarmonyImportDependencyParserPlugin = __webpack_require__(99433); -const HarmonyExportDependencyParserPlugin = __webpack_require__(49180); -const HarmonyTopLevelThisParserPlugin = __webpack_require__(58215); - -class HarmonyModulesPlugin { - constructor(options) { - this.options = options; - } +const ParserHelpers = __webpack_require__(23999); +class RequireIncludePlugin { apply(compiler) { compiler.hooks.compilation.tap( - "HarmonyModulesPlugin", + "RequireIncludePlugin", (compilation, { normalModuleFactory }) => { compilation.dependencyFactories.set( - HarmonyCompatibilityDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - HarmonyCompatibilityDependency, - new HarmonyCompatibilityDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyInitDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - HarmonyInitDependency, - new HarmonyInitDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyImportSideEffectDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyImportSideEffectDependency, - new HarmonyImportSideEffectDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyImportSpecifierDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyImportSpecifierDependency, - new HarmonyImportSpecifierDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyExportHeaderDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - HarmonyExportHeaderDependency, - new HarmonyExportHeaderDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyExportExpressionDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - HarmonyExportExpressionDependency, - new HarmonyExportExpressionDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyExportSpecifierDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - HarmonyExportSpecifierDependency, - new HarmonyExportSpecifierDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyExportImportedSpecifierDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - HarmonyExportImportedSpecifierDependency, - new HarmonyExportImportedSpecifierDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyAcceptDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - HarmonyAcceptDependency, - new HarmonyAcceptDependency.Template() - ); - - compilation.dependencyFactories.set( - HarmonyAcceptImportDependency, + RequireIncludeDependency, normalModuleFactory ); compilation.dependencyTemplates.set( - HarmonyAcceptImportDependency, - new HarmonyAcceptImportDependency.Template() + RequireIncludeDependency, + new RequireIncludeDependency.Template() ); const handler = (parser, parserOptions) => { - if (parserOptions.harmony !== undefined && !parserOptions.harmony) + if ( + parserOptions.requireInclude !== undefined && + !parserOptions.requireInclude + ) return; - new HarmonyDetectionParserPlugin().apply(parser); - new HarmonyImportDependencyParserPlugin(this.options).apply(parser); - new HarmonyExportDependencyParserPlugin(this.options).apply(parser); - new HarmonyTopLevelThisParserPlugin().apply(parser); + new RequireIncludeDependencyParserPlugin().apply(parser); + parser.hooks.evaluateTypeof + .for("require.include") + .tap( + "RequireIncludePlugin", + ParserHelpers.evaluateToString("function") + ); + parser.hooks.typeof + .for("require.include") + .tap( + "RequireIncludePlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") + ) + ); }; normalModuleFactory.hooks.parser .for("javascript/auto") - .tap("HarmonyModulesPlugin", handler); + .tap("RequireIncludePlugin", handler); normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("HarmonyModulesPlugin", handler); + .for("javascript/dynamic") + .tap("RequireIncludePlugin", handler); } ); } } -module.exports = HarmonyModulesPlugin; +module.exports = RequireIncludePlugin; /***/ }), -/***/ 58215: +/***/ 83309: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Florent Cailhol @ooflorent + Author Tobias Koppers @sokra */ +const ContextDependency = __webpack_require__(11583); +const ContextDependencyTemplateAsId = __webpack_require__(6174); -const ConstDependency = __webpack_require__(71101); +class RequireResolveContextDependency extends ContextDependency { + constructor(options, range, valueRange) { + super(options); + this.range = range; + this.valueRange = valueRange; + } -class HarmonyTopLevelThisParserPlugin { - apply(parser) { - parser.hooks.expression - .for("this") - .tap("HarmonyTopLevelThisParserPlugin", node => { - if (!parser.scope.topLevelScope) return; - const module = parser.state.module; - const isHarmony = !!(module.buildMeta && module.buildMeta.exportsType); - if (isHarmony) { - const dep = new ConstDependency("undefined", node.range, false); - dep.loc = node.loc; - parser.state.current.addDependency(dep); - } - }); + get type() { + return "amd require context"; } } -module.exports = HarmonyTopLevelThisParserPlugin; +RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; + +module.exports = RequireResolveContextDependency; /***/ }), -/***/ 20417: +/***/ 43519: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -101466,29 +99585,28 @@ module.exports = HarmonyTopLevelThisParserPlugin; Author Tobias Koppers @sokra */ -const ContextDependency = __webpack_require__(11583); -const ContextDependencyTemplateAsRequireCall = __webpack_require__(54380); +const ModuleDependency = __webpack_require__(90865); +const ModuleDependencyAsId = __webpack_require__(63708); -class ImportContextDependency extends ContextDependency { - constructor(options, range, valueRange) { - super(options); +class RequireResolveDependency extends ModuleDependency { + constructor(request, range) { + super(request); this.range = range; - this.valueRange = valueRange; } get type() { - return `import() context ${this.options.mode}`; + return "require.resolve"; } } -ImportContextDependency.Template = ContextDependencyTemplateAsRequireCall; +RequireResolveDependency.Template = ModuleDependencyAsId; -module.exports = ImportContextDependency; +module.exports = RequireResolveDependency; /***/ }), -/***/ 38875: +/***/ 68349: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -101497,24 +99615,92 @@ module.exports = ImportContextDependency; Author Tobias Koppers @sokra */ -const AsyncDependenciesBlock = __webpack_require__(22814); -const ImportDependency = __webpack_require__(50883); -module.exports = class ImportDependenciesBlock extends AsyncDependenciesBlock { - // TODO webpack 5 reorganize arguments - constructor(request, range, groupOptions, module, loc, originModule) { - super(groupOptions, module, loc, request); - this.range = range; - const dep = new ImportDependency(request, originModule, this); - dep.loc = loc; - this.addDependency(dep); +const RequireResolveDependency = __webpack_require__(43519); +const RequireResolveContextDependency = __webpack_require__(83309); +const RequireResolveHeaderDependency = __webpack_require__(69647); +const ContextDependencyHelpers = __webpack_require__(5594); + +class RequireResolveDependencyParserPlugin { + constructor(options) { + this.options = options; } -}; + + apply(parser) { + const options = this.options; + + const process = (expr, weak) => { + if (expr.arguments.length !== 1) return; + const param = parser.evaluateExpression(expr.arguments[0]); + if (param.isConditional()) { + for (const option of param.options) { + const result = processItem(expr, option, weak); + if (result === undefined) { + processContext(expr, option, weak); + } + } + const dep = new RequireResolveHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + } else { + const result = processItem(expr, param, weak); + if (result === undefined) { + processContext(expr, param, weak); + } + const dep = new RequireResolveHeaderDependency(expr.callee.range); + dep.loc = expr.loc; + parser.state.current.addDependency(dep); + return true; + } + }; + const processItem = (expr, param, weak) => { + if (param.isString()) { + const dep = new RequireResolveDependency(param.string, param.range); + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + dep.weak = weak; + parser.state.current.addDependency(dep); + return true; + } + }; + const processContext = (expr, param, weak) => { + const dep = ContextDependencyHelpers.create( + RequireResolveContextDependency, + param.range, + param, + expr, + options, + { + mode: weak ? "weak" : "sync" + }, + parser + ); + if (!dep) return; + dep.loc = expr.loc; + dep.optional = !!parser.scope.inTry; + parser.state.current.addDependency(dep); + return true; + }; + + parser.hooks.call + .for("require.resolve") + .tap("RequireResolveDependencyParserPlugin", expr => { + return process(expr, false); + }); + parser.hooks.call + .for("require.resolveWeak") + .tap("RequireResolveDependencyParserPlugin", expr => { + return process(expr, true); + }); + } +} +module.exports = RequireResolveDependencyParserPlugin; /***/ }), -/***/ 50883: +/***/ 69647: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -101523,40 +99709,32 @@ module.exports = class ImportDependenciesBlock extends AsyncDependenciesBlock { Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(90865); - -class ImportDependency extends ModuleDependency { - constructor(request, originModule, block) { - super(request); - this.originModule = originModule; - this.block = block; - } +const NullDependency = __webpack_require__(5088); - get type() { - return "import()"; +class RequireResolveHeaderDependency extends NullDependency { + constructor(range) { + super(); + if (!Array.isArray(range)) throw new Error("range must be valid"); + this.range = range; } } -ImportDependency.Template = class ImportDependencyTemplate { - apply(dep, source, runtime) { - const content = runtime.moduleNamespacePromise({ - block: dep.block, - module: dep.module, - request: dep.request, - strict: dep.originModule.buildMeta.strictHarmonyModule, - message: "import()" - }); +RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate { + apply(dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); + } - source.replace(dep.block.range[0], dep.block.range[1] - 1, content); + applyAsTemplateArgument(name, dep, source) { + source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); } }; -module.exports = ImportDependency; +module.exports = RequireResolveHeaderDependency; /***/ }), -/***/ 25552: +/***/ 84828: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -101567,36 +99745,25 @@ module.exports = ImportDependency; const ModuleDependency = __webpack_require__(90865); -class ImportEagerDependency extends ModuleDependency { - constructor(request, originModule, range) { +class SingleEntryDependency extends ModuleDependency { + /** + * @param {string} request request path for entry + */ + constructor(request) { super(request); - this.originModule = originModule; - this.range = range; } get type() { - return "import() eager"; + return "single entry"; } } -ImportEagerDependency.Template = class ImportEagerDependencyTemplate { - apply(dep, source, runtime) { - const content = runtime.moduleNamespacePromise({ - module: dep.module, - request: dep.request, - strict: dep.originModule.buildMeta.strictHarmonyModule, - message: "import() eager" - }); - source.replace(dep.range[0], dep.range[1] - 1, content); - } -}; - -module.exports = ImportEagerDependency; +module.exports = SingleEntryDependency; /***/ }), -/***/ 93382: +/***/ 68166: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -101606,340 +99773,127 @@ module.exports = ImportEagerDependency; */ -const ImportContextDependency = __webpack_require__(20417); -const ImportWeakDependency = __webpack_require__(86817); -const ImportDependenciesBlock = __webpack_require__(38875); -const ImportEagerDependency = __webpack_require__(25552); -const ContextDependencyHelpers = __webpack_require__(5594); -const UnsupportedFeatureWarning = __webpack_require__(99953); -const CommentCompilationWarning = __webpack_require__(51760); +const ParserHelpers = __webpack_require__(23999); +const WebpackError = __webpack_require__(97391); -class ImportParserPlugin { +class SystemPlugin { constructor(options) { this.options = options; } - apply(parser) { - parser.hooks.importCall.tap("ImportParserPlugin", expr => { - if (expr.arguments.length !== 1) { - throw new Error( - "Incorrect number of arguments provided to 'import(module: string) -> Promise'." - ); - } - - const param = parser.evaluateExpression(expr.arguments[0]); - - let chunkName = null; - let mode = "lazy"; - let include = null; - let exclude = null; - const groupOptions = {}; + apply(compiler) { + compiler.hooks.compilation.tap( + "SystemPlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + if (parserOptions.system !== undefined && !parserOptions.system) + return; - const { - options: importOptions, - errors: commentErrors - } = parser.parseCommentOptions(expr.range); + const shouldWarn = parserOptions.system === undefined; - if (commentErrors) { - for (const e of commentErrors) { - const { comment } = e; - parser.state.module.warnings.push( - new CommentCompilationWarning( - `Compilation error while processing magic comment(-s): /*${comment.value}*/: ${e.message}`, - parser.state.module, - comment.loc - ) - ); - } - } + const setNotSupported = name => { + parser.hooks.evaluateTypeof + .for(name) + .tap("SystemPlugin", ParserHelpers.evaluateToString("undefined")); + parser.hooks.expression + .for(name) + .tap( + "SystemPlugin", + ParserHelpers.expressionIsUnsupported( + parser, + name + " is not supported by webpack." + ) + ); + }; - if (importOptions) { - if (importOptions.webpackIgnore !== undefined) { - if (typeof importOptions.webpackIgnore !== "boolean") { - parser.state.module.warnings.push( - new UnsupportedFeatureWarning( - parser.state.module, - `\`webpackIgnore\` expected a boolean, but received: ${importOptions.webpackIgnore}.`, - expr.loc - ) - ); - } else { - // Do not instrument `import()` if `webpackIgnore` is `true` - if (importOptions.webpackIgnore) { - return false; - } - } - } - if (importOptions.webpackChunkName !== undefined) { - if (typeof importOptions.webpackChunkName !== "string") { - parser.state.module.warnings.push( - new UnsupportedFeatureWarning( - parser.state.module, - `\`webpackChunkName\` expected a string, but received: ${importOptions.webpackChunkName}.`, - expr.loc - ) - ); - } else { - chunkName = importOptions.webpackChunkName; - } - } - if (importOptions.webpackMode !== undefined) { - if (typeof importOptions.webpackMode !== "string") { - parser.state.module.warnings.push( - new UnsupportedFeatureWarning( - parser.state.module, - `\`webpackMode\` expected a string, but received: ${importOptions.webpackMode}.`, - expr.loc - ) - ); - } else { - mode = importOptions.webpackMode; - } - } - if (importOptions.webpackPrefetch !== undefined) { - if (importOptions.webpackPrefetch === true) { - groupOptions.prefetchOrder = 0; - } else if (typeof importOptions.webpackPrefetch === "number") { - groupOptions.prefetchOrder = importOptions.webpackPrefetch; - } else { - parser.state.module.warnings.push( - new UnsupportedFeatureWarning( - parser.state.module, - `\`webpackPrefetch\` expected true or a number, but received: ${importOptions.webpackPrefetch}.`, - expr.loc - ) - ); - } - } - if (importOptions.webpackPreload !== undefined) { - if (importOptions.webpackPreload === true) { - groupOptions.preloadOrder = 0; - } else if (typeof importOptions.webpackPreload === "number") { - groupOptions.preloadOrder = importOptions.webpackPreload; - } else { - parser.state.module.warnings.push( - new UnsupportedFeatureWarning( - parser.state.module, - `\`webpackPreload\` expected true or a number, but received: ${importOptions.webpackPreload}.`, - expr.loc - ) - ); - } - } - if (importOptions.webpackInclude !== undefined) { - if ( - !importOptions.webpackInclude || - importOptions.webpackInclude.constructor.name !== "RegExp" - ) { - parser.state.module.warnings.push( - new UnsupportedFeatureWarning( - parser.state.module, - `\`webpackInclude\` expected a regular expression, but received: ${importOptions.webpackInclude}.`, - expr.loc + parser.hooks.typeof + .for("System.import") + .tap( + "SystemPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("function") ) ); - } else { - include = new RegExp(importOptions.webpackInclude); - } - } - if (importOptions.webpackExclude !== undefined) { - if ( - !importOptions.webpackExclude || - importOptions.webpackExclude.constructor.name !== "RegExp" - ) { - parser.state.module.warnings.push( - new UnsupportedFeatureWarning( - parser.state.module, - `\`webpackExclude\` expected a regular expression, but received: ${importOptions.webpackExclude}.`, - expr.loc + parser.hooks.evaluateTypeof + .for("System.import") + .tap("SystemPlugin", ParserHelpers.evaluateToString("function")); + parser.hooks.typeof + .for("System") + .tap( + "SystemPlugin", + ParserHelpers.toConstantDependency( + parser, + JSON.stringify("object") ) ); - } else { - exclude = new RegExp(importOptions.webpackExclude); - } - } - } - - if (param.isString()) { - if (mode !== "lazy" && mode !== "eager" && mode !== "weak") { - parser.state.module.warnings.push( - new UnsupportedFeatureWarning( - parser.state.module, - `\`webpackMode\` expected 'lazy', 'eager' or 'weak', but received: ${mode}.`, - expr.loc - ) - ); - } - - if (mode === "eager") { - const dep = new ImportEagerDependency( - param.string, - parser.state.module, - expr.range - ); - parser.state.current.addDependency(dep); - } else if (mode === "weak") { - const dep = new ImportWeakDependency( - param.string, - parser.state.module, - expr.range - ); - parser.state.current.addDependency(dep); - } else { - const depBlock = new ImportDependenciesBlock( - param.string, - expr.range, - Object.assign(groupOptions, { - name: chunkName - }), - parser.state.module, - expr.loc, - parser.state.module - ); - parser.state.current.addBlock(depBlock); - } - return true; - } else { - if ( - mode !== "lazy" && - mode !== "lazy-once" && - mode !== "eager" && - mode !== "weak" - ) { - parser.state.module.warnings.push( - new UnsupportedFeatureWarning( - parser.state.module, - `\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`, - expr.loc - ) - ); - mode = "lazy"; - } - - if (mode === "weak") { - mode = "async-weak"; - } - const dep = ContextDependencyHelpers.create( - ImportContextDependency, - expr.range, - param, - expr, - this.options, - { - chunkName, - groupOptions, - include, - exclude, - mode, - namespaceObject: parser.state.module.buildMeta.strictHarmonyModule - ? "strict" - : true - }, - parser - ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - }); - } -} - -module.exports = ImportParserPlugin; - - -/***/ }), - -/***/ 58839: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const ImportDependency = __webpack_require__(50883); -const ImportEagerDependency = __webpack_require__(25552); -const ImportWeakDependency = __webpack_require__(86817); -const ImportContextDependency = __webpack_require__(20417); -const ImportParserPlugin = __webpack_require__(93382); - -class ImportPlugin { - constructor(options) { - this.options = options; - } - - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap( - "ImportPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { - compilation.dependencyFactories.set( - ImportDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ImportDependency, - new ImportDependency.Template() - ); - - compilation.dependencyFactories.set( - ImportEagerDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ImportEagerDependency, - new ImportEagerDependency.Template() - ); + parser.hooks.evaluateTypeof + .for("System") + .tap("SystemPlugin", ParserHelpers.evaluateToString("object")); - compilation.dependencyFactories.set( - ImportWeakDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - ImportWeakDependency, - new ImportWeakDependency.Template() - ); + setNotSupported("System.set"); + setNotSupported("System.get"); + setNotSupported("System.register"); - compilation.dependencyFactories.set( - ImportContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - ImportContextDependency, - new ImportContextDependency.Template() - ); + parser.hooks.expression.for("System").tap("SystemPlugin", () => { + const systemPolyfillRequire = ParserHelpers.requireFileAsExpression( + parser.state.module.context, + __webpack_require__.ab + "system.js" + ); + return ParserHelpers.addParsedVariableToModule( + parser, + "System", + systemPolyfillRequire + ); + }); - const handler = (parser, parserOptions) => { - if (parserOptions.import !== undefined && !parserOptions.import) - return; + parser.hooks.call.for("System.import").tap("SystemPlugin", expr => { + if (shouldWarn) { + parser.state.module.warnings.push( + new SystemImportDeprecationWarning( + parser.state.module, + expr.loc + ) + ); + } - new ImportParserPlugin(options).apply(parser); + return parser.hooks.importCall.call(expr); + }); }; normalModuleFactory.hooks.parser .for("javascript/auto") - .tap("ImportPlugin", handler); + .tap("SystemPlugin", handler); normalModuleFactory.hooks.parser .for("javascript/dynamic") - .tap("ImportPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("ImportPlugin", handler); + .tap("SystemPlugin", handler); } ); } } -module.exports = ImportPlugin; + +class SystemImportDeprecationWarning extends WebpackError { + constructor(module, loc) { + super( + "System.import() is deprecated and will be removed soon. Use import() instead.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" + ); + + this.name = "SystemImportDeprecationWarning"; + + this.module = module; + this.loc = loc; + + Error.captureStackTrace(this, this.constructor); + } +} + +module.exports = SystemPlugin; /***/ }), -/***/ 86817: +/***/ 15826: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -101948,40 +99902,33 @@ module.exports = ImportPlugin; Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(90865); +const NullDependency = __webpack_require__(5088); +const webpackMissingModule = __webpack_require__(75386).module; -class ImportWeakDependency extends ModuleDependency { - constructor(request, originModule, range) { - super(request); - this.originModule = originModule; +class UnsupportedDependency extends NullDependency { + constructor(request, range) { + super(); + this.request = request; this.range = range; - this.weak = true; - } - - get type() { - return "import() weak"; } } -ImportWeakDependency.Template = class ImportDependencyTemplate { +UnsupportedDependency.Template = class UnsupportedDependencyTemplate { apply(dep, source, runtime) { - const content = runtime.moduleNamespacePromise({ - module: dep.module, - request: dep.request, - strict: dep.originModule.buildMeta.strictHarmonyModule, - message: "import() weak", - weak: true - }); - source.replace(dep.range[0], dep.range[1] - 1, content); + source.replace( + dep.range[0], + dep.range[1], + webpackMissingModule(dep.request) + ); } }; -module.exports = ImportWeakDependency; +module.exports = UnsupportedDependency; /***/ }), -/***/ 54396: +/***/ 18925: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -101990,32 +99937,37 @@ module.exports = ImportWeakDependency; Author Tobias Koppers @sokra */ -const NullDependency = __webpack_require__(5088); -class JsonExportsDependency extends NullDependency { - constructor(exports) { - super(); - this.exports = exports; +const DependencyReference = __webpack_require__(71722); +const ModuleDependency = __webpack_require__(90865); + +class WebAssemblyExportImportedDependency extends ModuleDependency { + constructor(exportName, request, name, valueType) { + super(request); + /** @type {string} */ + this.exportName = exportName; + /** @type {string} */ + this.name = name; + /** @type {string} */ + this.valueType = valueType; } - get type() { - return "json exports"; + getReference() { + if (!this.module) return null; + return new DependencyReference(this.module, [this.name], false); } - getExports() { - return { - exports: this.exports, - dependencies: undefined - }; + get type() { + return "wasm export import"; } } -module.exports = JsonExportsDependency; +module.exports = WebAssemblyExportImportedDependency; /***/ }), -/***/ 1129: +/***/ 52959: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102024,28 +99976,61 @@ module.exports = JsonExportsDependency; Author Tobias Koppers @sokra */ + +const DependencyReference = __webpack_require__(71722); const ModuleDependency = __webpack_require__(90865); +const UnsupportedWebAssemblyFeatureError = __webpack_require__(43101); -class LoaderDependency extends ModuleDependency { +/** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ + +class WebAssemblyImportDependency extends ModuleDependency { /** - * @param {string} request request string + * @param {string} request the request + * @param {string} name the imported name + * @param {ModuleImportDescription} description the WASM ast node + * @param {false | string} onlyDirectImport if only direct imports are allowed */ - constructor(request) { + constructor(request, name, description, onlyDirectImport) { super(request); + /** @type {string} */ + this.name = name; + /** @type {ModuleImportDescription} */ + this.description = description; + /** @type {false | string} */ + this.onlyDirectImport = onlyDirectImport; + } + + getReference() { + if (!this.module) return null; + return new DependencyReference(this.module, [this.name], false); + } + + getErrors() { + if ( + this.onlyDirectImport && + this.module && + !this.module.type.startsWith("webassembly") + ) { + return [ + new UnsupportedWebAssemblyFeatureError( + `Import "${this.name}" from "${this.request}" with ${this.onlyDirectImport} can only be used for direct wasm to wasm dependencies` + ) + ]; + } } get type() { - return "loader"; + return "wasm import"; } } -module.exports = LoaderDependency; +module.exports = WebAssemblyImportDependency; /***/ }), -/***/ 31559: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 75386: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -102053,153 +100038,86 @@ module.exports = LoaderDependency; Author Tobias Koppers @sokra */ +const toErrorCode = err => + `var e = new Error(${JSON.stringify(err)}); e.code = 'MODULE_NOT_FOUND';`; -const LoaderDependency = __webpack_require__(1129); -const NormalModule = __webpack_require__(25963); - -/** @typedef {import("../Module")} Module */ - -/** - * @callback LoadModuleCallback - * @param {Error=} err error object - * @param {string=} source source code - * @param {object=} map source map - * @param {Module=} module loaded module if successful - */ +exports.module = request => + `!(function webpackMissingModule() { ${exports.moduleCode(request)} }())`; -class LoaderPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "LoaderPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - LoaderDependency, - normalModuleFactory - ); - } - ); +exports.promise = request => { + const errorCode = toErrorCode(`Cannot find module '${request}'`); + return `Promise.reject(function webpackMissingModule() { ${errorCode} return e; }())`; +}; - compiler.hooks.compilation.tap("LoaderPlugin", compilation => { - compilation.hooks.normalModuleLoader.tap( - "LoaderPlugin", - (loaderContext, module) => { - /** - * @param {string} request the request string to load the module from - * @param {LoadModuleCallback} callback callback returning the loaded module or error - * @returns {void} - */ - loaderContext.loadModule = (request, callback) => { - const dep = new LoaderDependency(request); - dep.loc = { - name: request - }; - const factory = compilation.dependencyFactories.get( - dep.constructor - ); - if (factory === undefined) { - return callback( - new Error( - `No module factory available for dependency type: ${dep.constructor.name}` - ) - ); - } - compilation.semaphore.release(); - compilation.addModuleDependencies( - module, - [ - { - factory, - dependencies: [dep] - } - ], - true, - "lm", - true, - err => { - compilation.semaphore.acquire(() => { - if (err) { - return callback(err); - } - if (!dep.module) { - return callback(new Error("Cannot load the module")); - } - // TODO consider removing this in webpack 5 - if (dep.module instanceof NormalModule && dep.module.error) { - return callback(dep.module.error); - } - if (!dep.module._source) { - throw new Error( - "The module created for a LoaderDependency must have a property _source" - ); - } - let source, map; - const moduleSource = dep.module._source; - if (moduleSource.sourceAndMap) { - const sourceAndMap = moduleSource.sourceAndMap(); - map = sourceAndMap.map; - source = sourceAndMap.source; - } else { - map = moduleSource.map(); - source = moduleSource.source(); - } - if (dep.module.buildInfo.fileDependencies) { - for (const d of dep.module.buildInfo.fileDependencies) { - loaderContext.addDependency(d); - } - } - if (dep.module.buildInfo.contextDependencies) { - for (const d of dep.module.buildInfo.contextDependencies) { - loaderContext.addContextDependency(d); - } - } - return callback(null, source, map, dep.module); - }); - } - ); - }; - } - ); - }); - } -} -module.exports = LoaderPlugin; +exports.moduleCode = request => { + const errorCode = toErrorCode(`Cannot find module '${request}'`); + return `${errorCode} throw e;`; +}; /***/ }), -/***/ 17356: +/***/ 64197: /***/ (function(module) { -"use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ - - -class LocalModule { - constructor(module, name, idx) { - this.module = module; - this.name = name; - this.idx = idx; - this.used = false; +module.exports = expr => { + // + if ( + expr.type === "FunctionExpression" || + expr.type === "ArrowFunctionExpression" + ) { + return { + fn: expr, + expressions: [], + needThis: false + }; } - flagUsed() { - this.used = true; + // .bind() + if ( + expr.type === "CallExpression" && + expr.callee.type === "MemberExpression" && + expr.callee.object.type === "FunctionExpression" && + expr.callee.property.type === "Identifier" && + expr.callee.property.name === "bind" && + expr.arguments.length === 1 + ) { + return { + fn: expr.callee.object, + expressions: [expr.arguments[0]], + needThis: undefined + }; } - - variableName() { - return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; + // (function(_this) {return })(this) (Coffeescript) + if ( + expr.type === "CallExpression" && + expr.callee.type === "FunctionExpression" && + expr.callee.body.type === "BlockStatement" && + expr.arguments.length === 1 && + expr.arguments[0].type === "ThisExpression" && + expr.callee.body.body && + expr.callee.body.body.length === 1 && + expr.callee.body.body[0].type === "ReturnStatement" && + expr.callee.body.body[0].argument && + expr.callee.body.body[0].argument.type === "FunctionExpression" + ) { + return { + fn: expr.callee.body.body[0].argument, + expressions: [], + needThis: true + }; } -} -module.exports = LocalModule; +}; /***/ }), -/***/ 56570: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 49: +/***/ (function(module) { "use strict"; /* @@ -102207,206 +100125,217 @@ module.exports = LocalModule; Author Tobias Koppers @sokra */ -const NullDependency = __webpack_require__(5088); -class LocalModuleDependency extends NullDependency { - constructor(localModule, range, callNew) { - super(); - localModule.flagUsed(); - this.localModule = localModule; - this.range = range; - this.callNew = callNew; + +/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ +/** @typedef {import("./Dependency").SourcePosition} SourcePosition */ + +// TODO webpack 5: pos must be SourcePosition +/** + * @param {SourcePosition|DependencyLocation|string} pos position + * @returns {string} formatted position + */ +const formatPosition = pos => { + if (pos === null) return ""; + // TODO webpack 5: Simplify this + if (typeof pos === "string") return pos; + if (typeof pos === "number") return `${pos}`; + if (typeof pos === "object") { + if ("line" in pos && "column" in pos) { + return `${pos.line}:${pos.column}`; + } else if ("line" in pos) { + return `${pos.line}:?`; + } else if ("index" in pos) { + // TODO webpack 5 remove this case + return `+${pos.index}`; + } else { + return ""; + } } -} + return ""; +}; -LocalModuleDependency.Template = class LocalModuleDependencyTemplate { - apply(dep, source) { - if (!dep.range) return; - const moduleInstance = dep.callNew - ? `new (function () { return ${dep.localModule.variableName()}; })()` - : dep.localModule.variableName(); - source.replace(dep.range[0], dep.range[1] - 1, moduleInstance); +// TODO webpack 5: loc must be DependencyLocation +/** + * @param {DependencyLocation|SourcePosition|string} loc location + * @returns {string} formatted location + */ +const formatLocation = loc => { + if (loc === null) return ""; + // TODO webpack 5: Simplify this + if (typeof loc === "string") return loc; + if (typeof loc === "number") return `${loc}`; + if (typeof loc === "object") { + if ("start" in loc && loc.start && "end" in loc && loc.end) { + if ( + typeof loc.start === "object" && + typeof loc.start.line === "number" && + typeof loc.end === "object" && + typeof loc.end.line === "number" && + typeof loc.end.column === "number" && + loc.start.line === loc.end.line + ) { + return `${formatPosition(loc.start)}-${loc.end.column}`; + } else { + return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; + } + } + if ("start" in loc && loc.start) { + return formatPosition(loc.start); + } + if ("name" in loc && "index" in loc) { + return `${loc.name}[${loc.index}]`; + } + if ("name" in loc) { + return loc.name; + } + return formatPosition(loc); } + return ""; }; -module.exports = LocalModuleDependency; +module.exports = formatLocation; /***/ }), -/***/ 39658: -/***/ (function(module, exports, __webpack_require__) { +/***/ 47194: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const LocalModule = __webpack_require__(17356); -const LocalModulesHelpers = exports; - -const lookup = (parent, mod) => { - if (mod.charAt(0) !== ".") return mod; + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ - var path = parent.split("/"); - var segs = mod.split("/"); - path.pop(); - for (let i = 0; i < segs.length; i++) { - const seg = segs[i]; - if (seg === "..") { - path.pop(); - } else if (seg !== ".") { - path.push(seg); - } - } - return path.join("/"); -}; +const LogType = Object.freeze({ + error: /** @type {"error"} */ ("error"), // message, c style arguments + warn: /** @type {"warn"} */ ("warn"), // message, c style arguments + info: /** @type {"info"} */ ("info"), // message, c style arguments + log: /** @type {"log"} */ ("log"), // message, c style arguments + debug: /** @type {"debug"} */ ("debug"), // message, c style arguments -LocalModulesHelpers.addLocalModule = (state, name) => { - if (!state.localModules) { - state.localModules = []; - } - const m = new LocalModule(state.module, name, state.localModules.length); - state.localModules.push(m); - return m; -}; + trace: /** @type {"trace"} */ ("trace"), // no arguments -LocalModulesHelpers.getLocalModule = (state, name, namedModule) => { - if (!state.localModules) return null; - if (namedModule) { - // resolve dependency name relative to the defining named module - name = lookup(namedModule, name); - } - for (let i = 0; i < state.localModules.length; i++) { - if (state.localModules[i].name === name) { - return state.localModules[i]; - } - } - return null; -}; + group: /** @type {"group"} */ ("group"), // [label] + groupCollapsed: /** @type {"groupCollapsed"} */ ("groupCollapsed"), // [label] + groupEnd: /** @type {"groupEnd"} */ ("groupEnd"), // [label] -module.exports = LocalModulesHelpers; + profile: /** @type {"profile"} */ ("profile"), // [profileName] + profileEnd: /** @type {"profileEnd"} */ ("profileEnd"), // [profileName] + time: /** @type {"time"} */ ("time"), // name, time as [seconds, nanoseconds] -/***/ }), + clear: /** @type {"clear"} */ ("clear"), // no arguments + status: /** @type {"status"} */ ("status") // message, arguments +}); -/***/ 90865: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +exports.LogType = LogType; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** @typedef {typeof LogType[keyof typeof LogType]} LogTypeEnum */ -const Dependency = __webpack_require__(57282); +const LOG_SYMBOL = Symbol("webpack logger raw log method"); +const TIMERS_SYMBOL = Symbol("webpack logger times"); -class ModuleDependency extends Dependency { +class WebpackLogger { /** - * @param {string} request request path which needs resolving + * @param {function(LogTypeEnum, any[]=): void} log log function */ - constructor(request) { - super(); - this.request = request; - this.userRequest = request; + constructor(log) { + this[LOG_SYMBOL] = log; } - getResourceIdentifier() { - return `module${this.request}`; + error(...args) { + this[LOG_SYMBOL](LogType.error, args); } -} - -module.exports = ModuleDependency; - -/***/ }), - -/***/ 63708: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + warn(...args) { + this[LOG_SYMBOL](LogType.warn, args); + } + info(...args) { + this[LOG_SYMBOL](LogType.info, args); + } -class ModuleDependencyTemplateAsId { - apply(dep, source, runtime) { - if (!dep.range) return; - const content = runtime.moduleId({ - module: dep.module, - request: dep.request - }); - source.replace(dep.range[0], dep.range[1] - 1, content); + log(...args) { + this[LOG_SYMBOL](LogType.log, args); } -} -module.exports = ModuleDependencyTemplateAsId; + debug(...args) { + this[LOG_SYMBOL](LogType.debug, args); + } -/***/ }), + assert(assertion, ...args) { + if (!assertion) { + this[LOG_SYMBOL](LogType.error, args); + } + } -/***/ 60441: -/***/ (function(module) { + trace() { + this[LOG_SYMBOL](LogType.trace, ["Trace"]); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + clear() { + this[LOG_SYMBOL](LogType.clear); + } + status(...args) { + this[LOG_SYMBOL](LogType.status, args); + } -class ModuleDependencyTemplateAsRequireId { - apply(dep, source, runtime) { - if (!dep.range) return; - const content = runtime.moduleExports({ - module: dep.module, - request: dep.request - }); - source.replace(dep.range[0], dep.range[1] - 1, content); + group(...args) { + this[LOG_SYMBOL](LogType.group, args); } -} -module.exports = ModuleDependencyTemplateAsRequireId; + groupCollapsed(...args) { + this[LOG_SYMBOL](LogType.groupCollapsed, args); + } -/***/ }), + groupEnd(...args) { + this[LOG_SYMBOL](LogType.groupEnd, args); + } -/***/ 29018: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + profile(label) { + this[LOG_SYMBOL](LogType.profile, [label]); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + profileEnd(label) { + this[LOG_SYMBOL](LogType.profileEnd, [label]); + } -const ModuleDependency = __webpack_require__(90865); -const ModuleDependencyTemplateAsId = __webpack_require__(63708); + time(label) { + this[TIMERS_SYMBOL] = this[TIMERS_SYMBOL] || new Map(); + this[TIMERS_SYMBOL].set(label, process.hrtime()); + } -class ModuleHotAcceptDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; - this.weak = true; + timeLog(label) { + const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); + if (!prev) { + throw new Error(`No such label '${label}' for WebpackLogger.timeLog()`); + } + const time = process.hrtime(prev); + this[LOG_SYMBOL](LogType.time, [label, ...time]); } - get type() { - return "module.hot.accept"; + timeEnd(label) { + const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); + if (!prev) { + throw new Error(`No such label '${label}' for WebpackLogger.timeEnd()`); + } + const time = process.hrtime(prev); + this[TIMERS_SYMBOL].delete(label); + this[LOG_SYMBOL](LogType.time, [label, ...time]); } } -ModuleHotAcceptDependency.Template = ModuleDependencyTemplateAsId; - -module.exports = ModuleHotAcceptDependency; +exports.Logger = WebpackLogger; /***/ }), -/***/ 60482: +/***/ 88838: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102415,90 +100344,300 @@ module.exports = ModuleHotAcceptDependency; Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(90865); -const ModuleDependencyTemplateAsId = __webpack_require__(63708); - -class ModuleHotDeclineDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; - this.weak = true; - } - - get type() { - return "module.hot.decline"; - } -} -ModuleHotDeclineDependency.Template = ModuleDependencyTemplateAsId; -module.exports = ModuleHotDeclineDependency; +const { LogType } = __webpack_require__(47194); +/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ +/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ +/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ -/***/ }), +/** @typedef {function(string): boolean} FilterFunction */ -/***/ 7791: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @typedef {Object} LoggerOptions + * @property {false|true|"none"|"error"|"warn"|"info"|"log"|"verbose"} level loglevel + * @property {FilterTypes|boolean} debug filter for debug logging + * @property {Console & { status?: Function, logTime?: Function }} console the console to log to + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @param {FilterItemTypes} item an input item + * @returns {FilterFunction} filter funtion + */ +const filterToFunction = item => { + if (typeof item === "string") { + const regExp = new RegExp( + `[\\\\/]${item.replace( + // eslint-disable-next-line no-useless-escape + /[-[\]{}()*+?.\\^$|]/g, + "\\$&" + )}([\\\\/]|$|!|\\?)` + ); + return ident => regExp.test(ident); + } + if (item && typeof item === "object" && typeof item.test === "function") { + return ident => item.test(ident); + } + if (typeof item === "function") { + return item; + } + if (typeof item === "boolean") { + return () => item; + } +}; -/** @typedef {import("./SingleEntryDependency")} SingleEntryDependency */ -const Dependency = __webpack_require__(57282); +/** + * @enum {number} + */ +const LogLevel = { + none: 6, + false: 6, + error: 5, + warn: 4, + info: 3, + log: 2, + true: 2, + verbose: 1 +}; + +/** + * @param {LoggerOptions} options options object + * @returns {function(string, LogTypeEnum, any[]): void} logging function + */ +module.exports = ({ level = "info", debug = false, console }) => { + const debugFilters = + typeof debug === "boolean" + ? [() => debug] + : /** @type {FilterItemTypes[]} */ ([]) + .concat(debug) + .map(filterToFunction); + /** @type {number} */ + const loglevel = LogLevel[`${level}`] || 0; -class MultiEntryDependency extends Dependency { /** - * @param {SingleEntryDependency[]} dependencies an array of SingleEntryDependencies - * @param {string} name entry name + * @param {string} name name of the logger + * @param {LogTypeEnum} type type of the log entry + * @param {any[]} args arguments of the log entry + * @returns {void} */ - constructor(dependencies, name) { - super(); - this.dependencies = dependencies; - this.name = name; - } - - get type() { - return "multi entry"; - } -} - -module.exports = MultiEntryDependency; + const logger = (name, type, args) => { + const labeledArgs = () => { + if (Array.isArray(args)) { + if (args.length > 0 && typeof args[0] === "string") { + return [`[${name}] ${args[0]}`, ...args.slice(1)]; + } else { + return [`[${name}]`, ...args]; + } + } else { + return []; + } + }; + const debug = debugFilters.some(f => f(name)); + switch (type) { + case LogType.debug: + if (!debug) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.debug === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.debug(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + case LogType.log: + if (!debug && loglevel > LogLevel.log) return; + console.log(...labeledArgs()); + break; + case LogType.info: + if (!debug && loglevel > LogLevel.info) return; + console.info(...labeledArgs()); + break; + case LogType.warn: + if (!debug && loglevel > LogLevel.warn) return; + console.warn(...labeledArgs()); + break; + case LogType.error: + if (!debug && loglevel > LogLevel.error) return; + console.error(...labeledArgs()); + break; + case LogType.trace: + if (!debug) return; + console.trace(); + break; + case LogType.groupCollapsed: + if (!debug && loglevel > LogLevel.log) return; + if (!debug && loglevel > LogLevel.verbose) { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.groupCollapsed === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.groupCollapsed(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + } + // falls through + case LogType.group: + if (!debug && loglevel > LogLevel.log) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.group === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.group(...labeledArgs()); + } else { + console.log(...labeledArgs()); + } + break; + case LogType.groupEnd: + if (!debug && loglevel > LogLevel.log) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.groupEnd === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.groupEnd(); + } + break; + case LogType.time: { + if (!debug && loglevel > LogLevel.log) return; + const ms = args[1] * 1000 + args[2] / 1000000; + const msg = `[${name}] ${args[0]}: ${ms}ms`; + if (typeof console.logTime === "function") { + console.logTime(msg); + } else { + console.log(msg); + } + break; + } + case LogType.profile: + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profile === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profile(...labeledArgs()); + } + break; + case LogType.profileEnd: + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.profileEnd === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.profileEnd(...labeledArgs()); + } + break; + case LogType.clear: + if (!debug && loglevel > LogLevel.log) return; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + if (typeof console.clear === "function") { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.clear(); + } + break; + case LogType.status: + if (!debug && loglevel > LogLevel.info) return; + if (typeof console.status === "function") { + if (args.length === 0) { + console.status(); + } else { + console.status(...labeledArgs()); + } + } else { + if (args.length !== 0) { + console.info(...labeledArgs()); + } + } + break; + default: + throw new Error(`Unexpected LogType ${type}`); + } + }; + return logger; +}; /***/ }), -/***/ 5088: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 62299: +/***/ (function(module) { "use strict"; /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ -const Dependency = __webpack_require__(57282); -class NullDependency extends Dependency { - get type() { - return "null"; + +/** + * @param {any[]} args items to be truncated + * @param {number} maxLength maximum length of args including spaces between + * @returns {string[]} truncated args + */ +const truncateArgs = (args, maxLength) => { + const lengths = args.map(a => `${a}`.length); + const availableLength = maxLength - lengths.length + 1; + + if (availableLength > 0 && args.length === 1) { + if (availableLength >= args[0].length) { + return args; + } else if (availableLength > 3) { + return ["..." + args[0].slice(-availableLength + 3)]; + } else { + return [args[0].slice(-availableLength)]; + } } - updateHash() {} -} + // Check if there is space for at least 4 chars per arg + if (availableLength < lengths.reduce((s, i) => s + Math.min(i, 6), 0)) { + // remove args + if (args.length > 1) + return truncateArgs(args.slice(0, args.length - 1), maxLength); + return []; + } -NullDependency.Template = class NullDependencyTemplate { - apply() {} + let currentLength = lengths.reduce((a, b) => a + b, 0); + + // Check if all fits into maxLength + if (currentLength <= availableLength) return args; + + // Try to remove chars from the longest items until it fits + while (currentLength > availableLength) { + const maxLength = Math.max(...lengths); + const shorterItems = lengths.filter(l => l !== maxLength); + const nextToMaxLength = + shorterItems.length > 0 ? Math.max(...shorterItems) : 0; + const maxReduce = maxLength - nextToMaxLength; + let maxItems = lengths.length - shorterItems.length; + let overrun = currentLength - availableLength; + for (let i = 0; i < lengths.length; i++) { + if (lengths[i] === maxLength) { + const reduce = Math.min(Math.floor(overrun / maxItems), maxReduce); + lengths[i] -= reduce; + currentLength -= reduce; + overrun -= reduce; + maxItems--; + } + } + } + + // Return args reduced to length in lengths + return args.map((a, i) => { + const str = `${a}`; + const length = lengths[i]; + if (str.length === length) { + return str; + } else if (length > 5) { + return "..." + str.slice(-length + 3); + } else if (length > 0) { + return str.slice(-length); + } else { + return ""; + } + }); }; -module.exports = NullDependency; +module.exports = truncateArgs; /***/ }), -/***/ 14237: +/***/ 45249: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102507,24 +100646,37 @@ module.exports = NullDependency; Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(90865); -class PrefetchDependency extends ModuleDependency { - constructor(request) { - super(request); - } - get type() { - return "prefetch"; +const { ConcatSource } = __webpack_require__(53665); + +class NodeChunkTemplatePlugin { + apply(chunkTemplate) { + chunkTemplate.hooks.render.tap( + "NodeChunkTemplatePlugin", + (modules, chunk) => { + const source = new ConcatSource(); + source.add( + `exports.ids = ${JSON.stringify(chunk.ids)};\nexports.modules = ` + ); + source.add(modules); + source.add(";"); + return source; + } + ); + chunkTemplate.hooks.hash.tap("NodeChunkTemplatePlugin", hash => { + hash.update("node"); + hash.update("3"); + }); } } -module.exports = PrefetchDependency; +module.exports = NodeChunkTemplatePlugin; /***/ }), -/***/ 79142: +/***/ 52520: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102533,28 +100685,50 @@ module.exports = PrefetchDependency; Author Tobias Koppers @sokra */ -const ContextDependency = __webpack_require__(11583); -const ModuleDependencyTemplateAsRequireId = __webpack_require__(60441); -class RequireContextDependency extends ContextDependency { - constructor(options, range) { - super(options); - this.range = range; +const NodeWatchFileSystem = __webpack_require__(71610); +const NodeOutputFileSystem = __webpack_require__(31836); +const NodeJsInputFileSystem = __webpack_require__(13445); +const CachedInputFileSystem = __webpack_require__(75544); +const createConsoleLogger = __webpack_require__(88838); +const nodeConsole = __webpack_require__(7886); + +class NodeEnvironmentPlugin { + constructor(options) { + this.options = options || {}; } - get type() { - return "require.context"; + apply(compiler) { + compiler.infrastructureLogger = createConsoleLogger( + Object.assign( + { + level: "info", + debug: false, + console: nodeConsole + }, + this.options.infrastructureLogging + ) + ); + compiler.inputFileSystem = new CachedInputFileSystem( + new NodeJsInputFileSystem(), + 60000 + ); + const inputFileSystem = compiler.inputFileSystem; + compiler.outputFileSystem = new NodeOutputFileSystem(); + compiler.watchFileSystem = new NodeWatchFileSystem( + compiler.inputFileSystem + ); + compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => { + if (compiler.inputFileSystem === inputFileSystem) inputFileSystem.purge(); + }); } } - -RequireContextDependency.Template = ModuleDependencyTemplateAsRequireId; - -module.exports = RequireContextDependency; +module.exports = NodeEnvironmentPlugin; /***/ }), -/***/ 10566: +/***/ 95909: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102564,212 +100738,466 @@ module.exports = RequireContextDependency; */ -const RequireContextDependency = __webpack_require__(79142); +const { ConcatSource } = __webpack_require__(53665); -module.exports = class RequireContextDependencyParserPlugin { - apply(parser) { - parser.hooks.call - .for("require.context") - .tap("RequireContextDependencyParserPlugin", expr => { - let regExp = /^\.\/.*$/; - let recursive = true; - let mode = "sync"; - switch (expr.arguments.length) { - case 4: { - const modeExpr = parser.evaluateExpression(expr.arguments[3]); - if (!modeExpr.isString()) return; - mode = modeExpr.string; - } - // falls through - case 3: { - const regExpExpr = parser.evaluateExpression(expr.arguments[2]); - if (!regExpExpr.isRegExp()) return; - regExp = regExpExpr.regExp; - } - // falls through - case 2: { - const recursiveExpr = parser.evaluateExpression(expr.arguments[1]); - if (!recursiveExpr.isBoolean()) return; - recursive = recursiveExpr.bool; - } - // falls through - case 1: { - const requestExpr = parser.evaluateExpression(expr.arguments[0]); - if (!requestExpr.isString()) return; - const dep = new RequireContextDependency( - { - request: requestExpr.string, - recursive, - regExp, - mode - }, - expr.range - ); - dep.loc = expr.loc; - dep.optional = parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - } - } - }); +class NodeHotUpdateChunkTemplatePlugin { + apply(hotUpdateChunkTemplate) { + hotUpdateChunkTemplate.hooks.render.tap( + "NodeHotUpdateChunkTemplatePlugin", + (modulesSource, modules, removedModules, hash, id) => { + const source = new ConcatSource(); + source.add( + "exports.id = " + JSON.stringify(id) + ";\nexports.modules = " + ); + source.add(modulesSource); + source.add(";"); + return source; + } + ); + hotUpdateChunkTemplate.hooks.hash.tap( + "NodeHotUpdateChunkTemplatePlugin", + hash => { + hash.update("NodeHotUpdateChunkTemplatePlugin"); + hash.update("3"); + hash.update( + hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "" + ); + hash.update(hotUpdateChunkTemplate.outputOptions.library + ""); + } + ); } -}; +} +module.exports = NodeHotUpdateChunkTemplatePlugin; /***/ }), -/***/ 89042: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 33514: +/***/ (function(module) { -"use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ +// eslint-disable-next-line no-unused-vars +var $hotChunkFilename$ = undefined; +var hotAddUpdateChunk = undefined; +var installedChunks = undefined; +var $hotMainFilename$ = undefined; +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + var chunk = require("./" + $hotChunkFilename$); + hotAddUpdateChunk(chunk.id, chunk.modules); + } -const RequireContextDependency = __webpack_require__(79142); -const ContextElementDependency = __webpack_require__(89079); - -const RequireContextDependencyParserPlugin = __webpack_require__(10566); - -class RequireContextPlugin { - constructor(modulesDirectories, extensions, mainFiles) { - if (!Array.isArray(modulesDirectories)) { - throw new Error("modulesDirectories must be an array"); - } - if (!Array.isArray(extensions)) { - throw new Error("extensions must be an array"); + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest() { + try { + var update = require("./" + $hotMainFilename$); + } catch (e) { + return Promise.resolve(); } - this.modulesDirectories = modulesDirectories; - this.extensions = extensions; - this.mainFiles = mainFiles; + return Promise.resolve(update); } - apply(compiler) { - compiler.hooks.compilation.tap( - "RequireContextPlugin", - (compilation, { contextModuleFactory, normalModuleFactory }) => { - compilation.dependencyFactories.set( - RequireContextDependency, - contextModuleFactory - ); - compilation.dependencyTemplates.set( - RequireContextDependency, - new RequireContextDependency.Template() - ); + //eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; - compilation.dependencyFactories.set( - ContextElementDependency, - normalModuleFactory - ); - const handler = (parser, parserOptions) => { - if ( - parserOptions.requireContext !== undefined && - !parserOptions.requireContext - ) - return; +/***/ }), - new RequireContextDependencyParserPlugin().apply(parser); - }; +/***/ 51433: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireContextPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireContextPlugin", handler); +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +// eslint-disable-next-line no-unused-vars +var $hotChunkFilename$ = undefined; +var $require$ = undefined; +var hotAddUpdateChunk = undefined; +var $hotMainFilename$ = undefined; +var installedChunks = undefined; - contextModuleFactory.hooks.alternatives.tap( - "RequireContextPlugin", - items => { - if (items.length === 0) return items; - return items - .map(obj => { - return this.extensions - .filter(ext => { - const l = obj.request.length; - return ( - l > ext.length && - obj.request.substr(l - ext.length, l) === ext - ); - }) - .map(ext => { - const l = obj.request.length; - return { - context: obj.context, - request: obj.request.substr(0, l - ext.length) - }; - }) - .concat(obj); - }) - .reduce((a, b) => a.concat(b), []); - } - ); +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + var filename = __webpack_require__(85622).join(__dirname, $hotChunkFilename$); + __webpack_require__(35747).readFile(filename, "utf-8", function(err, content) { + if (err) { + if ($require$.onError) return $require$.oe(err); + throw err; + } + var chunk = {}; + __webpack_require__(92184).runInThisContext( + "(function(exports) {" + content + "\n})", + { filename: filename } + )(chunk); + hotAddUpdateChunk(chunk.id, chunk.modules); + }); + } - contextModuleFactory.hooks.alternatives.tap( - "RequireContextPlugin", - items => { - if (items.length === 0) return items; - return items - .map(obj => { - return this.mainFiles - .filter(mainFile => { - const l = obj.request.length; - return ( - l > mainFile.length + 1 && - obj.request.substr(l - mainFile.length - 1, l) === - "/" + mainFile - ); - }) - .map(mainFile => { - const l = obj.request.length; - return [ - { - context: obj.context, - request: obj.request.substr(0, l - mainFile.length) - }, + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest() { + var filename = __webpack_require__(85622).join(__dirname, $hotMainFilename$); + return new Promise(function(resolve, reject) { + __webpack_require__(35747).readFile(filename, "utf-8", function(err, content) { + if (err) return resolve(); + try { + var update = JSON.parse(content); + } catch (e) { + return reject(e); + } + resolve(update); + }); + }); + } + + // eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; + + +/***/ }), + +/***/ 78597: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +const Template = __webpack_require__(96066); + +module.exports = class NodeMainTemplatePlugin { + constructor(asyncChunkLoading) { + this.asyncChunkLoading = asyncChunkLoading; + } + + apply(mainTemplate) { + const needChunkOnDemandLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.getNumberOfChildren() > 0) return true; + } + return false; + }; + const asyncChunkLoading = this.asyncChunkLoading; + mainTemplate.hooks.localVars.tap( + "NodeMainTemplatePlugin", + (source, chunk) => { + if (needChunkOnDemandLoadingCode(chunk)) { + return Template.asString([ + source, + "", + "// object to store loaded chunks", + '// "0" means "already loaded"', + "var installedChunks = {", + Template.indent( + chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") + ), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.requireExtensions.tap( + "NodeMainTemplatePlugin", + (source, chunk) => { + if (needChunkOnDemandLoadingCode(chunk)) { + return Template.asString([ + source, + "", + "// uncaught error handler for webpack runtime", + `${mainTemplate.requireFn}.oe = function(err) {`, + Template.indent([ + "process.nextTick(function() {", + Template.indent( + "throw err; // catch this error by using import().catch()" + ), + "});" + ]), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.requireEnsure.tap( + "NodeMainTemplatePlugin", + (source, chunk, hash) => { + const chunkFilename = mainTemplate.outputOptions.chunkFilename; + const chunkMaps = chunk.getChunkMaps(); + const insertMoreModules = [ + "var moreModules = chunk.modules, chunkIds = chunk.ids;", + "for(var moduleId in moreModules) {", + Template.indent( + mainTemplate.renderAddModule( + hash, + chunk, + "moduleId", + "moreModules[moduleId]" + ) + ), + "}" + ]; + if (asyncChunkLoading) { + return Template.asString([ + source, + "", + "// ReadFile + VM.run chunk loading for javascript", + "", + "var installedChunkData = installedChunks[chunkId];", + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + '// array of [resolve, reject, promise] means "currently loading"', + "if(installedChunkData) {", + Template.indent(["promises.push(installedChunkData[2]);"]), + "} else {", + Template.indent([ + "// load the chunk and return promise to it", + "var promise = new Promise(function(resolve, reject) {", + Template.indent([ + "installedChunkData = installedChunks[chunkId] = [resolve, reject];", + "var filename = require('path').join(__dirname, " + + mainTemplate.getAssetPath( + JSON.stringify(`/${chunkFilename}`), { - context: obj.context, - request: obj.request.substr(0, l - mainFile.length - 1) + hash: `" + ${mainTemplate.renderCurrentHashCode( + hash + )} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode( + hash, + length + )} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify( + chunkMaps.hash + )}[chunkId] + "`, + hashWithLength: length => { + const shortChunkHashMap = {}; + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[chunkId] + "`; + }, + contentHash: { + javascript: `" + ${JSON.stringify( + chunkMaps.contentHash.javascript + )}[chunkId] + "` + }, + contentHashWithLength: { + javascript: length => { + const shortContentHashMap = {}; + const contentHash = + chunkMaps.contentHash.javascript; + for (const chunkId of Object.keys(contentHash)) { + if (typeof contentHash[chunkId] === "string") { + shortContentHashMap[chunkId] = contentHash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortContentHashMap + )}[chunkId] + "`; + } + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + }, + contentHashType: "javascript" } - ]; - }) - .reduce((a, b) => a.concat(b), []) - .concat(obj); - }) - .reduce((a, b) => a.concat(b), []); + ) + + ");", + "require('fs').readFile(filename, 'utf-8', function(err, content) {", + Template.indent( + [ + "if(err) return reject(err);", + "var chunk = {};", + "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + + "(chunk, require, require('path').dirname(filename), filename);" + ] + .concat(insertMoreModules) + .concat([ + "var callbacks = [];", + "for(var i = 0; i < chunkIds.length; i++) {", + Template.indent([ + "if(installedChunks[chunkIds[i]])", + Template.indent([ + "callbacks = callbacks.concat(installedChunks[chunkIds[i]][0]);" + ]), + "installedChunks[chunkIds[i]] = 0;" + ]), + "}", + "for(i = 0; i < callbacks.length; i++)", + Template.indent("callbacks[i]();") + ]) + ), + "});" + ]), + "});", + "promises.push(installedChunkData[2] = promise);" + ]), + "}" + ]), + "}" + ]); + } else { + const request = mainTemplate.getAssetPath( + JSON.stringify(`./${chunkFilename}`), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, + hashWithLength: length => { + const shortChunkHashMap = {}; + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[chunkId] + "`; + }, + contentHash: { + javascript: `" + ${JSON.stringify( + chunkMaps.contentHash.javascript + )}[chunkId] + "` + }, + contentHashWithLength: { + javascript: length => { + const shortContentHashMap = {}; + const contentHash = chunkMaps.contentHash.javascript; + for (const chunkId of Object.keys(contentHash)) { + if (typeof contentHash[chunkId] === "string") { + shortContentHashMap[chunkId] = contentHash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortContentHashMap + )}[chunkId] + "`; + } + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + }, + contentHashType: "javascript" + } + ); + return Template.asString([ + source, + "", + "// require() chunk loading for javascript", + "", + '// "0" is the signal for "already loaded"', + "if(installedChunks[chunkId] !== 0) {", + Template.indent( + [`var chunk = require(${request});`] + .concat(insertMoreModules) + .concat([ + "for(var i = 0; i < chunkIds.length; i++)", + Template.indent("installedChunks[chunkIds[i]] = 0;") + ]) + ), + "}" + ]); + } + } + ); + mainTemplate.hooks.hotBootstrap.tap( + "NodeMainTemplatePlugin", + (source, chunk, hash) => { + const hotUpdateChunkFilename = + mainTemplate.outputOptions.hotUpdateChunkFilename; + const hotUpdateMainFilename = + mainTemplate.outputOptions.hotUpdateMainFilename; + const chunkMaps = chunk.getChunkMaps(); + const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateChunkFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, + hashWithLength: length => { + const shortChunkHashMap = {}; + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( + 0, + length + ); + } + } + return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`; + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + } } ); - - contextModuleFactory.hooks.alternatives.tap( - "RequireContextPlugin", - items => { - if (items.length === 0) return items; - return items.map(obj => { - for (let i = 0; i < this.modulesDirectories.length; i++) { - const dir = this.modulesDirectories[i]; - const idx = obj.request.indexOf("./" + dir + "/"); - if (idx === 0) { - obj.request = obj.request.slice(dir.length + 3); - break; - } - } - return obj; - }); + const currentHotUpdateMainFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateMainFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` } ); + return Template.getFunctionContent( + asyncChunkLoading + ? __webpack_require__(51433) + : __webpack_require__(33514) + ) + .replace(/\$require\$/g, mainTemplate.requireFn) + .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) + .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename); } ); + mainTemplate.hooks.hash.tap("NodeMainTemplatePlugin", hash => { + hash.update("node"); + hash.update("4"); + }); } -} -module.exports = RequireContextPlugin; +}; /***/ }), -/***/ 49105: +/***/ 31836: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102778,39 +101206,28 @@ module.exports = RequireContextPlugin; Author Tobias Koppers @sokra */ -const AsyncDependenciesBlock = __webpack_require__(22814); -const RequireEnsureDependency = __webpack_require__(75830); -module.exports = class RequireEnsureDependenciesBlock extends AsyncDependenciesBlock { - constructor( - expr, - successExpression, - errorExpression, - chunkName, - chunkNameRange, - module, - loc - ) { - super(chunkName, module, loc, null); - this.expr = expr; - const successBodyRange = - successExpression && - successExpression.body && - successExpression.body.range; - if (successBodyRange) { - this.range = [successBodyRange[0] + 1, successBodyRange[1] - 1]; - } - this.chunkNameRange = chunkNameRange; - const dep = new RequireEnsureDependency(this); - dep.loc = loc; - this.addDependency(dep); +const fs = __webpack_require__(35747); +const path = __webpack_require__(85622); +const mkdirp = __webpack_require__(50998); + +class NodeOutputFileSystem { + constructor() { + this.mkdirp = mkdirp; + this.mkdir = fs.mkdir.bind(fs); + this.rmdir = fs.rmdir.bind(fs); + this.unlink = fs.unlink.bind(fs); + this.writeFile = fs.writeFile.bind(fs); + this.join = path.join.bind(path); } -}; +} + +module.exports = NodeOutputFileSystem; /***/ }), -/***/ 24620: +/***/ 9128: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102819,122 +101236,147 @@ module.exports = class RequireEnsureDependenciesBlock extends AsyncDependenciesB Author Tobias Koppers @sokra */ +const AliasPlugin = __webpack_require__(15005); +const ParserHelpers = __webpack_require__(23999); +const nodeLibsBrowser = __webpack_require__(27852); -const RequireEnsureDependenciesBlock = __webpack_require__(49105); -const RequireEnsureItemDependency = __webpack_require__(5511); -const getFunctionExpression = __webpack_require__(64197); +module.exports = class NodeSourcePlugin { + constructor(options) { + this.options = options; + } + apply(compiler) { + const options = this.options; + if (options === false) { + // allow single kill switch to turn off this plugin + return; + } -module.exports = class RequireEnsureDependenciesBlockParserPlugin { - apply(parser) { - parser.hooks.call - .for("require.ensure") - .tap("RequireEnsureDependenciesBlockParserPlugin", expr => { - let chunkName = null; - let chunkNameRange = null; - let errorExpressionArg = null; - let errorExpression = null; - switch (expr.arguments.length) { - case 4: { - const chunkNameExpr = parser.evaluateExpression(expr.arguments[3]); - if (!chunkNameExpr.isString()) return; - chunkNameRange = chunkNameExpr.range; - chunkName = chunkNameExpr.string; - } - // falls through - case 3: { - errorExpressionArg = expr.arguments[2]; - errorExpression = getFunctionExpression(errorExpressionArg); + const getPathToModule = (module, type) => { + if (type === true || (type === undefined && nodeLibsBrowser[module])) { + if (!nodeLibsBrowser[module]) { + throw new Error( + `No browser version for node.js core module ${module} available` + ); + } + return nodeLibsBrowser[module]; + } else if (type === "mock") { + return require.resolve(`node-libs-browser/mock/${module}`); + } else if (type === "empty") { + return __webpack_require__.ab + "empty.js"; + } else { + return module; + } + }; - if (!errorExpression && !chunkName) { - const chunkNameExpr = parser.evaluateExpression( - expr.arguments[2] - ); - if (!chunkNameExpr.isString()) return; - chunkNameRange = chunkNameExpr.range; - chunkName = chunkNameExpr.string; - } - } - // falls through - case 2: { - const dependenciesExpr = parser.evaluateExpression( - expr.arguments[0] - ); - const dependenciesItems = dependenciesExpr.isArray() - ? dependenciesExpr.items - : [dependenciesExpr]; - const successExpressionArg = expr.arguments[1]; - const successExpression = getFunctionExpression( - successExpressionArg - ); + const addExpression = (parser, name, module, type, suffix) => { + suffix = suffix || ""; + parser.hooks.expression.for(name).tap("NodeSourcePlugin", () => { + if ( + parser.state.module && + parser.state.module.resource === getPathToModule(module, type) + ) + return; + const mockModule = ParserHelpers.requireFileAsExpression( + parser.state.module.context, + getPathToModule(module, type) + ); + return ParserHelpers.addParsedVariableToModule( + parser, + name, + mockModule + suffix + ); + }); + }; - if (successExpression) { - parser.walkExpressions(successExpression.expressions); - } - if (errorExpression) { - parser.walkExpressions(errorExpression.expressions); - } + compiler.hooks.compilation.tap( + "NodeSourcePlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + if (parserOptions.node === false) return; - const dep = new RequireEnsureDependenciesBlock( - expr, - successExpression ? successExpression.fn : successExpressionArg, - errorExpression ? errorExpression.fn : errorExpressionArg, - chunkName, - chunkNameRange, - parser.state.module, - expr.loc - ); - const old = parser.state.current; - parser.state.current = dep; - try { - let failed = false; - parser.inScope([], () => { - for (const ee of dependenciesItems) { - if (ee.isString()) { - const edep = new RequireEnsureItemDependency(ee.string); - edep.loc = dep.loc; - dep.addDependency(edep); - } else { - failed = true; - } - } + let localOptions = options; + if (parserOptions.node) { + localOptions = Object.assign({}, localOptions, parserOptions.node); + } + if (localOptions.global) { + parser.hooks.expression + .for("global") + .tap("NodeSourcePlugin", () => { + const retrieveGlobalModule = ParserHelpers.requireFileAsExpression( + parser.state.module.context, + __webpack_require__.ab + "global.js" + ); + return ParserHelpers.addParsedVariableToModule( + parser, + "global", + retrieveGlobalModule + ); }); - if (failed) { - return; - } - if (successExpression) { - if (successExpression.fn.body.type === "BlockStatement") { - parser.walkStatement(successExpression.fn.body); - } else { - parser.walkExpression(successExpression.fn.body); - } - } - old.addBlock(dep); - } finally { - parser.state.current = old; - } - if (!successExpression) { - parser.walkExpression(successExpressionArg); - } - if (errorExpression) { - if (errorExpression.fn.body.type === "BlockStatement") { - parser.walkStatement(errorExpression.fn.body); - } else { - parser.walkExpression(errorExpression.fn.body); - } - } else if (errorExpressionArg) { - parser.walkExpression(errorExpressionArg); - } - return true; } + if (localOptions.process) { + const processType = localOptions.process; + addExpression(parser, "process", "process", processType); + } + if (localOptions.console) { + const consoleType = localOptions.console; + addExpression(parser, "console", "console", consoleType); + } + const bufferType = localOptions.Buffer; + if (bufferType) { + addExpression(parser, "Buffer", "buffer", bufferType, ".Buffer"); + } + if (localOptions.setImmediate) { + const setImmediateType = localOptions.setImmediate; + addExpression( + parser, + "setImmediate", + "timers", + setImmediateType, + ".setImmediate" + ); + addExpression( + parser, + "clearImmediate", + "timers", + setImmediateType, + ".clearImmediate" + ); + } + }; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("NodeSourcePlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("NodeSourcePlugin", handler); + } + ); + compiler.hooks.afterResolvers.tap("NodeSourcePlugin", compiler => { + for (const lib of Object.keys(nodeLibsBrowser)) { + if (options[lib] !== false) { + compiler.resolverFactory.hooks.resolver + .for("normal") + .tap("NodeSourcePlugin", resolver => { + new AliasPlugin( + "described-resolve", + { + name: lib, + onlyModule: true, + alias: getPathToModule(lib, options[lib]) + }, + "resolve" + ).apply(resolver); + }); } - }); + } + }); } }; /***/ }), -/***/ 75830: +/***/ 59743: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -102943,64 +101385,25 @@ module.exports = class RequireEnsureDependenciesBlockParserPlugin { Author Tobias Koppers @sokra */ -const NullDependency = __webpack_require__(5088); -class RequireEnsureDependency extends NullDependency { - constructor(block) { - super(); - this.block = block; - } +const ExternalsPlugin = __webpack_require__(75705); - get type() { - return "require.ensure"; - } -} +const builtins = + // eslint-disable-next-line node/no-unsupported-features/node-builtins,node/no-deprecated-api + __webpack_require__(32282).builtinModules || Object.keys(process.binding("natives")); -RequireEnsureDependency.Template = class RequireEnsureDependencyTemplate { - apply(dep, source, runtime) { - const depBlock = dep.block; - const promise = runtime.blockPromise({ - block: depBlock, - message: "require.ensure" - }); - const errorCallbackExists = - depBlock.expr.arguments.length === 4 || - (!depBlock.chunkName && depBlock.expr.arguments.length === 3); - const startBlock = `${promise}.then((`; - const middleBlock = ").bind(null, __webpack_require__)).catch("; - const endBlock = `).bind(null, __webpack_require__)).catch(${runtime.onError()})`; - source.replace( - depBlock.expr.range[0], - depBlock.expr.arguments[1].range[0] - 1, - startBlock - ); - if (errorCallbackExists) { - source.replace( - depBlock.expr.arguments[1].range[1], - depBlock.expr.arguments[2].range[0] - 1, - middleBlock - ); - source.replace( - depBlock.expr.arguments[2].range[1], - depBlock.expr.range[1] - 1, - ")" - ); - } else { - source.replace( - depBlock.expr.arguments[1].range[1], - depBlock.expr.range[1] - 1, - endBlock - ); - } +class NodeTargetPlugin { + apply(compiler) { + new ExternalsPlugin("commonjs", builtins).apply(compiler); } -}; +} -module.exports = RequireEnsureDependency; +module.exports = NodeTargetPlugin; /***/ }), -/***/ 5511: +/***/ 90010: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103009,27 +101412,37 @@ module.exports = RequireEnsureDependency; Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(90865); -const NullDependency = __webpack_require__(5088); -class RequireEnsureItemDependency extends ModuleDependency { - constructor(request) { - super(request); + +const NodeMainTemplatePlugin = __webpack_require__(78597); +const NodeChunkTemplatePlugin = __webpack_require__(45249); +const NodeHotUpdateChunkTemplatePlugin = __webpack_require__(95909); + +class NodeTemplatePlugin { + constructor(options) { + options = options || {}; + this.asyncChunkLoading = options.asyncChunkLoading; } - get type() { - return "require.ensure item"; + apply(compiler) { + compiler.hooks.thisCompilation.tap("NodeTemplatePlugin", compilation => { + new NodeMainTemplatePlugin(this.asyncChunkLoading).apply( + compilation.mainTemplate + ); + new NodeChunkTemplatePlugin().apply(compilation.chunkTemplate); + new NodeHotUpdateChunkTemplatePlugin().apply( + compilation.hotUpdateChunkTemplate + ); + }); } } -RequireEnsureItemDependency.Template = NullDependency.Template; - -module.exports = RequireEnsureItemDependency; +module.exports = NodeTemplatePlugin; /***/ }), -/***/ 98655: +/***/ 71610: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103039,113 +101452,114 @@ module.exports = RequireEnsureItemDependency; */ -const RequireEnsureItemDependency = __webpack_require__(5511); -const RequireEnsureDependency = __webpack_require__(75830); - -const NullFactory = __webpack_require__(40438); - -const RequireEnsureDependenciesBlockParserPlugin = __webpack_require__(24620); - -const ParserHelpers = __webpack_require__(23999); - -class RequireEnsurePlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "RequireEnsurePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - RequireEnsureItemDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - RequireEnsureItemDependency, - new RequireEnsureItemDependency.Template() - ); - - compilation.dependencyFactories.set( - RequireEnsureDependency, - new NullFactory() - ); - compilation.dependencyTemplates.set( - RequireEnsureDependency, - new RequireEnsureDependency.Template() - ); - - const handler = (parser, parserOptions) => { - if ( - parserOptions.requireEnsure !== undefined && - !parserOptions.requireEnsure - ) - return; - - new RequireEnsureDependenciesBlockParserPlugin().apply(parser); - parser.hooks.evaluateTypeof - .for("require.ensure") - .tap( - "RequireEnsurePlugin", - ParserHelpers.evaluateToString("function") - ); - parser.hooks.typeof - .for("require.ensure") - .tap( - "RequireEnsurePlugin", - ParserHelpers.toConstantDependency( - parser, - JSON.stringify("function") - ) - ); - }; +const Watchpack = __webpack_require__(77056); +const objectToMap = __webpack_require__(1111); - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireEnsurePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireEnsurePlugin", handler); - } - ); +class NodeWatchFileSystem { + constructor(inputFileSystem) { + this.inputFileSystem = inputFileSystem; + this.watcherOptions = { + aggregateTimeout: 0 + }; + this.watcher = new Watchpack(this.watcherOptions); } -} -module.exports = RequireEnsurePlugin; - - -/***/ }), -/***/ 22928: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { + if (!Array.isArray(files)) { + throw new Error("Invalid arguments: 'files'"); + } + if (!Array.isArray(dirs)) { + throw new Error("Invalid arguments: 'dirs'"); + } + if (!Array.isArray(missing)) { + throw new Error("Invalid arguments: 'missing'"); + } + if (typeof callback !== "function") { + throw new Error("Invalid arguments: 'callback'"); + } + if (typeof startTime !== "number" && startTime) { + throw new Error("Invalid arguments: 'startTime'"); + } + if (typeof options !== "object") { + throw new Error("Invalid arguments: 'options'"); + } + if (typeof callbackUndelayed !== "function" && callbackUndelayed) { + throw new Error("Invalid arguments: 'callbackUndelayed'"); + } + const oldWatcher = this.watcher; + this.watcher = new Watchpack(options); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (callbackUndelayed) { + this.watcher.once("change", callbackUndelayed); + } + const cachedFiles = files; + const cachedDirs = dirs; + this.watcher.once("aggregated", (changes, removals) => { + changes = changes.concat(removals); + if (this.inputFileSystem && this.inputFileSystem.purge) { + this.inputFileSystem.purge(changes); + } + const times = objectToMap(this.watcher.getTimes()); + files = new Set(files); + dirs = new Set(dirs); + missing = new Set(missing); + removals = new Set(removals.filter(file => files.has(file))); + callback( + null, + changes.filter(file => files.has(file)).sort(), + changes.filter(file => dirs.has(file)).sort(), + changes.filter(file => missing.has(file)).sort(), + times, + times, + removals + ); + }); -const NullDependency = __webpack_require__(5088); + this.watcher.watch( + cachedFiles.concat(missing), + cachedDirs.concat(missing), + startTime + ); -class RequireHeaderDependency extends NullDependency { - constructor(range) { - super(); - if (!Array.isArray(range)) throw new Error("range must be valid"); - this.range = range; + if (oldWatcher) { + oldWatcher.close(); + } + return { + close: () => { + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + }, + pause: () => { + if (this.watcher) { + this.watcher.pause(); + } + }, + getFileTimestamps: () => { + if (this.watcher) { + return objectToMap(this.watcher.getTimes()); + } else { + return new Map(); + } + }, + getContextTimestamps: () => { + if (this.watcher) { + return objectToMap(this.watcher.getTimes()); + } else { + return new Map(); + } + } + }; } } -RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate { - apply(dep, source) { - source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__"); - } - - applyAsTemplateArgument(name, dep, source) { - source.replace(dep.range[0], dep.range[1] - 1, "require"); - } -}; - -module.exports = RequireHeaderDependency; +module.exports = NodeWatchFileSystem; /***/ }), -/***/ 58045: +/***/ 73839: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103155,75 +101569,66 @@ module.exports = RequireHeaderDependency; */ -const DependencyReference = __webpack_require__(71722); -const ModuleDependency = __webpack_require__(90865); const Template = __webpack_require__(96066); +const WasmMainTemplatePlugin = __webpack_require__(65331); -class RequireIncludeDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; - } - - getReference() { - if (!this.module) return null; - // This doesn't use any export - return new DependencyReference(this.module, [], false); +class ReadFileCompileWasmTemplatePlugin { + constructor(options) { + this.options = options || {}; } - get type() { - return "require.include"; - } -} + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "ReadFileCompileWasmTemplatePlugin", + compilation => { + const generateLoadBinaryCode = path => + Template.asString([ + "new Promise(function (resolve, reject) {", + Template.indent([ + "var { readFile } = require('fs');", + "var { join } = require('path');", + "", + "try {", + Template.indent([ + `readFile(join(__dirname, ${path}), function(err, buffer){`, + Template.indent([ + "if (err) return reject(err);", + "", + "// Fake fetch response", + "resolve({", + Template.indent([ + "arrayBuffer() { return Promise.resolve(buffer); }" + ]), + "});" + ]), + "});" + ]), + "} catch (err) { reject(err); }" + ]), + "})" + ]); -RequireIncludeDependency.Template = class RequireIncludeDependencyTemplate { - apply(dep, source, runtime) { - const comment = runtime.outputOptions.pathinfo - ? Template.toComment( - `require.include ${runtime.requestShortener.shorten(dep.request)}` - ) - : ""; - source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); + const plugin = new WasmMainTemplatePlugin( + Object.assign( + { + generateLoadBinaryCode, + supportsStreaming: false + }, + this.options + ) + ); + plugin.apply(compilation.mainTemplate); + } + ); } -}; - -module.exports = RequireIncludeDependency; - - -/***/ }), - -/***/ 36330: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const RequireIncludeDependency = __webpack_require__(58045); +} -module.exports = class RequireIncludeDependencyParserPlugin { - apply(parser) { - parser.hooks.call - .for("require.include") - .tap("RequireIncludeDependencyParserPlugin", expr => { - if (expr.arguments.length !== 1) return; - const param = parser.evaluateExpression(expr.arguments[0]); - if (!param.isString()) return; - const dep = new RequireIncludeDependency(param.string, expr.range); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return true; - }); - } -}; +module.exports = ReadFileCompileWasmTemplatePlugin; /***/ }), -/***/ 16522: +/***/ 7886: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103233,98 +101638,141 @@ module.exports = class RequireIncludeDependencyParserPlugin { */ -const RequireIncludeDependency = __webpack_require__(58045); -const RequireIncludeDependencyParserPlugin = __webpack_require__(36330); - -const ParserHelpers = __webpack_require__(23999); -class RequireIncludePlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "RequireIncludePlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - RequireIncludeDependency, - normalModuleFactory - ); - compilation.dependencyTemplates.set( - RequireIncludeDependency, - new RequireIncludeDependency.Template() - ); +const truncateArgs = __webpack_require__(62299); +const util = __webpack_require__(31669); - const handler = (parser, parserOptions) => { - if ( - parserOptions.requireInclude !== undefined && - !parserOptions.requireInclude - ) - return; +const tty = process.stderr.isTTY && process.env.TERM !== "dumb"; - new RequireIncludeDependencyParserPlugin().apply(parser); - parser.hooks.evaluateTypeof - .for("require.include") - .tap( - "RequireIncludePlugin", - ParserHelpers.evaluateToString("function") - ); - parser.hooks.typeof - .for("require.include") - .tap( - "RequireIncludePlugin", - ParserHelpers.toConstantDependency( - parser, - JSON.stringify("function") - ) - ); - }; +let currentStatusMessage = undefined; +let hasStatusMessage = false; +let currentIndent = ""; +let currentCollapsed = 0; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("RequireIncludePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("RequireIncludePlugin", handler); - } +const indent = (str, prefix, colorPrefix, colorSuffix) => { + if (str === "") return str; + prefix = currentIndent + prefix; + if (tty) { + return ( + prefix + + colorPrefix + + str.replace(/\n/g, colorSuffix + "\n" + prefix + colorPrefix) + + colorSuffix ); + } else { + return prefix + str.replace(/\n/g, "\n" + prefix); } -} -module.exports = RequireIncludePlugin; - - -/***/ }), - -/***/ 83309: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +const clearStatusMessage = () => { + if (hasStatusMessage) { + process.stderr.write("\x1b[2K\r"); + hasStatusMessage = false; + } +}; -const ContextDependency = __webpack_require__(11583); -const ContextDependencyTemplateAsId = __webpack_require__(6174); +const writeStatusMessage = () => { + if (!currentStatusMessage) return; + const l = process.stderr.columns; + const args = l + ? truncateArgs(currentStatusMessage, l - 1) + : currentStatusMessage; + const str = args.join(" "); + const coloredStr = `\u001b[1m${str}\u001b[39m\u001b[22m`; + process.stderr.write(`\x1b[2K\r${coloredStr}`); + hasStatusMessage = true; +}; -class RequireResolveContextDependency extends ContextDependency { - constructor(options, range, valueRange) { - super(options); - this.range = range; - this.valueRange = valueRange; - } +const writeColored = (prefix, colorPrefix, colorSuffix) => { + return (...args) => { + if (currentCollapsed > 0) return; + clearStatusMessage(); + // @ts-ignore + const str = indent(util.format(...args), prefix, colorPrefix, colorSuffix); + process.stderr.write(str + "\n"); + writeStatusMessage(); + }; +}; - get type() { - return "amd require context"; - } -} +const writeGroupMessage = writeColored( + "<-> ", + "\u001b[1m\u001b[36m", + "\u001b[39m\u001b[22m" +); -RequireResolveContextDependency.Template = ContextDependencyTemplateAsId; +const writeGroupCollapsedMessage = writeColored( + "<+> ", + "\u001b[1m\u001b[36m", + "\u001b[39m\u001b[22m" +); -module.exports = RequireResolveContextDependency; +module.exports = { + log: writeColored(" ", "\u001b[1m", "\u001b[22m"), + debug: writeColored(" ", "", ""), + trace: writeColored(" ", "", ""), + info: writeColored(" ", "\u001b[1m\u001b[32m", "\u001b[39m\u001b[22m"), + warn: writeColored(" ", "\u001b[1m\u001b[33m", "\u001b[39m\u001b[22m"), + error: writeColored(" ", "\u001b[1m\u001b[31m", "\u001b[39m\u001b[22m"), + logTime: writeColored(" ", "\u001b[1m\u001b[35m", "\u001b[39m\u001b[22m"), + group: (...args) => { + writeGroupMessage(...args); + if (currentCollapsed > 0) { + currentCollapsed++; + } else { + currentIndent += " "; + } + }, + groupCollapsed: (...args) => { + writeGroupCollapsedMessage(...args); + currentCollapsed++; + }, + groupEnd: () => { + if (currentCollapsed > 0) currentCollapsed--; + else if (currentIndent.length >= 2) + currentIndent = currentIndent.slice(0, currentIndent.length - 2); + }, + // eslint-disable-next-line node/no-unsupported-features/node-builtins + profile: console.profile && (name => console.profile(name)), + // eslint-disable-next-line node/no-unsupported-features/node-builtins + profileEnd: console.profileEnd && (name => console.profileEnd(name)), + clear: + tty && + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.clear && + (() => { + clearStatusMessage(); + // eslint-disable-next-line node/no-unsupported-features/node-builtins + console.clear(); + writeStatusMessage(); + }), + status: tty + ? (name, ...args) => { + args = args.filter(Boolean); + if (name === undefined && args.length === 0) { + clearStatusMessage(); + currentStatusMessage = undefined; + } else if ( + typeof name === "string" && + name.startsWith("[webpack.Progress] ") + ) { + currentStatusMessage = [name.slice(19), ...args]; + writeStatusMessage(); + } else if (name === "[webpack.Progress]") { + currentStatusMessage = [...args]; + writeStatusMessage(); + } else { + currentStatusMessage = [name, ...args]; + writeStatusMessage(); + } + } + : writeColored(" ", "", "") +}; /***/ }), -/***/ 43519: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 88197: +/***/ (function(module) { "use strict"; /* @@ -103332,122 +101780,93 @@ module.exports = RequireResolveContextDependency; Author Tobias Koppers @sokra */ -const ModuleDependency = __webpack_require__(90865); -const ModuleDependencyAsId = __webpack_require__(63708); - -class RequireResolveDependency extends ModuleDependency { - constructor(request, range) { - super(request); - this.range = range; - } - get type() { - return "require.resolve"; +class AggressiveMergingPlugin { + constructor(options) { + if ( + (options !== undefined && typeof options !== "object") || + Array.isArray(options) + ) { + throw new Error( + "Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.js.org/plugins/" + ); + } + this.options = options || {}; } -} -RequireResolveDependency.Template = ModuleDependencyAsId; - -module.exports = RequireResolveDependency; - - -/***/ }), - -/***/ 68349: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + apply(compiler) { + const options = this.options; + const minSizeReduce = options.minSizeReduce || 1.5; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + compiler.hooks.thisCompilation.tap( + "AggressiveMergingPlugin", + compilation => { + compilation.hooks.optimizeChunksAdvanced.tap( + "AggressiveMergingPlugin", + chunks => { + let combinations = []; + chunks.forEach((a, idx) => { + if (a.canBeInitial()) return; + for (let i = 0; i < idx; i++) { + const b = chunks[i]; + if (b.canBeInitial()) continue; + combinations.push({ + a, + b, + improvement: undefined + }); + } + }); + for (const pair of combinations) { + const a = pair.b.size({ + chunkOverhead: 0 + }); + const b = pair.a.size({ + chunkOverhead: 0 + }); + const ab = pair.b.integratedSize(pair.a, { + chunkOverhead: 0 + }); + let newSize; + if (ab === false) { + pair.improvement = false; + return; + } else { + newSize = ab; + } -const RequireResolveDependency = __webpack_require__(43519); -const RequireResolveContextDependency = __webpack_require__(83309); -const RequireResolveHeaderDependency = __webpack_require__(69647); -const ContextDependencyHelpers = __webpack_require__(5594); + pair.improvement = (a + b) / newSize; + } + combinations = combinations.filter(pair => { + return pair.improvement !== false; + }); + combinations.sort((a, b) => { + return b.improvement - a.improvement; + }); -class RequireResolveDependencyParserPlugin { - constructor(options) { - this.options = options; - } + const pair = combinations[0]; - apply(parser) { - const options = this.options; + if (!pair) return; + if (pair.improvement < minSizeReduce) return; - const process = (expr, weak) => { - if (expr.arguments.length !== 1) return; - const param = parser.evaluateExpression(expr.arguments[0]); - if (param.isConditional()) { - for (const option of param.options) { - const result = processItem(expr, option, weak); - if (result === undefined) { - processContext(expr, option, weak); + if (pair.b.integrate(pair.a, "aggressive-merge")) { + chunks.splice(chunks.indexOf(pair.a), 1); + return true; + } } - } - const dep = new RequireResolveHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return true; - } else { - const result = processItem(expr, param, weak); - if (result === undefined) { - processContext(expr, param, weak); - } - const dep = new RequireResolveHeaderDependency(expr.callee.range); - dep.loc = expr.loc; - parser.state.current.addDependency(dep); - return true; - } - }; - const processItem = (expr, param, weak) => { - if (param.isString()) { - const dep = new RequireResolveDependency(param.string, param.range); - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - dep.weak = weak; - parser.state.current.addDependency(dep); - return true; + ); } - }; - const processContext = (expr, param, weak) => { - const dep = ContextDependencyHelpers.create( - RequireResolveContextDependency, - param.range, - param, - expr, - options, - { - mode: weak ? "weak" : "sync" - }, - parser - ); - if (!dep) return; - dep.loc = expr.loc; - dep.optional = !!parser.scope.inTry; - parser.state.current.addDependency(dep); - return true; - }; - - parser.hooks.call - .for("require.resolve") - .tap("RequireResolveDependencyParserPlugin", expr => { - return process(expr, false); - }); - parser.hooks.call - .for("require.resolveWeak") - .tap("RequireResolveDependencyParserPlugin", expr => { - return process(expr, true); - }); + ); } } -module.exports = RequireResolveDependencyParserPlugin; + +module.exports = AggressiveMergingPlugin; /***/ }), -/***/ 69647: +/***/ 26688: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103456,227 +101875,301 @@ module.exports = RequireResolveDependencyParserPlugin; Author Tobias Koppers @sokra */ -const NullDependency = __webpack_require__(5088); -class RequireResolveHeaderDependency extends NullDependency { - constructor(range) { - super(); - if (!Array.isArray(range)) throw new Error("range must be valid"); - this.range = range; - } -} +const identifierUtils = __webpack_require__(94658); +const { intersect } = __webpack_require__(54262); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(71884); -RequireResolveHeaderDependency.Template = class RequireResolveHeaderDependencyTemplate { - apply(dep, source) { - source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); - } +/** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */ - applyAsTemplateArgument(name, dep, source) { - source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); - } +const moveModuleBetween = (oldChunk, newChunk) => { + return module => { + oldChunk.moveModule(module, newChunk); + }; }; -module.exports = RequireResolveHeaderDependency; - - -/***/ }), - -/***/ 84828: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const ModuleDependency = __webpack_require__(90865); +const isNotAEntryModule = entryModule => { + return module => { + return entryModule !== module; + }; +}; -class SingleEntryDependency extends ModuleDependency { +class AggressiveSplittingPlugin { /** - * @param {string} request request path for entry + * @param {AggressiveSplittingPluginOptions=} options options object */ - constructor(request) { - super(request); - } - - get type() { - return "single entry"; - } -} - -module.exports = SingleEntryDependency; + constructor(options) { + if (!options) options = {}; + validateOptions(schema, options, "Aggressive Splitting Plugin"); -/***/ }), - -/***/ 68166: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const ParserHelpers = __webpack_require__(23999); -const WebpackError = __webpack_require__(97391); - -class SystemPlugin { - constructor(options) { this.options = options; + if (typeof this.options.minSize !== "number") { + this.options.minSize = 30 * 1024; + } + if (typeof this.options.maxSize !== "number") { + this.options.maxSize = 50 * 1024; + } + if (typeof this.options.chunkOverhead !== "number") { + this.options.chunkOverhead = 0; + } + if (typeof this.options.entryChunkMultiplicator !== "number") { + this.options.entryChunkMultiplicator = 1; + } } - apply(compiler) { - compiler.hooks.compilation.tap( - "SystemPlugin", - (compilation, { normalModuleFactory }) => { - const handler = (parser, parserOptions) => { - if (parserOptions.system !== undefined && !parserOptions.system) - return; - - const shouldWarn = parserOptions.system === undefined; - - const setNotSupported = name => { - parser.hooks.evaluateTypeof - .for(name) - .tap("SystemPlugin", ParserHelpers.evaluateToString("undefined")); - parser.hooks.expression - .for(name) - .tap( - "SystemPlugin", - ParserHelpers.expressionIsUnsupported( - parser, - name + " is not supported by webpack." - ) + compiler.hooks.thisCompilation.tap( + "AggressiveSplittingPlugin", + compilation => { + let needAdditionalSeal = false; + let newSplits; + let fromAggressiveSplittingSet; + let chunkSplitDataMap; + compilation.hooks.optimize.tap("AggressiveSplittingPlugin", () => { + newSplits = []; + fromAggressiveSplittingSet = new Set(); + chunkSplitDataMap = new Map(); + }); + compilation.hooks.optimizeChunksAdvanced.tap( + "AggressiveSplittingPlugin", + chunks => { + // Precompute stuff + const nameToModuleMap = new Map(); + const moduleToNameMap = new Map(); + for (const m of compilation.modules) { + const name = identifierUtils.makePathsRelative( + compiler.context, + m.identifier(), + compilation.cache ); - }; + nameToModuleMap.set(name, m); + moduleToNameMap.set(m, name); + } - parser.hooks.typeof - .for("System.import") - .tap( - "SystemPlugin", - ParserHelpers.toConstantDependency( - parser, - JSON.stringify("function") - ) - ); - parser.hooks.evaluateTypeof - .for("System.import") - .tap("SystemPlugin", ParserHelpers.evaluateToString("function")); - parser.hooks.typeof - .for("System") - .tap( - "SystemPlugin", - ParserHelpers.toConstantDependency( - parser, - JSON.stringify("object") - ) - ); - parser.hooks.evaluateTypeof - .for("System") - .tap("SystemPlugin", ParserHelpers.evaluateToString("object")); + // Check used chunk ids + const usedIds = new Set(); + for (const chunk of chunks) { + usedIds.add(chunk.id); + } - setNotSupported("System.set"); - setNotSupported("System.get"); - setNotSupported("System.register"); + const recordedSplits = + (compilation.records && compilation.records.aggressiveSplits) || + []; + const usedSplits = newSplits + ? recordedSplits.concat(newSplits) + : recordedSplits; - parser.hooks.expression.for("System").tap("SystemPlugin", () => { - const systemPolyfillRequire = ParserHelpers.requireFileAsExpression( - parser.state.module.context, - __webpack_require__.ab + "system.js" - ); - return ParserHelpers.addParsedVariableToModule( - parser, - "System", - systemPolyfillRequire - ); - }); + const minSize = this.options.minSize; + const maxSize = this.options.maxSize; - parser.hooks.call.for("System.import").tap("SystemPlugin", expr => { - if (shouldWarn) { - parser.state.module.warnings.push( - new SystemImportDeprecationWarning( - parser.state.module, - expr.loc - ) + const applySplit = splitData => { + // Cannot split if id is already taken + if (splitData.id !== undefined && usedIds.has(splitData.id)) { + return false; + } + + // Get module objects from names + const selectedModules = splitData.modules.map(name => + nameToModuleMap.get(name) ); - } - return parser.hooks.importCall.call(expr); - }); - }; + // Does the modules exist at all? + if (!selectedModules.every(Boolean)) return false; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("SystemPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("SystemPlugin", handler); - } - ); - } -} + // Check if size matches (faster than waiting for hash) + const size = selectedModules.reduce( + (sum, m) => sum + m.size(), + 0 + ); + if (size !== splitData.size) return false; -class SystemImportDeprecationWarning extends WebpackError { - constructor(module, loc) { - super( - "System.import() is deprecated and will be removed soon. Use import() instead.\n" + - "For more info visit https://webpack.js.org/guides/code-splitting/" - ); + // get chunks with all modules + const selectedChunks = intersect( + selectedModules.map(m => new Set(m.chunksIterable)) + ); - this.name = "SystemImportDeprecationWarning"; + // No relevant chunks found + if (selectedChunks.size === 0) return false; - this.module = module; - this.loc = loc; + // The found chunk is already the split or similar + if ( + selectedChunks.size === 1 && + Array.from(selectedChunks)[0].getNumberOfModules() === + selectedModules.length + ) { + const chunk = Array.from(selectedChunks)[0]; + if (fromAggressiveSplittingSet.has(chunk)) return false; + fromAggressiveSplittingSet.add(chunk); + chunkSplitDataMap.set(chunk, splitData); + return true; + } - Error.captureStackTrace(this, this.constructor); - } -} + // split the chunk into two parts + const newChunk = compilation.addChunk(); + newChunk.chunkReason = "aggressive splitted"; + for (const chunk of selectedChunks) { + selectedModules.forEach(moveModuleBetween(chunk, newChunk)); + chunk.split(newChunk); + chunk.name = null; + } + fromAggressiveSplittingSet.add(newChunk); + chunkSplitDataMap.set(newChunk, splitData); -module.exports = SystemPlugin; + if (splitData.id !== null && splitData.id !== undefined) { + newChunk.id = splitData.id; + } + return true; + }; + // try to restore to recorded splitting + let changed = false; + for (let j = 0; j < usedSplits.length; j++) { + const splitData = usedSplits[j]; + if (applySplit(splitData)) changed = true; + } -/***/ }), + // for any chunk which isn't splitted yet, split it and create a new entry + // start with the biggest chunk + const sortedChunks = chunks.slice().sort((a, b) => { + const diff1 = b.modulesSize() - a.modulesSize(); + if (diff1) return diff1; + const diff2 = a.getNumberOfModules() - b.getNumberOfModules(); + if (diff2) return diff2; + const modulesA = Array.from(a.modulesIterable); + const modulesB = Array.from(b.modulesIterable); + modulesA.sort(); + modulesB.sort(); + const aI = modulesA[Symbol.iterator](); + const bI = modulesB[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = aI.next(); + const bItem = bI.next(); + if (aItem.done) return 0; + const aModuleIdentifier = aItem.value.identifier(); + const bModuleIdentifier = bItem.value.identifier(); + if (aModuleIdentifier > bModuleIdentifier) return -1; + if (aModuleIdentifier < bModuleIdentifier) return 1; + } + }); + for (const chunk of sortedChunks) { + if (fromAggressiveSplittingSet.has(chunk)) continue; + const size = chunk.modulesSize(); + if (size > maxSize && chunk.getNumberOfModules() > 1) { + const modules = chunk + .getModules() + .filter(isNotAEntryModule(chunk.entryModule)) + .sort((a, b) => { + a = a.identifier(); + b = b.identifier(); + if (a > b) return 1; + if (a < b) return -1; + return 0; + }); + const selectedModules = []; + let selectedModulesSize = 0; + for (let k = 0; k < modules.length; k++) { + const module = modules[k]; + const newSize = selectedModulesSize + module.size(); + if (newSize > maxSize && selectedModulesSize >= minSize) { + break; + } + selectedModulesSize = newSize; + selectedModules.push(module); + } + if (selectedModules.length === 0) continue; + const splitData = { + modules: selectedModules + .map(m => moduleToNameMap.get(m)) + .sort(), + size: selectedModulesSize + }; -/***/ 15826: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (applySplit(splitData)) { + newSplits = (newSplits || []).concat(splitData); + changed = true; + } + } + } + if (changed) return true; + } + ); + compilation.hooks.recordHash.tap( + "AggressiveSplittingPlugin", + records => { + // 4. save made splittings to records + const allSplits = new Set(); + const invalidSplits = new Set(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // Check if some splittings are invalid + // We remove invalid splittings and try again + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if (splitData !== undefined) { + if (splitData.hash && chunk.hash !== splitData.hash) { + // Split was successful, but hash doesn't equal + // We can throw away the split since it's useless now + invalidSplits.add(splitData); + } + } + } -const NullDependency = __webpack_require__(5088); -const webpackMissingModule = __webpack_require__(75386).module; + if (invalidSplits.size > 0) { + records.aggressiveSplits = records.aggressiveSplits.filter( + splitData => !invalidSplits.has(splitData) + ); + needAdditionalSeal = true; + } else { + // set hash and id values on all (new) splittings + for (const chunk of compilation.chunks) { + const splitData = chunkSplitDataMap.get(chunk); + if (splitData !== undefined) { + splitData.hash = chunk.hash; + splitData.id = chunk.id; + allSplits.add(splitData); + // set flag for stats + chunk.recorded = true; + } + } -class UnsupportedDependency extends NullDependency { - constructor(request, range) { - super(); - this.request = request; - this.range = range; - } -} + // Also add all unused historial splits (after the used ones) + // They can still be used in some future compilation + const recordedSplits = + compilation.records && compilation.records.aggressiveSplits; + if (recordedSplits) { + for (const splitData of recordedSplits) { + if (!invalidSplits.has(splitData)) allSplits.add(splitData); + } + } -UnsupportedDependency.Template = class UnsupportedDependencyTemplate { - apply(dep, source, runtime) { - source.replace( - dep.range[0], - dep.range[1], - webpackMissingModule(dep.request) + // record all splits + records.aggressiveSplits = Array.from(allSplits); + + needAdditionalSeal = false; + } + } + ); + compilation.hooks.needAdditionalSeal.tap( + "AggressiveSplittingPlugin", + () => { + if (needAdditionalSeal) { + needAdditionalSeal = false; + return true; + } + } + ); + } ); } -}; - -module.exports = UnsupportedDependency; +} +module.exports = AggressiveSplittingPlugin; /***/ }), -/***/ 18925: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 30346: +/***/ (function(module) { "use strict"; /* @@ -103685,36 +102178,71 @@ module.exports = UnsupportedDependency; */ -const DependencyReference = __webpack_require__(71722); -const ModuleDependency = __webpack_require__(90865); +const sortByIndex = (a, b) => { + return a.index - b.index; +}; -class WebAssemblyExportImportedDependency extends ModuleDependency { - constructor(exportName, request, name, valueType) { - super(request); - /** @type {string} */ - this.exportName = exportName; - /** @type {string} */ - this.name = name; - /** @type {string} */ - this.valueType = valueType; - } +const sortByIndex2 = (a, b) => { + return a.index2 - b.index2; +}; - getReference() { - if (!this.module) return null; - return new DependencyReference(this.module, [this.name], false); +class ChunkModuleIdRangePlugin { + constructor(options) { + this.options = options; } - get type() { - return "wasm export import"; + apply(compiler) { + const options = this.options; + compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => { + compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => { + const chunk = compilation.chunks.find( + chunk => chunk.name === options.name + ); + if (!chunk) { + throw new Error( + `ChunkModuleIdRangePlugin: Chunk with name '${options.name}"' was not found` + ); + } + + let chunkModules; + if (options.order) { + chunkModules = Array.from(chunk.modulesIterable); + switch (options.order) { + case "index": + chunkModules.sort(sortByIndex); + break; + case "index2": + chunkModules.sort(sortByIndex2); + break; + default: + throw new Error( + "ChunkModuleIdRangePlugin: unexpected value of order" + ); + } + } else { + chunkModules = modules.filter(m => { + return m.chunksIterable.has(chunk); + }); + } + + let currentId = options.start || 0; + for (let i = 0; i < chunkModules.length; i++) { + const m = chunkModules[i]; + if (m.id === null) { + m.id = currentId++; + } + if (options.end && currentId > options.end) break; + } + }); + }); } } - -module.exports = WebAssemblyExportImportedDependency; +module.exports = ChunkModuleIdRangePlugin; /***/ }), -/***/ 52959: +/***/ 16953: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -103724,758 +102252,1482 @@ module.exports = WebAssemblyExportImportedDependency; */ +const Module = __webpack_require__(75993); +const Template = __webpack_require__(96066); +const Parser = __webpack_require__(70558); +const eslintScope = __webpack_require__(41632); +const { ConcatSource, ReplaceSource } = __webpack_require__(53665); const DependencyReference = __webpack_require__(71722); -const ModuleDependency = __webpack_require__(90865); -const UnsupportedWebAssemblyFeatureError = __webpack_require__(43101); +const HarmonyImportDependency = __webpack_require__(81599); +const HarmonyImportSideEffectDependency = __webpack_require__(79171); +const HarmonyImportSpecifierDependency = __webpack_require__(95966); +const HarmonyExportSpecifierDependency = __webpack_require__(34834); +const HarmonyExportExpressionDependency = __webpack_require__(84245); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); +const HarmonyCompatibilityDependency = __webpack_require__(1533); +const createHash = __webpack_require__(15660); -/** @typedef {import("@webassemblyjs/ast").ModuleImportDescription} ModuleImportDescription */ +/** @typedef {import("../Dependency")} Dependency */ +/** @typedef {import("../Compilation")} Compilation */ +/** @typedef {import("../util/createHash").Hash} Hash */ +/** @typedef {import("../RequestShortener")} RequestShortener */ -class WebAssemblyImportDependency extends ModuleDependency { - /** - * @param {string} request the request - * @param {string} name the imported name - * @param {ModuleImportDescription} description the WASM ast node - * @param {false | string} onlyDirectImport if only direct imports are allowed - */ - constructor(request, name, description, onlyDirectImport) { - super(request); - /** @type {string} */ - this.name = name; - /** @type {ModuleImportDescription} */ - this.description = description; - /** @type {false | string} */ - this.onlyDirectImport = onlyDirectImport; +const joinIterableWithComma = iterable => { + // This is more performant than Array.from().join(", ") + // as it doesn't create an array + let str = ""; + let first = true; + for (const item of iterable) { + if (first) { + first = false; + } else { + str += ", "; + } + str += item; } + return str; +}; - getReference() { - if (!this.module) return null; - return new DependencyReference(this.module, [this.name], false); - } +/** + * @typedef {Object} ConcatenationEntry + * @property {"concatenated" | "external"} type + * @property {Module} module + */ - getErrors() { - if ( - this.onlyDirectImport && - this.module && - !this.module.type.startsWith("webassembly") - ) { - return [ - new UnsupportedWebAssemblyFeatureError( - `Import "${this.name}" from "${this.request}" with ${this.onlyDirectImport} can only be used for direct wasm to wasm dependencies` - ) - ]; +const ensureNsObjSource = ( + info, + moduleToInfoMap, + requestShortener, + strictHarmonyModule +) => { + if (!info.hasNamespaceObject) { + info.hasNamespaceObject = true; + const name = info.exportMap.get(true); + const nsObj = [`var ${name} = {};`, `__webpack_require__.r(${name});`]; + for (const exportName of info.module.buildMeta.providedExports) { + const finalName = getFinalName( + info, + exportName, + moduleToInfoMap, + requestShortener, + false, + strictHarmonyModule + ); + nsObj.push( + `__webpack_require__.d(${name}, ${JSON.stringify( + exportName + )}, function() { return ${finalName}; });` + ); } + info.namespaceObjectSource = nsObj.join("\n") + "\n"; } - - get type() { - return "wasm import"; - } -} - -module.exports = WebAssemblyImportDependency; - - -/***/ }), - -/***/ 75386: -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const toErrorCode = err => - `var e = new Error(${JSON.stringify(err)}); e.code = 'MODULE_NOT_FOUND';`; - -exports.module = request => - `!(function webpackMissingModule() { ${exports.moduleCode(request)} }())`; - -exports.promise = request => { - const errorCode = toErrorCode(`Cannot find module '${request}'`); - return `Promise.reject(function webpackMissingModule() { ${errorCode} return e; }())`; }; -exports.moduleCode = request => { - const errorCode = toErrorCode(`Cannot find module '${request}'`); - return `${errorCode} throw e;`; +const getExternalImport = ( + importedModule, + info, + exportName, + asCall, + strictHarmonyModule +) => { + const used = importedModule.isUsed(exportName); + if (!used) return "/* unused reexport */undefined"; + const comment = + used !== exportName ? ` ${Template.toNormalComment(exportName)}` : ""; + switch (importedModule.buildMeta.exportsType) { + case "named": + if (exportName === "default") { + return info.name; + } else if (exportName === true) { + info.interopNamespaceObjectUsed = true; + return info.interopNamespaceObjectName; + } else { + break; + } + case "namespace": + if (exportName === true) { + return info.name; + } else { + break; + } + default: + if (strictHarmonyModule) { + if (exportName === "default") { + return info.name; + } else if (exportName === true) { + info.interopNamespaceObjectUsed = true; + return info.interopNamespaceObjectName; + } else { + return "/* non-default import from non-esm module */undefined"; + } + } else { + if (exportName === "default") { + info.interopDefaultAccessUsed = true; + return asCall + ? `${info.interopDefaultAccessName}()` + : `${info.interopDefaultAccessName}.a`; + } else if (exportName === true) { + return info.name; + } else { + break; + } + } + } + const reference = `${info.name}[${JSON.stringify(used)}${comment}]`; + if (asCall) return `Object(${reference})`; + return reference; }; - -/***/ }), - -/***/ 64197: -/***/ (function(module) { - -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -module.exports = expr => { - // - if ( - expr.type === "FunctionExpression" || - expr.type === "ArrowFunctionExpression" - ) { - return { - fn: expr, - expressions: [], - needThis: false - }; +const getFinalName = ( + info, + exportName, + moduleToInfoMap, + requestShortener, + asCall, + strictHarmonyModule, + alreadyVisited = new Set() +) => { + switch (info.type) { + case "concatenated": { + const directExport = info.exportMap.get(exportName); + if (directExport) { + if (exportName === true) { + ensureNsObjSource( + info, + moduleToInfoMap, + requestShortener, + strictHarmonyModule + ); + } else if (!info.module.isUsed(exportName)) { + return "/* unused export */ undefined"; + } + if (info.globalExports.has(directExport)) { + return directExport; + } + const name = info.internalNames.get(directExport); + if (!name) { + throw new Error( + `The export "${directExport}" in "${info.module.readableIdentifier( + requestShortener + )}" has no internal name` + ); + } + return name; + } + const reexport = info.reexportMap.get(exportName); + if (reexport) { + if (alreadyVisited.has(reexport)) { + throw new Error( + `Circular reexports ${Array.from( + alreadyVisited, + e => + `"${e.module.readableIdentifier(requestShortener)}".${ + e.exportName + }` + ).join( + " --> " + )} -(circular)-> "${reexport.module.readableIdentifier( + requestShortener + )}".${reexport.exportName}` + ); + } + alreadyVisited.add(reexport); + const refInfo = moduleToInfoMap.get(reexport.module); + if (refInfo) { + // module is in the concatenation + return getFinalName( + refInfo, + reexport.exportName, + moduleToInfoMap, + requestShortener, + asCall, + strictHarmonyModule, + alreadyVisited + ); + } + } + const problem = + `Cannot get final name for export "${exportName}" in "${info.module.readableIdentifier( + requestShortener + )}"` + + ` (known exports: ${Array.from(info.exportMap.keys()) + .filter(name => name !== true) + .join(" ")}, ` + + `known reexports: ${Array.from(info.reexportMap.keys()).join(" ")})`; + return `${Template.toNormalComment(problem)} undefined`; + } + case "external": { + const importedModule = info.module; + return getExternalImport( + importedModule, + info, + exportName, + asCall, + strictHarmonyModule + ); + } } +}; - // .bind() - if ( - expr.type === "CallExpression" && - expr.callee.type === "MemberExpression" && - expr.callee.object.type === "FunctionExpression" && - expr.callee.property.type === "Identifier" && - expr.callee.property.name === "bind" && - expr.arguments.length === 1 - ) { - return { - fn: expr.callee.object, - expressions: [expr.arguments[0]], - needThis: undefined - }; - } - // (function(_this) {return })(this) (Coffeescript) - if ( - expr.type === "CallExpression" && - expr.callee.type === "FunctionExpression" && - expr.callee.body.type === "BlockStatement" && - expr.arguments.length === 1 && - expr.arguments[0].type === "ThisExpression" && - expr.callee.body.body && - expr.callee.body.body.length === 1 && - expr.callee.body.body[0].type === "ReturnStatement" && - expr.callee.body.body[0].argument && - expr.callee.body.body[0].argument.type === "FunctionExpression" - ) { - return { - fn: expr.callee.body.body[0].argument, - expressions: [], - needThis: true - }; +const addScopeSymbols1 = (s, nameSet, scopeSet) => { + let scope = s; + while (scope) { + if (scopeSet.has(scope)) break; + scopeSet.add(scope); + for (const variable of scope.variables) { + nameSet.add(variable.name); + } + scope = scope.upper; } }; - -/***/ }), - -/***/ 49: -/***/ (function(module) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - - -/** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */ -/** @typedef {import("./Dependency").SourcePosition} SourcePosition */ - -// TODO webpack 5: pos must be SourcePosition -/** - * @param {SourcePosition|DependencyLocation|string} pos position - * @returns {string} formatted position - */ -const formatPosition = pos => { - if (pos === null) return ""; - // TODO webpack 5: Simplify this - if (typeof pos === "string") return pos; - if (typeof pos === "number") return `${pos}`; - if (typeof pos === "object") { - if ("line" in pos && "column" in pos) { - return `${pos.line}:${pos.column}`; - } else if ("line" in pos) { - return `${pos.line}:?`; - } else if ("index" in pos) { - // TODO webpack 5 remove this case - return `+${pos.index}`; - } else { - return ""; +const addScopeSymbols2 = (s, nameSet, scopeSet1, scopeSet2) => { + let scope = s; + while (scope) { + if (scopeSet1.has(scope)) break; + if (scopeSet2.has(scope)) break; + scopeSet1.add(scope); + for (const variable of scope.variables) { + nameSet.add(variable.name); } + scope = scope.upper; } - return ""; }; -// TODO webpack 5: loc must be DependencyLocation -/** - * @param {DependencyLocation|SourcePosition|string} loc location - * @returns {string} formatted location - */ -const formatLocation = loc => { - if (loc === null) return ""; - // TODO webpack 5: Simplify this - if (typeof loc === "string") return loc; - if (typeof loc === "number") return `${loc}`; - if (typeof loc === "object") { - if ("start" in loc && loc.start && "end" in loc && loc.end) { - if ( - typeof loc.start === "object" && - typeof loc.start.line === "number" && - typeof loc.end === "object" && - typeof loc.end.line === "number" && - typeof loc.end.column === "number" && - loc.start.line === loc.end.line - ) { - return `${formatPosition(loc.start)}-${loc.end.column}`; - } else { - return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; +const getAllReferences = variable => { + let set = variable.references; + // Look for inner scope variables too (like in class Foo { t() { Foo } }) + const identifiers = new Set(variable.identifiers); + for (const scope of variable.scope.childScopes) { + for (const innerVar of scope.variables) { + if (innerVar.identifiers.some(id => identifiers.has(id))) { + set = set.concat(innerVar.references); + break; } } - if ("start" in loc && loc.start) { - return formatPosition(loc.start); - } - if ("name" in loc && "index" in loc) { - return `${loc.name}[${loc.index}]`; - } - if ("name" in loc) { - return loc.name; - } - return formatPosition(loc); } - return ""; + return set; }; -module.exports = formatLocation; - - -/***/ }), +const getPathInAst = (ast, node) => { + if (ast === node) { + return []; + } -/***/ 47194: -/***/ (function(__unused_webpack_module, exports) { + const nr = node.range; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ + const enterNode = n => { + if (!n) return undefined; + const r = n.range; + if (r) { + if (r[0] <= nr[0] && r[1] >= nr[1]) { + const path = getPathInAst(n, node); + if (path) { + path.push(n); + return path; + } + } + } + return undefined; + }; + var i; + if (Array.isArray(ast)) { + for (i = 0; i < ast.length; i++) { + const enterResult = enterNode(ast[i]); + if (enterResult !== undefined) return enterResult; + } + } else if (ast && typeof ast === "object") { + const keys = Object.keys(ast); + for (i = 0; i < keys.length; i++) { + const value = ast[keys[i]]; + if (Array.isArray(value)) { + const pathResult = getPathInAst(value, node); + if (pathResult !== undefined) return pathResult; + } else if (value && typeof value === "object") { + const enterResult = enterNode(value); + if (enterResult !== undefined) return enterResult; + } + } + } +}; +const getHarmonyExportImportedSpecifierDependencyExports = dep => { + const importModule = dep._module; + if (!importModule) return []; + if (dep._id) { + // export { named } from "module" + return [ + { + name: dep.name, + id: dep._id, + module: importModule + } + ]; + } + if (dep.name) { + // export * as abc from "module" + return [ + { + name: dep.name, + id: true, + module: importModule + } + ]; + } + // export * from "module" + return importModule.buildMeta.providedExports + .filter(exp => exp !== "default" && !dep.activeExports.has(exp)) + .map(exp => { + return { + name: exp, + id: exp, + module: importModule + }; + }); +}; -const LogType = Object.freeze({ - error: /** @type {"error"} */ ("error"), // message, c style arguments - warn: /** @type {"warn"} */ ("warn"), // message, c style arguments - info: /** @type {"info"} */ ("info"), // message, c style arguments - log: /** @type {"log"} */ ("log"), // message, c style arguments - debug: /** @type {"debug"} */ ("debug"), // message, c style arguments +class ConcatenatedModule extends Module { + constructor(rootModule, modules, concatenationList) { + super("javascript/esm", null); + super.setChunks(rootModule._chunks); - trace: /** @type {"trace"} */ ("trace"), // no arguments + // Info from Factory + this.rootModule = rootModule; + this.factoryMeta = rootModule.factoryMeta; - group: /** @type {"group"} */ ("group"), // [label] - groupCollapsed: /** @type {"groupCollapsed"} */ ("groupCollapsed"), // [label] - groupEnd: /** @type {"groupEnd"} */ ("groupEnd"), // [label] + // Info from Compilation + this.index = rootModule.index; + this.index2 = rootModule.index2; + this.depth = rootModule.depth; - profile: /** @type {"profile"} */ ("profile"), // [profileName] - profileEnd: /** @type {"profileEnd"} */ ("profileEnd"), // [profileName] + // Info from Optimization + this.used = rootModule.used; + this.usedExports = rootModule.usedExports; - time: /** @type {"time"} */ ("time"), // name, time as [seconds, nanoseconds] + // Info from Build + this.buildInfo = { + strict: true, + cacheable: modules.every(m => m.buildInfo.cacheable), + moduleArgument: rootModule.buildInfo.moduleArgument, + exportsArgument: rootModule.buildInfo.exportsArgument, + fileDependencies: new Set(), + contextDependencies: new Set(), + assets: undefined + }; + this.built = modules.some(m => m.built); + this.buildMeta = rootModule.buildMeta; - clear: /** @type {"clear"} */ ("clear"), // no arguments - status: /** @type {"status"} */ ("status") // message, arguments -}); + // Caching + this._numberOfConcatenatedModules = modules.length; -exports.LogType = LogType; + // Graph + const modulesSet = new Set(modules); + this.reasons = rootModule.reasons.filter( + reason => + !(reason.dependency instanceof HarmonyImportDependency) || + !modulesSet.has(reason.module) + ); -/** @typedef {typeof LogType[keyof typeof LogType]} LogTypeEnum */ + this.dependencies = []; + this.blocks = []; -const LOG_SYMBOL = Symbol("webpack logger raw log method"); -const TIMERS_SYMBOL = Symbol("webpack logger times"); + this.warnings = []; + this.errors = []; + this._orderedConcatenationList = + concatenationList || + ConcatenatedModule.createConcatenationList(rootModule, modulesSet, null); + for (const info of this._orderedConcatenationList) { + if (info.type === "concatenated") { + const m = info.module; -class WebpackLogger { - /** - * @param {function(LogTypeEnum, any[]=): void} log log function - */ - constructor(log) { - this[LOG_SYMBOL] = log; - } - - error(...args) { - this[LOG_SYMBOL](LogType.error, args); - } - - warn(...args) { - this[LOG_SYMBOL](LogType.warn, args); - } - - info(...args) { - this[LOG_SYMBOL](LogType.info, args); - } + // populate dependencies + for (const d of m.dependencies.filter( + dep => + !(dep instanceof HarmonyImportDependency) || + !modulesSet.has(dep._module) + )) { + this.dependencies.push(d); + } + // populate blocks + for (const d of m.blocks) { + this.blocks.push(d); + } + // populate file dependencies + if (m.buildInfo.fileDependencies) { + for (const file of m.buildInfo.fileDependencies) { + this.buildInfo.fileDependencies.add(file); + } + } + // populate context dependencies + if (m.buildInfo.contextDependencies) { + for (const context of m.buildInfo.contextDependencies) { + this.buildInfo.contextDependencies.add(context); + } + } + // populate warnings + for (const warning of m.warnings) { + this.warnings.push(warning); + } + // populate errors + for (const error of m.errors) { + this.errors.push(error); + } - log(...args) { - this[LOG_SYMBOL](LogType.log, args); + if (m.buildInfo.assets) { + if (this.buildInfo.assets === undefined) { + this.buildInfo.assets = Object.create(null); + } + Object.assign(this.buildInfo.assets, m.buildInfo.assets); + } + if (m.buildInfo.assetsInfo) { + if (this.buildInfo.assetsInfo === undefined) { + this.buildInfo.assetsInfo = new Map(); + } + for (const [key, value] of m.buildInfo.assetsInfo) { + this.buildInfo.assetsInfo.set(key, value); + } + } + } + } + this._identifier = this._createIdentifier(); } - debug(...args) { - this[LOG_SYMBOL](LogType.debug, args); + get modules() { + return this._orderedConcatenationList + .filter(info => info.type === "concatenated") + .map(info => info.module); } - assert(assertion, ...args) { - if (!assertion) { - this[LOG_SYMBOL](LogType.error, args); - } + identifier() { + return this._identifier; } - trace() { - this[LOG_SYMBOL](LogType.trace, ["Trace"]); + readableIdentifier(requestShortener) { + return ( + this.rootModule.readableIdentifier(requestShortener) + + ` + ${this._numberOfConcatenatedModules - 1} modules` + ); } - clear() { - this[LOG_SYMBOL](LogType.clear); + libIdent(options) { + return this.rootModule.libIdent(options); } - status(...args) { - this[LOG_SYMBOL](LogType.status, args); + nameForCondition() { + return this.rootModule.nameForCondition(); } - group(...args) { - this[LOG_SYMBOL](LogType.group, args); + build(options, compilation, resolver, fs, callback) { + throw new Error("Cannot build this module. It should be already built."); } - groupCollapsed(...args) { - this[LOG_SYMBOL](LogType.groupCollapsed, args); + size() { + // Guess size from embedded modules + return this._orderedConcatenationList.reduce((sum, info) => { + switch (info.type) { + case "concatenated": + return sum + info.module.size(); + case "external": + return sum + 5; + } + return sum; + }, 0); } - groupEnd(...args) { - this[LOG_SYMBOL](LogType.groupEnd, args); - } + /** + * @param {Module} rootModule the root of the concatenation + * @param {Set} modulesSet a set of modules which should be concatenated + * @param {Compilation} compilation the compilation context + * @returns {ConcatenationEntry[]} concatenation list + */ + static createConcatenationList(rootModule, modulesSet, compilation) { + const list = []; + const set = new Set(); - profile(label) { - this[LOG_SYMBOL](LogType.profile, [label]); - } + /** + * @param {Module} module a module + * @returns {(function(): Module)[]} imported modules in order + */ + const getConcatenatedImports = module => { + /** @type {WeakMap} */ + const map = new WeakMap(); + const references = module.dependencies + .filter(dep => dep instanceof HarmonyImportDependency) + .map(dep => { + const ref = compilation.getDependencyReference(module, dep); + if (ref) map.set(ref, dep); + return ref; + }) + .filter(ref => ref); + DependencyReference.sort(references); + // TODO webpack 5: remove this hack, see also DependencyReference + return references.map(ref => { + const dep = map.get(ref); + return () => compilation.getDependencyReference(module, dep).module; + }); + }; - profileEnd(label) { - this[LOG_SYMBOL](LogType.profileEnd, [label]); - } + const enterModule = getModule => { + const module = getModule(); + if (!module) return; + if (set.has(module)) return; + set.add(module); + if (modulesSet.has(module)) { + const imports = getConcatenatedImports(module); + imports.forEach(enterModule); + list.push({ + type: "concatenated", + module + }); + } else { + list.push({ + type: "external", + get module() { + // We need to use a getter here, because the module in the dependency + // could be replaced by some other process (i. e. also replaced with a + // concatenated module) + return getModule(); + } + }); + } + }; - time(label) { - this[TIMERS_SYMBOL] = this[TIMERS_SYMBOL] || new Map(); - this[TIMERS_SYMBOL].set(label, process.hrtime()); - } + enterModule(() => rootModule); - timeLog(label) { - const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); - if (!prev) { - throw new Error(`No such label '${label}' for WebpackLogger.timeLog()`); - } - const time = process.hrtime(prev); - this[LOG_SYMBOL](LogType.time, [label, ...time]); + return list; } - timeEnd(label) { - const prev = this[TIMERS_SYMBOL] && this[TIMERS_SYMBOL].get(label); - if (!prev) { - throw new Error(`No such label '${label}' for WebpackLogger.timeEnd()`); + _createIdentifier() { + let orderedConcatenationListIdentifiers = ""; + for (let i = 0; i < this._orderedConcatenationList.length; i++) { + if (this._orderedConcatenationList[i].type === "concatenated") { + orderedConcatenationListIdentifiers += this._orderedConcatenationList[ + i + ].module.identifier(); + orderedConcatenationListIdentifiers += " "; + } } - const time = process.hrtime(prev); - this[TIMERS_SYMBOL].delete(label); - this[LOG_SYMBOL](LogType.time, [label, ...time]); + const hash = createHash("md4"); + hash.update(orderedConcatenationListIdentifiers); + return this.rootModule.identifier() + " " + hash.digest("hex"); } -} - -exports.Logger = WebpackLogger; + source(dependencyTemplates, runtimeTemplate) { + const requestShortener = runtimeTemplate.requestShortener; + // Metainfo for each module + const modulesWithInfo = this._orderedConcatenationList.map((info, idx) => { + switch (info.type) { + case "concatenated": { + const exportMap = new Map(); + const reexportMap = new Map(); + for (const dep of info.module.dependencies) { + if (dep instanceof HarmonyExportSpecifierDependency) { + if (!exportMap.has(dep.name)) { + exportMap.set(dep.name, dep.id); + } + } else if (dep instanceof HarmonyExportExpressionDependency) { + if (!exportMap.has("default")) { + exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__"); + } + } else if ( + dep instanceof HarmonyExportImportedSpecifierDependency + ) { + const exportName = dep.name; + const importName = dep._id; + const importedModule = dep._module; + if (exportName && importName) { + if (!reexportMap.has(exportName)) { + reexportMap.set(exportName, { + module: importedModule, + exportName: importName, + dependency: dep + }); + } + } else if (exportName) { + if (!reexportMap.has(exportName)) { + reexportMap.set(exportName, { + module: importedModule, + exportName: true, + dependency: dep + }); + } + } else if (importedModule) { + for (const name of importedModule.buildMeta.providedExports) { + if (dep.activeExports.has(name) || name === "default") { + continue; + } + if (!reexportMap.has(name)) { + reexportMap.set(name, { + module: importedModule, + exportName: name, + dependency: dep + }); + } + } + } + } + } + return { + type: "concatenated", + module: info.module, + index: idx, + ast: undefined, + internalSource: undefined, + source: undefined, + globalScope: undefined, + moduleScope: undefined, + internalNames: new Map(), + globalExports: new Set(), + exportMap: exportMap, + reexportMap: reexportMap, + hasNamespaceObject: false, + namespaceObjectSource: null + }; + } + case "external": + return { + type: "external", + module: info.module, + index: idx, + name: undefined, + interopNamespaceObjectUsed: false, + interopNamespaceObjectName: undefined, + interopDefaultAccessUsed: false, + interopDefaultAccessName: undefined + }; + default: + throw new Error(`Unsupported concatenation entry type ${info.type}`); + } + }); -/***/ }), + // Create mapping from module to info + const moduleToInfoMap = new Map(); + for (const m of modulesWithInfo) { + moduleToInfoMap.set(m.module, m); + } -/***/ 88838: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Configure template decorators for dependencies + const innerDependencyTemplates = new Map(dependencyTemplates); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + innerDependencyTemplates.set( + HarmonyImportSpecifierDependency, + new HarmonyImportSpecifierDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyImportSpecifierDependency), + moduleToInfoMap + ) + ); + innerDependencyTemplates.set( + HarmonyImportSideEffectDependency, + new HarmonyImportSideEffectDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyImportSideEffectDependency), + moduleToInfoMap + ) + ); + innerDependencyTemplates.set( + HarmonyExportSpecifierDependency, + new NullTemplate() + ); + innerDependencyTemplates.set( + HarmonyExportExpressionDependency, + new HarmonyExportExpressionDependencyConcatenatedTemplate( + dependencyTemplates.get(HarmonyExportExpressionDependency), + this.rootModule + ) + ); + innerDependencyTemplates.set( + HarmonyExportImportedSpecifierDependency, + new NullTemplate() + ); + innerDependencyTemplates.set( + HarmonyCompatibilityDependency, + new NullTemplate() + ); + // Must use full identifier in our cache here to ensure that the source + // is updated should our dependencies list change. + // TODO webpack 5 refactor + innerDependencyTemplates.set( + "hash", + innerDependencyTemplates.get("hash") + this.identifier() + ); + // Generate source code and analyse scopes + // Prepare a ReplaceSource for the final source + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + const m = info.module; + const source = m.source(innerDependencyTemplates, runtimeTemplate); + const code = source.source(); + let ast; + try { + ast = Parser.parse(code, { + sourceType: "module" + }); + } catch (err) { + if ( + err.loc && + typeof err.loc === "object" && + typeof err.loc.line === "number" + ) { + const lineNumber = err.loc.line; + const lines = code.split("\n"); + err.message += + "\n| " + + lines + .slice(Math.max(0, lineNumber - 3), lineNumber + 2) + .join("\n| "); + } + throw err; + } + const scopeManager = eslintScope.analyze(ast, { + ecmaVersion: 6, + sourceType: "module", + optimistic: true, + ignoreEval: true, + impliedStrict: true + }); + const globalScope = scopeManager.acquire(ast); + const moduleScope = globalScope.childScopes[0]; + const resultSource = new ReplaceSource(source); + info.ast = ast; + info.internalSource = source; + info.source = resultSource; + info.globalScope = globalScope; + info.moduleScope = moduleScope; + } + } -const { LogType } = __webpack_require__(47194); + // List of all used names to avoid conflicts + const allUsedNames = new Set([ + "__WEBPACK_MODULE_DEFAULT_EXPORT__", // avoid using this internal name -/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */ -/** @typedef {import("../../declarations/WebpackOptions").FilterTypes} FilterTypes */ -/** @typedef {import("../../declarations/WebpackOptions").FilterItemTypes} FilterItemTypes */ + "abstract", + "arguments", + "async", + "await", + "boolean", + "break", + "byte", + "case", + "catch", + "char", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "double", + "else", + "enum", + "eval", + "export", + "extends", + "false", + "final", + "finally", + "float", + "for", + "function", + "goto", + "if", + "implements", + "import", + "in", + "instanceof", + "int", + "interface", + "let", + "long", + "native", + "new", + "null", + "package", + "private", + "protected", + "public", + "return", + "short", + "static", + "super", + "switch", + "synchronized", + "this", + "throw", + "throws", + "transient", + "true", + "try", + "typeof", + "var", + "void", + "volatile", + "while", + "with", + "yield", -/** @typedef {function(string): boolean} FilterFunction */ + "module", + "__dirname", + "__filename", + "exports", -/** - * @typedef {Object} LoggerOptions - * @property {false|true|"none"|"error"|"warn"|"info"|"log"|"verbose"} level loglevel - * @property {FilterTypes|boolean} debug filter for debug logging - * @property {Console & { status?: Function, logTime?: Function }} console the console to log to - */ + "Array", + "Date", + "eval", + "function", + "hasOwnProperty", + "Infinity", + "isFinite", + "isNaN", + "isPrototypeOf", + "length", + "Math", + "NaN", + "name", + "Number", + "Object", + "prototype", + "String", + "toString", + "undefined", + "valueOf", -/** - * @param {FilterItemTypes} item an input item - * @returns {FilterFunction} filter funtion - */ -const filterToFunction = item => { - if (typeof item === "string") { - const regExp = new RegExp( - `[\\\\/]${item.replace( - // eslint-disable-next-line no-useless-escape - /[-[\]{}()*+?.\\^$|]/g, - "\\$&" - )}([\\\\/]|$|!|\\?)` - ); - return ident => regExp.test(ident); - } - if (item && typeof item === "object" && typeof item.test === "function") { - return ident => item.test(ident); - } - if (typeof item === "function") { - return item; - } - if (typeof item === "boolean") { - return () => item; - } -}; + "alert", + "all", + "anchor", + "anchors", + "area", + "assign", + "blur", + "button", + "checkbox", + "clearInterval", + "clearTimeout", + "clientInformation", + "close", + "closed", + "confirm", + "constructor", + "crypto", + "decodeURI", + "decodeURIComponent", + "defaultStatus", + "document", + "element", + "elements", + "embed", + "embeds", + "encodeURI", + "encodeURIComponent", + "escape", + "event", + "fileUpload", + "focus", + "form", + "forms", + "frame", + "innerHeight", + "innerWidth", + "layer", + "layers", + "link", + "location", + "mimeTypes", + "navigate", + "navigator", + "frames", + "frameRate", + "hidden", + "history", + "image", + "images", + "offscreenBuffering", + "open", + "opener", + "option", + "outerHeight", + "outerWidth", + "packages", + "pageXOffset", + "pageYOffset", + "parent", + "parseFloat", + "parseInt", + "password", + "pkcs11", + "plugin", + "prompt", + "propertyIsEnum", + "radio", + "reset", + "screenX", + "screenY", + "scroll", + "secure", + "select", + "self", + "setInterval", + "setTimeout", + "status", + "submit", + "taint", + "text", + "textarea", + "top", + "unescape", + "untaint", + "window", -/** - * @enum {number} - */ -const LogLevel = { - none: 6, - false: 6, - error: 5, - warn: 4, - info: 3, - log: 2, - true: 2, - verbose: 1 -}; + "onblur", + "onclick", + "onerror", + "onfocus", + "onkeydown", + "onkeypress", + "onkeyup", + "onmouseover", + "onload", + "onmouseup", + "onmousedown", + "onsubmit" + ]); -/** - * @param {LoggerOptions} options options object - * @returns {function(string, LogTypeEnum, any[]): void} logging function - */ -module.exports = ({ level = "info", debug = false, console }) => { - const debugFilters = - typeof debug === "boolean" - ? [() => debug] - : /** @type {FilterItemTypes[]} */ ([]) - .concat(debug) - .map(filterToFunction); - /** @type {number} */ - const loglevel = LogLevel[`${level}`] || 0; + // Set of already checked scopes + const alreadyCheckedScopes = new Set(); - /** - * @param {string} name name of the logger - * @param {LogTypeEnum} type type of the log entry - * @param {any[]} args arguments of the log entry - * @returns {void} - */ - const logger = (name, type, args) => { - const labeledArgs = () => { - if (Array.isArray(args)) { - if (args.length > 0 && typeof args[0] === "string") { - return [`[${name}] ${args[0]}`, ...args.slice(1)]; - } else { - return [`[${name}]`, ...args]; + // get all global names + for (const info of modulesWithInfo) { + const superClassExpressions = []; + + // ignore symbols from moduleScope + if (info.moduleScope) { + alreadyCheckedScopes.add(info.moduleScope); + + // The super class expression in class scopes behaves weird + // We store ranges of all super class expressions to make + // renaming to work correctly + for (const childScope of info.moduleScope.childScopes) { + if (childScope.type !== "class") continue; + if (!childScope.block.superClass) continue; + superClassExpressions.push({ + range: childScope.block.superClass.range, + variables: childScope.variables + }); } - } else { - return []; } - }; - const debug = debugFilters.some(f => f(name)); - switch (type) { - case LogType.debug: - if (!debug) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.debug === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.debug(...labeledArgs()); - } else { - console.log(...labeledArgs()); - } - break; - case LogType.log: - if (!debug && loglevel > LogLevel.log) return; - console.log(...labeledArgs()); - break; - case LogType.info: - if (!debug && loglevel > LogLevel.info) return; - console.info(...labeledArgs()); - break; - case LogType.warn: - if (!debug && loglevel > LogLevel.warn) return; - console.warn(...labeledArgs()); - break; - case LogType.error: - if (!debug && loglevel > LogLevel.error) return; - console.error(...labeledArgs()); - break; - case LogType.trace: - if (!debug) return; - console.trace(); - break; - case LogType.groupCollapsed: - if (!debug && loglevel > LogLevel.log) return; - if (!debug && loglevel > LogLevel.verbose) { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.groupCollapsed === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.groupCollapsed(...labeledArgs()); + + // add global symbols + if (info.globalScope) { + for (const reference of info.globalScope.through) { + const name = reference.identifier.name; + if ( + /^__WEBPACK_MODULE_REFERENCE__\d+_([\da-f]+|ns)(_call)?(_strict)?__$/.test( + name + ) + ) { + for (const expr of superClassExpressions) { + if ( + expr.range[0] <= reference.identifier.range[0] && + expr.range[1] >= reference.identifier.range[1] + ) { + for (const variable of expr.variables) { + allUsedNames.add(variable.name); + } + } + } + addScopeSymbols1( + reference.from, + allUsedNames, + alreadyCheckedScopes + ); } else { - console.log(...labeledArgs()); + allUsedNames.add(name); } - break; - } - // falls through - case LogType.group: - if (!debug && loglevel > LogLevel.log) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.group === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.group(...labeledArgs()); - } else { - console.log(...labeledArgs()); - } - break; - case LogType.groupEnd: - if (!debug && loglevel > LogLevel.log) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.groupEnd === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.groupEnd(); - } - break; - case LogType.time: { - if (!debug && loglevel > LogLevel.log) return; - const ms = args[1] * 1000 + args[2] / 1000000; - const msg = `[${name}] ${args[0]}: ${ms}ms`; - if (typeof console.logTime === "function") { - console.logTime(msg); - } else { - console.log(msg); } - break; } - case LogType.profile: - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profile === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profile(...labeledArgs()); + + // add exported globals + if (info.type === "concatenated") { + const variables = new Set(); + for (const variable of info.moduleScope.variables) { + variables.add(variable.name); } - break; - case LogType.profileEnd: - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.profileEnd === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.profileEnd(...labeledArgs()); + for (const [, variable] of info.exportMap) { + if (!variables.has(variable)) { + info.globalExports.add(variable); + } } - break; - case LogType.clear: - if (!debug && loglevel > LogLevel.log) return; - // eslint-disable-next-line node/no-unsupported-features/node-builtins - if (typeof console.clear === "function") { - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.clear(); + } + } + + // generate names for symbols + for (const info of modulesWithInfo) { + switch (info.type) { + case "concatenated": { + const namespaceObjectName = this.findNewName( + "namespaceObject", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(namespaceObjectName); + info.internalNames.set(namespaceObjectName, namespaceObjectName); + info.exportMap.set(true, namespaceObjectName); + for (const variable of info.moduleScope.variables) { + const name = variable.name; + if (allUsedNames.has(name)) { + const references = getAllReferences(variable); + const symbolsInReferences = new Set(); + const alreadyCheckedInnerScopes = new Set(); + for (const ref of references) { + addScopeSymbols2( + ref.from, + symbolsInReferences, + alreadyCheckedInnerScopes, + alreadyCheckedScopes + ); + } + const newName = this.findNewName( + name, + allUsedNames, + symbolsInReferences, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(newName); + info.internalNames.set(name, newName); + const source = info.source; + const allIdentifiers = new Set( + references.map(r => r.identifier).concat(variable.identifiers) + ); + for (const identifier of allIdentifiers) { + const r = identifier.range; + const path = getPathInAst(info.ast, identifier); + if ( + path && + path.length > 1 && + path[1].type === "Property" && + path[1].shorthand + ) { + source.insert(r[1], `: ${newName}`); + } else { + source.replace(r[0], r[1] - 1, newName); + } + } + } else { + allUsedNames.add(name); + info.internalNames.set(name, name); + } + } + break; } - break; - case LogType.status: - if (!debug && loglevel > LogLevel.info) return; - if (typeof console.status === "function") { - if (args.length === 0) { - console.status(); - } else { - console.status(...labeledArgs()); + case "external": { + const externalName = this.findNewName( + "", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalName); + info.name = externalName; + if ( + info.module.buildMeta.exportsType === "named" || + !info.module.buildMeta.exportsType + ) { + const externalNameInterop = this.findNewName( + "namespaceObject", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopNamespaceObjectName = externalNameInterop; } - } else { - if (args.length !== 0) { - console.info(...labeledArgs()); + if (!info.module.buildMeta.exportsType) { + const externalNameInterop = this.findNewName( + "default", + allUsedNames, + null, + info.module.readableIdentifier(requestShortener) + ); + allUsedNames.add(externalNameInterop); + info.interopDefaultAccessName = externalNameInterop; } + break; } - break; - default: - throw new Error(`Unexpected LogType ${type}`); + } } - }; - return logger; -}; + // Find and replace referenced to modules + for (const info of modulesWithInfo) { + if (info.type === "concatenated") { + for (const reference of info.globalScope.through) { + const name = reference.identifier.name; + const match = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_strict)?__$/.exec( + name + ); + if (match) { + const referencedModule = modulesWithInfo[+match[1]]; + let exportName; + if (match[2] === "ns") { + exportName = true; + } else { + const exportData = match[2]; + exportName = Buffer.from(exportData, "hex").toString("utf-8"); + } + const asCall = !!match[3]; + const strictHarmonyModule = !!match[4]; + const finalName = getFinalName( + referencedModule, + exportName, + moduleToInfoMap, + requestShortener, + asCall, + strictHarmonyModule + ); + const r = reference.identifier.range; + const source = info.source; + source.replace(r[0], r[1] - 1, finalName); + } + } + } + } -/***/ }), + // Map with all root exposed used exports + /** @type {Map} */ + const exportsMap = new Map(); -/***/ 62299: -/***/ (function(module) { + // Set with all root exposed unused exports + /** @type {Set} */ + const unusedExports = new Set(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ + for (const dep of this.rootModule.dependencies) { + if (dep instanceof HarmonyExportSpecifierDependency) { + const used = this.rootModule.isUsed(dep.name); + if (used) { + const info = moduleToInfoMap.get(this.rootModule); + if (!exportsMap.has(used)) { + exportsMap.set( + used, + () => `/* binding */ ${info.internalNames.get(dep.id)}` + ); + } + } else { + unusedExports.add(dep.name || "namespace"); + } + } else if (dep instanceof HarmonyExportImportedSpecifierDependency) { + const exportDefs = getHarmonyExportImportedSpecifierDependencyExports( + dep + ); + for (const def of exportDefs) { + const info = moduleToInfoMap.get(def.module); + const used = dep.originModule.isUsed(def.name); + if (used) { + if (!exportsMap.has(used)) { + exportsMap.set(used, requestShortener => { + const finalName = getFinalName( + info, + def.id, + moduleToInfoMap, + requestShortener, + false, + this.rootModule.buildMeta.strictHarmonyModule + ); + return `/* reexport */ ${finalName}`; + }); + } + } else { + unusedExports.add(def.name); + } + } + } + } + const result = new ConcatSource(); + // add harmony compatibility flag (must be first because of possible circular dependencies) + const usedExports = this.rootModule.usedExports; + if (usedExports === true || usedExports === null) { + result.add(`// ESM COMPAT FLAG\n`); + result.add( + runtimeTemplate.defineEsModuleFlagStatement({ + exportsArgument: this.exportsArgument + }) + ); + } -/** - * @param {any[]} args items to be truncated - * @param {number} maxLength maximum length of args including spaces between - * @returns {string[]} truncated args - */ -const truncateArgs = (args, maxLength) => { - const lengths = args.map(a => `${a}`.length); - const availableLength = maxLength - lengths.length + 1; - - if (availableLength > 0 && args.length === 1) { - if (availableLength >= args[0].length) { - return args; - } else if (availableLength > 3) { - return ["..." + args[0].slice(-availableLength + 3)]; - } else { - return [args[0].slice(-availableLength)]; + // define exports + if (exportsMap.size > 0) { + result.add(`\n// EXPORTS\n`); + for (const [key, value] of exportsMap) { + result.add( + `__webpack_require__.d(${this.exportsArgument}, ${JSON.stringify( + key + )}, function() { return ${value(requestShortener)}; });\n` + ); + } } - } - - // Check if there is space for at least 4 chars per arg - if (availableLength < lengths.reduce((s, i) => s + Math.min(i, 6), 0)) { - // remove args - if (args.length > 1) - return truncateArgs(args.slice(0, args.length - 1), maxLength); - return []; - } - - let currentLength = lengths.reduce((a, b) => a + b, 0); - // Check if all fits into maxLength - if (currentLength <= availableLength) return args; + // list unused exports + if (unusedExports.size > 0) { + result.add( + `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n` + ); + } - // Try to remove chars from the longest items until it fits - while (currentLength > availableLength) { - const maxLength = Math.max(...lengths); - const shorterItems = lengths.filter(l => l !== maxLength); - const nextToMaxLength = - shorterItems.length > 0 ? Math.max(...shorterItems) : 0; - const maxReduce = maxLength - nextToMaxLength; - let maxItems = lengths.length - shorterItems.length; - let overrun = currentLength - availableLength; - for (let i = 0; i < lengths.length; i++) { - if (lengths[i] === maxLength) { - const reduce = Math.min(Math.floor(overrun / maxItems), maxReduce); - lengths[i] -= reduce; - currentLength -= reduce; - overrun -= reduce; - maxItems--; + // define required namespace objects (must be before evaluation modules) + for (const info of modulesWithInfo) { + if (info.namespaceObjectSource) { + result.add( + `\n// NAMESPACE OBJECT: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + result.add(info.namespaceObjectSource); } } - } - // Return args reduced to length in lengths - return args.map((a, i) => { - const str = `${a}`; - const length = lengths[i]; - if (str.length === length) { - return str; - } else if (length > 5) { - return "..." + str.slice(-length + 3); - } else if (length > 0) { - return str.slice(-length); - } else { - return ""; + // evaluate modules in order + for (const info of modulesWithInfo) { + switch (info.type) { + case "concatenated": + result.add( + `\n// CONCATENATED MODULE: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + result.add(info.source); + break; + case "external": + result.add( + `\n// EXTERNAL MODULE: ${info.module.readableIdentifier( + requestShortener + )}\n` + ); + result.add( + `var ${info.name} = __webpack_require__(${JSON.stringify( + info.module.id + )});\n` + ); + if (info.interopNamespaceObjectUsed) { + if (info.module.buildMeta.exportsType === "named") { + result.add( + `var ${info.interopNamespaceObjectName} = /*#__PURE__*/__webpack_require__.t(${info.name}, 2);\n` + ); + } else if (!info.module.buildMeta.exportsType) { + result.add( + `var ${info.interopNamespaceObjectName} = /*#__PURE__*/__webpack_require__.t(${info.name});\n` + ); + } + } + if (info.interopDefaultAccessUsed) { + result.add( + `var ${info.interopDefaultAccessName} = /*#__PURE__*/__webpack_require__.n(${info.name});\n` + ); + } + break; + default: + throw new Error(`Unsupported concatenation entry type ${info.type}`); + } } - }); -}; - -module.exports = truncateArgs; - -/***/ }), + return result; + } -/***/ 45249: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { + let name = oldName; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (name === "__WEBPACK_MODULE_DEFAULT_EXPORT__") name = ""; + // Remove uncool stuff + extraInfo = extraInfo.replace( + /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, + "" + ); + const splittedInfo = extraInfo.split("/"); + while (splittedInfo.length) { + name = splittedInfo.pop() + (name ? "_" + name : ""); + const nameIdent = Template.toIdentifier(name); + if ( + !usedNamed1.has(nameIdent) && + (!usedNamed2 || !usedNamed2.has(nameIdent)) + ) + return nameIdent; + } -const { ConcatSource } = __webpack_require__(53665); + let i = 0; + let nameWithNumber = Template.toIdentifier(`${name}_${i}`); + while ( + usedNamed1.has(nameWithNumber) || + (usedNamed2 && usedNamed2.has(nameWithNumber)) + ) { + i++; + nameWithNumber = Template.toIdentifier(`${name}_${i}`); + } + return nameWithNumber; + } -class NodeChunkTemplatePlugin { - apply(chunkTemplate) { - chunkTemplate.hooks.render.tap( - "NodeChunkTemplatePlugin", - (modules, chunk) => { - const source = new ConcatSource(); - source.add( - `exports.ids = ${JSON.stringify(chunk.ids)};\nexports.modules = ` - ); - source.add(modules); - source.add(";"); - return source; + /** + * @param {Hash} hash the hash used to track dependencies + * @returns {void} + */ + updateHash(hash) { + for (const info of this._orderedConcatenationList) { + switch (info.type) { + case "concatenated": + info.module.updateHash(hash); + break; + case "external": + hash.update(`${info.module.id}`); + break; } - ); - chunkTemplate.hooks.hash.tap("NodeChunkTemplatePlugin", hash => { - hash.update("node"); - hash.update("3"); - }); + } + super.updateHash(hash); } } -module.exports = NodeChunkTemplatePlugin; +class HarmonyImportSpecifierDependencyConcatenatedTemplate { + constructor(originalTemplate, modulesMap) { + this.originalTemplate = originalTemplate; + this.modulesMap = modulesMap; + } + getHarmonyInitOrder(dep) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + return this.originalTemplate.getHarmonyInitOrder(dep); + } + return NaN; + } -/***/ }), + harmonyInit(dep, source, runtimeTemplate, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.harmonyInit( + dep, + source, + runtimeTemplate, + dependencyTemplates + ); + return; + } + } -/***/ 52520: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + apply(dep, source, runtime, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); + return; + } + let content; + const callFlag = dep.call ? "_call" : ""; + const strictFlag = dep.originModule.buildMeta.strictHarmonyModule + ? "_strict" + : ""; + if (dep._id === null) { + content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns${strictFlag}__`; + } else if (dep.namespaceObjectAsContext) { + content = `__WEBPACK_MODULE_REFERENCE__${ + info.index + }_ns${strictFlag}__[${JSON.stringify(dep._id)}]`; + } else { + const exportData = Buffer.from(dep._id, "utf-8").toString("hex"); + content = `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${callFlag}${strictFlag}__`; + } + if (dep.shorthand) { + content = dep.name + ": " + content; + } + source.replace(dep.range[0], dep.range[1] - 1, content); + } +} -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +class HarmonyImportSideEffectDependencyConcatenatedTemplate { + constructor(originalTemplate, modulesMap) { + this.originalTemplate = originalTemplate; + this.modulesMap = modulesMap; + } + getHarmonyInitOrder(dep) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + return this.originalTemplate.getHarmonyInitOrder(dep); + } + return NaN; + } -const NodeWatchFileSystem = __webpack_require__(71610); -const NodeOutputFileSystem = __webpack_require__(31836); -const NodeJsInputFileSystem = __webpack_require__(13445); -const CachedInputFileSystem = __webpack_require__(75544); -const createConsoleLogger = __webpack_require__(88838); -const nodeConsole = __webpack_require__(7886); + harmonyInit(dep, source, runtime, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.harmonyInit( + dep, + source, + runtime, + dependencyTemplates + ); + return; + } + } -class NodeEnvironmentPlugin { - constructor(options) { - this.options = options || {}; + apply(dep, source, runtime, dependencyTemplates) { + const module = dep._module; + const info = this.modulesMap.get(module); + if (!info) { + this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); + return; + } } +} - apply(compiler) { - compiler.infrastructureLogger = createConsoleLogger( - Object.assign( - { - level: "info", - debug: false, - console: nodeConsole - }, - this.options.infrastructureLogging - ) - ); - compiler.inputFileSystem = new CachedInputFileSystem( - new NodeJsInputFileSystem(), - 60000 - ); - const inputFileSystem = compiler.inputFileSystem; - compiler.outputFileSystem = new NodeOutputFileSystem(); - compiler.watchFileSystem = new NodeWatchFileSystem( - compiler.inputFileSystem +class HarmonyExportExpressionDependencyConcatenatedTemplate { + constructor(originalTemplate, rootModule) { + this.originalTemplate = originalTemplate; + this.rootModule = rootModule; + } + + apply(dep, source, runtime, dependencyTemplates) { + let content = + "/* harmony default export */ var __WEBPACK_MODULE_DEFAULT_EXPORT__ = "; + if (dep.originModule === this.rootModule) { + const used = dep.originModule.isUsed("default"); + const exportsName = dep.originModule.exportsArgument; + if (used) content += `${exportsName}[${JSON.stringify(used)}] = `; + } + + if (dep.range) { + source.replace( + dep.rangeStatement[0], + dep.range[0] - 1, + content + "(" + dep.prefix + ); + source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); + return; + } + + source.replace( + dep.rangeStatement[0], + dep.rangeStatement[1] - 1, + content + dep.prefix ); - compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => { - if (compiler.inputFileSystem === inputFileSystem) inputFileSystem.purge(); - }); } } -module.exports = NodeEnvironmentPlugin; + +class NullTemplate { + apply() {} +} + +module.exports = ConcatenatedModule; /***/ }), -/***/ 95909: +/***/ 29720: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -104485,466 +103737,182 @@ module.exports = NodeEnvironmentPlugin; */ -const { ConcatSource } = __webpack_require__(53665); +const GraphHelpers = __webpack_require__(32973); -class NodeHotUpdateChunkTemplatePlugin { - apply(hotUpdateChunkTemplate) { - hotUpdateChunkTemplate.hooks.render.tap( - "NodeHotUpdateChunkTemplatePlugin", - (modulesSource, modules, removedModules, hash, id) => { - const source = new ConcatSource(); - source.add( - "exports.id = " + JSON.stringify(id) + ";\nexports.modules = " +class EnsureChunkConditionsPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "EnsureChunkConditionsPlugin", + compilation => { + const handler = chunks => { + let changed = false; + for (const module of compilation.modules) { + if (!module.chunkCondition) continue; + const sourceChunks = new Set(); + const chunkGroups = new Set(); + for (const chunk of module.chunksIterable) { + if (!module.chunkCondition(chunk)) { + sourceChunks.add(chunk); + for (const group of chunk.groupsIterable) { + chunkGroups.add(group); + } + } + } + if (sourceChunks.size === 0) continue; + const targetChunks = new Set(); + chunkGroupLoop: for (const chunkGroup of chunkGroups) { + // Can module be placed in a chunk of this group? + for (const chunk of chunkGroup.chunks) { + if (module.chunkCondition(chunk)) { + targetChunks.add(chunk); + continue chunkGroupLoop; + } + } + // We reached the entrypoint: fail + if (chunkGroup.isInitial()) { + throw new Error( + "Cannot fullfil chunk condition of " + module.identifier() + ); + } + // Try placing in all parents + for (const group of chunkGroup.parentsIterable) { + chunkGroups.add(group); + } + } + for (const sourceChunk of sourceChunks) { + GraphHelpers.disconnectChunkAndModule(sourceChunk, module); + } + for (const targetChunk of targetChunks) { + GraphHelpers.connectChunkAndModule(targetChunk, module); + } + } + if (changed) return true; + }; + compilation.hooks.optimizeChunksBasic.tap( + "EnsureChunkConditionsPlugin", + handler ); - source.add(modulesSource); - source.add(";"); - return source; - } - ); - hotUpdateChunkTemplate.hooks.hash.tap( - "NodeHotUpdateChunkTemplatePlugin", - hash => { - hash.update("NodeHotUpdateChunkTemplatePlugin"); - hash.update("3"); - hash.update( - hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "" + compilation.hooks.optimizeExtractedChunksBasic.tap( + "EnsureChunkConditionsPlugin", + handler ); - hash.update(hotUpdateChunkTemplate.outputOptions.library + ""); } ); } } -module.exports = NodeHotUpdateChunkTemplatePlugin; +module.exports = EnsureChunkConditionsPlugin; /***/ }), -/***/ 33514: +/***/ 25850: /***/ (function(module) { +"use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -// eslint-disable-next-line no-unused-vars -var $hotChunkFilename$ = undefined; -var hotAddUpdateChunk = undefined; -var installedChunks = undefined; -var $hotMainFilename$ = undefined; - -module.exports = function() { - // eslint-disable-next-line no-unused-vars - function hotDownloadUpdateChunk(chunkId) { - var chunk = require("./" + $hotChunkFilename$); - hotAddUpdateChunk(chunk.id, chunk.modules); - } - // eslint-disable-next-line no-unused-vars - function hotDownloadManifest() { - try { - var update = require("./" + $hotMainFilename$); - } catch (e) { - return Promise.resolve(); - } - return Promise.resolve(update); - } - //eslint-disable-next-line no-unused-vars - function hotDisposeChunk(chunkId) { - delete installedChunks[chunkId]; - } -}; +class FlagIncludedChunksPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("FlagIncludedChunksPlugin", compilation => { + compilation.hooks.optimizeChunkIds.tap( + "FlagIncludedChunksPlugin", + chunks => { + // prepare two bit integers for each module + // 2^31 is the max number represented as SMI in v8 + // we want the bits distributed this way: + // the bit 2^31 is pretty rar and only one module should get it + // so it has a probability of 1 / modulesCount + // the first bit (2^0) is the easiest and every module could get it + // if it doesn't get a better bit + // from bit 2^n to 2^(n+1) there is a probability of p + // so 1 / modulesCount == p^31 + // <=> p = sqrt31(1 / modulesCount) + // so we use a modulo of 1 / sqrt31(1 / modulesCount) + const moduleBits = new WeakMap(); + const modulesCount = compilation.modules.length; + // precalculate the modulo values for each bit + const modulo = 1 / Math.pow(1 / modulesCount, 1 / 31); + const modulos = Array.from( + { length: 31 }, + (x, i) => Math.pow(modulo, i) | 0 + ); -/***/ }), - -/***/ 51433: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -// eslint-disable-next-line no-unused-vars -var $hotChunkFilename$ = undefined; -var $require$ = undefined; -var hotAddUpdateChunk = undefined; -var $hotMainFilename$ = undefined; -var installedChunks = undefined; - -module.exports = function() { - // eslint-disable-next-line no-unused-vars - function hotDownloadUpdateChunk(chunkId) { - var filename = __webpack_require__(85622).join(__dirname, $hotChunkFilename$); - __webpack_require__(35747).readFile(filename, "utf-8", function(err, content) { - if (err) { - if ($require$.onError) return $require$.oe(err); - throw err; - } - var chunk = {}; - __webpack_require__(92184).runInThisContext( - "(function(exports) {" + content + "\n})", - { filename: filename } - )(chunk); - hotAddUpdateChunk(chunk.id, chunk.modules); - }); - } - - // eslint-disable-next-line no-unused-vars - function hotDownloadManifest() { - var filename = __webpack_require__(85622).join(__dirname, $hotMainFilename$); - return new Promise(function(resolve, reject) { - __webpack_require__(35747).readFile(filename, "utf-8", function(err, content) { - if (err) return resolve(); - try { - var update = JSON.parse(content); - } catch (e) { - return reject(e); - } - resolve(update); - }); - }); - } - - // eslint-disable-next-line no-unused-vars - function hotDisposeChunk(chunkId) { - delete installedChunks[chunkId]; - } -}; + // iterate all modules to generate bit values + let i = 0; + for (const module of compilation.modules) { + let bit = 30; + while (i % modulos[bit] !== 0) { + bit--; + } + moduleBits.set(module, 1 << bit); + i++; + } + // interate all chunks to generate bitmaps + const chunkModulesHash = new WeakMap(); + for (const chunk of chunks) { + let hash = 0; + for (const module of chunk.modulesIterable) { + hash |= moduleBits.get(module); + } + chunkModulesHash.set(chunk, hash); + } -/***/ }), + for (const chunkA of chunks) { + const chunkAHash = chunkModulesHash.get(chunkA); + const chunkAModulesCount = chunkA.getNumberOfModules(); + if (chunkAModulesCount === 0) continue; + let bestModule = undefined; + for (const module of chunkA.modulesIterable) { + if ( + bestModule === undefined || + bestModule.getNumberOfChunks() > module.getNumberOfChunks() + ) + bestModule = module; + } + loopB: for (const chunkB of bestModule.chunksIterable) { + // as we iterate the same iterables twice + // skip if we find ourselves + if (chunkA === chunkB) continue; -/***/ 78597: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const chunkBModulesCount = chunkB.getNumberOfModules(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // ids for empty chunks are not included + if (chunkBModulesCount === 0) continue; + // instead of swapping A and B just bail + // as we loop twice the current A will be B and B then A + if (chunkAModulesCount > chunkBModulesCount) continue; -const Template = __webpack_require__(96066); + // is chunkA in chunkB? -module.exports = class NodeMainTemplatePlugin { - constructor(asyncChunkLoading) { - this.asyncChunkLoading = asyncChunkLoading; - } + // we do a cheap check for the hash value + const chunkBHash = chunkModulesHash.get(chunkB); + if ((chunkBHash & chunkAHash) !== chunkAHash) continue; - apply(mainTemplate) { - const needChunkOnDemandLoadingCode = chunk => { - for (const chunkGroup of chunk.groupsIterable) { - if (chunkGroup.getNumberOfChildren() > 0) return true; - } - return false; - }; - const asyncChunkLoading = this.asyncChunkLoading; - mainTemplate.hooks.localVars.tap( - "NodeMainTemplatePlugin", - (source, chunk) => { - if (needChunkOnDemandLoadingCode(chunk)) { - return Template.asString([ - source, - "", - "// object to store loaded chunks", - '// "0" means "already loaded"', - "var installedChunks = {", - Template.indent( - chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") - ), - "};" - ]); - } - return source; - } - ); - mainTemplate.hooks.requireExtensions.tap( - "NodeMainTemplatePlugin", - (source, chunk) => { - if (needChunkOnDemandLoadingCode(chunk)) { - return Template.asString([ - source, - "", - "// uncaught error handler for webpack runtime", - `${mainTemplate.requireFn}.oe = function(err) {`, - Template.indent([ - "process.nextTick(function() {", - Template.indent( - "throw err; // catch this error by using import().catch()" - ), - "});" - ]), - "};" - ]); - } - return source; - } - ); - mainTemplate.hooks.requireEnsure.tap( - "NodeMainTemplatePlugin", - (source, chunk, hash) => { - const chunkFilename = mainTemplate.outputOptions.chunkFilename; - const chunkMaps = chunk.getChunkMaps(); - const insertMoreModules = [ - "var moreModules = chunk.modules, chunkIds = chunk.ids;", - "for(var moduleId in moreModules) {", - Template.indent( - mainTemplate.renderAddModule( - hash, - chunk, - "moduleId", - "moreModules[moduleId]" - ) - ), - "}" - ]; - if (asyncChunkLoading) { - return Template.asString([ - source, - "", - "// ReadFile + VM.run chunk loading for javascript", - "", - "var installedChunkData = installedChunks[chunkId];", - 'if(installedChunkData !== 0) { // 0 means "already installed".', - Template.indent([ - '// array of [resolve, reject, promise] means "currently loading"', - "if(installedChunkData) {", - Template.indent(["promises.push(installedChunkData[2]);"]), - "} else {", - Template.indent([ - "// load the chunk and return promise to it", - "var promise = new Promise(function(resolve, reject) {", - Template.indent([ - "installedChunkData = installedChunks[chunkId] = [resolve, reject];", - "var filename = require('path').join(__dirname, " + - mainTemplate.getAssetPath( - JSON.stringify(`/${chunkFilename}`), - { - hash: `" + ${mainTemplate.renderCurrentHashCode( - hash - )} + "`, - hashWithLength: length => - `" + ${mainTemplate.renderCurrentHashCode( - hash, - length - )} + "`, - chunk: { - id: '" + chunkId + "', - hash: `" + ${JSON.stringify( - chunkMaps.hash - )}[chunkId] + "`, - hashWithLength: length => { - const shortChunkHashMap = {}; - for (const chunkId of Object.keys(chunkMaps.hash)) { - if (typeof chunkMaps.hash[chunkId] === "string") { - shortChunkHashMap[chunkId] = chunkMaps.hash[ - chunkId - ].substr(0, length); - } - } - return `" + ${JSON.stringify( - shortChunkHashMap - )}[chunkId] + "`; - }, - contentHash: { - javascript: `" + ${JSON.stringify( - chunkMaps.contentHash.javascript - )}[chunkId] + "` - }, - contentHashWithLength: { - javascript: length => { - const shortContentHashMap = {}; - const contentHash = - chunkMaps.contentHash.javascript; - for (const chunkId of Object.keys(contentHash)) { - if (typeof contentHash[chunkId] === "string") { - shortContentHashMap[chunkId] = contentHash[ - chunkId - ].substr(0, length); - } - } - return `" + ${JSON.stringify( - shortContentHashMap - )}[chunkId] + "`; - } - }, - name: `" + (${JSON.stringify( - chunkMaps.name - )}[chunkId]||chunkId) + "` - }, - contentHashType: "javascript" - } - ) + - ");", - "require('fs').readFile(filename, 'utf-8', function(err, content) {", - Template.indent( - [ - "if(err) return reject(err);", - "var chunk = {};", - "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + - "(chunk, require, require('path').dirname(filename), filename);" - ] - .concat(insertMoreModules) - .concat([ - "var callbacks = [];", - "for(var i = 0; i < chunkIds.length; i++) {", - Template.indent([ - "if(installedChunks[chunkIds[i]])", - Template.indent([ - "callbacks = callbacks.concat(installedChunks[chunkIds[i]][0]);" - ]), - "installedChunks[chunkIds[i]] = 0;" - ]), - "}", - "for(i = 0; i < callbacks.length; i++)", - Template.indent("callbacks[i]();") - ]) - ), - "});" - ]), - "});", - "promises.push(installedChunkData[2] = promise);" - ]), - "}" - ]), - "}" - ]); - } else { - const request = mainTemplate.getAssetPath( - JSON.stringify(`./${chunkFilename}`), - { - hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, - hashWithLength: length => - `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, - chunk: { - id: '" + chunkId + "', - hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, - hashWithLength: length => { - const shortChunkHashMap = {}; - for (const chunkId of Object.keys(chunkMaps.hash)) { - if (typeof chunkMaps.hash[chunkId] === "string") { - shortChunkHashMap[chunkId] = chunkMaps.hash[ - chunkId - ].substr(0, length); - } - } - return `" + ${JSON.stringify( - shortChunkHashMap - )}[chunkId] + "`; - }, - contentHash: { - javascript: `" + ${JSON.stringify( - chunkMaps.contentHash.javascript - )}[chunkId] + "` - }, - contentHashWithLength: { - javascript: length => { - const shortContentHashMap = {}; - const contentHash = chunkMaps.contentHash.javascript; - for (const chunkId of Object.keys(contentHash)) { - if (typeof contentHash[chunkId] === "string") { - shortContentHashMap[chunkId] = contentHash[ - chunkId - ].substr(0, length); - } - } - return `" + ${JSON.stringify( - shortContentHashMap - )}[chunkId] + "`; - } - }, - name: `" + (${JSON.stringify( - chunkMaps.name - )}[chunkId]||chunkId) + "` - }, - contentHashType: "javascript" - } - ); - return Template.asString([ - source, - "", - "// require() chunk loading for javascript", - "", - '// "0" is the signal for "already loaded"', - "if(installedChunks[chunkId] !== 0) {", - Template.indent( - [`var chunk = require(${request});`] - .concat(insertMoreModules) - .concat([ - "for(var i = 0; i < chunkIds.length; i++)", - Template.indent("installedChunks[chunkIds[i]] = 0;") - ]) - ), - "}" - ]); - } - } - ); - mainTemplate.hooks.hotBootstrap.tap( - "NodeMainTemplatePlugin", - (source, chunk, hash) => { - const hotUpdateChunkFilename = - mainTemplate.outputOptions.hotUpdateChunkFilename; - const hotUpdateMainFilename = - mainTemplate.outputOptions.hotUpdateMainFilename; - const chunkMaps = chunk.getChunkMaps(); - const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( - JSON.stringify(hotUpdateChunkFilename), - { - hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, - hashWithLength: length => - `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, - chunk: { - id: '" + chunkId + "', - hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, - hashWithLength: length => { - const shortChunkHashMap = {}; - for (const chunkId of Object.keys(chunkMaps.hash)) { - if (typeof chunkMaps.hash[chunkId] === "string") { - shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( - 0, - length - ); - } - } - return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`; - }, - name: `" + (${JSON.stringify( - chunkMaps.name - )}[chunkId]||chunkId) + "` + // compare all modules + for (const m of chunkA.modulesIterable) { + if (!chunkB.containsModule(m)) continue loopB; + } + chunkB.ids.push(chunkA.id); } } - ); - const currentHotUpdateMainFilename = mainTemplate.getAssetPath( - JSON.stringify(hotUpdateMainFilename), - { - hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, - hashWithLength: length => - `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` - } - ); - return Template.getFunctionContent( - asyncChunkLoading - ? __webpack_require__(51433) - : __webpack_require__(33514) - ) - .replace(/\$require\$/g, mainTemplate.requireFn) - .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) - .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename); - } - ); - mainTemplate.hooks.hash.tap("NodeMainTemplatePlugin", hash => { - hash.update("node"); - hash.update("4"); + } + ); }); } -}; +} +module.exports = FlagIncludedChunksPlugin; /***/ }), -/***/ 31836: +/***/ 3846: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -104954,177 +103922,237 @@ module.exports = class NodeMainTemplatePlugin { */ -const fs = __webpack_require__(35747); -const path = __webpack_require__(85622); -const mkdirp = __webpack_require__(50998); - -class NodeOutputFileSystem { - constructor() { - this.mkdirp = mkdirp; - this.mkdir = fs.mkdir.bind(fs); - this.rmdir = fs.rmdir.bind(fs); - this.unlink = fs.unlink.bind(fs); - this.writeFile = fs.writeFile.bind(fs); - this.join = path.join.bind(path); - } -} - -module.exports = NodeOutputFileSystem; - - -/***/ }), +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(27993); +const LazyBucketSortedSet = __webpack_require__(52315); -/***/ 9128: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Compiler")} Compiler */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +/** + * @typedef {Object} ChunkCombination + * @property {boolean} deleted this is set to true when combination was removed + * @property {number} sizeDiff + * @property {number} integratedSize + * @property {Chunk} a + * @property {Chunk} b + * @property {number} aIdx + * @property {number} bIdx + * @property {number} aSize + * @property {number} bSize + */ -const AliasPlugin = __webpack_require__(15005); -const ParserHelpers = __webpack_require__(23999); -const nodeLibsBrowser = __webpack_require__(27852); +const addToSetMap = (map, key, value) => { + const set = map.get(key); + if (set === undefined) { + map.set(key, new Set([value])); + } else { + set.add(value); + } +}; -module.exports = class NodeSourcePlugin { +class LimitChunkCountPlugin { + /** + * @param {LimitChunkCountPluginOptions=} options options object + */ constructor(options) { + if (!options) options = {}; + + validateOptions(schema, options, "Limit Chunk Count Plugin"); this.options = options; } + + /** + * @param {Compiler} compiler the webpack compiler + * @returns {void} + */ apply(compiler) { const options = this.options; - if (options === false) { - // allow single kill switch to turn off this plugin - return; - } + compiler.hooks.compilation.tap("LimitChunkCountPlugin", compilation => { + compilation.hooks.optimizeChunksAdvanced.tap( + "LimitChunkCountPlugin", + chunks => { + const maxChunks = options.maxChunks; + if (!maxChunks) return; + if (maxChunks < 1) return; + if (chunks.length <= maxChunks) return; - const getPathToModule = (module, type) => { - if (type === true || (type === undefined && nodeLibsBrowser[module])) { - if (!nodeLibsBrowser[module]) { - throw new Error( - `No browser version for node.js core module ${module} available` - ); - } - return nodeLibsBrowser[module]; - } else if (type === "mock") { - return require.resolve(`node-libs-browser/mock/${module}`); - } else if (type === "empty") { - return __webpack_require__.ab + "empty.js"; - } else { - return module; - } - }; + let remainingChunksToMerge = chunks.length - maxChunks; - const addExpression = (parser, name, module, type, suffix) => { - suffix = suffix || ""; - parser.hooks.expression.for(name).tap("NodeSourcePlugin", () => { - if ( - parser.state.module && - parser.state.module.resource === getPathToModule(module, type) - ) - return; - const mockModule = ParserHelpers.requireFileAsExpression( - parser.state.module.context, - getPathToModule(module, type) - ); - return ParserHelpers.addParsedVariableToModule( - parser, - name, - mockModule + suffix - ); - }); - }; + // order chunks in a deterministic way + const orderedChunks = chunks.slice().sort((a, b) => a.compareTo(b)); - compiler.hooks.compilation.tap( - "NodeSourcePlugin", - (compilation, { normalModuleFactory }) => { - const handler = (parser, parserOptions) => { - if (parserOptions.node === false) return; + // create a lazy sorted data structure to keep all combinations + // this is large. Size = chunks * (chunks - 1) / 2 + // It uses a multi layer bucket sort plus normal sort in the last layer + // It's also lazy so only accessed buckets are sorted + const combinations = new LazyBucketSortedSet( + // Layer 1: ordered by largest size benefit + c => c.sizeDiff, + (a, b) => b - a, + // Layer 2: ordered by smallest combined size + c => c.integratedSize, + (a, b) => a - b, + // Layer 3: ordered by position difference in orderedChunk (-> to be deterministic) + c => c.bIdx - c.aIdx, + (a, b) => a - b, + // Layer 4: ordered by position in orderedChunk (-> to be deterministic) + (a, b) => a.bIdx - b.bIdx + ); - let localOptions = options; - if (parserOptions.node) { - localOptions = Object.assign({}, localOptions, parserOptions.node); - } - if (localOptions.global) { - parser.hooks.expression - .for("global") - .tap("NodeSourcePlugin", () => { - const retrieveGlobalModule = ParserHelpers.requireFileAsExpression( - parser.state.module.context, - __webpack_require__.ab + "global.js" - ); - return ParserHelpers.addParsedVariableToModule( - parser, - "global", - retrieveGlobalModule - ); - }); - } - if (localOptions.process) { - const processType = localOptions.process; - addExpression(parser, "process", "process", processType); - } - if (localOptions.console) { - const consoleType = localOptions.console; - addExpression(parser, "console", "console", consoleType); - } - const bufferType = localOptions.Buffer; - if (bufferType) { - addExpression(parser, "Buffer", "buffer", bufferType, ".Buffer"); - } - if (localOptions.setImmediate) { - const setImmediateType = localOptions.setImmediate; - addExpression( - parser, - "setImmediate", - "timers", - setImmediateType, - ".setImmediate" - ); - addExpression( - parser, - "clearImmediate", - "timers", - setImmediateType, - ".clearImmediate" - ); + // we keep a mappng from chunk to all combinations + // but this mapping is not kept up-to-date with deletions + // so `deleted` flag need to be considered when iterating this + /** @type {Map>} */ + const combinationsByChunk = new Map(); + + orderedChunks.forEach((b, bIdx) => { + // create combination pairs with size and integrated size + for (let aIdx = 0; aIdx < bIdx; aIdx++) { + const a = orderedChunks[aIdx]; + const integratedSize = a.integratedSize(b, options); + + // filter pairs that do not have an integratedSize + // meaning they can NOT be integrated! + if (integratedSize === false) continue; + + const aSize = a.size(options); + const bSize = b.size(options); + const c = { + deleted: false, + sizeDiff: aSize + bSize - integratedSize, + integratedSize, + a, + b, + aIdx, + bIdx, + aSize, + bSize + }; + combinations.add(c); + addToSetMap(combinationsByChunk, a, c); + addToSetMap(combinationsByChunk, b, c); + } + return combinations; + }); + + // list of modified chunks during this run + // combinations affected by this change are skipped to allow + // futher optimizations + /** @type {Set} */ + const modifiedChunks = new Set(); + + let changed = false; + // eslint-disable-next-line no-constant-condition + loop: while (true) { + const combination = combinations.popFirst(); + if (combination === undefined) break; + + combination.deleted = true; + const { a, b, integratedSize } = combination; + + // skip over pair when + // one of the already merged chunks is a parent of one of the chunks + if (modifiedChunks.size > 0) { + const queue = new Set(a.groupsIterable); + for (const group of b.groupsIterable) { + queue.add(group); + } + for (const group of queue) { + for (const mChunk of modifiedChunks) { + if (mChunk !== a && mChunk !== b && mChunk.isInGroup(group)) { + // This is a potential pair which needs recalculation + // We can't do that now, but it merge before following pairs + // so we leave space for it, and consider chunks as modified + // just for the worse case + remainingChunksToMerge--; + if (remainingChunksToMerge <= 0) break loop; + modifiedChunks.add(a); + modifiedChunks.add(b); + continue loop; + } + } + for (const parent of group.parentsIterable) { + queue.add(parent); + } + } + } + + // merge the chunks + if (a.integrate(b, "limit")) { + chunks.splice(chunks.indexOf(b), 1); + + // flag chunk a as modified as further optimization are possible for all children here + modifiedChunks.add(a); + + changed = true; + remainingChunksToMerge--; + if (remainingChunksToMerge <= 0) break; + + // Update all affected combinations + // delete all combination with the removed chunk + // we will use combinations with the kept chunk instead + for (const combination of combinationsByChunk.get(b)) { + if (combination.deleted) continue; + combination.deleted = true; + combinations.delete(combination); + } + + // Update combinations with the kept chunk with new sizes + for (const combination of combinationsByChunk.get(a)) { + if (combination.deleted) continue; + if (combination.a === a) { + // Update size + const newIntegratedSize = a.integratedSize( + combination.b, + options + ); + if (newIntegratedSize === false) { + combination.deleted = true; + combinations.delete(combination); + continue; + } + const finishUpdate = combinations.startUpdate(combination); + combination.integratedSize = newIntegratedSize; + combination.aSize = integratedSize; + combination.sizeDiff = + combination.bSize + integratedSize - newIntegratedSize; + finishUpdate(); + } else if (combination.b === a) { + // Update size + const newIntegratedSize = combination.a.integratedSize( + a, + options + ); + if (newIntegratedSize === false) { + combination.deleted = true; + combinations.delete(combination); + continue; + } + const finishUpdate = combinations.startUpdate(combination); + combination.integratedSize = newIntegratedSize; + combination.bSize = integratedSize; + combination.sizeDiff = + integratedSize + combination.aSize - newIntegratedSize; + finishUpdate(); + } + } + } } - }; - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("NodeSourcePlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("NodeSourcePlugin", handler); - } - ); - compiler.hooks.afterResolvers.tap("NodeSourcePlugin", compiler => { - for (const lib of Object.keys(nodeLibsBrowser)) { - if (options[lib] !== false) { - compiler.resolverFactory.hooks.resolver - .for("normal") - .tap("NodeSourcePlugin", resolver => { - new AliasPlugin( - "described-resolve", - { - name: lib, - onlyModule: true, - alias: getPathToModule(lib, options[lib]) - }, - "resolve" - ).apply(resolver); - }); + if (changed) return true; } - } + ); }); } -}; +} +module.exports = LimitChunkCountPlugin; /***/ }), -/***/ 59743: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 46214: +/***/ (function(module) { "use strict"; /* @@ -105133,24 +104161,83 @@ module.exports = class NodeSourcePlugin { */ -const ExternalsPlugin = __webpack_require__(75705); +class MergeDuplicateChunksPlugin { + apply(compiler) { + compiler.hooks.compilation.tap( + "MergeDuplicateChunksPlugin", + compilation => { + compilation.hooks.optimizeChunksBasic.tap( + "MergeDuplicateChunksPlugin", + chunks => { + // remember already tested chunks for performance + const notDuplicates = new Set(); -const builtins = - // eslint-disable-next-line node/no-unsupported-features/node-builtins,node/no-deprecated-api - __webpack_require__(32282).builtinModules || Object.keys(process.binding("natives")); + // for each chunk + for (const chunk of chunks) { + // track a Set of all chunk that could be duplicates + let possibleDuplicates; + for (const module of chunk.modulesIterable) { + if (possibleDuplicates === undefined) { + // when possibleDuplicates is not yet set, + // create a new Set from chunks of the current module + // including only chunks with the same number of modules + for (const dup of module.chunksIterable) { + if ( + dup !== chunk && + chunk.getNumberOfModules() === dup.getNumberOfModules() && + !notDuplicates.has(dup) + ) { + // delay allocating the new Set until here, reduce memory pressure + if (possibleDuplicates === undefined) { + possibleDuplicates = new Set(); + } + possibleDuplicates.add(dup); + } + } + // when no chunk is possible we can break here + if (possibleDuplicates === undefined) break; + } else { + // validate existing possible duplicates + for (const dup of possibleDuplicates) { + // remove possible duplicate when module is not contained + if (!dup.containsModule(module)) { + possibleDuplicates.delete(dup); + } + } + // when all chunks has been removed we can break here + if (possibleDuplicates.size === 0) break; + } + } -class NodeTargetPlugin { - apply(compiler) { - new ExternalsPlugin("commonjs", builtins).apply(compiler); + // when we found duplicates + if ( + possibleDuplicates !== undefined && + possibleDuplicates.size > 0 + ) { + for (const otherChunk of possibleDuplicates) { + if (otherChunk.hasRuntime() !== chunk.hasRuntime()) continue; + // merge them + if (chunk.integrate(otherChunk, "duplicate")) { + chunks.splice(chunks.indexOf(otherChunk), 1); + } + } + } + + // don't check already processed chunks twice + notDuplicates.add(chunk); + } + } + ); + } + ); } } - -module.exports = NodeTargetPlugin; +module.exports = MergeDuplicateChunksPlugin; /***/ }), -/***/ 90010: +/***/ 55607: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -105160,36 +104247,87 @@ module.exports = NodeTargetPlugin; */ +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(8670); -const NodeMainTemplatePlugin = __webpack_require__(78597); -const NodeChunkTemplatePlugin = __webpack_require__(45249); -const NodeHotUpdateChunkTemplatePlugin = __webpack_require__(95909); +/** @typedef {import("../../declarations/plugins/optimize/MinChunkSizePlugin").MinChunkSizePluginOptions} MinChunkSizePluginOptions */ -class NodeTemplatePlugin { +class MinChunkSizePlugin { + /** + * @param {MinChunkSizePluginOptions} options options object + */ constructor(options) { - options = options || {}; - this.asyncChunkLoading = options.asyncChunkLoading; + validateOptions(schema, options, "Min Chunk Size Plugin"); + this.options = options; } apply(compiler) { - compiler.hooks.thisCompilation.tap("NodeTemplatePlugin", compilation => { - new NodeMainTemplatePlugin(this.asyncChunkLoading).apply( - compilation.mainTemplate - ); - new NodeChunkTemplatePlugin().apply(compilation.chunkTemplate); - new NodeHotUpdateChunkTemplatePlugin().apply( - compilation.hotUpdateChunkTemplate + const options = this.options; + const minChunkSize = options.minChunkSize; + compiler.hooks.compilation.tap("MinChunkSizePlugin", compilation => { + compilation.hooks.optimizeChunksAdvanced.tap( + "MinChunkSizePlugin", + chunks => { + const equalOptions = { + chunkOverhead: 1, + entryChunkMultiplicator: 1 + }; + + const sortedSizeFilteredExtendedPairCombinations = chunks + .reduce((combinations, a, idx) => { + // create combination pairs + for (let i = 0; i < idx; i++) { + const b = chunks[i]; + combinations.push([b, a]); + } + return combinations; + }, []) + .filter(pair => { + // check if one of the chunks sizes is smaller than the minChunkSize + const p0SmallerThanMinChunkSize = + pair[0].size(equalOptions) < minChunkSize; + const p1SmallerThanMinChunkSize = + pair[1].size(equalOptions) < minChunkSize; + return p0SmallerThanMinChunkSize || p1SmallerThanMinChunkSize; + }) + .map(pair => { + // extend combination pairs with size and integrated size + const a = pair[0].size(options); + const b = pair[1].size(options); + const ab = pair[0].integratedSize(pair[1], options); + return [a + b - ab, ab, pair[0], pair[1]]; + }) + .filter(pair => { + // filter pairs that do not have an integratedSize + // meaning they can NOT be integrated! + return pair[1] !== false; + }) + .sort((a, b) => { + // sadly javascript does an inplace sort here + // sort by size + const diff = b[0] - a[0]; + if (diff !== 0) return diff; + return a[1] - b[1]; + }); + + if (sortedSizeFilteredExtendedPairCombinations.length === 0) return; + + const pair = sortedSizeFilteredExtendedPairCombinations[0]; + + pair[2].integrate(pair[3], "min-size"); + chunks.splice(chunks.indexOf(pair[3]), 1); + return true; + } ); }); } } - -module.exports = NodeTemplatePlugin; +module.exports = MinChunkSizePlugin; /***/ }), -/***/ 71610: +/***/ 25472: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -105199,183 +104337,34 @@ module.exports = NodeTemplatePlugin; */ -const Watchpack = __webpack_require__(77056); -const objectToMap = __webpack_require__(1111); +const WebpackError = __webpack_require__(97391); +const SizeFormatHelpers = __webpack_require__(12496); -class NodeWatchFileSystem { - constructor(inputFileSystem) { - this.inputFileSystem = inputFileSystem; - this.watcherOptions = { - aggregateTimeout: 0 - }; - this.watcher = new Watchpack(this.watcherOptions); +class MinMaxSizeWarning extends WebpackError { + constructor(keys, minSize, maxSize) { + let keysMessage = "Fallback cache group"; + if (keys) { + keysMessage = + keys.length > 1 + ? `Cache groups ${keys.sort().join(", ")}` + : `Cache group ${keys[0]}`; + } + super( + `SplitChunksPlugin\n` + + `${keysMessage}\n` + + `Configured minSize (${SizeFormatHelpers.formatSize(minSize)}) is ` + + `bigger than maxSize (${SizeFormatHelpers.formatSize(maxSize)}).\n` + + "This seem to be a invalid optimiziation.splitChunks configuration." + ); } +} - watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { - if (!Array.isArray(files)) { - throw new Error("Invalid arguments: 'files'"); - } - if (!Array.isArray(dirs)) { - throw new Error("Invalid arguments: 'dirs'"); - } - if (!Array.isArray(missing)) { - throw new Error("Invalid arguments: 'missing'"); - } - if (typeof callback !== "function") { - throw new Error("Invalid arguments: 'callback'"); - } - if (typeof startTime !== "number" && startTime) { - throw new Error("Invalid arguments: 'startTime'"); - } - if (typeof options !== "object") { - throw new Error("Invalid arguments: 'options'"); - } - if (typeof callbackUndelayed !== "function" && callbackUndelayed) { - throw new Error("Invalid arguments: 'callbackUndelayed'"); - } - const oldWatcher = this.watcher; - this.watcher = new Watchpack(options); +module.exports = MinMaxSizeWarning; - if (callbackUndelayed) { - this.watcher.once("change", callbackUndelayed); - } - const cachedFiles = files; - const cachedDirs = dirs; - this.watcher.once("aggregated", (changes, removals) => { - changes = changes.concat(removals); - if (this.inputFileSystem && this.inputFileSystem.purge) { - this.inputFileSystem.purge(changes); - } - const times = objectToMap(this.watcher.getTimes()); - files = new Set(files); - dirs = new Set(dirs); - missing = new Set(missing); - removals = new Set(removals.filter(file => files.has(file))); - callback( - null, - changes.filter(file => files.has(file)).sort(), - changes.filter(file => dirs.has(file)).sort(), - changes.filter(file => missing.has(file)).sort(), - times, - times, - removals - ); - }); - this.watcher.watch( - cachedFiles.concat(missing), - cachedDirs.concat(missing), - startTime - ); +/***/ }), - if (oldWatcher) { - oldWatcher.close(); - } - return { - close: () => { - if (this.watcher) { - this.watcher.close(); - this.watcher = null; - } - }, - pause: () => { - if (this.watcher) { - this.watcher.pause(); - } - }, - getFileTimestamps: () => { - if (this.watcher) { - return objectToMap(this.watcher.getTimes()); - } else { - return new Map(); - } - }, - getContextTimestamps: () => { - if (this.watcher) { - return objectToMap(this.watcher.getTimes()); - } else { - return new Map(); - } - } - }; - } -} - -module.exports = NodeWatchFileSystem; - - -/***/ }), - -/***/ 73839: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const Template = __webpack_require__(96066); -const WasmMainTemplatePlugin = __webpack_require__(65331); - -class ReadFileCompileWasmTemplatePlugin { - constructor(options) { - this.options = options || {}; - } - - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "ReadFileCompileWasmTemplatePlugin", - compilation => { - const generateLoadBinaryCode = path => - Template.asString([ - "new Promise(function (resolve, reject) {", - Template.indent([ - "var { readFile } = require('fs');", - "var { join } = require('path');", - "", - "try {", - Template.indent([ - `readFile(join(__dirname, ${path}), function(err, buffer){`, - Template.indent([ - "if (err) return reject(err);", - "", - "// Fake fetch response", - "resolve({", - Template.indent([ - "arrayBuffer() { return Promise.resolve(buffer); }" - ]), - "});" - ]), - "});" - ]), - "} catch (err) { reject(err); }" - ]), - "})" - ]); - - const plugin = new WasmMainTemplatePlugin( - Object.assign( - { - generateLoadBinaryCode, - supportsStreaming: false - }, - this.options - ) - ); - plugin.apply(compilation.mainTemplate); - } - ); - } -} - -module.exports = ReadFileCompileWasmTemplatePlugin; - - -/***/ }), - -/***/ 7886: +/***/ 45184: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -105385,537 +104374,490 @@ module.exports = ReadFileCompileWasmTemplatePlugin; */ +const HarmonyImportDependency = __webpack_require__(81599); +const ModuleHotAcceptDependency = __webpack_require__(29018); +const ModuleHotDeclineDependency = __webpack_require__(60482); +const ConcatenatedModule = __webpack_require__(16953); +const HarmonyCompatibilityDependency = __webpack_require__(1533); +const StackedSetMap = __webpack_require__(92251); -const truncateArgs = __webpack_require__(62299); -const util = __webpack_require__(31669); - -const tty = process.stderr.isTTY && process.env.TERM !== "dumb"; - -let currentStatusMessage = undefined; -let hasStatusMessage = false; -let currentIndent = ""; -let currentCollapsed = 0; - -const indent = (str, prefix, colorPrefix, colorSuffix) => { - if (str === "") return str; - prefix = currentIndent + prefix; - if (tty) { - return ( - prefix + - colorPrefix + - str.replace(/\n/g, colorSuffix + "\n" + prefix + colorPrefix) + - colorSuffix - ); - } else { - return prefix + str.replace(/\n/g, "\n" + prefix); - } +const formatBailoutReason = msg => { + return "ModuleConcatenation bailout: " + msg; }; -const clearStatusMessage = () => { - if (hasStatusMessage) { - process.stderr.write("\x1b[2K\r"); - hasStatusMessage = false; +class ModuleConcatenationPlugin { + constructor(options) { + if (typeof options !== "object") options = {}; + this.options = options; } -}; -const writeStatusMessage = () => { - if (!currentStatusMessage) return; - const l = process.stderr.columns; - const args = l - ? truncateArgs(currentStatusMessage, l - 1) - : currentStatusMessage; - const str = args.join(" "); - const coloredStr = `\u001b[1m${str}\u001b[39m\u001b[22m`; - process.stderr.write(`\x1b[2K\r${coloredStr}`); - hasStatusMessage = true; -}; + apply(compiler) { + compiler.hooks.compilation.tap( + "ModuleConcatenationPlugin", + (compilation, { normalModuleFactory }) => { + const handler = (parser, parserOptions) => { + parser.hooks.call.for("eval").tap("ModuleConcatenationPlugin", () => { + // Because of variable renaming we can't use modules with eval. + parser.state.module.buildMeta.moduleConcatenationBailout = "eval()"; + }); + }; -const writeColored = (prefix, colorPrefix, colorSuffix) => { - return (...args) => { - if (currentCollapsed > 0) return; - clearStatusMessage(); - // @ts-ignore - const str = indent(util.format(...args), prefix, colorPrefix, colorSuffix); - process.stderr.write(str + "\n"); - writeStatusMessage(); - }; -}; + normalModuleFactory.hooks.parser + .for("javascript/auto") + .tap("ModuleConcatenationPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/dynamic") + .tap("ModuleConcatenationPlugin", handler); + normalModuleFactory.hooks.parser + .for("javascript/esm") + .tap("ModuleConcatenationPlugin", handler); -const writeGroupMessage = writeColored( - "<-> ", - "\u001b[1m\u001b[36m", - "\u001b[39m\u001b[22m" -); + const bailoutReasonMap = new Map(); -const writeGroupCollapsedMessage = writeColored( - "<+> ", - "\u001b[1m\u001b[36m", - "\u001b[39m\u001b[22m" -); + const setBailoutReason = (module, reason) => { + bailoutReasonMap.set(module, reason); + module.optimizationBailout.push( + typeof reason === "function" + ? rs => formatBailoutReason(reason(rs)) + : formatBailoutReason(reason) + ); + }; -module.exports = { - log: writeColored(" ", "\u001b[1m", "\u001b[22m"), - debug: writeColored(" ", "", ""), - trace: writeColored(" ", "", ""), - info: writeColored(" ", "\u001b[1m\u001b[32m", "\u001b[39m\u001b[22m"), - warn: writeColored(" ", "\u001b[1m\u001b[33m", "\u001b[39m\u001b[22m"), - error: writeColored(" ", "\u001b[1m\u001b[31m", "\u001b[39m\u001b[22m"), - logTime: writeColored(" ", "\u001b[1m\u001b[35m", "\u001b[39m\u001b[22m"), - group: (...args) => { - writeGroupMessage(...args); - if (currentCollapsed > 0) { - currentCollapsed++; - } else { - currentIndent += " "; - } - }, - groupCollapsed: (...args) => { - writeGroupCollapsedMessage(...args); - currentCollapsed++; - }, - groupEnd: () => { - if (currentCollapsed > 0) currentCollapsed--; - else if (currentIndent.length >= 2) - currentIndent = currentIndent.slice(0, currentIndent.length - 2); - }, - // eslint-disable-next-line node/no-unsupported-features/node-builtins - profile: console.profile && (name => console.profile(name)), - // eslint-disable-next-line node/no-unsupported-features/node-builtins - profileEnd: console.profileEnd && (name => console.profileEnd(name)), - clear: - tty && - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.clear && - (() => { - clearStatusMessage(); - // eslint-disable-next-line node/no-unsupported-features/node-builtins - console.clear(); - writeStatusMessage(); - }), - status: tty - ? (name, ...args) => { - args = args.filter(Boolean); - if (name === undefined && args.length === 0) { - clearStatusMessage(); - currentStatusMessage = undefined; - } else if ( - typeof name === "string" && - name.startsWith("[webpack.Progress] ") - ) { - currentStatusMessage = [name.slice(19), ...args]; - writeStatusMessage(); - } else if (name === "[webpack.Progress]") { - currentStatusMessage = [...args]; - writeStatusMessage(); - } else { - currentStatusMessage = [name, ...args]; - writeStatusMessage(); - } - } - : writeColored(" ", "", "") -}; + const getBailoutReason = (module, requestShortener) => { + const reason = bailoutReasonMap.get(module); + if (typeof reason === "function") return reason(requestShortener); + return reason; + }; + compilation.hooks.optimizeChunkModules.tap( + "ModuleConcatenationPlugin", + (allChunks, modules) => { + const relevantModules = []; + const possibleInners = new Set(); + for (const module of modules) { + // Only harmony modules are valid for optimization + if ( + !module.buildMeta || + module.buildMeta.exportsType !== "namespace" || + !module.dependencies.some( + d => d instanceof HarmonyCompatibilityDependency + ) + ) { + setBailoutReason(module, "Module is not an ECMAScript module"); + continue; + } -/***/ }), + // Some expressions are not compatible with module concatenation + // because they may produce unexpected results. The plugin bails out + // if some were detected upfront. + if ( + module.buildMeta && + module.buildMeta.moduleConcatenationBailout + ) { + setBailoutReason( + module, + `Module uses ${module.buildMeta.moduleConcatenationBailout}` + ); + continue; + } -/***/ 88197: -/***/ (function(module) { + // Exports must be known (and not dynamic) + if (!Array.isArray(module.buildMeta.providedExports)) { + setBailoutReason(module, "Module exports are unknown"); + continue; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // Using dependency variables is not possible as this wraps the code in a function + if (module.variables.length > 0) { + setBailoutReason( + module, + `Module uses injected variables (${module.variables + .map(v => v.name) + .join(", ")})` + ); + continue; + } + // Hot Module Replacement need it's own module to work correctly + if ( + module.dependencies.some( + dep => + dep instanceof ModuleHotAcceptDependency || + dep instanceof ModuleHotDeclineDependency + ) + ) { + setBailoutReason(module, "Module uses Hot Module Replacement"); + continue; + } -class AggressiveMergingPlugin { - constructor(options) { - if ( - (options !== undefined && typeof options !== "object") || - Array.isArray(options) - ) { - throw new Error( - "Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.js.org/plugins/" - ); - } - this.options = options || {}; - } + relevantModules.push(module); - apply(compiler) { - const options = this.options; - const minSizeReduce = options.minSizeReduce || 1.5; + // Module must not be the entry points + if (module.isEntryModule()) { + setBailoutReason(module, "Module is an entry point"); + continue; + } - compiler.hooks.thisCompilation.tap( - "AggressiveMergingPlugin", - compilation => { - compilation.hooks.optimizeChunksAdvanced.tap( - "AggressiveMergingPlugin", - chunks => { - let combinations = []; - chunks.forEach((a, idx) => { - if (a.canBeInitial()) return; - for (let i = 0; i < idx; i++) { - const b = chunks[i]; - if (b.canBeInitial()) continue; - combinations.push({ - a, - b, - improvement: undefined - }); + // Module must be in any chunk (we don't want to do useless work) + if (module.getNumberOfChunks() === 0) { + setBailoutReason(module, "Module is not in any chunk"); + continue; } - }); - for (const pair of combinations) { - const a = pair.b.size({ - chunkOverhead: 0 - }); - const b = pair.a.size({ - chunkOverhead: 0 - }); - const ab = pair.b.integratedSize(pair.a, { - chunkOverhead: 0 - }); - let newSize; - if (ab === false) { - pair.improvement = false; - return; - } else { - newSize = ab; + // Module must only be used by Harmony Imports + const nonHarmonyReasons = module.reasons.filter( + reason => + !reason.dependency || + !(reason.dependency instanceof HarmonyImportDependency) + ); + if (nonHarmonyReasons.length > 0) { + const importingModules = new Set( + nonHarmonyReasons.map(r => r.module).filter(Boolean) + ); + const importingExplanations = new Set( + nonHarmonyReasons.map(r => r.explanation).filter(Boolean) + ); + const importingModuleTypes = new Map( + Array.from(importingModules).map( + m => /** @type {[string, Set]} */ ([ + m, + new Set( + nonHarmonyReasons + .filter(r => r.module === m) + .map(r => r.dependency.type) + .sort() + ) + ]) + ) + ); + setBailoutReason(module, requestShortener => { + const names = Array.from(importingModules) + .map( + m => + `${m.readableIdentifier( + requestShortener + )} (referenced with ${Array.from( + importingModuleTypes.get(m) + ).join(", ")})` + ) + .sort(); + const explanations = Array.from(importingExplanations).sort(); + if (names.length > 0 && explanations.length === 0) { + return `Module is referenced from these modules with unsupported syntax: ${names.join( + ", " + )}`; + } else if (names.length === 0 && explanations.length > 0) { + return `Module is referenced by: ${explanations.join( + ", " + )}`; + } else if (names.length > 0 && explanations.length > 0) { + return `Module is referenced from these modules with unsupported syntax: ${names.join( + ", " + )} and by: ${explanations.join(", ")}`; + } else { + return "Module is referenced in a unsupported way"; + } + }); + continue; } - pair.improvement = (a + b) / newSize; + possibleInners.add(module); } - combinations = combinations.filter(pair => { - return pair.improvement !== false; - }); - combinations.sort((a, b) => { - return b.improvement - a.improvement; + // sort by depth + // modules with lower depth are more likely suited as roots + // this improves performance, because modules already selected as inner are skipped + relevantModules.sort((a, b) => { + return a.depth - b.depth; }); + const concatConfigurations = []; + const usedAsInner = new Set(); + for (const currentRoot of relevantModules) { + // when used by another configuration as inner: + // the other configuration is better and we can skip this one + if (usedAsInner.has(currentRoot)) continue; - const pair = combinations[0]; + // create a configuration with the root + const currentConfiguration = new ConcatConfiguration(currentRoot); - if (!pair) return; - if (pair.improvement < minSizeReduce) return; + // cache failures to add modules + const failureCache = new Map(); - if (pair.b.integrate(pair.a, "aggressive-merge")) { - chunks.splice(chunks.indexOf(pair.a), 1); - return true; + // try to add all imports + for (const imp of this._getImports(compilation, currentRoot)) { + const problem = this._tryToAdd( + compilation, + currentConfiguration, + imp, + possibleInners, + failureCache + ); + if (problem) { + failureCache.set(imp, problem); + currentConfiguration.addWarning(imp, problem); + } + } + if (!currentConfiguration.isEmpty()) { + concatConfigurations.push(currentConfiguration); + for (const module of currentConfiguration.getModules()) { + if (module !== currentConfiguration.rootModule) { + usedAsInner.add(module); + } + } + } } - } - ); - } - ); - } -} - -module.exports = AggressiveMergingPlugin; - - -/***/ }), - -/***/ 26688: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const identifierUtils = __webpack_require__(94658); -const { intersect } = __webpack_require__(54262); -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(71884); - -/** @typedef {import("../../declarations/plugins/optimize/AggressiveSplittingPlugin").AggressiveSplittingPluginOptions} AggressiveSplittingPluginOptions */ - -const moveModuleBetween = (oldChunk, newChunk) => { - return module => { - oldChunk.moveModule(module, newChunk); - }; -}; + // HACK: Sort configurations by length and start with the longest one + // to get the biggers groups possible. Used modules are marked with usedModules + // TODO: Allow to reuse existing configuration while trying to add dependencies. + // This would improve performance. O(n^2) -> O(n) + concatConfigurations.sort((a, b) => { + return b.modules.size - a.modules.size; + }); + const usedModules = new Set(); + for (const concatConfiguration of concatConfigurations) { + if (usedModules.has(concatConfiguration.rootModule)) continue; + const modules = concatConfiguration.getModules(); + const rootModule = concatConfiguration.rootModule; + const newModule = new ConcatenatedModule( + rootModule, + Array.from(modules), + ConcatenatedModule.createConcatenationList( + rootModule, + modules, + compilation + ) + ); + for (const warning of concatConfiguration.getWarningsSorted()) { + newModule.optimizationBailout.push(requestShortener => { + const reason = getBailoutReason(warning[0], requestShortener); + const reasonWithPrefix = reason ? ` (<- ${reason})` : ""; + if (warning[0] === warning[1]) { + return formatBailoutReason( + `Cannot concat with ${warning[0].readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + } else { + return formatBailoutReason( + `Cannot concat with ${warning[0].readableIdentifier( + requestShortener + )} because of ${warning[1].readableIdentifier( + requestShortener + )}${reasonWithPrefix}` + ); + } + }); + } + const chunks = concatConfiguration.rootModule.getChunks(); + for (const m of modules) { + usedModules.add(m); + for (const chunk of chunks) { + chunk.removeModule(m); + } + } + for (const chunk of chunks) { + chunk.addModule(newModule); + newModule.addChunk(chunk); + } + for (const chunk of allChunks) { + if (chunk.entryModule === concatConfiguration.rootModule) { + chunk.entryModule = newModule; + } + } + compilation.modules.push(newModule); + for (const reason of newModule.reasons) { + if (reason.dependency.module === concatConfiguration.rootModule) + reason.dependency.module = newModule; + if ( + reason.dependency.redirectedModule === + concatConfiguration.rootModule + ) + reason.dependency.redirectedModule = newModule; + } + // TODO: remove when LTS node version contains fixed v8 version + // @see https://github.com/webpack/webpack/pull/6613 + // Turbofan does not correctly inline for-of loops with polymorphic input arrays. + // Work around issue by using a standard for loop and assigning dep.module.reasons + for (let i = 0; i < newModule.dependencies.length; i++) { + let dep = newModule.dependencies[i]; + if (dep.module) { + let reasons = dep.module.reasons; + for (let j = 0; j < reasons.length; j++) { + let reason = reasons[j]; + if (reason.dependency === dep) { + reason.module = newModule; + } + } + } + } + } + compilation.modules = compilation.modules.filter( + m => !usedModules.has(m) + ); + } + ); + } + ); + } -const isNotAEntryModule = entryModule => { - return module => { - return entryModule !== module; - }; -}; + _getImports(compilation, module) { + return new Set( + module.dependencies -class AggressiveSplittingPlugin { - /** - * @param {AggressiveSplittingPluginOptions=} options options object - */ - constructor(options) { - if (!options) options = {}; + // Get reference info only for harmony Dependencies + .map(dep => { + if (!(dep instanceof HarmonyImportDependency)) return null; + if (!compilation) return dep.getReference(); + return compilation.getDependencyReference(module, dep); + }) - validateOptions(schema, options, "Aggressive Splitting Plugin"); + // Reference is valid and has a module + // Dependencies are simple enough to concat them + .filter( + ref => + ref && + ref.module && + (Array.isArray(ref.importedNames) || + Array.isArray(ref.module.buildMeta.providedExports)) + ) - this.options = options; - if (typeof this.options.minSize !== "number") { - this.options.minSize = 30 * 1024; - } - if (typeof this.options.maxSize !== "number") { - this.options.maxSize = 50 * 1024; - } - if (typeof this.options.chunkOverhead !== "number") { - this.options.chunkOverhead = 0; - } - if (typeof this.options.entryChunkMultiplicator !== "number") { - this.options.entryChunkMultiplicator = 1; - } + // Take the imported module + .map(ref => ref.module) + ); } - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "AggressiveSplittingPlugin", - compilation => { - let needAdditionalSeal = false; - let newSplits; - let fromAggressiveSplittingSet; - let chunkSplitDataMap; - compilation.hooks.optimize.tap("AggressiveSplittingPlugin", () => { - newSplits = []; - fromAggressiveSplittingSet = new Set(); - chunkSplitDataMap = new Map(); - }); - compilation.hooks.optimizeChunksAdvanced.tap( - "AggressiveSplittingPlugin", - chunks => { - // Precompute stuff - const nameToModuleMap = new Map(); - const moduleToNameMap = new Map(); - for (const m of compilation.modules) { - const name = identifierUtils.makePathsRelative( - compiler.context, - m.identifier(), - compilation.cache - ); - nameToModuleMap.set(name, m); - moduleToNameMap.set(m, name); - } - - // Check used chunk ids - const usedIds = new Set(); - for (const chunk of chunks) { - usedIds.add(chunk.id); - } - const recordedSplits = - (compilation.records && compilation.records.aggressiveSplits) || - []; - const usedSplits = newSplits - ? recordedSplits.concat(newSplits) - : recordedSplits; + _tryToAdd(compilation, config, module, possibleModules, failureCache) { + const cacheEntry = failureCache.get(module); + if (cacheEntry) { + return cacheEntry; + } - const minSize = this.options.minSize; - const maxSize = this.options.maxSize; + // Already added? + if (config.has(module)) { + return null; + } - const applySplit = splitData => { - // Cannot split if id is already taken - if (splitData.id !== undefined && usedIds.has(splitData.id)) { - return false; - } + // Not possible to add? + if (!possibleModules.has(module)) { + failureCache.set(module, module); // cache failures for performance + return module; + } - // Get module objects from names - const selectedModules = splitData.modules.map(name => - nameToModuleMap.get(name) - ); + // module must be in the same chunks + if (!config.rootModule.hasEqualsChunks(module)) { + failureCache.set(module, module); // cache failures for performance + return module; + } - // Does the modules exist at all? - if (!selectedModules.every(Boolean)) return false; + // Clone config to make experimental changes + const testConfig = config.clone(); - // Check if size matches (faster than waiting for hash) - const size = selectedModules.reduce( - (sum, m) => sum + m.size(), - 0 - ); - if (size !== splitData.size) return false; + // Add the module + testConfig.add(module); - // get chunks with all modules - const selectedChunks = intersect( - selectedModules.map(m => new Set(m.chunksIterable)) - ); + // Every module which depends on the added module must be in the configuration too. + for (const reason of module.reasons) { + // Modules that are not used can be ignored + if ( + reason.module.factoryMeta.sideEffectFree && + reason.module.used === false + ) + continue; - // No relevant chunks found - if (selectedChunks.size === 0) return false; + const problem = this._tryToAdd( + compilation, + testConfig, + reason.module, + possibleModules, + failureCache + ); + if (problem) { + failureCache.set(module, problem); // cache failures for performance + return problem; + } + } - // The found chunk is already the split or similar - if ( - selectedChunks.size === 1 && - Array.from(selectedChunks)[0].getNumberOfModules() === - selectedModules.length - ) { - const chunk = Array.from(selectedChunks)[0]; - if (fromAggressiveSplittingSet.has(chunk)) return false; - fromAggressiveSplittingSet.add(chunk); - chunkSplitDataMap.set(chunk, splitData); - return true; - } + // Commit experimental changes + config.set(testConfig); - // split the chunk into two parts - const newChunk = compilation.addChunk(); - newChunk.chunkReason = "aggressive splitted"; - for (const chunk of selectedChunks) { - selectedModules.forEach(moveModuleBetween(chunk, newChunk)); - chunk.split(newChunk); - chunk.name = null; - } - fromAggressiveSplittingSet.add(newChunk); - chunkSplitDataMap.set(newChunk, splitData); + // Eagerly try to add imports too if possible + for (const imp of this._getImports(compilation, module)) { + const problem = this._tryToAdd( + compilation, + config, + imp, + possibleModules, + failureCache + ); + if (problem) { + config.addWarning(imp, problem); + } + } + return null; + } +} - if (splitData.id !== null && splitData.id !== undefined) { - newChunk.id = splitData.id; - } - return true; - }; +class ConcatConfiguration { + constructor(rootModule, cloneFrom) { + this.rootModule = rootModule; + if (cloneFrom) { + this.modules = cloneFrom.modules.createChild(5); + this.warnings = cloneFrom.warnings.createChild(5); + } else { + this.modules = new StackedSetMap(); + this.modules.add(rootModule); + this.warnings = new StackedSetMap(); + } + } - // try to restore to recorded splitting - let changed = false; - for (let j = 0; j < usedSplits.length; j++) { - const splitData = usedSplits[j]; - if (applySplit(splitData)) changed = true; - } + add(module) { + this.modules.add(module); + } - // for any chunk which isn't splitted yet, split it and create a new entry - // start with the biggest chunk - const sortedChunks = chunks.slice().sort((a, b) => { - const diff1 = b.modulesSize() - a.modulesSize(); - if (diff1) return diff1; - const diff2 = a.getNumberOfModules() - b.getNumberOfModules(); - if (diff2) return diff2; - const modulesA = Array.from(a.modulesIterable); - const modulesB = Array.from(b.modulesIterable); - modulesA.sort(); - modulesB.sort(); - const aI = modulesA[Symbol.iterator](); - const bI = modulesB[Symbol.iterator](); - // eslint-disable-next-line no-constant-condition - while (true) { - const aItem = aI.next(); - const bItem = bI.next(); - if (aItem.done) return 0; - const aModuleIdentifier = aItem.value.identifier(); - const bModuleIdentifier = bItem.value.identifier(); - if (aModuleIdentifier > bModuleIdentifier) return -1; - if (aModuleIdentifier < bModuleIdentifier) return 1; - } - }); - for (const chunk of sortedChunks) { - if (fromAggressiveSplittingSet.has(chunk)) continue; - const size = chunk.modulesSize(); - if (size > maxSize && chunk.getNumberOfModules() > 1) { - const modules = chunk - .getModules() - .filter(isNotAEntryModule(chunk.entryModule)) - .sort((a, b) => { - a = a.identifier(); - b = b.identifier(); - if (a > b) return 1; - if (a < b) return -1; - return 0; - }); - const selectedModules = []; - let selectedModulesSize = 0; - for (let k = 0; k < modules.length; k++) { - const module = modules[k]; - const newSize = selectedModulesSize + module.size(); - if (newSize > maxSize && selectedModulesSize >= minSize) { - break; - } - selectedModulesSize = newSize; - selectedModules.push(module); - } - if (selectedModules.length === 0) continue; - const splitData = { - modules: selectedModules - .map(m => moduleToNameMap.get(m)) - .sort(), - size: selectedModulesSize - }; + has(module) { + return this.modules.has(module); + } - if (applySplit(splitData)) { - newSplits = (newSplits || []).concat(splitData); - changed = true; - } - } - } - if (changed) return true; - } - ); - compilation.hooks.recordHash.tap( - "AggressiveSplittingPlugin", - records => { - // 4. save made splittings to records - const allSplits = new Set(); - const invalidSplits = new Set(); + isEmpty() { + return this.modules.size === 1; + } - // Check if some splittings are invalid - // We remove invalid splittings and try again - for (const chunk of compilation.chunks) { - const splitData = chunkSplitDataMap.get(chunk); - if (splitData !== undefined) { - if (splitData.hash && chunk.hash !== splitData.hash) { - // Split was successful, but hash doesn't equal - // We can throw away the split since it's useless now - invalidSplits.add(splitData); - } - } - } + addWarning(module, problem) { + this.warnings.set(module, problem); + } - if (invalidSplits.size > 0) { - records.aggressiveSplits = records.aggressiveSplits.filter( - splitData => !invalidSplits.has(splitData) - ); - needAdditionalSeal = true; - } else { - // set hash and id values on all (new) splittings - for (const chunk of compilation.chunks) { - const splitData = chunkSplitDataMap.get(chunk); - if (splitData !== undefined) { - splitData.hash = chunk.hash; - splitData.id = chunk.id; - allSplits.add(splitData); - // set flag for stats - chunk.recorded = true; - } - } + getWarningsSorted() { + return new Map( + this.warnings.asPairArray().sort((a, b) => { + const ai = a[0].identifier(); + const bi = b[0].identifier(); + if (ai < bi) return -1; + if (ai > bi) return 1; + return 0; + }) + ); + } - // Also add all unused historial splits (after the used ones) - // They can still be used in some future compilation - const recordedSplits = - compilation.records && compilation.records.aggressiveSplits; - if (recordedSplits) { - for (const splitData of recordedSplits) { - if (!invalidSplits.has(splitData)) allSplits.add(splitData); - } - } + getModules() { + return this.modules.asSet(); + } - // record all splits - records.aggressiveSplits = Array.from(allSplits); + clone() { + return new ConcatConfiguration(this.rootModule, this); + } - needAdditionalSeal = false; - } - } - ); - compilation.hooks.needAdditionalSeal.tap( - "AggressiveSplittingPlugin", - () => { - if (needAdditionalSeal) { - needAdditionalSeal = false; - return true; - } - } - ); - } - ); + set(config) { + this.rootModule = config.rootModule; + this.modules = config.modules; + this.warnings = config.warnings; } } -module.exports = AggressiveSplittingPlugin; + +module.exports = ModuleConcatenationPlugin; /***/ }), -/***/ 30346: +/***/ 68053: /***/ (function(module) { "use strict"; @@ -105925,71 +104867,46 @@ module.exports = AggressiveSplittingPlugin; */ -const sortByIndex = (a, b) => { - return a.index - b.index; -}; - -const sortByIndex2 = (a, b) => { - return a.index2 - b.index2; -}; - -class ChunkModuleIdRangePlugin { - constructor(options) { - this.options = options; - } +/** @typedef {import("../Compiler")} Compiler */ - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => { - compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => { - const chunk = compilation.chunks.find( - chunk => chunk.name === options.name - ); - if (!chunk) { - throw new Error( - `ChunkModuleIdRangePlugin: Chunk with name '${options.name}"' was not found` - ); - } - - let chunkModules; - if (options.order) { - chunkModules = Array.from(chunk.modulesIterable); - switch (options.order) { - case "index": - chunkModules.sort(sortByIndex); - break; - case "index2": - chunkModules.sort(sortByIndex2); - break; - default: - throw new Error( - "ChunkModuleIdRangePlugin: unexpected value of order" - ); - } - } else { - chunkModules = modules.filter(m => { - return m.chunksIterable.has(chunk); +class NaturalChunkOrderPlugin { + /** + * @param {Compiler} compiler webpack compiler + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap("NaturalChunkOrderPlugin", compilation => { + compilation.hooks.optimizeChunkOrder.tap( + "NaturalChunkOrderPlugin", + chunks => { + chunks.sort((chunkA, chunkB) => { + const a = chunkA.modulesIterable[Symbol.iterator](); + const b = chunkB.modulesIterable[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = a.next(); + const bItem = b.next(); + if (aItem.done && bItem.done) return 0; + if (aItem.done) return -1; + if (bItem.done) return 1; + const aModuleId = aItem.value.id; + const bModuleId = bItem.value.id; + if (aModuleId < bModuleId) return -1; + if (aModuleId > bModuleId) return 1; + } }); } - - let currentId = options.start || 0; - for (let i = 0; i < chunkModules.length; i++) { - const m = chunkModules[i]; - if (m.id === null) { - m.id = currentId++; - } - if (options.end && currentId > options.end) break; - } - }); + ); }); } } -module.exports = ChunkModuleIdRangePlugin; + +module.exports = NaturalChunkOrderPlugin; /***/ }), -/***/ 16953: +/***/ 83741: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -105999,2662 +104916,2440 @@ module.exports = ChunkModuleIdRangePlugin; */ -const Module = __webpack_require__(75993); -const Template = __webpack_require__(96066); -const Parser = __webpack_require__(70558); -const eslintScope = __webpack_require__(41632); -const { ConcatSource, ReplaceSource } = __webpack_require__(53665); -const DependencyReference = __webpack_require__(71722); -const HarmonyImportDependency = __webpack_require__(81599); -const HarmonyImportSideEffectDependency = __webpack_require__(79171); -const HarmonyImportSpecifierDependency = __webpack_require__(95966); -const HarmonyExportSpecifierDependency = __webpack_require__(34834); -const HarmonyExportExpressionDependency = __webpack_require__(84245); -const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); -const HarmonyCompatibilityDependency = __webpack_require__(1533); -const createHash = __webpack_require__(15660); +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(88771); -/** @typedef {import("../Dependency")} Dependency */ -/** @typedef {import("../Compilation")} Compilation */ -/** @typedef {import("../util/createHash").Hash} Hash */ -/** @typedef {import("../RequestShortener")} RequestShortener */ +/** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderChunkIdsPlugin").OccurrenceOrderChunkIdsPluginOptions} OccurrenceOrderChunkIdsPluginOptions */ -const joinIterableWithComma = iterable => { - // This is more performant than Array.from().join(", ") - // as it doesn't create an array - let str = ""; - let first = true; - for (const item of iterable) { - if (first) { - first = false; - } else { - str += ", "; - } - str += item; +class OccurrenceOrderChunkIdsPlugin { + /** + * @param {OccurrenceOrderChunkIdsPluginOptions=} options options object + */ + constructor(options = {}) { + validateOptions(schema, options, "Occurrence Order Chunk Ids Plugin"); + this.options = options; } - return str; -}; -/** - * @typedef {Object} ConcatenationEntry - * @property {"concatenated" | "external"} type - * @property {Module} module - */ + apply(compiler) { + const prioritiseInitial = this.options.prioritiseInitial; + compiler.hooks.compilation.tap( + "OccurrenceOrderChunkIdsPlugin", + compilation => { + compilation.hooks.optimizeChunkOrder.tap( + "OccurrenceOrderChunkIdsPlugin", + chunks => { + const occursInInitialChunksMap = new Map(); + const originalOrder = new Map(); -const ensureNsObjSource = ( - info, - moduleToInfoMap, - requestShortener, - strictHarmonyModule -) => { - if (!info.hasNamespaceObject) { - info.hasNamespaceObject = true; - const name = info.exportMap.get(true); - const nsObj = [`var ${name} = {};`, `__webpack_require__.r(${name});`]; - for (const exportName of info.module.buildMeta.providedExports) { - const finalName = getFinalName( - info, - exportName, - moduleToInfoMap, - requestShortener, - false, - strictHarmonyModule - ); - nsObj.push( - `__webpack_require__.d(${name}, ${JSON.stringify( - exportName - )}, function() { return ${finalName}; });` - ); - } - info.namespaceObjectSource = nsObj.join("\n") + "\n"; - } -}; + let i = 0; + for (const c of chunks) { + let occurs = 0; + for (const chunkGroup of c.groupsIterable) { + for (const parent of chunkGroup.parentsIterable) { + if (parent.isInitial()) occurs++; + } + } + occursInInitialChunksMap.set(c, occurs); + originalOrder.set(c, i++); + } -const getExternalImport = ( - importedModule, - info, - exportName, - asCall, - strictHarmonyModule -) => { - const used = importedModule.isUsed(exportName); - if (!used) return "/* unused reexport */undefined"; - const comment = - used !== exportName ? ` ${Template.toNormalComment(exportName)}` : ""; - switch (importedModule.buildMeta.exportsType) { - case "named": - if (exportName === "default") { - return info.name; - } else if (exportName === true) { - info.interopNamespaceObjectUsed = true; - return info.interopNamespaceObjectName; - } else { - break; - } - case "namespace": - if (exportName === true) { - return info.name; - } else { - break; - } - default: - if (strictHarmonyModule) { - if (exportName === "default") { - return info.name; - } else if (exportName === true) { - info.interopNamespaceObjectUsed = true; - return info.interopNamespaceObjectName; - } else { - return "/* non-default import from non-esm module */undefined"; - } - } else { - if (exportName === "default") { - info.interopDefaultAccessUsed = true; - return asCall - ? `${info.interopDefaultAccessName}()` - : `${info.interopDefaultAccessName}.a`; - } else if (exportName === true) { - return info.name; - } else { - break; - } + chunks.sort((a, b) => { + if (prioritiseInitial) { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + } + const aOccurs = a.getNumberOfGroups(); + const bOccurs = b.getNumberOfGroups(); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + const orgA = originalOrder.get(a); + const orgB = originalOrder.get(b); + return orgA - orgB; + }); + } + ); } + ); } - const reference = `${info.name}[${JSON.stringify(used)}${comment}]`; - if (asCall) return `Object(${reference})`; - return reference; -}; +} -const getFinalName = ( - info, - exportName, - moduleToInfoMap, - requestShortener, - asCall, - strictHarmonyModule, - alreadyVisited = new Set() -) => { - switch (info.type) { - case "concatenated": { - const directExport = info.exportMap.get(exportName); - if (directExport) { - if (exportName === true) { - ensureNsObjSource( - info, - moduleToInfoMap, - requestShortener, - strictHarmonyModule - ); - } else if (!info.module.isUsed(exportName)) { - return "/* unused export */ undefined"; - } - if (info.globalExports.has(directExport)) { - return directExport; - } - const name = info.internalNames.get(directExport); - if (!name) { - throw new Error( - `The export "${directExport}" in "${info.module.readableIdentifier( - requestShortener - )}" has no internal name` - ); - } - return name; - } - const reexport = info.reexportMap.get(exportName); - if (reexport) { - if (alreadyVisited.has(reexport)) { - throw new Error( - `Circular reexports ${Array.from( - alreadyVisited, - e => - `"${e.module.readableIdentifier(requestShortener)}".${ - e.exportName - }` - ).join( - " --> " - )} -(circular)-> "${reexport.module.readableIdentifier( - requestShortener - )}".${reexport.exportName}` - ); - } - alreadyVisited.add(reexport); - const refInfo = moduleToInfoMap.get(reexport.module); - if (refInfo) { - // module is in the concatenation - return getFinalName( - refInfo, - reexport.exportName, - moduleToInfoMap, - requestShortener, - asCall, - strictHarmonyModule, - alreadyVisited - ); - } - } - const problem = - `Cannot get final name for export "${exportName}" in "${info.module.readableIdentifier( - requestShortener - )}"` + - ` (known exports: ${Array.from(info.exportMap.keys()) - .filter(name => name !== true) - .join(" ")}, ` + - `known reexports: ${Array.from(info.reexportMap.keys()).join(" ")})`; - return `${Template.toNormalComment(problem)} undefined`; - } - case "external": { - const importedModule = info.module; - return getExternalImport( - importedModule, - info, - exportName, - asCall, - strictHarmonyModule - ); - } - } -}; +module.exports = OccurrenceOrderChunkIdsPlugin; -const addScopeSymbols1 = (s, nameSet, scopeSet) => { - let scope = s; - while (scope) { - if (scopeSet.has(scope)) break; - scopeSet.add(scope); - for (const variable of scope.variables) { - nameSet.add(variable.name); - } - scope = scope.upper; - } -}; -const addScopeSymbols2 = (s, nameSet, scopeSet1, scopeSet2) => { - let scope = s; - while (scope) { - if (scopeSet1.has(scope)) break; - if (scopeSet2.has(scope)) break; - scopeSet1.add(scope); - for (const variable of scope.variables) { - nameSet.add(variable.name); - } - scope = scope.upper; - } -}; +/***/ }), -const getAllReferences = variable => { - let set = variable.references; - // Look for inner scope variables too (like in class Foo { t() { Foo } }) - const identifiers = new Set(variable.identifiers); - for (const scope of variable.scope.childScopes) { - for (const innerVar of scope.variables) { - if (innerVar.identifiers.some(id => identifiers.has(id))) { - set = set.concat(innerVar.references); - break; - } - } - } - return set; -}; +/***/ 62000: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -const getPathInAst = (ast, node) => { - if (ast === node) { - return []; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const nr = node.range; - const enterNode = n => { - if (!n) return undefined; - const r = n.range; - if (r) { - if (r[0] <= nr[0] && r[1] >= nr[1]) { - const path = getPathInAst(n, node); - if (path) { - path.push(n); - return path; - } - } - } - return undefined; - }; +const validateOptions = __webpack_require__(33225); +const schema = __webpack_require__(81430); - var i; - if (Array.isArray(ast)) { - for (i = 0; i < ast.length; i++) { - const enterResult = enterNode(ast[i]); - if (enterResult !== undefined) return enterResult; - } - } else if (ast && typeof ast === "object") { - const keys = Object.keys(ast); - for (i = 0; i < keys.length; i++) { - const value = ast[keys[i]]; - if (Array.isArray(value)) { - const pathResult = getPathInAst(value, node); - if (pathResult !== undefined) return pathResult; - } else if (value && typeof value === "object") { - const enterResult = enterNode(value); - if (enterResult !== undefined) return enterResult; - } - } - } -}; +/** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderModuleIdsPlugin").OccurrenceOrderModuleIdsPluginOptions} OccurrenceOrderModuleIdsPluginOptions */ -const getHarmonyExportImportedSpecifierDependencyExports = dep => { - const importModule = dep._module; - if (!importModule) return []; - if (dep._id) { - // export { named } from "module" - return [ - { - name: dep.name, - id: dep._id, - module: importModule - } - ]; - } - if (dep.name) { - // export * as abc from "module" - return [ - { - name: dep.name, - id: true, - module: importModule - } - ]; +class OccurrenceOrderModuleIdsPlugin { + /** + * @param {OccurrenceOrderModuleIdsPluginOptions=} options options object + */ + constructor(options = {}) { + validateOptions(schema, options, "Occurrence Order Module Ids Plugin"); + this.options = options; } - // export * from "module" - return importModule.buildMeta.providedExports - .filter(exp => exp !== "default" && !dep.activeExports.has(exp)) - .map(exp => { - return { - name: exp, - id: exp, - module: importModule - }; - }); -}; -class ConcatenatedModule extends Module { - constructor(rootModule, modules, concatenationList) { - super("javascript/esm", null); - super.setChunks(rootModule._chunks); + apply(compiler) { + const prioritiseInitial = this.options.prioritiseInitial; + compiler.hooks.compilation.tap( + "OccurrenceOrderModuleIdsPlugin", + compilation => { + compilation.hooks.optimizeModuleOrder.tap( + "OccurrenceOrderModuleIdsPlugin", + modules => { + const occursInInitialChunksMap = new Map(); + const occursInAllChunksMap = new Map(); - // Info from Factory - this.rootModule = rootModule; - this.factoryMeta = rootModule.factoryMeta; + const initialChunkChunkMap = new Map(); + const entryCountMap = new Map(); + for (const m of modules) { + let initial = 0; + let entry = 0; + for (const c of m.chunksIterable) { + if (c.canBeInitial()) initial++; + if (c.entryModule === m) entry++; + } + initialChunkChunkMap.set(m, initial); + entryCountMap.set(m, entry); + } - // Info from Compilation - this.index = rootModule.index; - this.index2 = rootModule.index2; - this.depth = rootModule.depth; + const countOccursInEntry = (sum, r) => { + if (!r.module) { + return sum; + } + const count = initialChunkChunkMap.get(r.module); + if (!count) { + return sum; + } + return sum + count; + }; + const countOccurs = (sum, r) => { + if (!r.module) { + return sum; + } + let factor = 1; + if (typeof r.dependency.getNumberOfIdOccurrences === "function") { + factor = r.dependency.getNumberOfIdOccurrences(); + } + if (factor === 0) { + return sum; + } + return sum + factor * r.module.getNumberOfChunks(); + }; - // Info from Optimization - this.used = rootModule.used; - this.usedExports = rootModule.usedExports; - - // Info from Build - this.buildInfo = { - strict: true, - cacheable: modules.every(m => m.buildInfo.cacheable), - moduleArgument: rootModule.buildInfo.moduleArgument, - exportsArgument: rootModule.buildInfo.exportsArgument, - fileDependencies: new Set(), - contextDependencies: new Set(), - assets: undefined - }; - this.built = modules.some(m => m.built); - this.buildMeta = rootModule.buildMeta; + if (prioritiseInitial) { + for (const m of modules) { + const result = + m.reasons.reduce(countOccursInEntry, 0) + + initialChunkChunkMap.get(m) + + entryCountMap.get(m); + occursInInitialChunksMap.set(m, result); + } + } - // Caching - this._numberOfConcatenatedModules = modules.length; + const originalOrder = new Map(); + let i = 0; + for (const m of modules) { + const result = + m.reasons.reduce(countOccurs, 0) + + m.getNumberOfChunks() + + entryCountMap.get(m); + occursInAllChunksMap.set(m, result); + originalOrder.set(m, i++); + } - // Graph - const modulesSet = new Set(modules); - this.reasons = rootModule.reasons.filter( - reason => - !(reason.dependency instanceof HarmonyImportDependency) || - !modulesSet.has(reason.module) + modules.sort((a, b) => { + if (prioritiseInitial) { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + } + const aOccurs = occursInAllChunksMap.get(a); + const bOccurs = occursInAllChunksMap.get(b); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + const orgA = originalOrder.get(a); + const orgB = originalOrder.get(b); + return orgA - orgB; + }); + } + ); + } ); + } +} - this.dependencies = []; - this.blocks = []; +module.exports = OccurrenceOrderModuleIdsPlugin; - this.warnings = []; - this.errors = []; - this._orderedConcatenationList = - concatenationList || - ConcatenatedModule.createConcatenationList(rootModule, modulesSet, null); - for (const info of this._orderedConcatenationList) { - if (info.type === "concatenated") { - const m = info.module; - // populate dependencies - for (const d of m.dependencies.filter( - dep => - !(dep instanceof HarmonyImportDependency) || - !modulesSet.has(dep._module) - )) { - this.dependencies.push(d); - } - // populate blocks - for (const d of m.blocks) { - this.blocks.push(d); - } - // populate file dependencies - if (m.buildInfo.fileDependencies) { - for (const file of m.buildInfo.fileDependencies) { - this.buildInfo.fileDependencies.add(file); +/***/ }), + +/***/ 67340: +/***/ (function(module) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +// TODO webpack 5 remove this plugin +// It has been splitted into separate plugins for modules and chunks +class OccurrenceOrderPlugin { + constructor(preferEntry) { + if (preferEntry !== undefined && typeof preferEntry !== "boolean") { + throw new Error( + "Argument should be a boolean.\nFor more info on this plugin, see https://webpack.js.org/plugins/" + ); + } + this.preferEntry = preferEntry; + } + apply(compiler) { + const preferEntry = this.preferEntry; + compiler.hooks.compilation.tap("OccurrenceOrderPlugin", compilation => { + compilation.hooks.optimizeModuleOrder.tap( + "OccurrenceOrderPlugin", + modules => { + const occursInInitialChunksMap = new Map(); + const occursInAllChunksMap = new Map(); + + const initialChunkChunkMap = new Map(); + const entryCountMap = new Map(); + for (const m of modules) { + let initial = 0; + let entry = 0; + for (const c of m.chunksIterable) { + if (c.canBeInitial()) initial++; + if (c.entryModule === m) entry++; + } + initialChunkChunkMap.set(m, initial); + entryCountMap.set(m, entry); } - } - // populate context dependencies - if (m.buildInfo.contextDependencies) { - for (const context of m.buildInfo.contextDependencies) { - this.buildInfo.contextDependencies.add(context); + + const countOccursInEntry = (sum, r) => { + if (!r.module) { + return sum; + } + return sum + initialChunkChunkMap.get(r.module); + }; + const countOccurs = (sum, r) => { + if (!r.module) { + return sum; + } + let factor = 1; + if (typeof r.dependency.getNumberOfIdOccurrences === "function") { + factor = r.dependency.getNumberOfIdOccurrences(); + } + if (factor === 0) { + return sum; + } + return sum + factor * r.module.getNumberOfChunks(); + }; + + if (preferEntry) { + for (const m of modules) { + const result = + m.reasons.reduce(countOccursInEntry, 0) + + initialChunkChunkMap.get(m) + + entryCountMap.get(m); + occursInInitialChunksMap.set(m, result); + } } - } - // populate warnings - for (const warning of m.warnings) { - this.warnings.push(warning); - } - // populate errors - for (const error of m.errors) { - this.errors.push(error); - } - if (m.buildInfo.assets) { - if (this.buildInfo.assets === undefined) { - this.buildInfo.assets = Object.create(null); + const originalOrder = new Map(); + let i = 0; + for (const m of modules) { + const result = + m.reasons.reduce(countOccurs, 0) + + m.getNumberOfChunks() + + entryCountMap.get(m); + occursInAllChunksMap.set(m, result); + originalOrder.set(m, i++); } - Object.assign(this.buildInfo.assets, m.buildInfo.assets); + + modules.sort((a, b) => { + if (preferEntry) { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + } + const aOccurs = occursInAllChunksMap.get(a); + const bOccurs = occursInAllChunksMap.get(b); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + const orgA = originalOrder.get(a); + const orgB = originalOrder.get(b); + return orgA - orgB; + }); } - if (m.buildInfo.assetsInfo) { - if (this.buildInfo.assetsInfo === undefined) { - this.buildInfo.assetsInfo = new Map(); - } - for (const [key, value] of m.buildInfo.assetsInfo) { - this.buildInfo.assetsInfo.set(key, value); + ); + compilation.hooks.optimizeChunkOrder.tap( + "OccurrenceOrderPlugin", + chunks => { + const occursInInitialChunksMap = new Map(); + const originalOrder = new Map(); + + let i = 0; + for (const c of chunks) { + let occurs = 0; + for (const chunkGroup of c.groupsIterable) { + for (const parent of chunkGroup.parentsIterable) { + if (parent.isInitial()) occurs++; + } + } + occursInInitialChunksMap.set(c, occurs); + originalOrder.set(c, i++); } + + chunks.sort((a, b) => { + const aEntryOccurs = occursInInitialChunksMap.get(a); + const bEntryOccurs = occursInInitialChunksMap.get(b); + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; + const aOccurs = a.getNumberOfGroups(); + const bOccurs = b.getNumberOfGroups(); + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + const orgA = originalOrder.get(a); + const orgB = originalOrder.get(b); + return orgA - orgB; + }); } - } - } - this._identifier = this._createIdentifier(); + ); + }); } +} - get modules() { - return this._orderedConcatenationList - .filter(info => info.type === "concatenated") - .map(info => info.module); - } +module.exports = OccurrenceOrderPlugin; - identifier() { - return this._identifier; - } - readableIdentifier(requestShortener) { - return ( - this.rootModule.readableIdentifier(requestShortener) + - ` + ${this._numberOfConcatenatedModules - 1} modules` - ); - } +/***/ }), - libIdent(options) { - return this.rootModule.libIdent(options); - } +/***/ 78085: +/***/ (function(module) { - nameForCondition() { - return this.rootModule.nameForCondition(); - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - build(options, compilation, resolver, fs, callback) { - throw new Error("Cannot build this module. It should be already built."); - } - size() { - // Guess size from embedded modules - return this._orderedConcatenationList.reduce((sum, info) => { - switch (info.type) { - case "concatenated": - return sum + info.module.size(); - case "external": - return sum + 5; - } - return sum; - }, 0); +class RemoveEmptyChunksPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("RemoveEmptyChunksPlugin", compilation => { + const handler = chunks => { + for (let i = chunks.length - 1; i >= 0; i--) { + const chunk = chunks[i]; + if ( + chunk.isEmpty() && + !chunk.hasRuntime() && + !chunk.hasEntryModule() + ) { + chunk.remove("empty"); + chunks.splice(i, 1); + } + } + }; + compilation.hooks.optimizeChunksBasic.tap( + "RemoveEmptyChunksPlugin", + handler + ); + compilation.hooks.optimizeChunksAdvanced.tap( + "RemoveEmptyChunksPlugin", + handler + ); + compilation.hooks.optimizeExtractedChunksBasic.tap( + "RemoveEmptyChunksPlugin", + handler + ); + compilation.hooks.optimizeExtractedChunksAdvanced.tap( + "RemoveEmptyChunksPlugin", + handler + ); + }); } +} +module.exports = RemoveEmptyChunksPlugin; - /** - * @param {Module} rootModule the root of the concatenation - * @param {Set} modulesSet a set of modules which should be concatenated - * @param {Compilation} compilation the compilation context - * @returns {ConcatenationEntry[]} concatenation list - */ - static createConcatenationList(rootModule, modulesSet, compilation) { - const list = []; - const set = new Set(); - /** - * @param {Module} module a module - * @returns {(function(): Module)[]} imported modules in order - */ - const getConcatenatedImports = module => { - /** @type {WeakMap} */ - const map = new WeakMap(); - const references = module.dependencies - .filter(dep => dep instanceof HarmonyImportDependency) - .map(dep => { - const ref = compilation.getDependencyReference(module, dep); - if (ref) map.set(ref, dep); - return ref; - }) - .filter(ref => ref); - DependencyReference.sort(references); - // TODO webpack 5: remove this hack, see also DependencyReference - return references.map(ref => { - const dep = map.get(ref); - return () => compilation.getDependencyReference(module, dep).module; - }); - }; +/***/ }), - const enterModule = getModule => { - const module = getModule(); - if (!module) return; - if (set.has(module)) return; - set.add(module); - if (modulesSet.has(module)) { - const imports = getConcatenatedImports(module); - imports.forEach(enterModule); - list.push({ - type: "concatenated", - module - }); - } else { - list.push({ - type: "external", - get module() { - // We need to use a getter here, because the module in the dependency - // could be replaced by some other process (i. e. also replaced with a - // concatenated module) - return getModule(); - } - }); - } - }; +/***/ 58142: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - enterModule(() => rootModule); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - return list; - } - _createIdentifier() { - let orderedConcatenationListIdentifiers = ""; - for (let i = 0; i < this._orderedConcatenationList.length; i++) { - if (this._orderedConcatenationList[i].type === "concatenated") { - orderedConcatenationListIdentifiers += this._orderedConcatenationList[ - i - ].module.identifier(); - orderedConcatenationListIdentifiers += " "; +const Queue = __webpack_require__(38637); +const { intersect } = __webpack_require__(54262); + +const getParentChunksWithModule = (currentChunk, module) => { + const chunks = []; + const stack = new Set(currentChunk.parentsIterable); + + for (const chunk of stack) { + if (chunk.containsModule(module)) { + chunks.push(chunk); + } else { + for (const parent of chunk.parentsIterable) { + stack.add(parent); } } - const hash = createHash("md4"); - hash.update(orderedConcatenationListIdentifiers); - return this.rootModule.identifier() + " " + hash.digest("hex"); } - source(dependencyTemplates, runtimeTemplate) { - const requestShortener = runtimeTemplate.requestShortener; - // Metainfo for each module - const modulesWithInfo = this._orderedConcatenationList.map((info, idx) => { - switch (info.type) { - case "concatenated": { - const exportMap = new Map(); - const reexportMap = new Map(); - for (const dep of info.module.dependencies) { - if (dep instanceof HarmonyExportSpecifierDependency) { - if (!exportMap.has(dep.name)) { - exportMap.set(dep.name, dep.id); - } - } else if (dep instanceof HarmonyExportExpressionDependency) { - if (!exportMap.has("default")) { - exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__"); - } - } else if ( - dep instanceof HarmonyExportImportedSpecifierDependency - ) { - const exportName = dep.name; - const importName = dep._id; - const importedModule = dep._module; - if (exportName && importName) { - if (!reexportMap.has(exportName)) { - reexportMap.set(exportName, { - module: importedModule, - exportName: importName, - dependency: dep - }); - } - } else if (exportName) { - if (!reexportMap.has(exportName)) { - reexportMap.set(exportName, { - module: importedModule, - exportName: true, - dependency: dep - }); - } - } else if (importedModule) { - for (const name of importedModule.buildMeta.providedExports) { - if (dep.activeExports.has(name) || name === "default") { - continue; + return chunks; +}; + +class RemoveParentModulesPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { + const handler = (chunks, chunkGroups) => { + const queue = new Queue(); + const availableModulesMap = new WeakMap(); + + for (const chunkGroup of compilation.entrypoints.values()) { + // initialize available modules for chunks without parents + availableModulesMap.set(chunkGroup, new Set()); + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } + + while (queue.length > 0) { + const chunkGroup = queue.dequeue(); + let availableModules = availableModulesMap.get(chunkGroup); + let changed = false; + for (const parent of chunkGroup.parentsIterable) { + const availableModulesInParent = availableModulesMap.get(parent); + if (availableModulesInParent !== undefined) { + // If we know the available modules in parent: process these + if (availableModules === undefined) { + // if we have not own info yet: create new entry + availableModules = new Set(availableModulesInParent); + for (const chunk of parent.chunks) { + for (const m of chunk.modulesIterable) { + availableModules.add(m); } - if (!reexportMap.has(name)) { - reexportMap.set(name, { - module: importedModule, - exportName: name, - dependency: dep - }); + } + availableModulesMap.set(chunkGroup, availableModules); + changed = true; + } else { + for (const m of availableModules) { + if ( + !parent.containsModule(m) && + !availableModulesInParent.has(m) + ) { + availableModules.delete(m); + changed = true; } } } } } - return { - type: "concatenated", - module: info.module, - index: idx, - ast: undefined, - internalSource: undefined, - source: undefined, - globalScope: undefined, - moduleScope: undefined, - internalNames: new Map(), - globalExports: new Set(), - exportMap: exportMap, - reexportMap: reexportMap, - hasNamespaceObject: false, - namespaceObjectSource: null - }; + if (changed) { + // if something changed: enqueue our children + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } + } } - case "external": - return { - type: "external", - module: info.module, - index: idx, - name: undefined, - interopNamespaceObjectUsed: false, - interopNamespaceObjectName: undefined, - interopDefaultAccessUsed: false, - interopDefaultAccessName: undefined - }; - default: - throw new Error(`Unsupported concatenation entry type ${info.type}`); - } + + // now we have available modules for every chunk + for (const chunk of chunks) { + const availableModulesSets = Array.from( + chunk.groupsIterable, + chunkGroup => availableModulesMap.get(chunkGroup) + ); + if (availableModulesSets.some(s => s === undefined)) continue; // No info about this chunk group + const availableModules = + availableModulesSets.length === 1 + ? availableModulesSets[0] + : intersect(availableModulesSets); + const numberOfModules = chunk.getNumberOfModules(); + const toRemove = new Set(); + if (numberOfModules < availableModules.size) { + for (const m of chunk.modulesIterable) { + if (availableModules.has(m)) { + toRemove.add(m); + } + } + } else { + for (const m of availableModules) { + if (chunk.containsModule(m)) { + toRemove.add(m); + } + } + } + for (const module of toRemove) { + module.rewriteChunkInReasons( + chunk, + getParentChunksWithModule(chunk, module) + ); + chunk.removeModule(module); + } + } + }; + compilation.hooks.optimizeChunksBasic.tap( + "RemoveParentModulesPlugin", + handler + ); + compilation.hooks.optimizeExtractedChunksBasic.tap( + "RemoveParentModulesPlugin", + handler + ); }); + } +} +module.exports = RemoveParentModulesPlugin; - // Create mapping from module to info - const moduleToInfoMap = new Map(); - for (const m of modulesWithInfo) { - moduleToInfoMap.set(m.module, m); - } - // Configure template decorators for dependencies - const innerDependencyTemplates = new Map(dependencyTemplates); +/***/ }), - innerDependencyTemplates.set( - HarmonyImportSpecifierDependency, - new HarmonyImportSpecifierDependencyConcatenatedTemplate( - dependencyTemplates.get(HarmonyImportSpecifierDependency), - moduleToInfoMap - ) - ); - innerDependencyTemplates.set( - HarmonyImportSideEffectDependency, - new HarmonyImportSideEffectDependencyConcatenatedTemplate( - dependencyTemplates.get(HarmonyImportSideEffectDependency), - moduleToInfoMap - ) - ); - innerDependencyTemplates.set( - HarmonyExportSpecifierDependency, - new NullTemplate() - ); - innerDependencyTemplates.set( - HarmonyExportExpressionDependency, - new HarmonyExportExpressionDependencyConcatenatedTemplate( - dependencyTemplates.get(HarmonyExportExpressionDependency), - this.rootModule - ) - ); - innerDependencyTemplates.set( - HarmonyExportImportedSpecifierDependency, - new NullTemplate() - ); - innerDependencyTemplates.set( - HarmonyCompatibilityDependency, - new NullTemplate() - ); +/***/ 76894: +/***/ (function(module) { - // Must use full identifier in our cache here to ensure that the source - // is updated should our dependencies list change. - // TODO webpack 5 refactor - innerDependencyTemplates.set( - "hash", - innerDependencyTemplates.get("hash") + this.identifier() +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + + +module.exports = class RuntimeChunkPlugin { + constructor(options) { + this.options = Object.assign( + { + name: entrypoint => `runtime~${entrypoint.name}` + }, + options ); + } - // Generate source code and analyse scopes - // Prepare a ReplaceSource for the final source - for (const info of modulesWithInfo) { - if (info.type === "concatenated") { - const m = info.module; - const source = m.source(innerDependencyTemplates, runtimeTemplate); - const code = source.source(); - let ast; - try { - ast = Parser.parse(code, { - sourceType: "module" - }); - } catch (err) { + apply(compiler) { + compiler.hooks.thisCompilation.tap("RuntimeChunkPlugin", compilation => { + compilation.hooks.optimizeChunksAdvanced.tap("RuntimeChunkPlugin", () => { + for (const entrypoint of compilation.entrypoints.values()) { + const chunk = entrypoint.getRuntimeChunk(); + let name = this.options.name; + if (typeof name === "function") { + name = name(entrypoint); + } if ( - err.loc && - typeof err.loc === "object" && - typeof err.loc.line === "number" + chunk.getNumberOfModules() > 0 || + !chunk.preventIntegration || + chunk.name !== name ) { - const lineNumber = err.loc.line; - const lines = code.split("\n"); - err.message += - "\n| " + - lines - .slice(Math.max(0, lineNumber - 3), lineNumber + 2) - .join("\n| "); + const newChunk = compilation.addChunk(name); + newChunk.preventIntegration = true; + entrypoint.unshiftChunk(newChunk); + newChunk.addGroup(entrypoint); + entrypoint.setRuntimeChunk(newChunk); } - throw err; } - const scopeManager = eslintScope.analyze(ast, { - ecmaVersion: 6, - sourceType: "module", - optimistic: true, - ignoreEval: true, - impliedStrict: true - }); - const globalScope = scopeManager.acquire(ast); - const moduleScope = globalScope.childScopes[0]; - const resultSource = new ReplaceSource(source); - info.ast = ast; - info.internalSource = source; - info.source = resultSource; - info.globalScope = globalScope; - info.moduleScope = moduleScope; - } - } + }); + }); + } +}; - // List of all used names to avoid conflicts - const allUsedNames = new Set([ - "__WEBPACK_MODULE_DEFAULT_EXPORT__", // avoid using this internal name - "abstract", - "arguments", - "async", - "await", - "boolean", - "break", - "byte", - "case", - "catch", - "char", - "class", - "const", - "continue", - "debugger", - "default", - "delete", - "do", - "double", - "else", - "enum", - "eval", - "export", - "extends", - "false", - "final", - "finally", - "float", - "for", - "function", - "goto", - "if", - "implements", - "import", - "in", - "instanceof", - "int", - "interface", - "let", - "long", - "native", - "new", - "null", - "package", - "private", - "protected", - "public", - "return", - "short", - "static", - "super", - "switch", - "synchronized", - "this", - "throw", - "throws", - "transient", - "true", - "try", - "typeof", - "var", - "void", - "volatile", - "while", - "with", - "yield", +/***/ }), - "module", - "__dirname", - "__filename", - "exports", +/***/ 83654: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - "Array", - "Date", - "eval", - "function", - "hasOwnProperty", - "Infinity", - "isFinite", - "isNaN", - "isPrototypeOf", - "length", - "Math", - "NaN", - "name", - "Number", - "Object", - "prototype", - "String", - "toString", - "undefined", - "valueOf", +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - "alert", - "all", - "anchor", - "anchors", - "area", - "assign", - "blur", - "button", - "checkbox", - "clearInterval", - "clearTimeout", - "clientInformation", - "close", - "closed", - "confirm", - "constructor", - "crypto", - "decodeURI", - "decodeURIComponent", - "defaultStatus", - "document", - "element", - "elements", - "embed", - "embeds", - "encodeURI", - "encodeURIComponent", - "escape", - "event", - "fileUpload", - "focus", - "form", - "forms", - "frame", - "innerHeight", - "innerWidth", - "layer", - "layers", - "link", - "location", - "mimeTypes", - "navigate", - "navigator", - "frames", - "frameRate", - "hidden", - "history", - "image", - "images", - "offscreenBuffering", - "open", - "opener", - "option", - "outerHeight", - "outerWidth", - "packages", - "pageXOffset", - "pageYOffset", - "parent", - "parseFloat", - "parseInt", - "password", - "pkcs11", - "plugin", - "prompt", - "propertyIsEnum", - "radio", - "reset", - "screenX", - "screenY", - "scroll", - "secure", - "select", - "self", - "setInterval", - "setTimeout", - "status", - "submit", - "taint", - "text", - "textarea", - "top", - "unescape", - "untaint", - "window", - "onblur", - "onclick", - "onerror", - "onfocus", - "onkeydown", - "onkeypress", - "onkeyup", - "onmouseover", - "onload", - "onmouseup", - "onmousedown", - "onsubmit" - ]); +const mm = __webpack_require__(67849); +const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); +const HarmonyImportSideEffectDependency = __webpack_require__(79171); +const HarmonyImportSpecifierDependency = __webpack_require__(95966); - // Set of already checked scopes - const alreadyCheckedScopes = new Set(); +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../Dependency")} Dependency */ - // get all global names - for (const info of modulesWithInfo) { - const superClassExpressions = []; +/** + * @typedef {Object} ExportInModule + * @property {Module} module the module + * @property {string} exportName the name of the export + * @property {boolean} checked if the export is conditional + */ - // ignore symbols from moduleScope - if (info.moduleScope) { - alreadyCheckedScopes.add(info.moduleScope); +/** + * @typedef {Object} ReexportInfo + * @property {Map} static + * @property {Map>} dynamic + */ - // The super class expression in class scopes behaves weird - // We store ranges of all super class expressions to make - // renaming to work correctly - for (const childScope of info.moduleScope.childScopes) { - if (childScope.type !== "class") continue; - if (!childScope.block.superClass) continue; - superClassExpressions.push({ - range: childScope.block.superClass.range, - variables: childScope.variables - }); - } - } +/** + * @param {ReexportInfo} info info object + * @param {string} exportName name of export + * @returns {ExportInModule | undefined} static export + */ +const getMappingFromInfo = (info, exportName) => { + const staticMappings = info.static.get(exportName); + if (staticMappings !== undefined) { + if (staticMappings.length === 1) return staticMappings[0]; + return undefined; + } + const dynamicMappings = Array.from(info.dynamic).filter( + ([_, ignored]) => !ignored.has(exportName) + ); + if (dynamicMappings.length === 1) { + return { + module: dynamicMappings[0][0], + exportName, + checked: true + }; + } + return undefined; +}; - // add global symbols - if (info.globalScope) { - for (const reference of info.globalScope.through) { - const name = reference.identifier.name; - if ( - /^__WEBPACK_MODULE_REFERENCE__\d+_([\da-f]+|ns)(_call)?(_strict)?__$/.test( - name - ) - ) { - for (const expr of superClassExpressions) { - if ( - expr.range[0] <= reference.identifier.range[0] && - expr.range[1] >= reference.identifier.range[1] - ) { - for (const variable of expr.variables) { - allUsedNames.add(variable.name); - } - } - } - addScopeSymbols1( - reference.from, - allUsedNames, - alreadyCheckedScopes - ); - } else { - allUsedNames.add(name); - } - } - } - - // add exported globals - if (info.type === "concatenated") { - const variables = new Set(); - for (const variable of info.moduleScope.variables) { - variables.add(variable.name); - } - for (const [, variable] of info.exportMap) { - if (!variables.has(variable)) { - info.globalExports.add(variable); - } - } +/** + * @param {ReexportInfo} info info object + * @param {string} exportName name of export of source module + * @param {Module} module the target module + * @param {string} innerExportName name of export of target module + * @param {boolean} checked true, if existence of target module is checked + */ +const addStaticReexport = ( + info, + exportName, + module, + innerExportName, + checked +) => { + let mappings = info.static.get(exportName); + if (mappings !== undefined) { + for (const mapping of mappings) { + if (mapping.module === module && mapping.exportName === innerExportName) { + mapping.checked = mapping.checked && checked; + return; } } + } else { + mappings = []; + info.static.set(exportName, mappings); + } + mappings.push({ + module, + exportName: innerExportName, + checked + }); +}; - // generate names for symbols - for (const info of modulesWithInfo) { - switch (info.type) { - case "concatenated": { - const namespaceObjectName = this.findNewName( - "namespaceObject", - allUsedNames, - null, - info.module.readableIdentifier(requestShortener) +/** + * @param {ReexportInfo} info info object + * @param {Module} module the reexport module + * @param {Set} ignored ignore list + * @returns {void} + */ +const addDynamicReexport = (info, module, ignored) => { + const existingList = info.dynamic.get(module); + if (existingList !== undefined) { + for (const key of existingList) { + if (!ignored.has(key)) existingList.delete(key); + } + } else { + info.dynamic.set(module, new Set(ignored)); + } +}; + +class SideEffectsFlagPlugin { + apply(compiler) { + compiler.hooks.normalModuleFactory.tap("SideEffectsFlagPlugin", nmf => { + nmf.hooks.module.tap("SideEffectsFlagPlugin", (module, data) => { + const resolveData = data.resourceResolveData; + if ( + resolveData && + resolveData.descriptionFileData && + resolveData.relativePath + ) { + const sideEffects = resolveData.descriptionFileData.sideEffects; + const hasSideEffects = SideEffectsFlagPlugin.moduleHasSideEffects( + resolveData.relativePath, + sideEffects ); - allUsedNames.add(namespaceObjectName); - info.internalNames.set(namespaceObjectName, namespaceObjectName); - info.exportMap.set(true, namespaceObjectName); - for (const variable of info.moduleScope.variables) { - const name = variable.name; - if (allUsedNames.has(name)) { - const references = getAllReferences(variable); - const symbolsInReferences = new Set(); - const alreadyCheckedInnerScopes = new Set(); - for (const ref of references) { - addScopeSymbols2( - ref.from, - symbolsInReferences, - alreadyCheckedInnerScopes, - alreadyCheckedScopes - ); - } - const newName = this.findNewName( - name, - allUsedNames, - symbolsInReferences, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(newName); - info.internalNames.set(name, newName); - const source = info.source; - const allIdentifiers = new Set( - references.map(r => r.identifier).concat(variable.identifiers) - ); - for (const identifier of allIdentifiers) { - const r = identifier.range; - const path = getPathInAst(info.ast, identifier); - if ( - path && - path.length > 1 && - path[1].type === "Property" && - path[1].shorthand - ) { - source.insert(r[1], `: ${newName}`); - } else { - source.replace(r[0], r[1] - 1, newName); - } - } - } else { - allUsedNames.add(name); - info.internalNames.set(name, name); - } + if (!hasSideEffects) { + module.factoryMeta.sideEffectFree = true; } - break; } - case "external": { - const externalName = this.findNewName( - "", - allUsedNames, - null, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(externalName); - info.name = externalName; - if ( - info.module.buildMeta.exportsType === "named" || - !info.module.buildMeta.exportsType - ) { - const externalNameInterop = this.findNewName( - "namespaceObject", - allUsedNames, - null, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(externalNameInterop); - info.interopNamespaceObjectName = externalNameInterop; - } - if (!info.module.buildMeta.exportsType) { - const externalNameInterop = this.findNewName( - "default", - allUsedNames, - null, - info.module.readableIdentifier(requestShortener) - ); - allUsedNames.add(externalNameInterop); - info.interopDefaultAccessName = externalNameInterop; - } - break; + + return module; + }); + nmf.hooks.module.tap("SideEffectsFlagPlugin", (module, data) => { + if (data.settings.sideEffects === false) { + module.factoryMeta.sideEffectFree = true; + } else if (data.settings.sideEffects === true) { + module.factoryMeta.sideEffectFree = false; } - } - } + }); + }); + compiler.hooks.compilation.tap("SideEffectsFlagPlugin", compilation => { + compilation.hooks.optimizeDependencies.tap( + "SideEffectsFlagPlugin", + modules => { + /** @type {Map} */ + const reexportMaps = new Map(); - // Find and replace referenced to modules - for (const info of modulesWithInfo) { - if (info.type === "concatenated") { - for (const reference of info.globalScope.through) { - const name = reference.identifier.name; - const match = /^__WEBPACK_MODULE_REFERENCE__(\d+)_([\da-f]+|ns)(_call)?(_strict)?__$/.exec( - name - ); - if (match) { - const referencedModule = modulesWithInfo[+match[1]]; - let exportName; - if (match[2] === "ns") { - exportName = true; - } else { - const exportData = match[2]; - exportName = Buffer.from(exportData, "hex").toString("utf-8"); + // Capture reexports of sideEffectFree modules + for (const module of modules) { + /** @type {Dependency[]} */ + const removeDependencies = []; + for (const dep of module.dependencies) { + if (dep instanceof HarmonyImportSideEffectDependency) { + if (dep.module && dep.module.factoryMeta.sideEffectFree) { + removeDependencies.push(dep); + } + } else if ( + dep instanceof HarmonyExportImportedSpecifierDependency + ) { + if (module.factoryMeta.sideEffectFree) { + const mode = dep.getMode(true); + if ( + mode.type === "safe-reexport" || + mode.type === "checked-reexport" || + mode.type === "dynamic-reexport" || + mode.type === "reexport-non-harmony-default" || + mode.type === "reexport-non-harmony-default-strict" || + mode.type === "reexport-named-default" + ) { + let info = reexportMaps.get(module); + if (!info) { + reexportMaps.set( + module, + (info = { + static: new Map(), + dynamic: new Map() + }) + ); + } + const targetModule = dep._module; + switch (mode.type) { + case "safe-reexport": + for (const [key, id] of mode.map) { + if (id) { + addStaticReexport( + info, + key, + targetModule, + id, + false + ); + } + } + break; + case "checked-reexport": + for (const [key, id] of mode.map) { + if (id) { + addStaticReexport( + info, + key, + targetModule, + id, + true + ); + } + } + break; + case "dynamic-reexport": + addDynamicReexport(info, targetModule, mode.ignored); + break; + case "reexport-non-harmony-default": + case "reexport-non-harmony-default-strict": + case "reexport-named-default": + addStaticReexport( + info, + mode.name, + targetModule, + "default", + false + ); + break; + } + } + } + } } - const asCall = !!match[3]; - const strictHarmonyModule = !!match[4]; - const finalName = getFinalName( - referencedModule, - exportName, - moduleToInfoMap, - requestShortener, - asCall, - strictHarmonyModule - ); - const r = reference.identifier.range; - const source = info.source; - source.replace(r[0], r[1] - 1, finalName); } - } - } - } - // Map with all root exposed used exports - /** @type {Map} */ - const exportsMap = new Map(); + // Flatten reexports + for (const info of reexportMaps.values()) { + const dynamicReexports = info.dynamic; + info.dynamic = new Map(); + for (const reexport of dynamicReexports) { + let [targetModule, ignored] = reexport; + for (;;) { + const innerInfo = reexportMaps.get(targetModule); + if (!innerInfo) break; - // Set with all root exposed unused exports - /** @type {Set} */ - const unusedExports = new Set(); + for (const [key, reexports] of innerInfo.static) { + if (ignored.has(key)) continue; + for (const { module, exportName, checked } of reexports) { + addStaticReexport(info, key, module, exportName, checked); + } + } - for (const dep of this.rootModule.dependencies) { - if (dep instanceof HarmonyExportSpecifierDependency) { - const used = this.rootModule.isUsed(dep.name); - if (used) { - const info = moduleToInfoMap.get(this.rootModule); - if (!exportsMap.has(used)) { - exportsMap.set( - used, - () => `/* binding */ ${info.internalNames.get(dep.id)}` - ); + // Follow dynamic reexport if there is only one + if (innerInfo.dynamic.size !== 1) { + // When there are more then one, we don't know which one + break; + } + + ignored = new Set(ignored); + for (const [innerModule, innerIgnored] of innerInfo.dynamic) { + for (const key of innerIgnored) { + if (ignored.has(key)) continue; + // This reexports ends here + addStaticReexport(info, key, targetModule, key, true); + ignored.add(key); + } + targetModule = innerModule; + } + } + + // Update reexport as all other cases has been handled + addDynamicReexport(info, targetModule, ignored); + } } - } else { - unusedExports.add(dep.name || "namespace"); - } - } else if (dep instanceof HarmonyExportImportedSpecifierDependency) { - const exportDefs = getHarmonyExportImportedSpecifierDependencyExports( - dep - ); - for (const def of exportDefs) { - const info = moduleToInfoMap.get(def.module); - const used = dep.originModule.isUsed(def.name); - if (used) { - if (!exportsMap.has(used)) { - exportsMap.set(used, requestShortener => { - const finalName = getFinalName( + + for (const info of reexportMaps.values()) { + const staticReexports = info.static; + info.static = new Map(); + for (const [key, reexports] of staticReexports) { + for (let mapping of reexports) { + for (;;) { + const innerInfo = reexportMaps.get(mapping.module); + if (!innerInfo) break; + + const newMapping = getMappingFromInfo( + innerInfo, + mapping.exportName + ); + if (!newMapping) break; + mapping = newMapping; + } + addStaticReexport( info, - def.id, - moduleToInfoMap, - requestShortener, - false, - this.rootModule.buildMeta.strictHarmonyModule + key, + mapping.module, + mapping.exportName, + mapping.checked ); - return `/* reexport */ ${finalName}`; - }); + } } - } else { - unusedExports.add(def.name); } - } - } - } - - const result = new ConcatSource(); - // add harmony compatibility flag (must be first because of possible circular dependencies) - const usedExports = this.rootModule.usedExports; - if (usedExports === true || usedExports === null) { - result.add(`// ESM COMPAT FLAG\n`); - result.add( - runtimeTemplate.defineEsModuleFlagStatement({ - exportsArgument: this.exportsArgument - }) + // Update imports along the reexports from sideEffectFree modules + for (const pair of reexportMaps) { + const module = pair[0]; + const info = pair[1]; + let newReasons = undefined; + for (let i = 0; i < module.reasons.length; i++) { + const reason = module.reasons[i]; + const dep = reason.dependency; + if ( + (dep instanceof HarmonyExportImportedSpecifierDependency || + (dep instanceof HarmonyImportSpecifierDependency && + !dep.namespaceObjectAsContext)) && + dep._id + ) { + const mapping = getMappingFromInfo(info, dep._id); + if (mapping) { + dep.redirectedModule = mapping.module; + dep.redirectedId = mapping.exportName; + mapping.module.addReason( + reason.module, + dep, + reason.explanation + ? reason.explanation + + " (skipped side-effect-free modules)" + : "(skipped side-effect-free modules)" + ); + // removing the currect reason, by not adding it to the newReasons array + // lazily create the newReasons array + if (newReasons === undefined) { + newReasons = i === 0 ? [] : module.reasons.slice(0, i); + } + continue; + } + } + if (newReasons !== undefined) newReasons.push(reason); + } + if (newReasons !== undefined) { + module.reasons = newReasons; + } + } + } ); - } + }); + } - // define exports - if (exportsMap.size > 0) { - result.add(`\n// EXPORTS\n`); - for (const [key, value] of exportsMap) { - result.add( - `__webpack_require__.d(${this.exportsArgument}, ${JSON.stringify( - key - )}, function() { return ${value(requestShortener)}; });\n` + static moduleHasSideEffects(moduleName, flagValue) { + switch (typeof flagValue) { + case "undefined": + return true; + case "boolean": + return flagValue; + case "string": + if (process.platform === "win32") { + flagValue = flagValue.replace(/\\/g, "/"); + } + return mm.isMatch(moduleName, flagValue, { + matchBase: true + }); + case "object": + return flagValue.some(glob => + SideEffectsFlagPlugin.moduleHasSideEffects(moduleName, glob) ); - } } + } +} +module.exports = SideEffectsFlagPlugin; - // list unused exports - if (unusedExports.size > 0) { - result.add( - `\n// UNUSED EXPORTS: ${joinIterableWithComma(unusedExports)}\n` - ); - } - // define required namespace objects (must be before evaluation modules) - for (const info of modulesWithInfo) { - if (info.namespaceObjectSource) { - result.add( - `\n// NAMESPACE OBJECT: ${info.module.readableIdentifier( - requestShortener - )}\n` - ); - result.add(info.namespaceObjectSource); - } - } +/***/ }), - // evaluate modules in order - for (const info of modulesWithInfo) { - switch (info.type) { - case "concatenated": - result.add( - `\n// CONCATENATED MODULE: ${info.module.readableIdentifier( - requestShortener - )}\n` - ); - result.add(info.source); - break; - case "external": - result.add( - `\n// EXTERNAL MODULE: ${info.module.readableIdentifier( - requestShortener - )}\n` - ); - result.add( - `var ${info.name} = __webpack_require__(${JSON.stringify( - info.module.id - )});\n` - ); - if (info.interopNamespaceObjectUsed) { - if (info.module.buildMeta.exportsType === "named") { - result.add( - `var ${info.interopNamespaceObjectName} = /*#__PURE__*/__webpack_require__.t(${info.name}, 2);\n` - ); - } else if (!info.module.buildMeta.exportsType) { - result.add( - `var ${info.interopNamespaceObjectName} = /*#__PURE__*/__webpack_require__.t(${info.name});\n` - ); - } - } - if (info.interopDefaultAccessUsed) { - result.add( - `var ${info.interopDefaultAccessName} = /*#__PURE__*/__webpack_require__.n(${info.name});\n` - ); - } - break; - default: - throw new Error(`Unsupported concatenation entry type ${info.type}`); - } - } +/***/ 60474: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - return result; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - findNewName(oldName, usedNamed1, usedNamed2, extraInfo) { - let name = oldName; - if (name === "__WEBPACK_MODULE_DEFAULT_EXPORT__") name = ""; +const crypto = __webpack_require__(76417); +const SortableSet = __webpack_require__(50071); +const GraphHelpers = __webpack_require__(32973); +const { isSubset } = __webpack_require__(54262); +const deterministicGrouping = __webpack_require__(30815); +const MinMaxSizeWarning = __webpack_require__(25472); +const contextify = __webpack_require__(94658).contextify; - // Remove uncool stuff - extraInfo = extraInfo.replace( - /\.+\/|(\/index)?\.([a-zA-Z0-9]{1,4})($|\s|\?)|\s*\+\s*\d+\s*modules/g, - "" - ); +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Chunk")} Chunk */ +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../util/deterministicGrouping").Options} DeterministicGroupingOptionsForModule */ +/** @typedef {import("../util/deterministicGrouping").GroupedItems} DeterministicGroupingGroupedItemsForModule */ - const splittedInfo = extraInfo.split("/"); - while (splittedInfo.length) { - name = splittedInfo.pop() + (name ? "_" + name : ""); - const nameIdent = Template.toIdentifier(name); - if ( - !usedNamed1.has(nameIdent) && - (!usedNamed2 || !usedNamed2.has(nameIdent)) - ) - return nameIdent; - } +const deterministicGroupingForModules = /** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ (deterministicGrouping); - let i = 0; - let nameWithNumber = Template.toIdentifier(`${name}_${i}`); - while ( - usedNamed1.has(nameWithNumber) || - (usedNamed2 && usedNamed2.has(nameWithNumber)) - ) { - i++; - nameWithNumber = Template.toIdentifier(`${name}_${i}`); - } - return nameWithNumber; - } +const hashFilename = name => { + return crypto + .createHash("md4") + .update(name) + .digest("hex") + .slice(0, 8); +}; - /** - * @param {Hash} hash the hash used to track dependencies - * @returns {void} - */ - updateHash(hash) { - for (const info of this._orderedConcatenationList) { - switch (info.type) { - case "concatenated": - info.module.updateHash(hash); - break; - case "external": - hash.update(`${info.module.id}`); - break; - } - } - super.updateHash(hash); +const sortByIdentifier = (a, b) => { + if (a.identifier() > b.identifier()) return 1; + if (a.identifier() < b.identifier()) return -1; + return 0; +}; + +const getRequests = chunk => { + let requests = 0; + for (const chunkGroup of chunk.groupsIterable) { + requests = Math.max(requests, chunkGroup.chunks.length); } -} + return requests; +}; -class HarmonyImportSpecifierDependencyConcatenatedTemplate { - constructor(originalTemplate, modulesMap) { - this.originalTemplate = originalTemplate; - this.modulesMap = modulesMap; +const getModulesSize = modules => { + let sum = 0; + for (const m of modules) { + sum += m.size(); } + return sum; +}; - getHarmonyInitOrder(dep) { - const module = dep._module; - const info = this.modulesMap.get(module); - if (!info) { - return this.originalTemplate.getHarmonyInitOrder(dep); - } - return NaN; +/** + * @template T + * @param {Set} a set + * @param {Set} b other set + * @returns {boolean} true if at least one item of a is in b + */ +const isOverlap = (a, b) => { + for (const item of a) { + if (b.has(item)) return true; } + return false; +}; - harmonyInit(dep, source, runtimeTemplate, dependencyTemplates) { - const module = dep._module; - const info = this.modulesMap.get(module); - if (!info) { - this.originalTemplate.harmonyInit( - dep, - source, - runtimeTemplate, - dependencyTemplates - ); - return; - } +const compareEntries = (a, b) => { + // 1. by priority + const diffPriority = a.cacheGroup.priority - b.cacheGroup.priority; + if (diffPriority) return diffPriority; + // 2. by number of chunks + const diffCount = a.chunks.size - b.chunks.size; + if (diffCount) return diffCount; + // 3. by size reduction + const aSizeReduce = a.size * (a.chunks.size - 1); + const bSizeReduce = b.size * (b.chunks.size - 1); + const diffSizeReduce = aSizeReduce - bSizeReduce; + if (diffSizeReduce) return diffSizeReduce; + // 4. by cache group index + const indexDiff = a.cacheGroupIndex - b.cacheGroupIndex; + if (indexDiff) return indexDiff; + // 5. by number of modules (to be able to compare by identifier) + const modulesA = a.modules; + const modulesB = b.modules; + const diff = modulesA.size - modulesB.size; + if (diff) return diff; + // 6. by module identifiers + modulesA.sort(); + modulesB.sort(); + const aI = modulesA[Symbol.iterator](); + const bI = modulesB[Symbol.iterator](); + // eslint-disable-next-line no-constant-condition + while (true) { + const aItem = aI.next(); + const bItem = bI.next(); + if (aItem.done) return 0; + const aModuleIdentifier = aItem.value.identifier(); + const bModuleIdentifier = bItem.value.identifier(); + if (aModuleIdentifier > bModuleIdentifier) return -1; + if (aModuleIdentifier < bModuleIdentifier) return 1; } +}; - apply(dep, source, runtime, dependencyTemplates) { - const module = dep._module; - const info = this.modulesMap.get(module); - if (!info) { - this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); - return; - } - let content; - const callFlag = dep.call ? "_call" : ""; - const strictFlag = dep.originModule.buildMeta.strictHarmonyModule - ? "_strict" - : ""; - if (dep._id === null) { - content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns${strictFlag}__`; - } else if (dep.namespaceObjectAsContext) { - content = `__WEBPACK_MODULE_REFERENCE__${ - info.index - }_ns${strictFlag}__[${JSON.stringify(dep._id)}]`; - } else { - const exportData = Buffer.from(dep._id, "utf-8").toString("hex"); - content = `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportData}${callFlag}${strictFlag}__`; - } - if (dep.shorthand) { - content = dep.name + ": " + content; - } - source.replace(dep.range[0], dep.range[1] - 1, content); +const compareNumbers = (a, b) => a - b; + +const INITIAL_CHUNK_FILTER = chunk => chunk.canBeInitial(); +const ASYNC_CHUNK_FILTER = chunk => !chunk.canBeInitial(); +const ALL_CHUNK_FILTER = chunk => true; + +module.exports = class SplitChunksPlugin { + constructor(options) { + this.options = SplitChunksPlugin.normalizeOptions(options); } -} -class HarmonyImportSideEffectDependencyConcatenatedTemplate { - constructor(originalTemplate, modulesMap) { - this.originalTemplate = originalTemplate; - this.modulesMap = modulesMap; + static normalizeOptions(options = {}) { + return { + chunksFilter: SplitChunksPlugin.normalizeChunksFilter( + options.chunks || "all" + ), + minSize: options.minSize || 0, + enforceSizeThreshold: options.enforceSizeThreshold || 0, + maxSize: options.maxSize || 0, + minChunks: options.minChunks || 1, + maxAsyncRequests: options.maxAsyncRequests || 1, + maxInitialRequests: options.maxInitialRequests || 1, + hidePathInfo: options.hidePathInfo || false, + filename: options.filename || undefined, + getCacheGroups: SplitChunksPlugin.normalizeCacheGroups({ + cacheGroups: options.cacheGroups, + name: options.name, + automaticNameDelimiter: options.automaticNameDelimiter, + automaticNameMaxLength: options.automaticNameMaxLength + }), + automaticNameDelimiter: options.automaticNameDelimiter, + automaticNameMaxLength: options.automaticNameMaxLength || 109, + fallbackCacheGroup: SplitChunksPlugin.normalizeFallbackCacheGroup( + options.fallbackCacheGroup || {}, + options + ) + }; } - getHarmonyInitOrder(dep) { - const module = dep._module; - const info = this.modulesMap.get(module); - if (!info) { - return this.originalTemplate.getHarmonyInitOrder(dep); + static normalizeName({ + name, + automaticNameDelimiter, + automaticNamePrefix, + automaticNameMaxLength + }) { + if (name === true) { + /** @type {WeakMap>} */ + const cache = new WeakMap(); + const fn = (module, chunks, cacheGroup) => { + let cacheEntry = cache.get(chunks); + if (cacheEntry === undefined) { + cacheEntry = {}; + cache.set(chunks, cacheEntry); + } else if (cacheGroup in cacheEntry) { + return cacheEntry[cacheGroup]; + } + const names = chunks.map(c => c.name); + if (!names.every(Boolean)) { + cacheEntry[cacheGroup] = undefined; + return; + } + names.sort(); + const prefix = + typeof automaticNamePrefix === "string" + ? automaticNamePrefix + : cacheGroup; + const namePrefix = prefix ? prefix + automaticNameDelimiter : ""; + let name = namePrefix + names.join(automaticNameDelimiter); + // Filenames and paths can't be too long otherwise an + // ENAMETOOLONG error is raised. If the generated name if too + // long, it is truncated and a hash is appended. The limit has + // been set to 109 to prevent `[name].[chunkhash].[ext]` from + // generating a 256+ character string. + if (name.length > automaticNameMaxLength) { + const hashedFilename = hashFilename(name); + const sliceLength = + automaticNameMaxLength - + (automaticNameDelimiter.length + hashedFilename.length); + name = + name.slice(0, sliceLength) + + automaticNameDelimiter + + hashedFilename; + } + cacheEntry[cacheGroup] = name; + return name; + }; + return fn; } - return NaN; + if (typeof name === "string") { + const fn = () => { + return name; + }; + return fn; + } + if (typeof name === "function") return name; } - harmonyInit(dep, source, runtime, dependencyTemplates) { - const module = dep._module; - const info = this.modulesMap.get(module); - if (!info) { - this.originalTemplate.harmonyInit( - dep, - source, - runtime, - dependencyTemplates - ); - return; + static normalizeChunksFilter(chunks) { + if (chunks === "initial") { + return INITIAL_CHUNK_FILTER; + } + if (chunks === "async") { + return ASYNC_CHUNK_FILTER; } + if (chunks === "all") { + return ALL_CHUNK_FILTER; + } + if (typeof chunks === "function") return chunks; } - apply(dep, source, runtime, dependencyTemplates) { - const module = dep._module; - const info = this.modulesMap.get(module); - if (!info) { - this.originalTemplate.apply(dep, source, runtime, dependencyTemplates); - return; + static normalizeFallbackCacheGroup( + { + minSize = undefined, + maxSize = undefined, + automaticNameDelimiter = undefined + }, + { + minSize: defaultMinSize = undefined, + maxSize: defaultMaxSize = undefined, + automaticNameDelimiter: defaultAutomaticNameDelimiter = undefined } + ) { + return { + minSize: typeof minSize === "number" ? minSize : defaultMinSize || 0, + maxSize: typeof maxSize === "number" ? maxSize : defaultMaxSize || 0, + automaticNameDelimiter: + automaticNameDelimiter || defaultAutomaticNameDelimiter || "~" + }; } -} -class HarmonyExportExpressionDependencyConcatenatedTemplate { - constructor(originalTemplate, rootModule) { - this.originalTemplate = originalTemplate; - this.rootModule = rootModule; + static normalizeCacheGroups({ + cacheGroups, + name, + automaticNameDelimiter, + automaticNameMaxLength + }) { + if (typeof cacheGroups === "function") { + // TODO webpack 5 remove this + if (cacheGroups.length !== 1) { + return module => cacheGroups(module, module.getChunks()); + } + return cacheGroups; + } + if (cacheGroups && typeof cacheGroups === "object") { + const fn = module => { + let results; + for (const key of Object.keys(cacheGroups)) { + let option = cacheGroups[key]; + if (option === false) continue; + if (option instanceof RegExp || typeof option === "string") { + option = { + test: option + }; + } + if (typeof option === "function") { + let result = option(module); + if (result) { + if (results === undefined) results = []; + for (const r of Array.isArray(result) ? result : [result]) { + const result = Object.assign({ key }, r); + if (result.name) result.getName = () => result.name; + if (result.chunks) { + result.chunksFilter = SplitChunksPlugin.normalizeChunksFilter( + result.chunks + ); + } + results.push(result); + } + } + } else if (SplitChunksPlugin.checkTest(option.test, module)) { + if (results === undefined) results = []; + results.push({ + key: key, + priority: option.priority, + getName: + SplitChunksPlugin.normalizeName({ + name: option.name || name, + automaticNameDelimiter: + typeof option.automaticNameDelimiter === "string" + ? option.automaticNameDelimiter + : automaticNameDelimiter, + automaticNamePrefix: option.automaticNamePrefix, + automaticNameMaxLength: + option.automaticNameMaxLength || automaticNameMaxLength + }) || (() => {}), + chunksFilter: SplitChunksPlugin.normalizeChunksFilter( + option.chunks + ), + enforce: option.enforce, + minSize: option.minSize, + enforceSizeThreshold: option.enforceSizeThreshold, + maxSize: option.maxSize, + minChunks: option.minChunks, + maxAsyncRequests: option.maxAsyncRequests, + maxInitialRequests: option.maxInitialRequests, + filename: option.filename, + reuseExistingChunk: option.reuseExistingChunk + }); + } + } + return results; + }; + return fn; + } + const fn = () => {}; + return fn; } - apply(dep, source, runtime, dependencyTemplates) { - let content = - "/* harmony default export */ var __WEBPACK_MODULE_DEFAULT_EXPORT__ = "; - if (dep.originModule === this.rootModule) { - const used = dep.originModule.isUsed("default"); - const exportsName = dep.originModule.exportsArgument; - if (used) content += `${exportsName}[${JSON.stringify(used)}] = `; + static checkTest(test, module) { + if (test === undefined) return true; + if (typeof test === "function") { + if (test.length !== 1) { + return test(module, module.getChunks()); + } + return test(module); } - - if (dep.range) { - source.replace( - dep.rangeStatement[0], - dep.range[0] - 1, - content + "(" + dep.prefix - ); - source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); - return; + if (typeof test === "boolean") return test; + if (typeof test === "string") { + if ( + module.nameForCondition && + module.nameForCondition().startsWith(test) + ) { + return true; + } + for (const chunk of module.chunksIterable) { + if (chunk.name && chunk.name.startsWith(test)) { + return true; + } + } + return false; } - - source.replace( - dep.rangeStatement[0], - dep.rangeStatement[1] - 1, - content + dep.prefix - ); + if (test instanceof RegExp) { + if (module.nameForCondition && test.test(module.nameForCondition())) { + return true; + } + for (const chunk of module.chunksIterable) { + if (chunk.name && test.test(chunk.name)) { + return true; + } + } + return false; + } + return false; } -} - -class NullTemplate { - apply() {} -} - -module.exports = ConcatenatedModule; - - -/***/ }), - -/***/ 29720: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - - -const GraphHelpers = __webpack_require__(32973); -class EnsureChunkConditionsPlugin { + /** + * @param {Compiler} compiler webpack compiler + * @returns {void} + */ apply(compiler) { - compiler.hooks.compilation.tap( - "EnsureChunkConditionsPlugin", - compilation => { - const handler = chunks => { - let changed = false; - for (const module of compilation.modules) { - if (!module.chunkCondition) continue; - const sourceChunks = new Set(); - const chunkGroups = new Set(); - for (const chunk of module.chunksIterable) { - if (!module.chunkCondition(chunk)) { - sourceChunks.add(chunk); - for (const group of chunk.groupsIterable) { - chunkGroups.add(group); - } - } + compiler.hooks.thisCompilation.tap("SplitChunksPlugin", compilation => { + let alreadyOptimized = false; + compilation.hooks.unseal.tap("SplitChunksPlugin", () => { + alreadyOptimized = false; + }); + compilation.hooks.optimizeChunksAdvanced.tap( + "SplitChunksPlugin", + chunks => { + if (alreadyOptimized) return; + alreadyOptimized = true; + // Give each selected chunk an index (to create strings from chunks) + const indexMap = new Map(); + let index = 1; + for (const chunk of chunks) { + indexMap.set(chunk, index++); + } + const getKey = chunks => { + return Array.from(chunks, c => indexMap.get(c)) + .sort(compareNumbers) + .join(); + }; + /** @type {Map>} */ + const chunkSetsInGraph = new Map(); + for (const module of compilation.modules) { + const chunksKey = getKey(module.chunksIterable); + if (!chunkSetsInGraph.has(chunksKey)) { + chunkSetsInGraph.set(chunksKey, new Set(module.chunksIterable)); } - if (sourceChunks.size === 0) continue; - const targetChunks = new Set(); - chunkGroupLoop: for (const chunkGroup of chunkGroups) { - // Can module be placed in a chunk of this group? - for (const chunk of chunkGroup.chunks) { - if (module.chunkCondition(chunk)) { - targetChunks.add(chunk); - continue chunkGroupLoop; + } + + // group these set of chunks by count + // to allow to check less sets via isSubset + // (only smaller sets can be subset) + /** @type {Map>>} */ + const chunkSetsByCount = new Map(); + for (const chunksSet of chunkSetsInGraph.values()) { + const count = chunksSet.size; + let array = chunkSetsByCount.get(count); + if (array === undefined) { + array = []; + chunkSetsByCount.set(count, array); + } + array.push(chunksSet); + } + + // Create a list of possible combinations + const combinationsCache = new Map(); // Map[]> + + const getCombinations = key => { + const chunksSet = chunkSetsInGraph.get(key); + var array = [chunksSet]; + if (chunksSet.size > 1) { + for (const [count, setArray] of chunkSetsByCount) { + // "equal" is not needed because they would have been merge in the first step + if (count < chunksSet.size) { + for (const set of setArray) { + if (isSubset(chunksSet, set)) { + array.push(set); + } + } } } - // We reached the entrypoint: fail - if (chunkGroup.isInitial()) { - throw new Error( - "Cannot fullfil chunk condition of " + module.identifier() - ); - } - // Try placing in all parents - for (const group of chunkGroup.parentsIterable) { - chunkGroups.add(group); - } - } - for (const sourceChunk of sourceChunks) { - GraphHelpers.disconnectChunkAndModule(sourceChunk, module); - } - for (const targetChunk of targetChunks) { - GraphHelpers.connectChunkAndModule(targetChunk, module); } - } - if (changed) return true; - }; - compilation.hooks.optimizeChunksBasic.tap( - "EnsureChunkConditionsPlugin", - handler - ); - compilation.hooks.optimizeExtractedChunksBasic.tap( - "EnsureChunkConditionsPlugin", - handler - ); - } - ); - } -} -module.exports = EnsureChunkConditionsPlugin; + return array; + }; + /** + * @typedef {Object} SelectedChunksResult + * @property {Chunk[]} chunks the list of chunks + * @property {string} key a key of the list + */ -/***/ }), + /** + * @typedef {function(Chunk): boolean} ChunkFilterFunction + */ -/***/ 25850: -/***/ (function(module) { + /** @type {WeakMap, WeakMap>} */ + const selectedChunksCacheByChunksSet = new WeakMap(); -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * get list and key by applying the filter function to the list + * It is cached for performance reasons + * @param {Set} chunks list of chunks + * @param {ChunkFilterFunction} chunkFilter filter function for chunks + * @returns {SelectedChunksResult} list and key + */ + const getSelectedChunks = (chunks, chunkFilter) => { + let entry = selectedChunksCacheByChunksSet.get(chunks); + if (entry === undefined) { + entry = new WeakMap(); + selectedChunksCacheByChunksSet.set(chunks, entry); + } + /** @type {SelectedChunksResult} */ + let entry2 = entry.get(chunkFilter); + if (entry2 === undefined) { + /** @type {Chunk[]} */ + const selectedChunks = []; + for (const chunk of chunks) { + if (chunkFilter(chunk)) selectedChunks.push(chunk); + } + entry2 = { + chunks: selectedChunks, + key: getKey(selectedChunks) + }; + entry.set(chunkFilter, entry2); + } + return entry2; + }; + /** + * @typedef {Object} ChunksInfoItem + * @property {SortableSet} modules + * @property {TODO} cacheGroup + * @property {number} cacheGroupIndex + * @property {string} name + * @property {number} size + * @property {Set} chunks + * @property {Set} reuseableChunks + * @property {Set} chunksKeys + */ -class FlagIncludedChunksPlugin { - apply(compiler) { - compiler.hooks.compilation.tap("FlagIncludedChunksPlugin", compilation => { - compilation.hooks.optimizeChunkIds.tap( - "FlagIncludedChunksPlugin", - chunks => { - // prepare two bit integers for each module - // 2^31 is the max number represented as SMI in v8 - // we want the bits distributed this way: - // the bit 2^31 is pretty rar and only one module should get it - // so it has a probability of 1 / modulesCount - // the first bit (2^0) is the easiest and every module could get it - // if it doesn't get a better bit - // from bit 2^n to 2^(n+1) there is a probability of p - // so 1 / modulesCount == p^31 - // <=> p = sqrt31(1 / modulesCount) - // so we use a modulo of 1 / sqrt31(1 / modulesCount) - const moduleBits = new WeakMap(); - const modulesCount = compilation.modules.length; + // Map a list of chunks to a list of modules + // For the key the chunk "index" is used, the value is a SortableSet of modules + /** @type {Map} */ + const chunksInfoMap = new Map(); - // precalculate the modulo values for each bit - const modulo = 1 / Math.pow(1 / modulesCount, 1 / 31); - const modulos = Array.from( - { length: 31 }, - (x, i) => Math.pow(modulo, i) | 0 - ); + /** + * @param {TODO} cacheGroup the current cache group + * @param {number} cacheGroupIndex the index of the cache group of ordering + * @param {Chunk[]} selectedChunks chunks selected for this module + * @param {string} selectedChunksKey a key of selectedChunks + * @param {Module} module the current module + * @returns {void} + */ + const addModuleToChunksInfoMap = ( + cacheGroup, + cacheGroupIndex, + selectedChunks, + selectedChunksKey, + module + ) => { + // Break if minimum number of chunks is not reached + if (selectedChunks.length < cacheGroup.minChunks) return; + // Determine name for split chunk + const name = cacheGroup.getName( + module, + selectedChunks, + cacheGroup.key + ); + // Create key for maps + // When it has a name we use the name as key + // Elsewise we create the key from chunks and cache group key + // This automatically merges equal names + const key = + cacheGroup.key + + (name ? ` name:${name}` : ` chunks:${selectedChunksKey}`); + // Add module to maps + let info = chunksInfoMap.get(key); + if (info === undefined) { + chunksInfoMap.set( + key, + (info = { + modules: new SortableSet(undefined, sortByIdentifier), + cacheGroup, + cacheGroupIndex, + name, + size: 0, + chunks: new Set(), + reuseableChunks: new Set(), + chunksKeys: new Set() + }) + ); + } + info.modules.add(module); + info.size += module.size(); + if (!info.chunksKeys.has(selectedChunksKey)) { + info.chunksKeys.add(selectedChunksKey); + for (const chunk of selectedChunks) { + info.chunks.add(chunk); + } + } + }; - // iterate all modules to generate bit values - let i = 0; + // Walk through all modules for (const module of compilation.modules) { - let bit = 30; - while (i % modulos[bit] !== 0) { - bit--; + // Get cache group + let cacheGroups = this.options.getCacheGroups(module); + if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { + continue; } - moduleBits.set(module, 1 << bit); - i++; - } - // interate all chunks to generate bitmaps - const chunkModulesHash = new WeakMap(); - for (const chunk of chunks) { - let hash = 0; - for (const module of chunk.modulesIterable) { - hash |= moduleBits.get(module); + // Prepare some values + const chunksKey = getKey(module.chunksIterable); + let combs = combinationsCache.get(chunksKey); + if (combs === undefined) { + combs = getCombinations(chunksKey); + combinationsCache.set(chunksKey, combs); } - chunkModulesHash.set(chunk, hash); - } - for (const chunkA of chunks) { - const chunkAHash = chunkModulesHash.get(chunkA); - const chunkAModulesCount = chunkA.getNumberOfModules(); - if (chunkAModulesCount === 0) continue; - let bestModule = undefined; - for (const module of chunkA.modulesIterable) { - if ( - bestModule === undefined || - bestModule.getNumberOfChunks() > module.getNumberOfChunks() - ) - bestModule = module; - } - loopB: for (const chunkB of bestModule.chunksIterable) { - // as we iterate the same iterables twice - // skip if we find ourselves - if (chunkA === chunkB) continue; + let cacheGroupIndex = 0; + for (const cacheGroupSource of cacheGroups) { + const minSize = + cacheGroupSource.minSize !== undefined + ? cacheGroupSource.minSize + : cacheGroupSource.enforce + ? 0 + : this.options.minSize; + const enforceSizeThreshold = + cacheGroupSource.enforceSizeThreshold !== undefined + ? cacheGroupSource.enforceSizeThreshold + : cacheGroupSource.enforce + ? 0 + : this.options.enforceSizeThreshold; + const cacheGroup = { + key: cacheGroupSource.key, + priority: cacheGroupSource.priority || 0, + chunksFilter: + cacheGroupSource.chunksFilter || this.options.chunksFilter, + minSize, + minSizeForMaxSize: + cacheGroupSource.minSize !== undefined + ? cacheGroupSource.minSize + : this.options.minSize, + enforceSizeThreshold, + maxSize: + cacheGroupSource.maxSize !== undefined + ? cacheGroupSource.maxSize + : cacheGroupSource.enforce + ? 0 + : this.options.maxSize, + minChunks: + cacheGroupSource.minChunks !== undefined + ? cacheGroupSource.minChunks + : cacheGroupSource.enforce + ? 1 + : this.options.minChunks, + maxAsyncRequests: + cacheGroupSource.maxAsyncRequests !== undefined + ? cacheGroupSource.maxAsyncRequests + : cacheGroupSource.enforce + ? Infinity + : this.options.maxAsyncRequests, + maxInitialRequests: + cacheGroupSource.maxInitialRequests !== undefined + ? cacheGroupSource.maxInitialRequests + : cacheGroupSource.enforce + ? Infinity + : this.options.maxInitialRequests, + getName: + cacheGroupSource.getName !== undefined + ? cacheGroupSource.getName + : this.options.getName, + filename: + cacheGroupSource.filename !== undefined + ? cacheGroupSource.filename + : this.options.filename, + automaticNameDelimiter: + cacheGroupSource.automaticNameDelimiter !== undefined + ? cacheGroupSource.automaticNameDelimiter + : this.options.automaticNameDelimiter, + reuseExistingChunk: cacheGroupSource.reuseExistingChunk, + _validateSize: minSize > 0, + _conditionalEnforce: enforceSizeThreshold > 0 + }; + // For all combination of chunk selection + for (const chunkCombination of combs) { + // Break if minimum number of chunks is not reached + if (chunkCombination.size < cacheGroup.minChunks) continue; + // Select chunks by configuration + const { + chunks: selectedChunks, + key: selectedChunksKey + } = getSelectedChunks( + chunkCombination, + cacheGroup.chunksFilter + ); - const chunkBModulesCount = chunkB.getNumberOfModules(); + addModuleToChunksInfoMap( + cacheGroup, + cacheGroupIndex, + selectedChunks, + selectedChunksKey, + module + ); + } + cacheGroupIndex++; + } + } - // ids for empty chunks are not included - if (chunkBModulesCount === 0) continue; + // Filter items were size < minSize + for (const pair of chunksInfoMap) { + const info = pair[1]; + if ( + info.cacheGroup._validateSize && + info.size < info.cacheGroup.minSize + ) { + chunksInfoMap.delete(pair[0]); + } + } - // instead of swapping A and B just bail - // as we loop twice the current A will be B and B then A - if (chunkAModulesCount > chunkBModulesCount) continue; + /** @type {Map} */ + const maxSizeQueueMap = new Map(); - // is chunkA in chunkB? + while (chunksInfoMap.size > 0) { + // Find best matching entry + let bestEntryKey; + let bestEntry; + for (const pair of chunksInfoMap) { + const key = pair[0]; + const info = pair[1]; + if (bestEntry === undefined) { + bestEntry = info; + bestEntryKey = key; + } else if (compareEntries(bestEntry, info) < 0) { + bestEntry = info; + bestEntryKey = key; + } + } - // we do a cheap check for the hash value - const chunkBHash = chunkModulesHash.get(chunkB); - if ((chunkBHash & chunkAHash) !== chunkAHash) continue; + const item = bestEntry; + chunksInfoMap.delete(bestEntryKey); - // compare all modules - for (const m of chunkA.modulesIterable) { - if (!chunkB.containsModule(m)) continue loopB; + let chunkName = item.name; + // Variable for the new chunk (lazy created) + /** @type {Chunk} */ + let newChunk; + // When no chunk name, check if we can reuse a chunk instead of creating a new one + let isReused = false; + if (item.cacheGroup.reuseExistingChunk) { + outer: for (const chunk of item.chunks) { + if (chunk.getNumberOfModules() !== item.modules.size) continue; + if (chunk.hasEntryModule()) continue; + for (const module of item.modules) { + if (!chunk.containsModule(module)) continue outer; + } + if (!newChunk || !newChunk.name) { + newChunk = chunk; + } else if ( + chunk.name && + chunk.name.length < newChunk.name.length + ) { + newChunk = chunk; + } else if ( + chunk.name && + chunk.name.length === newChunk.name.length && + chunk.name < newChunk.name + ) { + newChunk = chunk; + } + chunkName = undefined; + isReused = true; } - chunkB.ids.push(chunkA.id); } - } - } - ); - }); - } -} -module.exports = FlagIncludedChunksPlugin; + // Check if maxRequests condition can be fulfilled + const selectedChunks = Array.from(item.chunks).filter(chunk => { + // skip if we address ourself + return ( + (!chunkName || chunk.name !== chunkName) && chunk !== newChunk + ); + }); -/***/ }), + const enforced = + item.cacheGroup._conditionalEnforce && + item.size >= item.cacheGroup.enforceSizeThreshold; -/***/ 3846: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + // Skip when no chunk selected + if (selectedChunks.length === 0) continue; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + const usedChunks = new Set(selectedChunks); + // Check if maxRequests condition can be fulfilled + if ( + !enforced && + (Number.isFinite(item.cacheGroup.maxInitialRequests) || + Number.isFinite(item.cacheGroup.maxAsyncRequests)) + ) { + for (const chunk of usedChunks) { + // respect max requests + const maxRequests = chunk.isOnlyInitial() + ? item.cacheGroup.maxInitialRequests + : chunk.canBeInitial() + ? Math.min( + item.cacheGroup.maxInitialRequests, + item.cacheGroup.maxAsyncRequests + ) + : item.cacheGroup.maxAsyncRequests; + if ( + isFinite(maxRequests) && + getRequests(chunk) >= maxRequests + ) { + usedChunks.delete(chunk); + } + } + } -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(27993); -const LazyBucketSortedSet = __webpack_require__(52315); + outer: for (const chunk of usedChunks) { + for (const module of item.modules) { + if (chunk.containsModule(module)) continue outer; + } + usedChunks.delete(chunk); + } -/** @typedef {import("../../declarations/plugins/optimize/LimitChunkCountPlugin").LimitChunkCountPluginOptions} LimitChunkCountPluginOptions */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Compiler")} Compiler */ - -/** - * @typedef {Object} ChunkCombination - * @property {boolean} deleted this is set to true when combination was removed - * @property {number} sizeDiff - * @property {number} integratedSize - * @property {Chunk} a - * @property {Chunk} b - * @property {number} aIdx - * @property {number} bIdx - * @property {number} aSize - * @property {number} bSize - */ - -const addToSetMap = (map, key, value) => { - const set = map.get(key); - if (set === undefined) { - map.set(key, new Set([value])); - } else { - set.add(value); - } -}; - -class LimitChunkCountPlugin { - /** - * @param {LimitChunkCountPluginOptions=} options options object - */ - constructor(options) { - if (!options) options = {}; - - validateOptions(schema, options, "Limit Chunk Count Plugin"); - this.options = options; - } - - /** - * @param {Compiler} compiler the webpack compiler - * @returns {void} - */ - apply(compiler) { - const options = this.options; - compiler.hooks.compilation.tap("LimitChunkCountPlugin", compilation => { - compilation.hooks.optimizeChunksAdvanced.tap( - "LimitChunkCountPlugin", - chunks => { - const maxChunks = options.maxChunks; - if (!maxChunks) return; - if (maxChunks < 1) return; - if (chunks.length <= maxChunks) return; - - let remainingChunksToMerge = chunks.length - maxChunks; - - // order chunks in a deterministic way - const orderedChunks = chunks.slice().sort((a, b) => a.compareTo(b)); - - // create a lazy sorted data structure to keep all combinations - // this is large. Size = chunks * (chunks - 1) / 2 - // It uses a multi layer bucket sort plus normal sort in the last layer - // It's also lazy so only accessed buckets are sorted - const combinations = new LazyBucketSortedSet( - // Layer 1: ordered by largest size benefit - c => c.sizeDiff, - (a, b) => b - a, - // Layer 2: ordered by smallest combined size - c => c.integratedSize, - (a, b) => a - b, - // Layer 3: ordered by position difference in orderedChunk (-> to be deterministic) - c => c.bIdx - c.aIdx, - (a, b) => a - b, - // Layer 4: ordered by position in orderedChunk (-> to be deterministic) - (a, b) => a.bIdx - b.bIdx - ); - - // we keep a mappng from chunk to all combinations - // but this mapping is not kept up-to-date with deletions - // so `deleted` flag need to be considered when iterating this - /** @type {Map>} */ - const combinationsByChunk = new Map(); - - orderedChunks.forEach((b, bIdx) => { - // create combination pairs with size and integrated size - for (let aIdx = 0; aIdx < bIdx; aIdx++) { - const a = orderedChunks[aIdx]; - const integratedSize = a.integratedSize(b, options); - - // filter pairs that do not have an integratedSize - // meaning they can NOT be integrated! - if (integratedSize === false) continue; - - const aSize = a.size(options); - const bSize = b.size(options); - const c = { - deleted: false, - sizeDiff: aSize + bSize - integratedSize, - integratedSize, - a, - b, - aIdx, - bIdx, - aSize, - bSize - }; - combinations.add(c); - addToSetMap(combinationsByChunk, a, c); - addToSetMap(combinationsByChunk, b, c); + // Were some (invalid) chunks removed from usedChunks? + // => readd all modules to the queue, as things could have been changed + if (usedChunks.size < selectedChunks.length) { + if (usedChunks.size >= item.cacheGroup.minChunks) { + const chunksArr = Array.from(usedChunks); + for (const module of item.modules) { + addModuleToChunksInfoMap( + item.cacheGroup, + item.cacheGroupIndex, + chunksArr, + getKey(usedChunks), + module + ); + } + } + continue; } - return combinations; - }); - - // list of modified chunks during this run - // combinations affected by this change are skipped to allow - // futher optimizations - /** @type {Set} */ - const modifiedChunks = new Set(); - - let changed = false; - // eslint-disable-next-line no-constant-condition - loop: while (true) { - const combination = combinations.popFirst(); - if (combination === undefined) break; - combination.deleted = true; - const { a, b, integratedSize } = combination; + // Create the new chunk if not reusing one + if (!isReused) { + newChunk = compilation.addChunk(chunkName); + } + // Walk through all chunks + for (const chunk of usedChunks) { + // Add graph connections for splitted chunk + chunk.split(newChunk); + } - // skip over pair when - // one of the already merged chunks is a parent of one of the chunks - if (modifiedChunks.size > 0) { - const queue = new Set(a.groupsIterable); - for (const group of b.groupsIterable) { - queue.add(group); + // Add a note to the chunk + newChunk.chunkReason = isReused + ? "reused as split chunk" + : "split chunk"; + if (item.cacheGroup.key) { + newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`; + } + if (chunkName) { + newChunk.chunkReason += ` (name: ${chunkName})`; + // If the chosen name is already an entry point we remove the entry point + const entrypoint = compilation.entrypoints.get(chunkName); + if (entrypoint) { + compilation.entrypoints.delete(chunkName); + entrypoint.remove(); + newChunk.entryModule = undefined; } - for (const group of queue) { - for (const mChunk of modifiedChunks) { - if (mChunk !== a && mChunk !== b && mChunk.isInGroup(group)) { - // This is a potential pair which needs recalculation - // We can't do that now, but it merge before following pairs - // so we leave space for it, and consider chunks as modified - // just for the worse case - remainingChunksToMerge--; - if (remainingChunksToMerge <= 0) break loop; - modifiedChunks.add(a); - modifiedChunks.add(b); - continue loop; - } + } + if (item.cacheGroup.filename) { + if (!newChunk.isOnlyInitial()) { + throw new Error( + "SplitChunksPlugin: You are trying to set a filename for a chunk which is (also) loaded on demand. " + + "The runtime can only handle loading of chunks which match the chunkFilename schema. " + + "Using a custom filename would fail at runtime. " + + `(cache group: ${item.cacheGroup.key})` + ); + } + newChunk.filenameTemplate = item.cacheGroup.filename; + } + if (!isReused) { + // Add all modules to the new chunk + for (const module of item.modules) { + if (typeof module.chunkCondition === "function") { + if (!module.chunkCondition(newChunk)) continue; } - for (const parent of group.parentsIterable) { - queue.add(parent); + // Add module to new chunk + GraphHelpers.connectChunkAndModule(newChunk, module); + // Remove module from used chunks + for (const chunk of usedChunks) { + chunk.removeModule(module); + module.rewriteChunkInReasons(chunk, [newChunk]); + } + } + } else { + // Remove all modules from used chunks + for (const module of item.modules) { + for (const chunk of usedChunks) { + chunk.removeModule(module); + module.rewriteChunkInReasons(chunk, [newChunk]); } } } - // merge the chunks - if (a.integrate(b, "limit")) { - chunks.splice(chunks.indexOf(b), 1); + if (item.cacheGroup.maxSize > 0) { + const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk); + maxSizeQueueMap.set(newChunk, { + minSize: Math.max( + oldMaxSizeSettings ? oldMaxSizeSettings.minSize : 0, + item.cacheGroup.minSizeForMaxSize + ), + maxSize: Math.min( + oldMaxSizeSettings ? oldMaxSizeSettings.maxSize : Infinity, + item.cacheGroup.maxSize + ), + automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter, + keys: oldMaxSizeSettings + ? oldMaxSizeSettings.keys.concat(item.cacheGroup.key) + : [item.cacheGroup.key] + }); + } - // flag chunk a as modified as further optimization are possible for all children here - modifiedChunks.add(a); + // remove all modules from other entries and update size + for (const [key, info] of chunksInfoMap) { + if (isOverlap(info.chunks, usedChunks)) { + // update modules and total size + // may remove it from the map when < minSize + const oldSize = info.modules.size; + for (const module of item.modules) { + info.modules.delete(module); + } + if (info.modules.size !== oldSize) { + if (info.modules.size === 0) { + chunksInfoMap.delete(key); + continue; + } + info.size = getModulesSize(info.modules); + if ( + info.cacheGroup._validateSize && + info.size < info.cacheGroup.minSize + ) { + chunksInfoMap.delete(key); + } + if (info.modules.size === 0) { + chunksInfoMap.delete(key); + } + } + } + } + } - changed = true; - remainingChunksToMerge--; - if (remainingChunksToMerge <= 0) break; + const incorrectMinMaxSizeSet = new Set(); - // Update all affected combinations - // delete all combination with the removed chunk - // we will use combinations with the kept chunk instead - for (const combination of combinationsByChunk.get(b)) { - if (combination.deleted) continue; - combination.deleted = true; - combinations.delete(combination); + // Make sure that maxSize is fulfilled + for (const chunk of compilation.chunks.slice()) { + const { minSize, maxSize, automaticNameDelimiter, keys } = + maxSizeQueueMap.get(chunk) || this.options.fallbackCacheGroup; + if (!maxSize) continue; + if (minSize > maxSize) { + const warningKey = `${keys && keys.join()} ${minSize} ${maxSize}`; + if (!incorrectMinMaxSizeSet.has(warningKey)) { + incorrectMinMaxSizeSet.add(warningKey); + compilation.warnings.push( + new MinMaxSizeWarning(keys, minSize, maxSize) + ); } - - // Update combinations with the kept chunk with new sizes - for (const combination of combinationsByChunk.get(a)) { - if (combination.deleted) continue; - if (combination.a === a) { - // Update size - const newIntegratedSize = a.integratedSize( - combination.b, - options - ); - if (newIntegratedSize === false) { - combination.deleted = true; - combinations.delete(combination); - continue; - } - const finishUpdate = combinations.startUpdate(combination); - combination.integratedSize = newIntegratedSize; - combination.aSize = integratedSize; - combination.sizeDiff = - combination.bSize + integratedSize - newIntegratedSize; - finishUpdate(); - } else if (combination.b === a) { - // Update size - const newIntegratedSize = combination.a.integratedSize( - a, - options - ); - if (newIntegratedSize === false) { - combination.deleted = true; - combinations.delete(combination); - continue; + } + const results = deterministicGroupingForModules({ + maxSize: Math.max(minSize, maxSize), + minSize, + items: chunk.modulesIterable, + getKey(module) { + const ident = contextify( + compilation.options.context, + module.identifier() + ); + const name = module.nameForCondition + ? contextify( + compilation.options.context, + module.nameForCondition() + ) + : ident.replace(/^.*!|\?[^?!]*$/g, ""); + const fullKey = + name + automaticNameDelimiter + hashFilename(ident); + return fullKey.replace(/[\\/?]/g, "_"); + }, + getSize(module) { + return module.size(); + } + }); + results.sort((a, b) => { + if (a.key < b.key) return -1; + if (a.key > b.key) return 1; + return 0; + }); + for (let i = 0; i < results.length; i++) { + const group = results[i]; + const key = this.options.hidePathInfo + ? hashFilename(group.key) + : group.key; + let name = chunk.name + ? chunk.name + automaticNameDelimiter + key + : null; + if (name && name.length > 100) { + name = + name.slice(0, 100) + + automaticNameDelimiter + + hashFilename(name); + } + let newPart; + if (i !== results.length - 1) { + newPart = compilation.addChunk(name); + chunk.split(newPart); + newPart.chunkReason = chunk.chunkReason; + // Add all modules to the new chunk + for (const module of group.items) { + if (typeof module.chunkCondition === "function") { + if (!module.chunkCondition(newPart)) continue; } - const finishUpdate = combinations.startUpdate(combination); - combination.integratedSize = newIntegratedSize; - combination.bSize = integratedSize; - combination.sizeDiff = - integratedSize + combination.aSize - newIntegratedSize; - finishUpdate(); + // Add module to new chunk + GraphHelpers.connectChunkAndModule(newPart, module); + // Remove module from used chunks + chunk.removeModule(module); + module.rewriteChunkInReasons(chunk, [newPart]); } + } else { + // change the chunk to be a part + newPart = chunk; + chunk.name = name; } } } - if (changed) return true; } ); }); } -} -module.exports = LimitChunkCountPlugin; +}; /***/ }), -/***/ 46214: -/***/ (function(module) { +/***/ 89339: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sean Larkin @thelarkinn */ -class MergeDuplicateChunksPlugin { - apply(compiler) { - compiler.hooks.compilation.tap( - "MergeDuplicateChunksPlugin", - compilation => { - compilation.hooks.optimizeChunksBasic.tap( - "MergeDuplicateChunksPlugin", - chunks => { - // remember already tested chunks for performance - const notDuplicates = new Set(); +const WebpackError = __webpack_require__(97391); +const SizeFormatHelpers = __webpack_require__(12496); - // for each chunk - for (const chunk of chunks) { - // track a Set of all chunk that could be duplicates - let possibleDuplicates; - for (const module of chunk.modulesIterable) { - if (possibleDuplicates === undefined) { - // when possibleDuplicates is not yet set, - // create a new Set from chunks of the current module - // including only chunks with the same number of modules - for (const dup of module.chunksIterable) { - if ( - dup !== chunk && - chunk.getNumberOfModules() === dup.getNumberOfModules() && - !notDuplicates.has(dup) - ) { - // delay allocating the new Set until here, reduce memory pressure - if (possibleDuplicates === undefined) { - possibleDuplicates = new Set(); - } - possibleDuplicates.add(dup); - } - } - // when no chunk is possible we can break here - if (possibleDuplicates === undefined) break; - } else { - // validate existing possible duplicates - for (const dup of possibleDuplicates) { - // remove possible duplicate when module is not contained - if (!dup.containsModule(module)) { - possibleDuplicates.delete(dup); - } - } - // when all chunks has been removed we can break here - if (possibleDuplicates.size === 0) break; - } - } +module.exports = class AssetsOverSizeLimitWarning extends WebpackError { + constructor(assetsOverSizeLimit, assetLimit) { + const assetLists = assetsOverSizeLimit + .map( + asset => + `\n ${asset.name} (${SizeFormatHelpers.formatSize(asset.size)})` + ) + .join(""); - // when we found duplicates - if ( - possibleDuplicates !== undefined && - possibleDuplicates.size > 0 - ) { - for (const otherChunk of possibleDuplicates) { - if (otherChunk.hasRuntime() !== chunk.hasRuntime()) continue; - // merge them - if (chunk.integrate(otherChunk, "duplicate")) { - chunks.splice(chunks.indexOf(otherChunk), 1); - } - } - } + super(`asset size limit: The following asset(s) exceed the recommended size limit (${SizeFormatHelpers.formatSize( + assetLimit + )}). +This can impact web performance. +Assets: ${assetLists}`); - // don't check already processed chunks twice - notDuplicates.add(chunk); - } - } - ); - } - ); + this.name = "AssetsOverSizeLimitWarning"; + this.assets = assetsOverSizeLimit; + + Error.captureStackTrace(this, this.constructor); } -} -module.exports = MergeDuplicateChunksPlugin; +}; /***/ }), -/***/ 55607: +/***/ 41336: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sean Larkin @thelarkinn */ -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(8670); +const WebpackError = __webpack_require__(97391); +const SizeFormatHelpers = __webpack_require__(12496); -/** @typedef {import("../../declarations/plugins/optimize/MinChunkSizePlugin").MinChunkSizePluginOptions} MinChunkSizePluginOptions */ +module.exports = class EntrypointsOverSizeLimitWarning extends WebpackError { + constructor(entrypoints, entrypointLimit) { + const entrypointList = entrypoints + .map( + entrypoint => + `\n ${entrypoint.name} (${SizeFormatHelpers.formatSize( + entrypoint.size + )})\n${entrypoint.files.map(asset => ` ${asset}`).join("\n")}` + ) + .join(""); + super(`entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (${SizeFormatHelpers.formatSize( + entrypointLimit + )}). This can impact web performance. +Entrypoints:${entrypointList}\n`); -class MinChunkSizePlugin { - /** - * @param {MinChunkSizePluginOptions} options options object - */ - constructor(options) { - validateOptions(schema, options, "Min Chunk Size Plugin"); - this.options = options; - } - - apply(compiler) { - const options = this.options; - const minChunkSize = options.minChunkSize; - compiler.hooks.compilation.tap("MinChunkSizePlugin", compilation => { - compilation.hooks.optimizeChunksAdvanced.tap( - "MinChunkSizePlugin", - chunks => { - const equalOptions = { - chunkOverhead: 1, - entryChunkMultiplicator: 1 - }; - - const sortedSizeFilteredExtendedPairCombinations = chunks - .reduce((combinations, a, idx) => { - // create combination pairs - for (let i = 0; i < idx; i++) { - const b = chunks[i]; - combinations.push([b, a]); - } - return combinations; - }, []) - .filter(pair => { - // check if one of the chunks sizes is smaller than the minChunkSize - const p0SmallerThanMinChunkSize = - pair[0].size(equalOptions) < minChunkSize; - const p1SmallerThanMinChunkSize = - pair[1].size(equalOptions) < minChunkSize; - return p0SmallerThanMinChunkSize || p1SmallerThanMinChunkSize; - }) - .map(pair => { - // extend combination pairs with size and integrated size - const a = pair[0].size(options); - const b = pair[1].size(options); - const ab = pair[0].integratedSize(pair[1], options); - return [a + b - ab, ab, pair[0], pair[1]]; - }) - .filter(pair => { - // filter pairs that do not have an integratedSize - // meaning they can NOT be integrated! - return pair[1] !== false; - }) - .sort((a, b) => { - // sadly javascript does an inplace sort here - // sort by size - const diff = b[0] - a[0]; - if (diff !== 0) return diff; - return a[1] - b[1]; - }); - - if (sortedSizeFilteredExtendedPairCombinations.length === 0) return; - - const pair = sortedSizeFilteredExtendedPairCombinations[0]; + this.name = "EntrypointsOverSizeLimitWarning"; + this.entrypoints = entrypoints; - pair[2].integrate(pair[3], "min-size"); - chunks.splice(chunks.indexOf(pair[3]), 1); - return true; - } - ); - }); + Error.captureStackTrace(this, this.constructor); } -} -module.exports = MinChunkSizePlugin; +}; /***/ }), -/***/ 25472: +/***/ 53006: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sean Larkin @thelarkinn */ const WebpackError = __webpack_require__(97391); -const SizeFormatHelpers = __webpack_require__(12496); -class MinMaxSizeWarning extends WebpackError { - constructor(keys, minSize, maxSize) { - let keysMessage = "Fallback cache group"; - if (keys) { - keysMessage = - keys.length > 1 - ? `Cache groups ${keys.sort().join(", ")}` - : `Cache group ${keys[0]}`; - } +module.exports = class NoAsyncChunksWarning extends WebpackError { + constructor() { super( - `SplitChunksPlugin\n` + - `${keysMessage}\n` + - `Configured minSize (${SizeFormatHelpers.formatSize(minSize)}) is ` + - `bigger than maxSize (${SizeFormatHelpers.formatSize(maxSize)}).\n` + - "This seem to be a invalid optimiziation.splitChunks configuration." + "webpack performance recommendations: \n" + + "You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\n" + + "For more info visit https://webpack.js.org/guides/code-splitting/" ); - } -} -module.exports = MinMaxSizeWarning; + this.name = "NoAsyncChunksWarning"; + + Error.captureStackTrace(this, this.constructor); + } +}; /***/ }), -/***/ 45184: +/***/ 68310: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + Author Sean Larkin @thelarkinn */ +const EntrypointsOverSizeLimitWarning = __webpack_require__(41336); +const AssetsOverSizeLimitWarning = __webpack_require__(89339); +const NoAsyncChunksWarning = __webpack_require__(53006); -const HarmonyImportDependency = __webpack_require__(81599); -const ModuleHotAcceptDependency = __webpack_require__(29018); -const ModuleHotDeclineDependency = __webpack_require__(60482); -const ConcatenatedModule = __webpack_require__(16953); -const HarmonyCompatibilityDependency = __webpack_require__(1533); -const StackedSetMap = __webpack_require__(92251); - -const formatBailoutReason = msg => { - return "ModuleConcatenation bailout: " + msg; -}; +/** @typedef {import("../Compiler")} Compiler */ +/** @typedef {import("../Entrypoint")} Entrypoint */ -class ModuleConcatenationPlugin { +module.exports = class SizeLimitsPlugin { constructor(options) { - if (typeof options !== "object") options = {}; - this.options = options; + this.hints = options.hints; + this.maxAssetSize = options.maxAssetSize; + this.maxEntrypointSize = options.maxEntrypointSize; + this.assetFilter = options.assetFilter; } + /** + * @param {Compiler} compiler webpack compiler + * @returns {void} + */ apply(compiler) { - compiler.hooks.compilation.tap( - "ModuleConcatenationPlugin", - (compilation, { normalModuleFactory }) => { - const handler = (parser, parserOptions) => { - parser.hooks.call.for("eval").tap("ModuleConcatenationPlugin", () => { - // Because of variable renaming we can't use modules with eval. - parser.state.module.buildMeta.moduleConcatenationBailout = "eval()"; + const entrypointSizeLimit = this.maxEntrypointSize; + const assetSizeLimit = this.maxAssetSize; + const hints = this.hints; + const assetFilter = + this.assetFilter || ((name, source, info) => !info.development); + + compiler.hooks.afterEmit.tap("SizeLimitsPlugin", compilation => { + const warnings = []; + + /** + * @param {Entrypoint} entrypoint an entrypoint + * @returns {number} the size of the entrypoint + */ + const getEntrypointSize = entrypoint => + entrypoint.getFiles().reduce((currentSize, file) => { + const asset = compilation.getAsset(file); + if ( + asset && + assetFilter(asset.name, asset.source, asset.info) && + asset.source + ) { + return currentSize + (asset.info.size || asset.source.size()); + } + + return currentSize; + }, 0); + + const assetsOverSizeLimit = []; + for (const { name, source, info } of compilation.getAssets()) { + if (!assetFilter(name, source, info) || !source) { + continue; + } + + const size = info.size || source.size(); + if (size > assetSizeLimit) { + assetsOverSizeLimit.push({ + name, + size }); - }; + /** @type {any} */ (source).isOverSizeLimit = true; + } + } - normalModuleFactory.hooks.parser - .for("javascript/auto") - .tap("ModuleConcatenationPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/dynamic") - .tap("ModuleConcatenationPlugin", handler); - normalModuleFactory.hooks.parser - .for("javascript/esm") - .tap("ModuleConcatenationPlugin", handler); + const fileFilter = name => { + const asset = compilation.getAsset(name); + return asset && assetFilter(asset.name, asset.source, asset.info); + }; - const bailoutReasonMap = new Map(); + const entrypointsOverLimit = []; + for (const [name, entry] of compilation.entrypoints) { + const size = getEntrypointSize(entry); - const setBailoutReason = (module, reason) => { - bailoutReasonMap.set(module, reason); - module.optimizationBailout.push( - typeof reason === "function" - ? rs => formatBailoutReason(reason(rs)) - : formatBailoutReason(reason) + if (size > entrypointSizeLimit) { + entrypointsOverLimit.push({ + name: name, + size: size, + files: entry.getFiles().filter(fileFilter) + }); + /** @type {any} */ (entry).isOverSizeLimit = true; + } + } + + if (hints) { + // 1. Individual Chunk: Size < 250kb + // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb + // 3. No Async Chunks + // if !1, then 2, if !2 return + if (assetsOverSizeLimit.length > 0) { + warnings.push( + new AssetsOverSizeLimitWarning(assetsOverSizeLimit, assetSizeLimit) ); - }; + } + if (entrypointsOverLimit.length > 0) { + warnings.push( + new EntrypointsOverSizeLimitWarning( + entrypointsOverLimit, + entrypointSizeLimit + ) + ); + } - const getBailoutReason = (module, requestShortener) => { - const reason = bailoutReasonMap.get(module); - if (typeof reason === "function") return reason(requestShortener); - return reason; - }; + if (warnings.length > 0) { + const hasAsyncChunks = + compilation.chunks.filter(chunk => !chunk.canBeInitial()).length > + 0; - compilation.hooks.optimizeChunkModules.tap( - "ModuleConcatenationPlugin", - (allChunks, modules) => { - const relevantModules = []; - const possibleInners = new Set(); - for (const module of modules) { - // Only harmony modules are valid for optimization - if ( - !module.buildMeta || - module.buildMeta.exportsType !== "namespace" || - !module.dependencies.some( - d => d instanceof HarmonyCompatibilityDependency - ) - ) { - setBailoutReason(module, "Module is not an ECMAScript module"); - continue; - } + if (!hasAsyncChunks) { + warnings.push(new NoAsyncChunksWarning()); + } - // Some expressions are not compatible with module concatenation - // because they may produce unexpected results. The plugin bails out - // if some were detected upfront. - if ( - module.buildMeta && - module.buildMeta.moduleConcatenationBailout - ) { - setBailoutReason( - module, - `Module uses ${module.buildMeta.moduleConcatenationBailout}` - ); - continue; - } + if (hints === "error") { + compilation.errors.push(...warnings); + } else { + compilation.warnings.push(...warnings); + } + } + } + }); + } +}; - // Exports must be known (and not dynamic) - if (!Array.isArray(module.buildMeta.providedExports)) { - setBailoutReason(module, "Module exports are unknown"); - continue; - } - // Using dependency variables is not possible as this wraps the code in a function - if (module.variables.length > 0) { - setBailoutReason( - module, - `Module uses injected variables (${module.variables - .map(v => v.name) - .join(", ")})` - ); - continue; - } +/***/ }), - // Hot Module Replacement need it's own module to work correctly - if ( - module.dependencies.some( - dep => - dep instanceof ModuleHotAcceptDependency || - dep instanceof ModuleHotDeclineDependency - ) - ) { - setBailoutReason(module, "Module uses Hot Module Replacement"); - continue; - } +/***/ 52315: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - relevantModules.push(module); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Module must not be the entry points - if (module.isEntryModule()) { - setBailoutReason(module, "Module is an entry point"); - continue; - } - // Module must be in any chunk (we don't want to do useless work) - if (module.getNumberOfChunks() === 0) { - setBailoutReason(module, "Module is not in any chunk"); - continue; - } - // Module must only be used by Harmony Imports - const nonHarmonyReasons = module.reasons.filter( - reason => - !reason.dependency || - !(reason.dependency instanceof HarmonyImportDependency) - ); - if (nonHarmonyReasons.length > 0) { - const importingModules = new Set( - nonHarmonyReasons.map(r => r.module).filter(Boolean) - ); - const importingExplanations = new Set( - nonHarmonyReasons.map(r => r.explanation).filter(Boolean) - ); - const importingModuleTypes = new Map( - Array.from(importingModules).map( - m => /** @type {[string, Set]} */ ([ - m, - new Set( - nonHarmonyReasons - .filter(r => r.module === m) - .map(r => r.dependency.type) - .sort() - ) - ]) - ) - ); - setBailoutReason(module, requestShortener => { - const names = Array.from(importingModules) - .map( - m => - `${m.readableIdentifier( - requestShortener - )} (referenced with ${Array.from( - importingModuleTypes.get(m) - ).join(", ")})` - ) - .sort(); - const explanations = Array.from(importingExplanations).sort(); - if (names.length > 0 && explanations.length === 0) { - return `Module is referenced from these modules with unsupported syntax: ${names.join( - ", " - )}`; - } else if (names.length === 0 && explanations.length > 0) { - return `Module is referenced by: ${explanations.join( - ", " - )}`; - } else if (names.length > 0 && explanations.length > 0) { - return `Module is referenced from these modules with unsupported syntax: ${names.join( - ", " - )} and by: ${explanations.join(", ")}`; - } else { - return "Module is referenced in a unsupported way"; - } - }); - continue; - } +const SortableSet = __webpack_require__(50071); - possibleInners.add(module); - } - // sort by depth - // modules with lower depth are more likely suited as roots - // this improves performance, because modules already selected as inner are skipped - relevantModules.sort((a, b) => { - return a.depth - b.depth; - }); - const concatConfigurations = []; - const usedAsInner = new Set(); - for (const currentRoot of relevantModules) { - // when used by another configuration as inner: - // the other configuration is better and we can skip this one - if (usedAsInner.has(currentRoot)) continue; +/** + * @template T + * @template K + * Multi layer bucket sorted set + * Supports adding non-existing items (DO NOT ADD ITEM TWICE) + * Supports removing exiting items (DO NOT REMOVE ITEM NOT IN SET) + * Supports popping the first items according to defined order + * Supports iterating all items without order + * Supports updating an item in an efficient way + * Supports size property, which is the number of items + * Items are lazy partially sorted when needed + */ +class LazyBucketSortedSet { + /** + * @param {function(T): K} getKey function to get key from item + * @param {function(K, K): number} comparator comparator to sort keys + * @param {...((function(T): any) | (function(any, any): number))} args more pairs of getKey and comparator plus optional final comparator for the last layer + */ + constructor(getKey, comparator, ...args) { + this._getKey = getKey; + this._innerArgs = args; + this._leaf = args.length <= 1; + this._keys = new SortableSet(undefined, comparator); + /** @type {Map | SortableSet>} */ + this._map = new Map(); + this._unsortedItems = new Set(); + this.size = 0; + } - // create a configuration with the root - const currentConfiguration = new ConcatConfiguration(currentRoot); + /** + * @param {T} item an item + * @returns {void} + */ + add(item) { + this.size++; + this._unsortedItems.add(item); + } - // cache failures to add modules - const failureCache = new Map(); + /** + * @param {K} key key of item + * @param {T} item the item + * @returns {void} + */ + _addInternal(key, item) { + let entry = this._map.get(key); + if (entry === undefined) { + entry = this._leaf + ? new SortableSet(undefined, this._innerArgs[0]) + : new /** @type {any} */ (LazyBucketSortedSet)(...this._innerArgs); + this._keys.add(key); + this._map.set(key, entry); + } + entry.add(item); + } - // try to add all imports - for (const imp of this._getImports(compilation, currentRoot)) { - const problem = this._tryToAdd( - compilation, - currentConfiguration, - imp, - possibleInners, - failureCache - ); - if (problem) { - failureCache.set(imp, problem); - currentConfiguration.addWarning(imp, problem); - } - } - if (!currentConfiguration.isEmpty()) { - concatConfigurations.push(currentConfiguration); - for (const module of currentConfiguration.getModules()) { - if (module !== currentConfiguration.rootModule) { - usedAsInner.add(module); - } - } - } - } - // HACK: Sort configurations by length and start with the longest one - // to get the biggers groups possible. Used modules are marked with usedModules - // TODO: Allow to reuse existing configuration while trying to add dependencies. - // This would improve performance. O(n^2) -> O(n) - concatConfigurations.sort((a, b) => { - return b.modules.size - a.modules.size; - }); - const usedModules = new Set(); - for (const concatConfiguration of concatConfigurations) { - if (usedModules.has(concatConfiguration.rootModule)) continue; - const modules = concatConfiguration.getModules(); - const rootModule = concatConfiguration.rootModule; - const newModule = new ConcatenatedModule( - rootModule, - Array.from(modules), - ConcatenatedModule.createConcatenationList( - rootModule, - modules, - compilation - ) - ); - for (const warning of concatConfiguration.getWarningsSorted()) { - newModule.optimizationBailout.push(requestShortener => { - const reason = getBailoutReason(warning[0], requestShortener); - const reasonWithPrefix = reason ? ` (<- ${reason})` : ""; - if (warning[0] === warning[1]) { - return formatBailoutReason( - `Cannot concat with ${warning[0].readableIdentifier( - requestShortener - )}${reasonWithPrefix}` - ); - } else { - return formatBailoutReason( - `Cannot concat with ${warning[0].readableIdentifier( - requestShortener - )} because of ${warning[1].readableIdentifier( - requestShortener - )}${reasonWithPrefix}` - ); - } - }); - } - const chunks = concatConfiguration.rootModule.getChunks(); - for (const m of modules) { - usedModules.add(m); - for (const chunk of chunks) { - chunk.removeModule(m); - } - } - for (const chunk of chunks) { - chunk.addModule(newModule); - newModule.addChunk(chunk); - } - for (const chunk of allChunks) { - if (chunk.entryModule === concatConfiguration.rootModule) { - chunk.entryModule = newModule; - } - } - compilation.modules.push(newModule); - for (const reason of newModule.reasons) { - if (reason.dependency.module === concatConfiguration.rootModule) - reason.dependency.module = newModule; - if ( - reason.dependency.redirectedModule === - concatConfiguration.rootModule - ) - reason.dependency.redirectedModule = newModule; - } - // TODO: remove when LTS node version contains fixed v8 version - // @see https://github.com/webpack/webpack/pull/6613 - // Turbofan does not correctly inline for-of loops with polymorphic input arrays. - // Work around issue by using a standard for loop and assigning dep.module.reasons - for (let i = 0; i < newModule.dependencies.length; i++) { - let dep = newModule.dependencies[i]; - if (dep.module) { - let reasons = dep.module.reasons; - for (let j = 0; j < reasons.length; j++) { - let reason = reasons[j]; - if (reason.dependency === dep) { - reason.module = newModule; - } - } - } - } - } - compilation.modules = compilation.modules.filter( - m => !usedModules.has(m) - ); - } - ); - } - ); - } - - _getImports(compilation, module) { - return new Set( - module.dependencies - - // Get reference info only for harmony Dependencies - .map(dep => { - if (!(dep instanceof HarmonyImportDependency)) return null; - if (!compilation) return dep.getReference(); - return compilation.getDependencyReference(module, dep); - }) - - // Reference is valid and has a module - // Dependencies are simple enough to concat them - .filter( - ref => - ref && - ref.module && - (Array.isArray(ref.importedNames) || - Array.isArray(ref.module.buildMeta.providedExports)) - ) - - // Take the imported module - .map(ref => ref.module) - ); - } - - _tryToAdd(compilation, config, module, possibleModules, failureCache) { - const cacheEntry = failureCache.get(module); - if (cacheEntry) { - return cacheEntry; - } - - // Already added? - if (config.has(module)) { - return null; - } - - // Not possible to add? - if (!possibleModules.has(module)) { - failureCache.set(module, module); // cache failures for performance - return module; + /** + * @param {T} item an item + * @returns {void} + */ + delete(item) { + this.size--; + if (this._unsortedItems.has(item)) { + this._unsortedItems.delete(item); + return; } - - // module must be in the same chunks - if (!config.rootModule.hasEqualsChunks(module)) { - failureCache.set(module, module); // cache failures for performance - return module; + const key = this._getKey(item); + const entry = this._map.get(key); + entry.delete(item); + if (entry.size === 0) { + this._deleteKey(key); } + } - // Clone config to make experimental changes - const testConfig = config.clone(); - - // Add the module - testConfig.add(module); - - // Every module which depends on the added module must be in the configuration too. - for (const reason of module.reasons) { - // Modules that are not used can be ignored - if ( - reason.module.factoryMeta.sideEffectFree && - reason.module.used === false - ) - continue; + /** + * @param {K} key key to be removed + * @returns {void} + */ + _deleteKey(key) { + this._keys.delete(key); + this._map.delete(key); + } - const problem = this._tryToAdd( - compilation, - testConfig, - reason.module, - possibleModules, - failureCache - ); - if (problem) { - failureCache.set(module, problem); // cache failures for performance - return problem; + /** + * @returns {T | undefined} an item + */ + popFirst() { + if (this.size === 0) return undefined; + this.size--; + if (this._unsortedItems.size > 0) { + for (const item of this._unsortedItems) { + const key = this._getKey(item); + this._addInternal(key, item); } + this._unsortedItems.clear(); } - - // Commit experimental changes - config.set(testConfig); - - // Eagerly try to add imports too if possible - for (const imp of this._getImports(compilation, module)) { - const problem = this._tryToAdd( - compilation, - config, - imp, - possibleModules, - failureCache - ); - if (problem) { - config.addWarning(imp, problem); + this._keys.sort(); + const key = this._keys.values().next().value; + const entry = this._map.get(key); + if (this._leaf) { + const leafEntry = /** @type {SortableSet} */ (entry); + leafEntry.sort(); + const item = leafEntry.values().next().value; + leafEntry.delete(item); + if (leafEntry.size === 0) { + this._deleteKey(key); + } + return item; + } else { + const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); + const item = nodeEntry.popFirst(); + if (nodeEntry.size === 0) { + this._deleteKey(key); } + return item; } - return null; } -} -class ConcatConfiguration { - constructor(rootModule, cloneFrom) { - this.rootModule = rootModule; - if (cloneFrom) { - this.modules = cloneFrom.modules.createChild(5); - this.warnings = cloneFrom.warnings.createChild(5); + /** + * @param {T} item to be updated item + * @returns {function(true=): void} finish update + */ + startUpdate(item) { + if (this._unsortedItems.has(item)) { + return remove => { + if (remove) { + this._unsortedItems.delete(item); + this.size--; + return; + } + }; + } + const key = this._getKey(item); + if (this._leaf) { + const oldEntry = /** @type {SortableSet} */ (this._map.get(key)); + return remove => { + if (remove) { + this.size--; + oldEntry.delete(item); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + return; + } + const newKey = this._getKey(item); + if (key === newKey) { + // This flags the sortable set as unordered + oldEntry.add(item); + } else { + oldEntry.delete(item); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + this._addInternal(newKey, item); + } + }; } else { - this.modules = new StackedSetMap(); - this.modules.add(rootModule); - this.warnings = new StackedSetMap(); + const oldEntry = /** @type {LazyBucketSortedSet} */ (this._map.get( + key + )); + const finishUpdate = oldEntry.startUpdate(item); + return remove => { + if (remove) { + this.size--; + finishUpdate(true); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + return; + } + const newKey = this._getKey(item); + if (key === newKey) { + finishUpdate(); + } else { + finishUpdate(true); + if (oldEntry.size === 0) { + this._deleteKey(key); + } + this._addInternal(newKey, item); + } + }; } } - add(module) { - this.modules.add(module); - } - - has(module) { - return this.modules.has(module); - } - - isEmpty() { - return this.modules.size === 1; - } - - addWarning(module, problem) { - this.warnings.set(module, problem); - } - - getWarningsSorted() { - return new Map( - this.warnings.asPairArray().sort((a, b) => { - const ai = a[0].identifier(); - const bi = b[0].identifier(); - if (ai < bi) return -1; - if (ai > bi) return 1; - return 0; - }) - ); - } - - getModules() { - return this.modules.asSet(); - } - - clone() { - return new ConcatConfiguration(this.rootModule, this); + /** + * @param {Iterator[]} iterators list of iterators to append to + * @returns {void} + */ + _appendIterators(iterators) { + if (this._unsortedItems.size > 0) + iterators.push(this._unsortedItems[Symbol.iterator]()); + for (const key of this._keys) { + const entry = this._map.get(key); + if (this._leaf) { + const leafEntry = /** @type {SortableSet} */ (entry); + const iterator = leafEntry[Symbol.iterator](); + iterators.push(iterator); + } else { + const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); + nodeEntry._appendIterators(iterators); + } + } } - set(config) { - this.rootModule = config.rootModule; - this.modules = config.modules; - this.warnings = config.warnings; + /** + * @returns {Iterator} the iterator + */ + [Symbol.iterator]() { + const iterators = []; + this._appendIterators(iterators); + iterators.reverse(); + let currentIterator = iterators.pop(); + return { + next: () => { + const res = currentIterator.next(); + if (res.done) { + if (iterators.length === 0) return res; + currentIterator = iterators.pop(); + return currentIterator.next(); + } + return res; + } + }; } } -module.exports = ModuleConcatenationPlugin; +module.exports = LazyBucketSortedSet; /***/ }), -/***/ 68053: +/***/ 38637: /***/ (function(module) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -/** @typedef {import("../Compiler")} Compiler */ +/** + * @template T + */ +class Queue { + /** + * @param {Iterable=} items The initial elements. + */ + constructor(items) { + /** @private @type {Set} */ + this.set = new Set(items); + /** @private @type {Iterator} */ + this.iterator = this.set[Symbol.iterator](); + } -class NaturalChunkOrderPlugin { /** - * @param {Compiler} compiler webpack compiler + * Returns the number of elements in this queue. + * @returns {number} The number of elements in this queue. + */ + get length() { + return this.set.size; + } + + /** + * Appends the specified element to this queue. + * @param {T} item The element to add. * @returns {void} */ - apply(compiler) { - compiler.hooks.compilation.tap("NaturalChunkOrderPlugin", compilation => { - compilation.hooks.optimizeChunkOrder.tap( - "NaturalChunkOrderPlugin", - chunks => { - chunks.sort((chunkA, chunkB) => { - const a = chunkA.modulesIterable[Symbol.iterator](); - const b = chunkB.modulesIterable[Symbol.iterator](); - // eslint-disable-next-line no-constant-condition - while (true) { - const aItem = a.next(); - const bItem = b.next(); - if (aItem.done && bItem.done) return 0; - if (aItem.done) return -1; - if (bItem.done) return 1; - const aModuleId = aItem.value.id; - const bModuleId = bItem.value.id; - if (aModuleId < bModuleId) return -1; - if (aModuleId > bModuleId) return 1; - } - }); - } - ); - }); + enqueue(item) { + this.set.add(item); + } + + /** + * Retrieves and removes the head of this queue. + * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + */ + dequeue() { + const result = this.iterator.next(); + if (result.done) return undefined; + this.set.delete(result.value); + return result.value; } } -module.exports = NaturalChunkOrderPlugin; +module.exports = Queue; /***/ }), -/***/ 83741: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 33349: +/***/ (function(module) { "use strict"; /* @@ -108663,384 +107358,262 @@ module.exports = NaturalChunkOrderPlugin; */ -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(88771); - -/** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderChunkIdsPlugin").OccurrenceOrderChunkIdsPluginOptions} OccurrenceOrderChunkIdsPluginOptions */ - -class OccurrenceOrderChunkIdsPlugin { +class Semaphore { /** - * @param {OccurrenceOrderChunkIdsPluginOptions=} options options object + * Creates an instance of Semaphore. + * + * @param {number} available the amount available number of "tasks" + * in the Semaphore */ - constructor(options = {}) { - validateOptions(schema, options, "Occurrence Order Chunk Ids Plugin"); - this.options = options; + constructor(available) { + this.available = available; + /** @type {(function(): void)[]} */ + this.waiters = []; + /** @private */ + this._continue = this._continue.bind(this); } - apply(compiler) { - const prioritiseInitial = this.options.prioritiseInitial; - compiler.hooks.compilation.tap( - "OccurrenceOrderChunkIdsPlugin", - compilation => { - compilation.hooks.optimizeChunkOrder.tap( - "OccurrenceOrderChunkIdsPlugin", - chunks => { - const occursInInitialChunksMap = new Map(); - const originalOrder = new Map(); + /** + * @param {function(): void} callback function block to capture and run + * @returns {void} + */ + acquire(callback) { + if (this.available > 0) { + this.available--; + callback(); + } else { + this.waiters.push(callback); + } + } - let i = 0; - for (const c of chunks) { - let occurs = 0; - for (const chunkGroup of c.groupsIterable) { - for (const parent of chunkGroup.parentsIterable) { - if (parent.isInitial()) occurs++; - } - } - occursInInitialChunksMap.set(c, occurs); - originalOrder.set(c, i++); - } + release() { + this.available++; + if (this.waiters.length > 0) { + process.nextTick(this._continue); + } + } - chunks.sort((a, b) => { - if (prioritiseInitial) { - const aEntryOccurs = occursInInitialChunksMap.get(a); - const bEntryOccurs = occursInInitialChunksMap.get(b); - if (aEntryOccurs > bEntryOccurs) return -1; - if (aEntryOccurs < bEntryOccurs) return 1; - } - const aOccurs = a.getNumberOfGroups(); - const bOccurs = b.getNumberOfGroups(); - if (aOccurs > bOccurs) return -1; - if (aOccurs < bOccurs) return 1; - const orgA = originalOrder.get(a); - const orgB = originalOrder.get(b); - return orgA - orgB; - }); - } - ); + _continue() { + if (this.available > 0) { + if (this.waiters.length > 0) { + this.available--; + const callback = this.waiters.pop(); + callback(); } - ); + } } } -module.exports = OccurrenceOrderChunkIdsPlugin; +module.exports = Semaphore; /***/ }), -/***/ 62000: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 54262: +/***/ (function(__unused_webpack_module, exports) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - -const validateOptions = __webpack_require__(33225); -const schema = __webpack_require__(81430); - -/** @typedef {import("../../declarations/plugins/optimize/OccurrenceOrderModuleIdsPlugin").OccurrenceOrderModuleIdsPluginOptions} OccurrenceOrderModuleIdsPluginOptions */ -class OccurrenceOrderModuleIdsPlugin { - /** - * @param {OccurrenceOrderModuleIdsPluginOptions=} options options object - */ - constructor(options = {}) { - validateOptions(schema, options, "Occurrence Order Module Ids Plugin"); - this.options = options; +/** + * intersect creates Set containing the intersection of elements between all sets + * @param {Set[]} sets an array of sets being checked for shared elements + * @returns {Set} returns a new Set containing the intersecting items + */ +const intersect = sets => { + if (sets.length === 0) return new Set(); + if (sets.length === 1) return new Set(sets[0]); + let minSize = Infinity; + let minIndex = -1; + for (let i = 0; i < sets.length; i++) { + const size = sets[i].size; + if (size < minSize) { + minIndex = i; + minSize = size; + } } - - apply(compiler) { - const prioritiseInitial = this.options.prioritiseInitial; - compiler.hooks.compilation.tap( - "OccurrenceOrderModuleIdsPlugin", - compilation => { - compilation.hooks.optimizeModuleOrder.tap( - "OccurrenceOrderModuleIdsPlugin", - modules => { - const occursInInitialChunksMap = new Map(); - const occursInAllChunksMap = new Map(); - - const initialChunkChunkMap = new Map(); - const entryCountMap = new Map(); - for (const m of modules) { - let initial = 0; - let entry = 0; - for (const c of m.chunksIterable) { - if (c.canBeInitial()) initial++; - if (c.entryModule === m) entry++; - } - initialChunkChunkMap.set(m, initial); - entryCountMap.set(m, entry); - } - - const countOccursInEntry = (sum, r) => { - if (!r.module) { - return sum; - } - const count = initialChunkChunkMap.get(r.module); - if (!count) { - return sum; - } - return sum + count; - }; - const countOccurs = (sum, r) => { - if (!r.module) { - return sum; - } - let factor = 1; - if (typeof r.dependency.getNumberOfIdOccurrences === "function") { - factor = r.dependency.getNumberOfIdOccurrences(); - } - if (factor === 0) { - return sum; - } - return sum + factor * r.module.getNumberOfChunks(); - }; - - if (prioritiseInitial) { - for (const m of modules) { - const result = - m.reasons.reduce(countOccursInEntry, 0) + - initialChunkChunkMap.get(m) + - entryCountMap.get(m); - occursInInitialChunksMap.set(m, result); - } - } - - const originalOrder = new Map(); - let i = 0; - for (const m of modules) { - const result = - m.reasons.reduce(countOccurs, 0) + - m.getNumberOfChunks() + - entryCountMap.get(m); - occursInAllChunksMap.set(m, result); - originalOrder.set(m, i++); - } - - modules.sort((a, b) => { - if (prioritiseInitial) { - const aEntryOccurs = occursInInitialChunksMap.get(a); - const bEntryOccurs = occursInInitialChunksMap.get(b); - if (aEntryOccurs > bEntryOccurs) return -1; - if (aEntryOccurs < bEntryOccurs) return 1; - } - const aOccurs = occursInAllChunksMap.get(a); - const bOccurs = occursInAllChunksMap.get(b); - if (aOccurs > bOccurs) return -1; - if (aOccurs < bOccurs) return 1; - const orgA = originalOrder.get(a); - const orgB = originalOrder.get(b); - return orgA - orgB; - }); - } - ); + const current = new Set(sets[minIndex]); + for (let i = 0; i < sets.length; i++) { + if (i === minIndex) continue; + const set = sets[i]; + for (const item of current) { + if (!set.has(item)) { + current.delete(item); } - ); + } } -} + return current; +}; -module.exports = OccurrenceOrderModuleIdsPlugin; +/** + * Checks if a set is the subset of another set + * @param {Set} bigSet a Set which contains the original elements to compare against + * @param {Set} smallSet the set whos elements might be contained inside of bigSet + * @returns {boolean} returns true if smallSet contains all elements inside of the bigSet + */ +const isSubset = (bigSet, smallSet) => { + if (bigSet.size < smallSet.size) return false; + for (const item of smallSet) { + if (!bigSet.has(item)) return false; + } + return true; +}; + +exports.intersect = intersect; +exports.isSubset = isSubset; /***/ }), -/***/ 67340: +/***/ 50071: /***/ (function(module) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -// TODO webpack 5 remove this plugin -// It has been splitted into separate plugins for modules and chunks -class OccurrenceOrderPlugin { - constructor(preferEntry) { - if (preferEntry !== undefined && typeof preferEntry !== "boolean") { - throw new Error( - "Argument should be a boolean.\nFor more info on this plugin, see https://webpack.js.org/plugins/" - ); - } - this.preferEntry = preferEntry; +/** + * A subset of Set that offers sorting functionality + * @template T item type in set + * @extends {Set} + */ +class SortableSet extends Set { + /** + * Create a new sortable set + * @param {Iterable=} initialIterable The initial iterable value + * @typedef {function(T, T): number} SortFunction + * @param {SortFunction=} defaultSort Default sorting function + */ + constructor(initialIterable, defaultSort) { + super(initialIterable); + /** @private @type {function(T, T): number}} */ + this._sortFn = defaultSort; + /** @private @type {function(T, T): number} | null} */ + this._lastActiveSortFn = null; + /** @private @type {Map | undefined} */ + this._cache = undefined; + /** @private @type {Map | undefined} */ + this._cacheOrderIndependent = undefined; } - apply(compiler) { - const preferEntry = this.preferEntry; - compiler.hooks.compilation.tap("OccurrenceOrderPlugin", compilation => { - compilation.hooks.optimizeModuleOrder.tap( - "OccurrenceOrderPlugin", - modules => { - const occursInInitialChunksMap = new Map(); - const occursInAllChunksMap = new Map(); - - const initialChunkChunkMap = new Map(); - const entryCountMap = new Map(); - for (const m of modules) { - let initial = 0; - let entry = 0; - for (const c of m.chunksIterable) { - if (c.canBeInitial()) initial++; - if (c.entryModule === m) entry++; - } - initialChunkChunkMap.set(m, initial); - entryCountMap.set(m, entry); - } - - const countOccursInEntry = (sum, r) => { - if (!r.module) { - return sum; - } - return sum + initialChunkChunkMap.get(r.module); - }; - const countOccurs = (sum, r) => { - if (!r.module) { - return sum; - } - let factor = 1; - if (typeof r.dependency.getNumberOfIdOccurrences === "function") { - factor = r.dependency.getNumberOfIdOccurrences(); - } - if (factor === 0) { - return sum; - } - return sum + factor * r.module.getNumberOfChunks(); - }; - - if (preferEntry) { - for (const m of modules) { - const result = - m.reasons.reduce(countOccursInEntry, 0) + - initialChunkChunkMap.get(m) + - entryCountMap.get(m); - occursInInitialChunksMap.set(m, result); - } - } - - const originalOrder = new Map(); - let i = 0; - for (const m of modules) { - const result = - m.reasons.reduce(countOccurs, 0) + - m.getNumberOfChunks() + - entryCountMap.get(m); - occursInAllChunksMap.set(m, result); - originalOrder.set(m, i++); - } - modules.sort((a, b) => { - if (preferEntry) { - const aEntryOccurs = occursInInitialChunksMap.get(a); - const bEntryOccurs = occursInInitialChunksMap.get(b); - if (aEntryOccurs > bEntryOccurs) return -1; - if (aEntryOccurs < bEntryOccurs) return 1; - } - const aOccurs = occursInAllChunksMap.get(a); - const bOccurs = occursInAllChunksMap.get(b); - if (aOccurs > bOccurs) return -1; - if (aOccurs < bOccurs) return 1; - const orgA = originalOrder.get(a); - const orgB = originalOrder.get(b); - return orgA - orgB; - }); - } - ); - compilation.hooks.optimizeChunkOrder.tap( - "OccurrenceOrderPlugin", - chunks => { - const occursInInitialChunksMap = new Map(); - const originalOrder = new Map(); + /** + * @param {T} value value to add to set + * @returns {this} returns itself + */ + add(value) { + this._lastActiveSortFn = null; + this._invalidateCache(); + this._invalidateOrderedCache(); + super.add(value); + return this; + } - let i = 0; - for (const c of chunks) { - let occurs = 0; - for (const chunkGroup of c.groupsIterable) { - for (const parent of chunkGroup.parentsIterable) { - if (parent.isInitial()) occurs++; - } - } - occursInInitialChunksMap.set(c, occurs); - originalOrder.set(c, i++); - } + /** + * @param {T} value value to delete + * @returns {boolean} true if value existed in set, false otherwise + */ + delete(value) { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.delete(value); + } - chunks.sort((a, b) => { - const aEntryOccurs = occursInInitialChunksMap.get(a); - const bEntryOccurs = occursInInitialChunksMap.get(b); - if (aEntryOccurs > bEntryOccurs) return -1; - if (aEntryOccurs < bEntryOccurs) return 1; - const aOccurs = a.getNumberOfGroups(); - const bOccurs = b.getNumberOfGroups(); - if (aOccurs > bOccurs) return -1; - if (aOccurs < bOccurs) return 1; - const orgA = originalOrder.get(a); - const orgB = originalOrder.get(b); - return orgA - orgB; - }); - } - ); - }); + /** + * @returns {void} + */ + clear() { + this._invalidateCache(); + this._invalidateOrderedCache(); + return super.clear(); } -} -module.exports = OccurrenceOrderPlugin; + /** + * Sort with a comparer function + * @param {SortFunction} sortFn Sorting comparer function + * @returns {void} + */ + sortWith(sortFn) { + if (this.size <= 1 || sortFn === this._lastActiveSortFn) { + // already sorted - nothing to do + return; + } + const sortedArray = Array.from(this).sort(sortFn); + super.clear(); + for (let i = 0; i < sortedArray.length; i += 1) { + super.add(sortedArray[i]); + } + this._lastActiveSortFn = sortFn; + this._invalidateCache(); + } -/***/ }), + sort() { + this.sortWith(this._sortFn); + } -/***/ 78085: -/***/ (function(module) { + /** + * Get data from cache + * @param {function(SortableSet): T[]} fn function to calculate value + * @returns {T[]} returns result of fn(this), cached until set changes + */ + getFromCache(fn) { + if (this._cache === undefined) { + this._cache = new Map(); + } else { + const data = this._cache.get(fn); + if (data !== undefined) { + return data; + } + } + const newData = fn(this); + this._cache.set(fn, newData); + return newData; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + /** + * @param {function(SortableSet): string|number|T[]} fn function to calculate value + * @returns {any} returns result of fn(this), cached until set changes + */ + getFromUnorderedCache(fn) { + if (this._cacheOrderIndependent === undefined) { + this._cacheOrderIndependent = new Map(); + } else { + const data = this._cacheOrderIndependent.get(fn); + if (data !== undefined) { + return data; + } + } + const newData = fn(this); + this._cacheOrderIndependent.set(fn, newData); + return newData; + } + /** + * @private + * @returns {void} + */ + _invalidateCache() { + if (this._cache !== undefined) { + this._cache.clear(); + } + } -class RemoveEmptyChunksPlugin { - apply(compiler) { - compiler.hooks.compilation.tap("RemoveEmptyChunksPlugin", compilation => { - const handler = chunks => { - for (let i = chunks.length - 1; i >= 0; i--) { - const chunk = chunks[i]; - if ( - chunk.isEmpty() && - !chunk.hasRuntime() && - !chunk.hasEntryModule() - ) { - chunk.remove("empty"); - chunks.splice(i, 1); - } - } - }; - compilation.hooks.optimizeChunksBasic.tap( - "RemoveEmptyChunksPlugin", - handler - ); - compilation.hooks.optimizeChunksAdvanced.tap( - "RemoveEmptyChunksPlugin", - handler - ); - compilation.hooks.optimizeExtractedChunksBasic.tap( - "RemoveEmptyChunksPlugin", - handler - ); - compilation.hooks.optimizeExtractedChunksAdvanced.tap( - "RemoveEmptyChunksPlugin", - handler - ); - }); + /** + * @private + * @returns {void} + */ + _invalidateOrderedCache() { + if (this._cacheOrderIndependent !== undefined) { + this._cacheOrderIndependent.clear(); + } } } -module.exports = RemoveEmptyChunksPlugin; + +module.exports = SortableSet; /***/ }), -/***/ 58142: +/***/ 92251: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -109050,133 +107623,148 @@ module.exports = RemoveEmptyChunksPlugin; */ -const Queue = __webpack_require__(38637); -const { intersect } = __webpack_require__(54262); +const util = __webpack_require__(31669); -const getParentChunksWithModule = (currentChunk, module) => { - const chunks = []; - const stack = new Set(currentChunk.parentsIterable); +const TOMBSTONE = {}; +const UNDEFINED_MARKER = {}; - for (const chunk of stack) { - if (chunk.containsModule(module)) { - chunks.push(chunk); - } else { - for (const parent of chunk.parentsIterable) { - stack.add(parent); - } - } +class StackedSetMap { + constructor(parentStack) { + this.stack = parentStack === undefined ? [] : parentStack.slice(); + this.map = new Map(); + this.stack.push(this.map); } - return chunks; -}; + add(item) { + this.map.set(item, true); + } -class RemoveParentModulesPlugin { - apply(compiler) { - compiler.hooks.compilation.tap("RemoveParentModulesPlugin", compilation => { - const handler = (chunks, chunkGroups) => { - const queue = new Queue(); - const availableModulesMap = new WeakMap(); + set(item, value) { + this.map.set(item, value === undefined ? UNDEFINED_MARKER : value); + } - for (const chunkGroup of compilation.entrypoints.values()) { - // initialize available modules for chunks without parents - availableModulesMap.set(chunkGroup, new Set()); - for (const child of chunkGroup.childrenIterable) { - queue.enqueue(child); - } + delete(item) { + if (this.stack.length > 1) { + this.map.set(item, TOMBSTONE); + } else { + this.map.delete(item); + } + } + + has(item) { + const topValue = this.map.get(item); + if (topValue !== undefined) return topValue !== TOMBSTONE; + if (this.stack.length > 1) { + for (var i = this.stack.length - 2; i >= 0; i--) { + const value = this.stack[i].get(item); + if (value !== undefined) { + this.map.set(item, value); + return value !== TOMBSTONE; } + } + this.map.set(item, TOMBSTONE); + } + return false; + } - while (queue.length > 0) { - const chunkGroup = queue.dequeue(); - let availableModules = availableModulesMap.get(chunkGroup); - let changed = false; - for (const parent of chunkGroup.parentsIterable) { - const availableModulesInParent = availableModulesMap.get(parent); - if (availableModulesInParent !== undefined) { - // If we know the available modules in parent: process these - if (availableModules === undefined) { - // if we have not own info yet: create new entry - availableModules = new Set(availableModulesInParent); - for (const chunk of parent.chunks) { - for (const m of chunk.modulesIterable) { - availableModules.add(m); - } - } - availableModulesMap.set(chunkGroup, availableModules); - changed = true; - } else { - for (const m of availableModules) { - if ( - !parent.containsModule(m) && - !availableModulesInParent.has(m) - ) { - availableModules.delete(m); - changed = true; - } - } - } - } - } - if (changed) { - // if something changed: enqueue our children - for (const child of chunkGroup.childrenIterable) { - queue.enqueue(child); - } - } + get(item) { + const topValue = this.map.get(item); + if (topValue !== undefined) { + return topValue === TOMBSTONE || topValue === UNDEFINED_MARKER + ? undefined + : topValue; + } + if (this.stack.length > 1) { + for (var i = this.stack.length - 2; i >= 0; i--) { + const value = this.stack[i].get(item); + if (value !== undefined) { + this.map.set(item, value); + return value === TOMBSTONE || value === UNDEFINED_MARKER + ? undefined + : value; } + } + this.map.set(item, TOMBSTONE); + } + return undefined; + } - // now we have available modules for every chunk - for (const chunk of chunks) { - const availableModulesSets = Array.from( - chunk.groupsIterable, - chunkGroup => availableModulesMap.get(chunkGroup) - ); - if (availableModulesSets.some(s => s === undefined)) continue; // No info about this chunk group - const availableModules = - availableModulesSets.length === 1 - ? availableModulesSets[0] - : intersect(availableModulesSets); - const numberOfModules = chunk.getNumberOfModules(); - const toRemove = new Set(); - if (numberOfModules < availableModules.size) { - for (const m of chunk.modulesIterable) { - if (availableModules.has(m)) { - toRemove.add(m); - } - } - } else { - for (const m of availableModules) { - if (chunk.containsModule(m)) { - toRemove.add(m); - } - } - } - for (const module of toRemove) { - module.rewriteChunkInReasons( - chunk, - getParentChunksWithModule(chunk, module) - ); - chunk.removeModule(module); - } + _compress() { + if (this.stack.length === 1) return; + this.map = new Map(); + for (const data of this.stack) { + for (const pair of data) { + if (pair[1] === TOMBSTONE) { + this.map.delete(pair[0]); + } else { + this.map.set(pair[0], pair[1]); } - }; - compilation.hooks.optimizeChunksBasic.tap( - "RemoveParentModulesPlugin", - handler - ); - compilation.hooks.optimizeExtractedChunksBasic.tap( - "RemoveParentModulesPlugin", - handler - ); - }); + } + } + this.stack = [this.map]; + } + + asArray() { + this._compress(); + return Array.from(this.map.entries(), pair => pair[0]); + } + + asSet() { + return new Set(this.asArray()); + } + + asPairArray() { + this._compress(); + return Array.from(this.map.entries(), pair => + /** @type {[TODO, TODO]} */ (pair[1] === UNDEFINED_MARKER + ? [pair[0], undefined] + : pair) + ); + } + + asMap() { + return new Map(this.asPairArray()); + } + + get size() { + this._compress(); + return this.map.size; + } + + createChild() { + return new StackedSetMap(this.stack); + } + + get length() { + throw new Error("This is no longer an Array"); + } + + set length(value) { + throw new Error("This is no longer an Array"); } } -module.exports = RemoveParentModulesPlugin; + +// TODO remove in webpack 5 +StackedSetMap.prototype.push = util.deprecate( + /** + * @deprecated + * @this {StackedSetMap} + * @param {any} item Item to add + * @returns {void} + */ + function(item) { + this.add(item); + }, + "This is no longer an Array: Use add instead." +); + +module.exports = StackedSetMap; /***/ }), -/***/ 76894: -/***/ (function(module) { +/***/ 67916: +/***/ (function(__unused_webpack_module, exports) { "use strict"; /* @@ -109185,47 +107773,83 @@ module.exports = RemoveParentModulesPlugin; */ -module.exports = class RuntimeChunkPlugin { - constructor(options) { - this.options = Object.assign( - { - name: entrypoint => `runtime~${entrypoint.name}` - }, - options - ); + +const mergeCache = new WeakMap(); + +/** + * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again. + * @example + * // performs cleverMerge(first, second), stores the result in WeakMap and returns result + * cachedCleverMerge({a: 1}, {a: 2}) + * {a: 2} + * // when same arguments passed, gets the result from WeakMap and returns it. + * cachedCleverMerge({a: 1}, {a: 2}) + * {a: 2} + * @param {object} first first object + * @param {object} second second object + * @returns {object} merged object of first and second object + */ +const cachedCleverMerge = (first, second) => { + let innerCache = mergeCache.get(first); + if (innerCache === undefined) { + innerCache = new WeakMap(); + mergeCache.set(first, innerCache); } + const prevMerge = innerCache.get(second); + if (prevMerge !== undefined) return prevMerge; + const newMerge = cleverMerge(first, second); + innerCache.set(second, newMerge); + return newMerge; +}; - apply(compiler) { - compiler.hooks.thisCompilation.tap("RuntimeChunkPlugin", compilation => { - compilation.hooks.optimizeChunksAdvanced.tap("RuntimeChunkPlugin", () => { - for (const entrypoint of compilation.entrypoints.values()) { - const chunk = entrypoint.getRuntimeChunk(); - let name = this.options.name; - if (typeof name === "function") { - name = name(entrypoint); - } - if ( - chunk.getNumberOfModules() > 0 || - !chunk.preventIntegration || - chunk.name !== name - ) { - const newChunk = compilation.addChunk(name); - newChunk.preventIntegration = true; - entrypoint.unshiftChunk(newChunk); - newChunk.addGroup(entrypoint); - entrypoint.setRuntimeChunk(newChunk); +/** + * Merges two objects. Objects are not deeply merged. + * TODO webpack 5: merge objects deeply clever. + * Arrays might reference the old value with "..." + * @param {object} first first object + * @param {object} second second object + * @returns {object} merged object of first and second object + */ +const cleverMerge = (first, second) => { + const newObject = Object.assign({}, first); + for (const key of Object.keys(second)) { + if (!(key in newObject)) { + newObject[key] = second[key]; + continue; + } + const secondValue = second[key]; + if (!Array.isArray(secondValue)) { + newObject[key] = secondValue; + continue; + } + const firstValue = newObject[key]; + if (Array.isArray(firstValue)) { + const newArray = []; + for (const item of secondValue) { + if (item === "...") { + for (const item of firstValue) { + newArray.push(item); } + } else { + newArray.push(item); } - }); - }); + } + newObject[key] = newArray; + } else { + newObject[key] = secondValue; + } } + return newObject; }; +exports.cachedCleverMerge = cachedCleverMerge; +exports.cleverMerge = cleverMerge; + /***/ }), -/***/ 83654: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 15660: +/***/ (function(module, exports, __webpack_require__) { "use strict"; /* @@ -109234,1869 +107858,1671 @@ module.exports = class RuntimeChunkPlugin { */ -const mm = __webpack_require__(53024); -const HarmonyExportImportedSpecifierDependency = __webpack_require__(22864); -const HarmonyImportSideEffectDependency = __webpack_require__(79171); -const HarmonyImportSpecifierDependency = __webpack_require__(95966); +const AbstractMethodError = __webpack_require__(36104); -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../Dependency")} Dependency */ +const BULK_SIZE = 1000; -/** - * @typedef {Object} ExportInModule - * @property {Module} module the module - * @property {string} exportName the name of the export - * @property {boolean} checked if the export is conditional - */ +class Hash { + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + throw new AbstractMethodError(); + } + + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + throw new AbstractMethodError(); + } +} + +exports.Hash = Hash; +/** @typedef {typeof Hash} HashConstructor */ + +class BulkUpdateDecorator extends Hash { + /** + * @param {Hash} hash hash + */ + constructor(hash) { + super(); + this.hash = hash; + this.buffer = ""; + } + + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + if ( + inputEncoding !== undefined || + typeof data !== "string" || + data.length > BULK_SIZE + ) { + if (this.buffer.length > 0) { + this.hash.update(this.buffer); + this.buffer = ""; + } + this.hash.update(data, inputEncoding); + } else { + this.buffer += data; + if (this.buffer.length > BULK_SIZE) { + this.hash.update(this.buffer); + this.buffer = ""; + } + } + return this; + } + + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + if (this.buffer.length > 0) { + this.hash.update(this.buffer); + } + var digestResult = this.hash.digest(encoding); + return typeof digestResult === "string" + ? digestResult + : digestResult.toString(); + } +} /** - * @typedef {Object} ReexportInfo - * @property {Map} static - * @property {Map>} dynamic + * istanbul ignore next */ +class DebugHash extends Hash { + constructor() { + super(); + this.string = ""; + } + + /** + * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} + * @param {string|Buffer} data data + * @param {string=} inputEncoding data encoding + * @returns {this} updated hash + */ + update(data, inputEncoding) { + if (typeof data !== "string") data = data.toString("utf-8"); + this.string += data; + return this; + } + + /** + * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} + * @param {string=} encoding encoding of the return value + * @returns {string|Buffer} digest + */ + digest(encoding) { + return this.string.replace(/[^a-z0-9]+/gi, m => + Buffer.from(m).toString("hex") + ); + } +} /** - * @param {ReexportInfo} info info object - * @param {string} exportName name of export - * @returns {ExportInModule | undefined} static export + * Creates a hash by name or function + * @param {string | HashConstructor} algorithm the algorithm name or a constructor creating a hash + * @returns {Hash} the hash */ -const getMappingFromInfo = (info, exportName) => { - const staticMappings = info.static.get(exportName); - if (staticMappings !== undefined) { - if (staticMappings.length === 1) return staticMappings[0]; - return undefined; +module.exports = algorithm => { + if (typeof algorithm === "function") { + return new BulkUpdateDecorator(new algorithm()); } - const dynamicMappings = Array.from(info.dynamic).filter( - ([_, ignored]) => !ignored.has(exportName) - ); - if (dynamicMappings.length === 1) { - return { - module: dynamicMappings[0][0], - exportName, - checked: true - }; + switch (algorithm) { + // TODO add non-cryptographic algorithm here + case "debug": + return new DebugHash(); + default: + return new BulkUpdateDecorator(__webpack_require__(76417).createHash(algorithm)); } - return undefined; }; + +/***/ }), + +/***/ 30815: +/***/ (function(module) { + +"use strict"; + + +// Simulations show these probabilities for a single change +// 93.1% that one group is invalidated +// 4.8% that two groups are invalidated +// 1.1% that 3 groups are invalidated +// 0.1% that 4 or more groups are invalidated +// +// And these for removing/adding 10 lexically adjacent files +// 64.5% that one group is invalidated +// 24.8% that two groups are invalidated +// 7.8% that 3 groups are invalidated +// 2.7% that 4 or more groups are invalidated +// +// And these for removing/adding 3 random files +// 0% that one group is invalidated +// 3.7% that two groups are invalidated +// 80.8% that 3 groups are invalidated +// 12.3% that 4 groups are invalidated +// 3.2% that 5 or more groups are invalidated + /** - * @param {ReexportInfo} info info object - * @param {string} exportName name of export of source module - * @param {Module} module the target module - * @param {string} innerExportName name of export of target module - * @param {boolean} checked true, if existence of target module is checked + * + * @param {string} a key + * @param {string} b key + * @returns {number} the similarity as number */ -const addStaticReexport = ( - info, - exportName, - module, - innerExportName, - checked -) => { - let mappings = info.static.get(exportName); - if (mappings !== undefined) { - for (const mapping of mappings) { - if (mapping.module === module && mapping.exportName === innerExportName) { - mapping.checked = mapping.checked && checked; - return; - } - } - } else { - mappings = []; - info.static.set(exportName, mappings); +const similarity = (a, b) => { + const l = Math.min(a.length, b.length); + let dist = 0; + for (let i = 0; i < l; i++) { + const ca = a.charCodeAt(i); + const cb = b.charCodeAt(i); + dist += Math.max(0, 10 - Math.abs(ca - cb)); } - mappings.push({ - module, - exportName: innerExportName, - checked - }); + return dist; }; /** - * @param {ReexportInfo} info info object - * @param {Module} module the reexport module - * @param {Set} ignored ignore list - * @returns {void} + * @param {string} a key + * @param {string} b key + * @returns {string} the common part and a single char for the difference */ -const addDynamicReexport = (info, module, ignored) => { - const existingList = info.dynamic.get(module); - if (existingList !== undefined) { - for (const key of existingList) { - if (!ignored.has(key)) existingList.delete(key); +const getName = (a, b) => { + const l = Math.min(a.length, b.length); + let r = ""; + for (let i = 0; i < l; i++) { + const ca = a.charAt(i); + const cb = b.charAt(i); + r += ca; + if (ca === cb) { + continue; } - } else { - info.dynamic.set(module, new Set(ignored)); + return r; } + return a; }; -class SideEffectsFlagPlugin { - apply(compiler) { - compiler.hooks.normalModuleFactory.tap("SideEffectsFlagPlugin", nmf => { - nmf.hooks.module.tap("SideEffectsFlagPlugin", (module, data) => { - const resolveData = data.resourceResolveData; - if ( - resolveData && - resolveData.descriptionFileData && - resolveData.relativePath - ) { - const sideEffects = resolveData.descriptionFileData.sideEffects; - const hasSideEffects = SideEffectsFlagPlugin.moduleHasSideEffects( - resolveData.relativePath, - sideEffects - ); - if (!hasSideEffects) { - module.factoryMeta.sideEffectFree = true; - } - } +/** + * @template T + */ +class Node { + /** + * @param {T} item item + * @param {string} key key + * @param {number} size size + */ + constructor(item, key, size) { + this.item = item; + this.key = key; + this.size = size; + } +} - return module; - }); - nmf.hooks.module.tap("SideEffectsFlagPlugin", (module, data) => { - if (data.settings.sideEffects === false) { - module.factoryMeta.sideEffectFree = true; - } else if (data.settings.sideEffects === true) { - module.factoryMeta.sideEffectFree = false; - } - }); - }); - compiler.hooks.compilation.tap("SideEffectsFlagPlugin", compilation => { - compilation.hooks.optimizeDependencies.tap( - "SideEffectsFlagPlugin", - modules => { - /** @type {Map} */ - const reexportMaps = new Map(); +/** + * @template T + */ +class Group { + /** + * @param {Node[]} nodes nodes + * @param {number[]} similarities similarities between the nodes (length = nodes.length - 1) + */ + constructor(nodes, similarities) { + this.nodes = nodes; + this.similarities = similarities; + this.size = nodes.reduce((size, node) => size + node.size, 0); + /** @type {string} */ + this.key = undefined; + } +} - // Capture reexports of sideEffectFree modules - for (const module of modules) { - /** @type {Dependency[]} */ - const removeDependencies = []; - for (const dep of module.dependencies) { - if (dep instanceof HarmonyImportSideEffectDependency) { - if (dep.module && dep.module.factoryMeta.sideEffectFree) { - removeDependencies.push(dep); - } - } else if ( - dep instanceof HarmonyExportImportedSpecifierDependency - ) { - if (module.factoryMeta.sideEffectFree) { - const mode = dep.getMode(true); - if ( - mode.type === "safe-reexport" || - mode.type === "checked-reexport" || - mode.type === "dynamic-reexport" || - mode.type === "reexport-non-harmony-default" || - mode.type === "reexport-non-harmony-default-strict" || - mode.type === "reexport-named-default" - ) { - let info = reexportMaps.get(module); - if (!info) { - reexportMaps.set( - module, - (info = { - static: new Map(), - dynamic: new Map() - }) - ); - } - const targetModule = dep._module; - switch (mode.type) { - case "safe-reexport": - for (const [key, id] of mode.map) { - if (id) { - addStaticReexport( - info, - key, - targetModule, - id, - false - ); - } - } - break; - case "checked-reexport": - for (const [key, id] of mode.map) { - if (id) { - addStaticReexport( - info, - key, - targetModule, - id, - true - ); - } - } - break; - case "dynamic-reexport": - addDynamicReexport(info, targetModule, mode.ignored); - break; - case "reexport-non-harmony-default": - case "reexport-non-harmony-default-strict": - case "reexport-named-default": - addStaticReexport( - info, - mode.name, - targetModule, - "default", - false - ); - break; - } - } - } - } - } - } +/** + * @template T + * @typedef {Object} GroupedItems + * @property {string} key + * @property {T[]} items + * @property {number} size + */ - // Flatten reexports - for (const info of reexportMaps.values()) { - const dynamicReexports = info.dynamic; - info.dynamic = new Map(); - for (const reexport of dynamicReexports) { - let [targetModule, ignored] = reexport; - for (;;) { - const innerInfo = reexportMaps.get(targetModule); - if (!innerInfo) break; +/** + * @template T + * @typedef {Object} Options + * @property {number} maxSize maximum size of a group + * @property {number} minSize minimum size of a group (preferred over maximum size) + * @property {Iterable} items a list of items + * @property {function(T): number} getSize function to get size of an item + * @property {function(T): string} getKey function to get the key of an item + */ - for (const [key, reexports] of innerInfo.static) { - if (ignored.has(key)) continue; - for (const { module, exportName, checked } of reexports) { - addStaticReexport(info, key, module, exportName, checked); - } - } +/** + * @template T + * @param {Options} options options object + * @returns {GroupedItems[]} grouped items + */ +module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { + /** @type {Group[]} */ + const result = []; - // Follow dynamic reexport if there is only one - if (innerInfo.dynamic.size !== 1) { - // When there are more then one, we don't know which one - break; - } + const nodes = Array.from( + items, + item => new Node(item, getKey(item), getSize(item)) + ); - ignored = new Set(ignored); - for (const [innerModule, innerIgnored] of innerInfo.dynamic) { - for (const key of innerIgnored) { - if (ignored.has(key)) continue; - // This reexports ends here - addStaticReexport(info, key, targetModule, key, true); - ignored.add(key); - } - targetModule = innerModule; - } - } + /** @type {Node[]} */ + const initialNodes = []; - // Update reexport as all other cases has been handled - addDynamicReexport(info, targetModule, ignored); - } - } + // lexically ordering of keys + nodes.sort((a, b) => { + if (a.key < b.key) return -1; + if (a.key > b.key) return 1; + return 0; + }); - for (const info of reexportMaps.values()) { - const staticReexports = info.static; - info.static = new Map(); - for (const [key, reexports] of staticReexports) { - for (let mapping of reexports) { - for (;;) { - const innerInfo = reexportMaps.get(mapping.module); - if (!innerInfo) break; + // return nodes bigger than maxSize directly as group + for (const node of nodes) { + if (node.size >= maxSize) { + result.push(new Group([node], [])); + } else { + initialNodes.push(node); + } + } - const newMapping = getMappingFromInfo( - innerInfo, - mapping.exportName - ); - if (!newMapping) break; - mapping = newMapping; - } - addStaticReexport( - info, - key, - mapping.module, - mapping.exportName, - mapping.checked - ); - } - } - } + if (initialNodes.length > 0) { + // calculate similarities between lexically adjacent nodes + /** @type {number[]} */ + const similarities = []; + for (let i = 1; i < initialNodes.length; i++) { + const a = initialNodes[i - 1]; + const b = initialNodes[i]; + similarities.push(similarity(a.key, b.key)); + } - // Update imports along the reexports from sideEffectFree modules - for (const pair of reexportMaps) { - const module = pair[0]; - const info = pair[1]; - let newReasons = undefined; - for (let i = 0; i < module.reasons.length; i++) { - const reason = module.reasons[i]; - const dep = reason.dependency; - if ( - (dep instanceof HarmonyExportImportedSpecifierDependency || - (dep instanceof HarmonyImportSpecifierDependency && - !dep.namespaceObjectAsContext)) && - dep._id - ) { - const mapping = getMappingFromInfo(info, dep._id); - if (mapping) { - dep.redirectedModule = mapping.module; - dep.redirectedId = mapping.exportName; - mapping.module.addReason( - reason.module, - dep, - reason.explanation - ? reason.explanation + - " (skipped side-effect-free modules)" - : "(skipped side-effect-free modules)" - ); - // removing the currect reason, by not adding it to the newReasons array - // lazily create the newReasons array - if (newReasons === undefined) { - newReasons = i === 0 ? [] : module.reasons.slice(0, i); - } - continue; - } - } - if (newReasons !== undefined) newReasons.push(reason); - } - if (newReasons !== undefined) { - module.reasons = newReasons; + const initialGroup = new Group(initialNodes, similarities); + + if (initialGroup.size < minSize) { + // We hit an edgecase where the working set is already smaller than minSize + // We merge it with the smallest result node to keep minSize intact + if (result.length > 0) { + const smallestGroup = result.reduce((min, group) => + min.size > group.size ? group : min + ); + for (const node of initialGroup.nodes) smallestGroup.nodes.push(node); + smallestGroup.nodes.sort((a, b) => { + if (a.key < b.key) return -1; + if (a.key > b.key) return 1; + return 0; + }); + } else { + // There are no other nodes + // We use all nodes and have to accept that it's smaller than minSize + result.push(initialGroup); + } + } else { + const queue = [initialGroup]; + + while (queue.length) { + const group = queue.pop(); + // only groups bigger than maxSize need to be splitted + if (group.size < maxSize) { + result.push(group); + continue; + } + + // find unsplittable area from left and right + // going minSize from left and right + // at least one node need to be included otherwise we get stuck + let left = 0; + let leftSize = 0; + while (leftSize <= minSize) { + leftSize += group.nodes[left].size; + left++; + } + let right = group.nodes.length - 1; + let rightSize = 0; + while (rightSize <= minSize) { + rightSize += group.nodes[right].size; + right--; + } + + if (left - 1 > right) { + // can't split group while holding minSize + // because minSize is preferred of maxSize we return + // the group here even while it's too big + // To avoid this make sure maxSize > minSize * 3 + result.push(group); + continue; + } + if (left <= right) { + // when there is a area between left and right + // we look for best split point + // we split at the minimum similarity + // here key space is separated the most + let best = left - 1; + let bestSimilarity = group.similarities[best]; + for (let i = left; i <= right; i++) { + const similarity = group.similarities[i]; + if (similarity < bestSimilarity) { + best = i; + bestSimilarity = similarity; } } + left = best + 1; + right = best; } - ); - }); - } - static moduleHasSideEffects(moduleName, flagValue) { - switch (typeof flagValue) { - case "undefined": - return true; - case "boolean": - return flagValue; - case "string": - if (process.platform === "win32") { - flagValue = flagValue.replace(/\\/g, "/"); + // create two new groups for left and right area + // and queue them up + const rightNodes = [group.nodes[right + 1]]; + /** @type {number[]} */ + const rightSimilaries = []; + for (let i = right + 2; i < group.nodes.length; i++) { + rightSimilaries.push(group.similarities[i - 1]); + rightNodes.push(group.nodes[i]); } - return mm.isMatch(moduleName, flagValue, { - matchBase: true - }); - case "object": - return flagValue.some(glob => - SideEffectsFlagPlugin.moduleHasSideEffects(moduleName, glob) - ); + queue.push(new Group(rightNodes, rightSimilaries)); + + const leftNodes = [group.nodes[0]]; + /** @type {number[]} */ + const leftSimilaries = []; + for (let i = 1; i < left; i++) { + leftSimilaries.push(group.similarities[i - 1]); + leftNodes.push(group.nodes[i]); + } + queue.push(new Group(leftNodes, leftSimilaries)); + } } } -} -module.exports = SideEffectsFlagPlugin; + // lexically ordering + result.sort((a, b) => { + if (a.nodes[0].key < b.nodes[0].key) return -1; + if (a.nodes[0].key > b.nodes[0].key) return 1; + return 0; + }); -/***/ }), - -/***/ 60474: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // give every group a name + for (let i = 0; i < result.length; i++) { + const group = result[i]; + const first = group.nodes[0]; + const last = group.nodes[group.nodes.length - 1]; + let name = getName(first.key, last.key); + group.key = name; + } + // return the results + return result.map(group => { + /** @type {GroupedItems} */ + return { + key: group.key, + items: group.nodes.map(node => node.item), + size: group.size + }; + }); +}; -const crypto = __webpack_require__(76417); -const SortableSet = __webpack_require__(50071); -const GraphHelpers = __webpack_require__(32973); -const { isSubset } = __webpack_require__(54262); -const deterministicGrouping = __webpack_require__(30815); -const MinMaxSizeWarning = __webpack_require__(25472); -const contextify = __webpack_require__(94658).contextify; -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Chunk")} Chunk */ -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../util/deterministicGrouping").Options} DeterministicGroupingOptionsForModule */ -/** @typedef {import("../util/deterministicGrouping").GroupedItems} DeterministicGroupingGroupedItemsForModule */ +/***/ }), -const deterministicGroupingForModules = /** @type {function(DeterministicGroupingOptionsForModule): DeterministicGroupingGroupedItemsForModule[]} */ (deterministicGrouping); +/***/ 94658: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -const hashFilename = name => { - return crypto - .createHash("md4") - .update(name) - .digest("hex") - .slice(0, 8); -}; +"use strict"; -const sortByIdentifier = (a, b) => { - if (a.identifier() > b.identifier()) return 1; - if (a.identifier() < b.identifier()) return -1; - return 0; -}; +const path = __webpack_require__(85622); -const getRequests = chunk => { - let requests = 0; - for (const chunkGroup of chunk.groupsIterable) { - requests = Math.max(requests, chunkGroup.chunks.length); - } - return requests; +/** + * @param {string} context context for relative path + * @param {string} relativePath path + * @returns {string} absolute path + */ +const requestToAbsolute = (context, relativePath) => { + if (relativePath.startsWith("./") || relativePath.startsWith("../")) + return path.join(context, relativePath); + return relativePath; }; -const getModulesSize = modules => { - let sum = 0; - for (const m of modules) { - sum += m.size(); - } - return sum; -}; +/** + * @typedef {Object} MakeRelativePathsCache + * @property {Map>=} relativePaths + */ /** - * @template T - * @param {Set} a set - * @param {Set} b other set - * @returns {boolean} true if at least one item of a is in b + * + * @param {string} maybeAbsolutePath path to check + * @returns {boolean} returns true if path is "Absolute Path"-like */ -const isOverlap = (a, b) => { - for (const item of a) { - if (b.has(item)) return true; +const looksLikeAbsolutePath = maybeAbsolutePath => { + if (/^\/.*\/$/.test(maybeAbsolutePath)) { + // this 'path' is actually a regexp generated by dynamic requires. + // Don't treat it as an absolute path. + return false; } - return false; + return /^(?:[a-z]:\\|\/)/i.test(maybeAbsolutePath); }; -const compareEntries = (a, b) => { - // 1. by priority - const diffPriority = a.cacheGroup.priority - b.cacheGroup.priority; - if (diffPriority) return diffPriority; - // 2. by number of chunks - const diffCount = a.chunks.size - b.chunks.size; - if (diffCount) return diffCount; - // 3. by size reduction - const aSizeReduce = a.size * (a.chunks.size - 1); - const bSizeReduce = b.size * (b.chunks.size - 1); - const diffSizeReduce = aSizeReduce - bSizeReduce; - if (diffSizeReduce) return diffSizeReduce; - // 4. by cache group index - const indexDiff = a.cacheGroupIndex - b.cacheGroupIndex; - if (indexDiff) return indexDiff; - // 5. by number of modules (to be able to compare by identifier) - const modulesA = a.modules; - const modulesB = b.modules; - const diff = modulesA.size - modulesB.size; - if (diff) return diff; - // 6. by module identifiers - modulesA.sort(); - modulesB.sort(); - const aI = modulesA[Symbol.iterator](); - const bI = modulesB[Symbol.iterator](); - // eslint-disable-next-line no-constant-condition - while (true) { - const aItem = aI.next(); - const bItem = bI.next(); - if (aItem.done) return 0; - const aModuleIdentifier = aItem.value.identifier(); - const bModuleIdentifier = bItem.value.identifier(); - if (aModuleIdentifier > bModuleIdentifier) return -1; - if (aModuleIdentifier < bModuleIdentifier) return 1; - } +/** + * + * @param {string} p path to normalize + * @returns {string} normalized version of path + */ +const normalizePathSeparator = p => p.replace(/\\/g, "/"); + +/** + * + * @param {string} context context for relative path + * @param {string} identifier identifier for path + * @returns {string} a converted relative path + */ +const _makePathsRelative = (context, identifier) => { + return identifier + .split(/([|! ])/) + .map(str => + looksLikeAbsolutePath(str) + ? normalizePathSeparator(path.relative(context, str)) + : str + ) + .join(""); }; -const compareNumbers = (a, b) => a - b; +/** + * + * @param {string} context context used to create relative path + * @param {string} identifier identifier used to create relative path + * @param {MakeRelativePathsCache=} cache the cache object being set + * @returns {string} the returned relative path + */ +exports.makePathsRelative = (context, identifier, cache) => { + if (!cache) return _makePathsRelative(context, identifier); -const INITIAL_CHUNK_FILTER = chunk => chunk.canBeInitial(); -const ASYNC_CHUNK_FILTER = chunk => !chunk.canBeInitial(); -const ALL_CHUNK_FILTER = chunk => true; + const relativePaths = + cache.relativePaths || (cache.relativePaths = new Map()); -module.exports = class SplitChunksPlugin { - constructor(options) { - this.options = SplitChunksPlugin.normalizeOptions(options); + let cachedResult; + let contextCache = relativePaths.get(context); + if (contextCache === undefined) { + relativePaths.set(context, (contextCache = new Map())); + } else { + cachedResult = contextCache.get(identifier); } - static normalizeOptions(options = {}) { - return { - chunksFilter: SplitChunksPlugin.normalizeChunksFilter( - options.chunks || "all" - ), - minSize: options.minSize || 0, - enforceSizeThreshold: options.enforceSizeThreshold || 0, - maxSize: options.maxSize || 0, - minChunks: options.minChunks || 1, - maxAsyncRequests: options.maxAsyncRequests || 1, - maxInitialRequests: options.maxInitialRequests || 1, - hidePathInfo: options.hidePathInfo || false, - filename: options.filename || undefined, - getCacheGroups: SplitChunksPlugin.normalizeCacheGroups({ - cacheGroups: options.cacheGroups, - name: options.name, - automaticNameDelimiter: options.automaticNameDelimiter, - automaticNameMaxLength: options.automaticNameMaxLength - }), - automaticNameDelimiter: options.automaticNameDelimiter, - automaticNameMaxLength: options.automaticNameMaxLength || 109, - fallbackCacheGroup: SplitChunksPlugin.normalizeFallbackCacheGroup( - options.fallbackCacheGroup || {}, - options - ) - }; + if (cachedResult !== undefined) { + return cachedResult; + } else { + const relativePath = _makePathsRelative(context, identifier); + contextCache.set(identifier, relativePath); + return relativePath; } +}; - static normalizeName({ - name, - automaticNameDelimiter, - automaticNamePrefix, - automaticNameMaxLength - }) { - if (name === true) { - /** @type {WeakMap>} */ - const cache = new WeakMap(); - const fn = (module, chunks, cacheGroup) => { - let cacheEntry = cache.get(chunks); - if (cacheEntry === undefined) { - cacheEntry = {}; - cache.set(chunks, cacheEntry); - } else if (cacheGroup in cacheEntry) { - return cacheEntry[cacheGroup]; - } - const names = chunks.map(c => c.name); - if (!names.every(Boolean)) { - cacheEntry[cacheGroup] = undefined; - return; - } - names.sort(); - const prefix = - typeof automaticNamePrefix === "string" - ? automaticNamePrefix - : cacheGroup; - const namePrefix = prefix ? prefix + automaticNameDelimiter : ""; - let name = namePrefix + names.join(automaticNameDelimiter); - // Filenames and paths can't be too long otherwise an - // ENAMETOOLONG error is raised. If the generated name if too - // long, it is truncated and a hash is appended. The limit has - // been set to 109 to prevent `[name].[chunkhash].[ext]` from - // generating a 256+ character string. - if (name.length > automaticNameMaxLength) { - const hashedFilename = hashFilename(name); - const sliceLength = - automaticNameMaxLength - - (automaticNameDelimiter.length + hashedFilename.length); - name = - name.slice(0, sliceLength) + - automaticNameDelimiter + - hashedFilename; +/** + * @param {string} context absolute context path + * @param {string} request any request string may containing absolute paths, query string, etc. + * @returns {string} a new request string avoiding absolute paths when possible + */ +exports.contextify = (context, request) => { + return request + .split("!") + .map(r => { + const splitPath = r.split("?", 2); + if (/^[a-zA-Z]:\\/.test(splitPath[0])) { + splitPath[0] = path.win32.relative(context, splitPath[0]); + if (!/^[a-zA-Z]:\\/.test(splitPath[0])) { + splitPath[0] = splitPath[0].replace(/\\/g, "/"); } - cacheEntry[cacheGroup] = name; - return name; - }; - return fn; - } - if (typeof name === "string") { - const fn = () => { - return name; - }; - return fn; - } - if (typeof name === "function") return name; - } + } + if (/^\//.test(splitPath[0])) { + splitPath[0] = path.posix.relative(context, splitPath[0]); + } + if (!/^(\.\.\/|\/|[a-zA-Z]:\\)/.test(splitPath[0])) { + splitPath[0] = "./" + splitPath[0]; + } + return splitPath.join("?"); + }) + .join("!"); +}; - static normalizeChunksFilter(chunks) { - if (chunks === "initial") { - return INITIAL_CHUNK_FILTER; - } - if (chunks === "async") { - return ASYNC_CHUNK_FILTER; - } - if (chunks === "all") { - return ALL_CHUNK_FILTER; - } - if (typeof chunks === "function") return chunks; - } +/** + * @param {string} context absolute context path + * @param {string} request any request string + * @returns {string} a new request string using absolute paths when possible + */ +const _absolutify = (context, request) => { + return request + .split("!") + .map(r => requestToAbsolute(context, r)) + .join("!"); +}; - static normalizeFallbackCacheGroup( - { - minSize = undefined, - maxSize = undefined, - automaticNameDelimiter = undefined - }, - { - minSize: defaultMinSize = undefined, - maxSize: defaultMaxSize = undefined, - automaticNameDelimiter: defaultAutomaticNameDelimiter = undefined - } - ) { - return { - minSize: typeof minSize === "number" ? minSize : defaultMinSize || 0, - maxSize: typeof maxSize === "number" ? maxSize : defaultMaxSize || 0, - automaticNameDelimiter: - automaticNameDelimiter || defaultAutomaticNameDelimiter || "~" - }; - } +exports.absolutify = _absolutify; - static normalizeCacheGroups({ - cacheGroups, - name, - automaticNameDelimiter, - automaticNameMaxLength - }) { - if (typeof cacheGroups === "function") { - // TODO webpack 5 remove this - if (cacheGroups.length !== 1) { - return module => cacheGroups(module, module.getChunks()); - } - return cacheGroups; - } - if (cacheGroups && typeof cacheGroups === "object") { - const fn = module => { - let results; - for (const key of Object.keys(cacheGroups)) { - let option = cacheGroups[key]; - if (option === false) continue; - if (option instanceof RegExp || typeof option === "string") { - option = { - test: option - }; - } - if (typeof option === "function") { - let result = option(module); - if (result) { - if (results === undefined) results = []; - for (const r of Array.isArray(result) ? result : [result]) { - const result = Object.assign({ key }, r); - if (result.name) result.getName = () => result.name; - if (result.chunks) { - result.chunksFilter = SplitChunksPlugin.normalizeChunksFilter( - result.chunks - ); - } - results.push(result); - } - } - } else if (SplitChunksPlugin.checkTest(option.test, module)) { - if (results === undefined) results = []; - results.push({ - key: key, - priority: option.priority, - getName: - SplitChunksPlugin.normalizeName({ - name: option.name || name, - automaticNameDelimiter: - typeof option.automaticNameDelimiter === "string" - ? option.automaticNameDelimiter - : automaticNameDelimiter, - automaticNamePrefix: option.automaticNamePrefix, - automaticNameMaxLength: - option.automaticNameMaxLength || automaticNameMaxLength - }) || (() => {}), - chunksFilter: SplitChunksPlugin.normalizeChunksFilter( - option.chunks - ), - enforce: option.enforce, - minSize: option.minSize, - enforceSizeThreshold: option.enforceSizeThreshold, - maxSize: option.maxSize, - minChunks: option.minChunks, - maxAsyncRequests: option.maxAsyncRequests, - maxInitialRequests: option.maxInitialRequests, - filename: option.filename, - reuseExistingChunk: option.reuseExistingChunk - }); - } + +/***/ }), + +/***/ 1111: +/***/ (function(module) { + +/** + * convert an object into its 2D array equivalent to be turned + * into an ES6 map + * + * @param {object} obj any object type that works with Object.keys() + * @returns {Map} an ES6 Map of KV pairs + */ +module.exports = function objectToMap(obj) { + return new Map( + Object.keys(obj).map(key => { + /** @type {[string, string]} */ + const pair = [key, obj[key]]; + return pair; + }) + ); +}; + + +/***/ }), + +/***/ 68935: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Gajus Kuizinas @gajus +*/ + + +const Ajv = __webpack_require__(21414); +const ajv = new Ajv({ + errorDataPath: "configuration", + allErrors: true, + verbose: true +}); +__webpack_require__(82133)(ajv, ["instanceof"]); +__webpack_require__(51613)(ajv); + +const validateSchema = (schema, options) => { + if (Array.isArray(options)) { + const errors = options.map(options => validateObject(schema, options)); + errors.forEach((list, idx) => { + const applyPrefix = err => { + err.dataPath = `[${idx}]${err.dataPath}`; + if (err.children) { + err.children.forEach(applyPrefix); } - return results; }; - return fn; - } - const fn = () => {}; - return fn; + list.forEach(applyPrefix); + }); + return errors.reduce((arr, items) => { + return arr.concat(items); + }, []); + } else { + return validateObject(schema, options); } +}; - static checkTest(test, module) { - if (test === undefined) return true; - if (typeof test === "function") { - if (test.length !== 1) { - return test(module, module.getChunks()); - } - return test(module); - } - if (typeof test === "boolean") return test; - if (typeof test === "string") { - if ( - module.nameForCondition && - module.nameForCondition().startsWith(test) - ) { - return true; - } - for (const chunk of module.chunksIterable) { - if (chunk.name && chunk.name.startsWith(test)) { - return true; - } - } - return false; - } - if (test instanceof RegExp) { - if (module.nameForCondition && test.test(module.nameForCondition())) { - return true; - } - for (const chunk of module.chunksIterable) { - if (chunk.name && test.test(chunk.name)) { - return true; +const validateObject = (schema, options) => { + const validate = ajv.compile(schema); + const valid = validate(options); + return valid ? [] : filterErrors(validate.errors); +}; + +const filterErrors = errors => { + let newErrors = []; + for (const err of errors) { + const dataPath = err.dataPath; + let children = []; + newErrors = newErrors.filter(oldError => { + if (oldError.dataPath.includes(dataPath)) { + if (oldError.children) { + children = children.concat(oldError.children.slice(0)); } + oldError.children = undefined; + children.push(oldError); + return false; } - return false; + return true; + }); + if (children.length) { + err.children = children; } - return false; + newErrors.push(err); } - /** - * @param {Compiler} compiler webpack compiler - * @returns {void} - */ - apply(compiler) { - compiler.hooks.thisCompilation.tap("SplitChunksPlugin", compilation => { - let alreadyOptimized = false; - compilation.hooks.unseal.tap("SplitChunksPlugin", () => { - alreadyOptimized = false; - }); - compilation.hooks.optimizeChunksAdvanced.tap( - "SplitChunksPlugin", - chunks => { - if (alreadyOptimized) return; - alreadyOptimized = true; - // Give each selected chunk an index (to create strings from chunks) - const indexMap = new Map(); - let index = 1; - for (const chunk of chunks) { - indexMap.set(chunk, index++); - } - const getKey = chunks => { - return Array.from(chunks, c => indexMap.get(c)) - .sort(compareNumbers) - .join(); - }; - /** @type {Map>} */ - const chunkSetsInGraph = new Map(); - for (const module of compilation.modules) { - const chunksKey = getKey(module.chunksIterable); - if (!chunkSetsInGraph.has(chunksKey)) { - chunkSetsInGraph.set(chunksKey, new Set(module.chunksIterable)); - } - } + return newErrors; +}; - // group these set of chunks by count - // to allow to check less sets via isSubset - // (only smaller sets can be subset) - /** @type {Map>>} */ - const chunkSetsByCount = new Map(); - for (const chunksSet of chunkSetsInGraph.values()) { - const count = chunksSet.size; - let array = chunkSetsByCount.get(count); - if (array === undefined) { - array = []; - chunkSetsByCount.set(count, array); - } - array.push(chunksSet); - } +module.exports = validateSchema; - // Create a list of possible combinations - const combinationsCache = new Map(); // Map[]> - const getCombinations = key => { - const chunksSet = chunkSetsInGraph.get(key); - var array = [chunksSet]; - if (chunksSet.size > 1) { - for (const [count, setArray] of chunkSetsByCount) { - // "equal" is not needed because they would have been merge in the first step - if (count < chunksSet.size) { - for (const set of setArray) { - if (isSubset(chunksSet, set)) { - array.push(set); - } - } - } - } - } - return array; - }; +/***/ }), - /** - * @typedef {Object} SelectedChunksResult - * @property {Chunk[]} chunks the list of chunks - * @property {string} key a key of the list - */ +/***/ 43101: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** - * @typedef {function(Chunk): boolean} ChunkFilterFunction - */ +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ - /** @type {WeakMap, WeakMap>} */ - const selectedChunksCacheByChunksSet = new WeakMap(); - /** - * get list and key by applying the filter function to the list - * It is cached for performance reasons - * @param {Set} chunks list of chunks - * @param {ChunkFilterFunction} chunkFilter filter function for chunks - * @returns {SelectedChunksResult} list and key - */ - const getSelectedChunks = (chunks, chunkFilter) => { - let entry = selectedChunksCacheByChunksSet.get(chunks); - if (entry === undefined) { - entry = new WeakMap(); - selectedChunksCacheByChunksSet.set(chunks, entry); - } - /** @type {SelectedChunksResult} */ - let entry2 = entry.get(chunkFilter); - if (entry2 === undefined) { - /** @type {Chunk[]} */ - const selectedChunks = []; - for (const chunk of chunks) { - if (chunkFilter(chunk)) selectedChunks.push(chunk); - } - entry2 = { - chunks: selectedChunks, - key: getKey(selectedChunks) - }; - entry.set(chunkFilter, entry2); - } - return entry2; - }; +const WebpackError = __webpack_require__(97391); - /** - * @typedef {Object} ChunksInfoItem - * @property {SortableSet} modules - * @property {TODO} cacheGroup - * @property {number} cacheGroupIndex - * @property {string} name - * @property {number} size - * @property {Set} chunks - * @property {Set} reuseableChunks - * @property {Set} chunksKeys - */ +module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { + /** @param {string} message Error message */ + constructor(message) { + super(message); + this.name = "UnsupportedWebAssemblyFeatureError"; + this.hideStack = true; - // Map a list of chunks to a list of modules - // For the key the chunk "index" is used, the value is a SortableSet of modules - /** @type {Map} */ - const chunksInfoMap = new Map(); + Error.captureStackTrace(this, this.constructor); + } +}; - /** - * @param {TODO} cacheGroup the current cache group - * @param {number} cacheGroupIndex the index of the cache group of ordering - * @param {Chunk[]} selectedChunks chunks selected for this module - * @param {string} selectedChunksKey a key of selectedChunks - * @param {Module} module the current module - * @returns {void} - */ - const addModuleToChunksInfoMap = ( - cacheGroup, - cacheGroupIndex, - selectedChunks, - selectedChunksKey, - module - ) => { - // Break if minimum number of chunks is not reached - if (selectedChunks.length < cacheGroup.minChunks) return; - // Determine name for split chunk - const name = cacheGroup.getName( - module, - selectedChunks, - cacheGroup.key - ); - // Create key for maps - // When it has a name we use the name as key - // Elsewise we create the key from chunks and cache group key - // This automatically merges equal names - const key = - cacheGroup.key + - (name ? ` name:${name}` : ` chunks:${selectedChunksKey}`); - // Add module to maps - let info = chunksInfoMap.get(key); - if (info === undefined) { - chunksInfoMap.set( - key, - (info = { - modules: new SortableSet(undefined, sortByIdentifier), - cacheGroup, - cacheGroupIndex, - name, - size: 0, - chunks: new Set(), - reuseableChunks: new Set(), - chunksKeys: new Set() - }) - ); - } - info.modules.add(module); - info.size += module.size(); - if (!info.chunksKeys.has(selectedChunksKey)) { - info.chunksKeys.add(selectedChunksKey); - for (const chunk of selectedChunks) { - info.chunks.add(chunk); - } - } - }; - // Walk through all modules - for (const module of compilation.modules) { - // Get cache group - let cacheGroups = this.options.getCacheGroups(module); - if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { - continue; - } +/***/ }), - // Prepare some values - const chunksKey = getKey(module.chunksIterable); - let combs = combinationsCache.get(chunksKey); - if (combs === undefined) { - combs = getCombinations(chunksKey); - combinationsCache.set(chunksKey, combs); - } +/***/ 10557: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - let cacheGroupIndex = 0; - for (const cacheGroupSource of cacheGroups) { - const minSize = - cacheGroupSource.minSize !== undefined - ? cacheGroupSource.minSize - : cacheGroupSource.enforce - ? 0 - : this.options.minSize; - const enforceSizeThreshold = - cacheGroupSource.enforceSizeThreshold !== undefined - ? cacheGroupSource.enforceSizeThreshold - : cacheGroupSource.enforce - ? 0 - : this.options.enforceSizeThreshold; - const cacheGroup = { - key: cacheGroupSource.key, - priority: cacheGroupSource.priority || 0, - chunksFilter: - cacheGroupSource.chunksFilter || this.options.chunksFilter, - minSize, - minSizeForMaxSize: - cacheGroupSource.minSize !== undefined - ? cacheGroupSource.minSize - : this.options.minSize, - enforceSizeThreshold, - maxSize: - cacheGroupSource.maxSize !== undefined - ? cacheGroupSource.maxSize - : cacheGroupSource.enforce - ? 0 - : this.options.maxSize, - minChunks: - cacheGroupSource.minChunks !== undefined - ? cacheGroupSource.minChunks - : cacheGroupSource.enforce - ? 1 - : this.options.minChunks, - maxAsyncRequests: - cacheGroupSource.maxAsyncRequests !== undefined - ? cacheGroupSource.maxAsyncRequests - : cacheGroupSource.enforce - ? Infinity - : this.options.maxAsyncRequests, - maxInitialRequests: - cacheGroupSource.maxInitialRequests !== undefined - ? cacheGroupSource.maxInitialRequests - : cacheGroupSource.enforce - ? Infinity - : this.options.maxInitialRequests, - getName: - cacheGroupSource.getName !== undefined - ? cacheGroupSource.getName - : this.options.getName, - filename: - cacheGroupSource.filename !== undefined - ? cacheGroupSource.filename - : this.options.filename, - automaticNameDelimiter: - cacheGroupSource.automaticNameDelimiter !== undefined - ? cacheGroupSource.automaticNameDelimiter - : this.options.automaticNameDelimiter, - reuseExistingChunk: cacheGroupSource.reuseExistingChunk, - _validateSize: minSize > 0, - _conditionalEnforce: enforceSizeThreshold > 0 - }; - // For all combination of chunk selection - for (const chunkCombination of combs) { - // Break if minimum number of chunks is not reached - if (chunkCombination.size < cacheGroup.minChunks) continue; - // Select chunks by configuration - const { - chunks: selectedChunks, - key: selectedChunksKey - } = getSelectedChunks( - chunkCombination, - cacheGroup.chunksFilter - ); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra + */ - addModuleToChunksInfoMap( - cacheGroup, - cacheGroupIndex, - selectedChunks, - selectedChunksKey, - module - ); - } - cacheGroupIndex++; - } - } - // Filter items were size < minSize - for (const pair of chunksInfoMap) { - const info = pair[1]; - if ( - info.cacheGroup._validateSize && - info.size < info.cacheGroup.minSize - ) { - chunksInfoMap.delete(pair[0]); - } - } +const UnsupportedWebAssemblyFeatureError = __webpack_require__(43101); - /** @type {Map} */ - const maxSizeQueueMap = new Map(); +class WasmFinalizeExportsPlugin { + apply(compiler) { + compiler.hooks.compilation.tap("WasmFinalizeExportsPlugin", compilation => { + compilation.hooks.finishModules.tap( + "WasmFinalizeExportsPlugin", + modules => { + for (const module of modules) { + // 1. if a WebAssembly module + if (module.type.startsWith("webassembly") === true) { + const jsIncompatibleExports = + module.buildMeta.jsIncompatibleExports; - while (chunksInfoMap.size > 0) { - // Find best matching entry - let bestEntryKey; - let bestEntry; - for (const pair of chunksInfoMap) { - const key = pair[0]; - const info = pair[1]; - if (bestEntry === undefined) { - bestEntry = info; - bestEntryKey = key; - } else if (compareEntries(bestEntry, info) < 0) { - bestEntry = info; - bestEntryKey = key; + if (jsIncompatibleExports === undefined) { + continue; } - } - const item = bestEntry; - chunksInfoMap.delete(bestEntryKey); + for (const reason of module.reasons) { + // 2. is referenced by a non-WebAssembly module + if (reason.module.type.startsWith("webassembly") === false) { + const ref = compilation.getDependencyReference( + reason.module, + reason.dependency + ); - let chunkName = item.name; - // Variable for the new chunk (lazy created) - /** @type {Chunk} */ - let newChunk; - // When no chunk name, check if we can reuse a chunk instead of creating a new one - let isReused = false; - if (item.cacheGroup.reuseExistingChunk) { - outer: for (const chunk of item.chunks) { - if (chunk.getNumberOfModules() !== item.modules.size) continue; - if (chunk.hasEntryModule()) continue; - for (const module of item.modules) { - if (!chunk.containsModule(module)) continue outer; - } - if (!newChunk || !newChunk.name) { - newChunk = chunk; - } else if ( - chunk.name && - chunk.name.length < newChunk.name.length - ) { - newChunk = chunk; - } else if ( - chunk.name && - chunk.name.length === newChunk.name.length && - chunk.name < newChunk.name - ) { - newChunk = chunk; + if (!ref) continue; + + const importedNames = ref.importedNames; + + if (Array.isArray(importedNames)) { + importedNames.forEach(name => { + // 3. and uses a func with an incompatible JS signature + if ( + Object.prototype.hasOwnProperty.call( + jsIncompatibleExports, + name + ) + ) { + // 4. error + /** @type {any} */ + const error = new UnsupportedWebAssemblyFeatureError( + `Export "${name}" with ${jsIncompatibleExports[name]} can only be used for direct wasm to wasm dependencies` + ); + error.module = module; + error.origin = reason.module; + error.originLoc = reason.dependency.loc; + error.dependencies = [reason.dependency]; + compilation.errors.push(error); + } + }); + } } - chunkName = undefined; - isReused = true; } } - // Check if maxRequests condition can be fulfilled + } + } + ); + }); + } +} - const selectedChunks = Array.from(item.chunks).filter(chunk => { - // skip if we address ourself - return ( - (!chunkName || chunk.name !== chunkName) && chunk !== newChunk - ); - }); +module.exports = WasmFinalizeExportsPlugin; - const enforced = - item.cacheGroup._conditionalEnforce && - item.size >= item.cacheGroup.enforceSizeThreshold; - // Skip when no chunk selected - if (selectedChunks.length === 0) continue; +/***/ }), - const usedChunks = new Set(selectedChunks); +/***/ 65331: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Check if maxRequests condition can be fulfilled - if ( - !enforced && - (Number.isFinite(item.cacheGroup.maxInitialRequests) || - Number.isFinite(item.cacheGroup.maxAsyncRequests)) - ) { - for (const chunk of usedChunks) { - // respect max requests - const maxRequests = chunk.isOnlyInitial() - ? item.cacheGroup.maxInitialRequests - : chunk.canBeInitial() - ? Math.min( - item.cacheGroup.maxInitialRequests, - item.cacheGroup.maxAsyncRequests - ) - : item.cacheGroup.maxAsyncRequests; - if ( - isFinite(maxRequests) && - getRequests(chunk) >= maxRequests - ) { - usedChunks.delete(chunk); - } - } - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - outer: for (const chunk of usedChunks) { - for (const module of item.modules) { - if (chunk.containsModule(module)) continue outer; - } - usedChunks.delete(chunk); - } - // Were some (invalid) chunks removed from usedChunks? - // => readd all modules to the queue, as things could have been changed - if (usedChunks.size < selectedChunks.length) { - if (usedChunks.size >= item.cacheGroup.minChunks) { - const chunksArr = Array.from(usedChunks); - for (const module of item.modules) { - addModuleToChunksInfoMap( - item.cacheGroup, - item.cacheGroupIndex, - chunksArr, - getKey(usedChunks), - module - ); - } - } - continue; - } +const Template = __webpack_require__(96066); +const WebAssemblyUtils = __webpack_require__(52136); - // Create the new chunk if not reusing one - if (!isReused) { - newChunk = compilation.addChunk(chunkName); - } - // Walk through all chunks - for (const chunk of usedChunks) { - // Add graph connections for splitted chunk - chunk.split(newChunk); - } +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../MainTemplate")} MainTemplate */ - // Add a note to the chunk - newChunk.chunkReason = isReused - ? "reused as split chunk" - : "split chunk"; - if (item.cacheGroup.key) { - newChunk.chunkReason += ` (cache group: ${item.cacheGroup.key})`; - } - if (chunkName) { - newChunk.chunkReason += ` (name: ${chunkName})`; - // If the chosen name is already an entry point we remove the entry point - const entrypoint = compilation.entrypoints.get(chunkName); - if (entrypoint) { - compilation.entrypoints.delete(chunkName); - entrypoint.remove(); - newChunk.entryModule = undefined; - } - } - if (item.cacheGroup.filename) { - if (!newChunk.isOnlyInitial()) { - throw new Error( - "SplitChunksPlugin: You are trying to set a filename for a chunk which is (also) loaded on demand. " + - "The runtime can only handle loading of chunks which match the chunkFilename schema. " + - "Using a custom filename would fail at runtime. " + - `(cache group: ${item.cacheGroup.key})` - ); - } - newChunk.filenameTemplate = item.cacheGroup.filename; - } - if (!isReused) { - // Add all modules to the new chunk - for (const module of item.modules) { - if (typeof module.chunkCondition === "function") { - if (!module.chunkCondition(newChunk)) continue; - } - // Add module to new chunk - GraphHelpers.connectChunkAndModule(newChunk, module); - // Remove module from used chunks - for (const chunk of usedChunks) { - chunk.removeModule(module); - module.rewriteChunkInReasons(chunk, [newChunk]); - } - } - } else { - // Remove all modules from used chunks - for (const module of item.modules) { - for (const chunk of usedChunks) { - chunk.removeModule(module); - module.rewriteChunkInReasons(chunk, [newChunk]); - } - } - } +// Get all wasm modules +const getAllWasmModules = chunk => { + const wasmModules = chunk.getAllAsyncChunks(); + const array = []; + for (const chunk of wasmModules) { + for (const m of chunk.modulesIterable) { + if (m.type.startsWith("webassembly")) { + array.push(m); + } + } + } - if (item.cacheGroup.maxSize > 0) { - const oldMaxSizeSettings = maxSizeQueueMap.get(newChunk); - maxSizeQueueMap.set(newChunk, { - minSize: Math.max( - oldMaxSizeSettings ? oldMaxSizeSettings.minSize : 0, - item.cacheGroup.minSizeForMaxSize - ), - maxSize: Math.min( - oldMaxSizeSettings ? oldMaxSizeSettings.maxSize : Infinity, - item.cacheGroup.maxSize - ), - automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter, - keys: oldMaxSizeSettings - ? oldMaxSizeSettings.keys.concat(item.cacheGroup.key) - : [item.cacheGroup.key] - }); - } + return array; +}; - // remove all modules from other entries and update size - for (const [key, info] of chunksInfoMap) { - if (isOverlap(info.chunks, usedChunks)) { - // update modules and total size - // may remove it from the map when < minSize - const oldSize = info.modules.size; - for (const module of item.modules) { - info.modules.delete(module); - } - if (info.modules.size !== oldSize) { - if (info.modules.size === 0) { - chunksInfoMap.delete(key); - continue; - } - info.size = getModulesSize(info.modules); - if ( - info.cacheGroup._validateSize && - info.size < info.cacheGroup.minSize - ) { - chunksInfoMap.delete(key); - } - if (info.modules.size === 0) { - chunksInfoMap.delete(key); - } - } - } - } - } +/** + * generates the import object function for a module + * @param {Module} module the module + * @param {boolean} mangle mangle imports + * @returns {string} source code + */ +const generateImportObject = (module, mangle) => { + const waitForInstances = new Map(); + const properties = []; + const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies( + module, + mangle + ); + for (const usedDep of usedWasmDependencies) { + const dep = usedDep.dependency; + const importedModule = dep.module; + const exportName = dep.name; + const usedName = importedModule && importedModule.isUsed(exportName); + const description = dep.description; + const direct = dep.onlyDirectImport; - const incorrectMinMaxSizeSet = new Set(); + const module = usedDep.module; + const name = usedDep.name; - // Make sure that maxSize is fulfilled - for (const chunk of compilation.chunks.slice()) { - const { minSize, maxSize, automaticNameDelimiter, keys } = - maxSizeQueueMap.get(chunk) || this.options.fallbackCacheGroup; - if (!maxSize) continue; - if (minSize > maxSize) { - const warningKey = `${keys && keys.join()} ${minSize} ${maxSize}`; - if (!incorrectMinMaxSizeSet.has(warningKey)) { - incorrectMinMaxSizeSet.add(warningKey); - compilation.warnings.push( - new MinMaxSizeWarning(keys, minSize, maxSize) - ); - } - } - const results = deterministicGroupingForModules({ - maxSize: Math.max(minSize, maxSize), - minSize, - items: chunk.modulesIterable, - getKey(module) { - const ident = contextify( - compilation.options.context, - module.identifier() - ); - const name = module.nameForCondition - ? contextify( - compilation.options.context, - module.nameForCondition() - ) - : ident.replace(/^.*!|\?[^?!]*$/g, ""); - const fullKey = - name + automaticNameDelimiter + hashFilename(ident); - return fullKey.replace(/[\\/?]/g, "_"); - }, - getSize(module) { - return module.size(); - } - }); - results.sort((a, b) => { - if (a.key < b.key) return -1; - if (a.key > b.key) return 1; - return 0; - }); - for (let i = 0; i < results.length; i++) { - const group = results[i]; - const key = this.options.hidePathInfo - ? hashFilename(group.key) - : group.key; - let name = chunk.name - ? chunk.name + automaticNameDelimiter + key - : null; - if (name && name.length > 100) { - name = - name.slice(0, 100) + - automaticNameDelimiter + - hashFilename(name); - } - let newPart; - if (i !== results.length - 1) { - newPart = compilation.addChunk(name); - chunk.split(newPart); - newPart.chunkReason = chunk.chunkReason; - // Add all modules to the new chunk - for (const module of group.items) { - if (typeof module.chunkCondition === "function") { - if (!module.chunkCondition(newPart)) continue; + if (direct) { + const instanceVar = `m${waitForInstances.size}`; + waitForInstances.set(instanceVar, importedModule.id); + properties.push({ + module, + name, + value: `${instanceVar}[${JSON.stringify(usedName)}]` + }); + } else { + const params = description.signature.params.map( + (param, k) => "p" + k + param.valtype + ); + + const mod = `installedModules[${JSON.stringify(importedModule.id)}]`; + const func = `${mod}.exports[${JSON.stringify(usedName)}]`; + + properties.push({ + module, + name, + value: Template.asString([ + (importedModule.type.startsWith("webassembly") + ? `${mod} ? ${func} : ` + : "") + `function(${params}) {`, + Template.indent([`return ${func}(${params});`]), + "}" + ]) + }); + } + } + + let importObject; + if (mangle) { + importObject = [ + "return {", + Template.indent([ + properties.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") + ]), + "};" + ]; + } else { + const propertiesByModule = new Map(); + for (const p of properties) { + let list = propertiesByModule.get(p.module); + if (list === undefined) { + propertiesByModule.set(p.module, (list = [])); + } + list.push(p); + } + importObject = [ + "return {", + Template.indent([ + Array.from(propertiesByModule, ([module, list]) => { + return Template.asString([ + `${JSON.stringify(module)}: {`, + Template.indent([ + list.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") + ]), + "}" + ]); + }).join(",\n") + ]), + "};" + ]; + } + + if (waitForInstances.size === 1) { + const moduleId = Array.from(waitForInstances.values())[0]; + const promise = `installedWasmModules[${JSON.stringify(moduleId)}]`; + const variable = Array.from(waitForInstances.keys())[0]; + return Template.asString([ + `${JSON.stringify(module.id)}: function() {`, + Template.indent([ + `return promiseResolve().then(function() { return ${promise}; }).then(function(${variable}) {`, + Template.indent(importObject), + "});" + ]), + "}," + ]); + } else if (waitForInstances.size > 0) { + const promises = Array.from( + waitForInstances.values(), + id => `installedWasmModules[${JSON.stringify(id)}]` + ).join(", "); + const variables = Array.from( + waitForInstances.keys(), + (name, i) => `${name} = array[${i}]` + ).join(", "); + return Template.asString([ + `${JSON.stringify(module.id)}: function() {`, + Template.indent([ + `return promiseResolve().then(function() { return Promise.all([${promises}]); }).then(function(array) {`, + Template.indent([`var ${variables};`, ...importObject]), + "});" + ]), + "}," + ]); + } else { + return Template.asString([ + `${JSON.stringify(module.id)}: function() {`, + Template.indent(importObject), + "}," + ]); + } +}; + +class WasmMainTemplatePlugin { + constructor({ generateLoadBinaryCode, supportsStreaming, mangleImports }) { + this.generateLoadBinaryCode = generateLoadBinaryCode; + this.supportsStreaming = supportsStreaming; + this.mangleImports = mangleImports; + } + + /** + * @param {MainTemplate} mainTemplate main template + * @returns {void} + */ + apply(mainTemplate) { + mainTemplate.hooks.localVars.tap( + "WasmMainTemplatePlugin", + (source, chunk) => { + const wasmModules = getAllWasmModules(chunk); + if (wasmModules.length === 0) return source; + const importObjects = wasmModules.map(module => { + return generateImportObject(module, this.mangleImports); + }); + return Template.asString([ + source, + "", + "// object to store loaded and loading wasm modules", + "var installedWasmModules = {};", + "", + // This function is used to delay reading the installed wasm module promises + // by a microtask. Sorting them doesn't help because there are egdecases where + // sorting is not possible (modules splitted into different chunks). + // So we not even trying and solve this by a microtask delay. + "function promiseResolve() { return Promise.resolve(); }", + "", + "var wasmImportObjects = {", + Template.indent(importObjects), + "};" + ]); + } + ); + mainTemplate.hooks.requireEnsure.tap( + "WasmMainTemplatePlugin", + (source, chunk, hash) => { + const webassemblyModuleFilename = + mainTemplate.outputOptions.webassemblyModuleFilename; + + const chunkModuleMaps = chunk.getChunkModuleMaps(m => + m.type.startsWith("webassembly") + ); + if (Object.keys(chunkModuleMaps.id).length === 0) return source; + const wasmModuleSrcPath = mainTemplate.getAssetPath( + JSON.stringify(webassemblyModuleFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + module: { + id: '" + wasmModuleId + "', + hash: `" + ${JSON.stringify( + chunkModuleMaps.hash + )}[wasmModuleId] + "`, + hashWithLength(length) { + const shortChunkHashMap = Object.create(null); + for (const wasmModuleId of Object.keys(chunkModuleMaps.hash)) { + if (typeof chunkModuleMaps.hash[wasmModuleId] === "string") { + shortChunkHashMap[wasmModuleId] = chunkModuleMaps.hash[ + wasmModuleId + ].substr(0, length); } - // Add module to new chunk - GraphHelpers.connectChunkAndModule(newPart, module); - // Remove module from used chunks - chunk.removeModule(module); - module.rewriteChunkInReasons(chunk, [newPart]); } - } else { - // change the chunk to be a part - newPart = chunk; - chunk.name = name; + return `" + ${JSON.stringify( + shortChunkHashMap + )}[wasmModuleId] + "`; } } } + ); + const createImportObject = content => + this.mangleImports + ? `{ ${JSON.stringify( + WebAssemblyUtils.MANGLED_MODULE + )}: ${content} }` + : content; + return Template.asString([ + source, + "", + "// Fetch + compile chunk loading for webassembly", + "", + `var wasmModules = ${JSON.stringify( + chunkModuleMaps.id + )}[chunkId] || [];`, + "", + "wasmModules.forEach(function(wasmModuleId) {", + Template.indent([ + "var installedWasmModuleData = installedWasmModules[wasmModuleId];", + "", + '// a Promise means "currently loading" or "already loaded".', + "if(installedWasmModuleData)", + Template.indent(["promises.push(installedWasmModuleData);"]), + "else {", + Template.indent([ + `var importObject = wasmImportObjects[wasmModuleId]();`, + `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, + "var promise;", + this.supportsStreaming + ? Template.asString([ + "if(importObject instanceof Promise && typeof WebAssembly.compileStreaming === 'function') {", + Template.indent([ + "promise = Promise.all([WebAssembly.compileStreaming(req), importObject]).then(function(items) {", + Template.indent([ + `return WebAssembly.instantiate(items[0], ${createImportObject( + "items[1]" + )});` + ]), + "});" + ]), + "} else if(typeof WebAssembly.instantiateStreaming === 'function') {", + Template.indent([ + `promise = WebAssembly.instantiateStreaming(req, ${createImportObject( + "importObject" + )});` + ]) + ]) + : Template.asString([ + "if(importObject instanceof Promise) {", + Template.indent([ + "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", + "promise = Promise.all([", + Template.indent([ + "bytesPromise.then(function(bytes) { return WebAssembly.compile(bytes); }),", + "importObject" + ]), + "]).then(function(items) {", + Template.indent([ + `return WebAssembly.instantiate(items[0], ${createImportObject( + "items[1]" + )});` + ]), + "});" + ]) + ]), + "} else {", + Template.indent([ + "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", + "promise = bytesPromise.then(function(bytes) {", + Template.indent([ + `return WebAssembly.instantiate(bytes, ${createImportObject( + "importObject" + )});` + ]), + "});" + ]), + "}", + "promises.push(installedWasmModules[wasmModuleId] = promise.then(function(res) {", + Template.indent([ + `return ${mainTemplate.requireFn}.w[wasmModuleId] = (res.instance || res).exports;` + ]), + "}));" + ]), + "}" + ]), + "});" + ]); + } + ); + mainTemplate.hooks.requireExtensions.tap( + "WasmMainTemplatePlugin", + (source, chunk) => { + if (!chunk.hasModuleInGraph(m => m.type.startsWith("webassembly"))) { + return source; } - ); + return Template.asString([ + source, + "", + "// object with all WebAssembly.instance exports", + `${mainTemplate.requireFn}.w = {};` + ]); + } + ); + mainTemplate.hooks.hash.tap("WasmMainTemplatePlugin", hash => { + hash.update("WasmMainTemplatePlugin"); + hash.update("2"); }); } -}; +} + +module.exports = WasmMainTemplatePlugin; /***/ }), -/***/ 89339: +/***/ 13099: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn + Author Tobias Koppers @sokra */ -const WebpackError = __webpack_require__(97391); -const SizeFormatHelpers = __webpack_require__(12496); - -module.exports = class AssetsOverSizeLimitWarning extends WebpackError { - constructor(assetsOverSizeLimit, assetLimit) { - const assetLists = assetsOverSizeLimit - .map( - asset => - `\n ${asset.name} (${SizeFormatHelpers.formatSize(asset.size)})` - ) - .join(""); - - super(`asset size limit: The following asset(s) exceed the recommended size limit (${SizeFormatHelpers.formatSize( - assetLimit - )}). -This can impact web performance. -Assets: ${assetLists}`); - - this.name = "AssetsOverSizeLimitWarning"; - this.assets = assetsOverSizeLimit; +const Generator = __webpack_require__(39172); +const Template = __webpack_require__(96066); +const WebAssemblyUtils = __webpack_require__(52136); +const { RawSource } = __webpack_require__(53665); - Error.captureStackTrace(this, this.constructor); - } -}; +const { editWithAST, addWithAST } = __webpack_require__(65584); +const { decode } = __webpack_require__(27352); +const t = __webpack_require__(81875); +const { + moduleContextFromModuleAST +} = __webpack_require__(71234); +const WebAssemblyExportImportedDependency = __webpack_require__(18925); -/***/ }), +/** @typedef {import("../Module")} Module */ +/** @typedef {import("./WebAssemblyUtils").UsedWasmDependency} UsedWasmDependency */ +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Dependency").DependencyTemplate} DependencyTemplate */ -/***/ 41336: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * @typedef {(ArrayBuffer) => ArrayBuffer} ArrayBufferTransform + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ +/** + * @template T + * @param {Function[]} fns transforms + * @returns {Function} composed transform + */ +const compose = (...fns) => { + return fns.reduce( + (prevFn, nextFn) => { + return value => nextFn(prevFn(value)); + }, + value => value + ); +}; +// TODO replace with @callback -const WebpackError = __webpack_require__(97391); -const SizeFormatHelpers = __webpack_require__(12496); +/** + * Removes the start instruction + * + * @param {Object} state unused state + * @returns {ArrayBufferTransform} transform + */ +const removeStartFunc = state => bin => { + return editWithAST(state.ast, bin, { + Start(path) { + path.remove(); + } + }); +}; -module.exports = class EntrypointsOverSizeLimitWarning extends WebpackError { - constructor(entrypoints, entrypointLimit) { - const entrypointList = entrypoints - .map( - entrypoint => - `\n ${entrypoint.name} (${SizeFormatHelpers.formatSize( - entrypoint.size - )})\n${entrypoint.files.map(asset => ` ${asset}`).join("\n")}` - ) - .join(""); - super(`entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (${SizeFormatHelpers.formatSize( - entrypointLimit - )}). This can impact web performance. -Entrypoints:${entrypointList}\n`); +/** + * Get imported globals + * + * @param {Object} ast Module's AST + * @returns {Array} - nodes + */ +const getImportedGlobals = ast => { + const importedGlobals = []; - this.name = "EntrypointsOverSizeLimitWarning"; - this.entrypoints = entrypoints; + t.traverse(ast, { + ModuleImport({ node }) { + if (t.isGlobalType(node.descr)) { + importedGlobals.push(node); + } + } + }); - Error.captureStackTrace(this, this.constructor); - } + return importedGlobals; }; +/** + * Get the count for imported func + * + * @param {Object} ast Module's AST + * @returns {Number} - count + */ +const getCountImportedFunc = ast => { + let count = 0; -/***/ }), - -/***/ 53006: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ + t.traverse(ast, { + ModuleImport({ node }) { + if (t.isFuncImportDescr(node.descr)) { + count++; + } + } + }); + return count; +}; -const WebpackError = __webpack_require__(97391); +/** + * Get next type index + * + * @param {Object} ast Module's AST + * @returns {t.Index} - index + */ +const getNextTypeIndex = ast => { + const typeSectionMetadata = t.getSectionMetadata(ast, "type"); -module.exports = class NoAsyncChunksWarning extends WebpackError { - constructor() { - super( - "webpack performance recommendations: \n" + - "You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.\n" + - "For more info visit https://webpack.js.org/guides/code-splitting/" - ); + if (typeSectionMetadata === undefined) { + return t.indexLiteral(0); + } - this.name = "NoAsyncChunksWarning"; + return t.indexLiteral(typeSectionMetadata.vectorOfSize.value); +}; - Error.captureStackTrace(this, this.constructor); +/** + * Get next func index + * + * The Func section metadata provide informations for implemented funcs + * in order to have the correct index we shift the index by number of external + * functions. + * + * @param {Object} ast Module's AST + * @param {Number} countImportedFunc number of imported funcs + * @returns {t.Index} - index + */ +const getNextFuncIndex = (ast, countImportedFunc) => { + const funcSectionMetadata = t.getSectionMetadata(ast, "func"); + + if (funcSectionMetadata === undefined) { + return t.indexLiteral(0 + countImportedFunc); } -}; + const vectorOfSize = funcSectionMetadata.vectorOfSize.value; -/***/ }), + return t.indexLiteral(vectorOfSize + countImportedFunc); +}; -/***/ 68310: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/** + * Creates an init instruction for a global type + * @param {t.GlobalType} globalType the global type + * @returns {t.Instruction} init expression + */ +const createDefaultInitForGlobal = globalType => { + if (globalType.valtype[0] === "i") { + // create NumberLiteral global initializer + return t.objectInstruction("const", globalType.valtype, [ + t.numberLiteralFromRaw(66) + ]); + } else if (globalType.valtype[0] === "f") { + // create FloatLiteral global initializer + return t.objectInstruction("const", globalType.valtype, [ + t.floatLiteral(66, false, false, "66") + ]); + } else { + throw new Error("unknown type: " + globalType.valtype); + } +}; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Sean Larkin @thelarkinn -*/ +/** + * Rewrite the import globals: + * - removes the ModuleImport instruction + * - injects at the same offset a mutable global of the same type + * + * Since the imported globals are before the other global declarations, our + * indices will be preserved. + * + * Note that globals will become mutable. + * + * @param {Object} state unused state + * @returns {ArrayBufferTransform} transform + */ +const rewriteImportedGlobals = state => bin => { + const additionalInitCode = state.additionalInitCode; + const newGlobals = []; -const EntrypointsOverSizeLimitWarning = __webpack_require__(41336); -const AssetsOverSizeLimitWarning = __webpack_require__(89339); -const NoAsyncChunksWarning = __webpack_require__(53006); + bin = editWithAST(state.ast, bin, { + ModuleImport(path) { + if (t.isGlobalType(path.node.descr)) { + const globalType = path.node.descr; -/** @typedef {import("../Compiler")} Compiler */ -/** @typedef {import("../Entrypoint")} Entrypoint */ + globalType.mutability = "var"; -module.exports = class SizeLimitsPlugin { - constructor(options) { - this.hints = options.hints; - this.maxAssetSize = options.maxAssetSize; - this.maxEntrypointSize = options.maxEntrypointSize; - this.assetFilter = options.assetFilter; - } + const init = [ + createDefaultInitForGlobal(globalType), + t.instruction("end") + ]; - /** - * @param {Compiler} compiler webpack compiler - * @returns {void} - */ - apply(compiler) { - const entrypointSizeLimit = this.maxEntrypointSize; - const assetSizeLimit = this.maxAssetSize; - const hints = this.hints; - const assetFilter = - this.assetFilter || ((name, source, info) => !info.development); + newGlobals.push(t.global(globalType, init)); - compiler.hooks.afterEmit.tap("SizeLimitsPlugin", compilation => { - const warnings = []; + path.remove(); + } + }, - /** - * @param {Entrypoint} entrypoint an entrypoint - * @returns {number} the size of the entrypoint - */ - const getEntrypointSize = entrypoint => - entrypoint.getFiles().reduce((currentSize, file) => { - const asset = compilation.getAsset(file); - if ( - asset && - assetFilter(asset.name, asset.source, asset.info) && - asset.source - ) { - return currentSize + (asset.info.size || asset.source.size()); - } + // in order to preserve non-imported global's order we need to re-inject + // those as well + Global(path) { + const { node } = path; + const [init] = node.init; - return currentSize; - }, 0); + if (init.id === "get_global") { + node.globalType.mutability = "var"; - const assetsOverSizeLimit = []; - for (const { name, source, info } of compilation.getAssets()) { - if (!assetFilter(name, source, info) || !source) { - continue; - } + const initialGlobalidx = init.args[0]; - const size = info.size || source.size(); - if (size > assetSizeLimit) { - assetsOverSizeLimit.push({ - name, - size - }); - /** @type {any} */ (source).isOverSizeLimit = true; - } + node.init = [ + createDefaultInitForGlobal(node.globalType), + t.instruction("end") + ]; + + additionalInitCode.push( + /** + * get_global in global initializer only works for imported globals. + * They have the same indices as the init params, so use the + * same index. + */ + t.instruction("get_local", [initialGlobalidx]), + t.instruction("set_global", [t.indexLiteral(newGlobals.length)]) + ); } - const fileFilter = name => { - const asset = compilation.getAsset(name); - return asset && assetFilter(asset.name, asset.source, asset.info); - }; + newGlobals.push(node); - const entrypointsOverLimit = []; - for (const [name, entry] of compilation.entrypoints) { - const size = getEntrypointSize(entry); + path.remove(); + } + }); - if (size > entrypointSizeLimit) { - entrypointsOverLimit.push({ - name: name, - size: size, - files: entry.getFiles().filter(fileFilter) - }); - /** @type {any} */ (entry).isOverSizeLimit = true; - } + // Add global declaration instructions + return addWithAST(state.ast, bin, newGlobals); +}; + +/** + * Rewrite the export names + * @param {Object} state state + * @param {Object} state.ast Module's ast + * @param {Module} state.module Module + * @param {Set} state.externalExports Module + * @returns {ArrayBufferTransform} transform + */ +const rewriteExportNames = ({ ast, module, externalExports }) => bin => { + return editWithAST(ast, bin, { + ModuleExport(path) { + const isExternal = externalExports.has(path.node.name); + if (isExternal) { + path.remove(); + return; + } + const usedName = module.isUsed(path.node.name); + if (!usedName) { + path.remove(); + return; } + path.node.name = usedName; + } + }); +}; - if (hints) { - // 1. Individual Chunk: Size < 250kb - // 2. Collective Initial Chunks [entrypoint] (Each Set?): Size < 250kb - // 3. No Async Chunks - // if !1, then 2, if !2 return - if (assetsOverSizeLimit.length > 0) { - warnings.push( - new AssetsOverSizeLimitWarning(assetsOverSizeLimit, assetSizeLimit) - ); - } - if (entrypointsOverLimit.length > 0) { - warnings.push( - new EntrypointsOverSizeLimitWarning( - entrypointsOverLimit, - entrypointSizeLimit - ) - ); - } +/** + * Mangle import names and modules + * @param {Object} state state + * @param {Object} state.ast Module's ast + * @param {Map} state.usedDependencyMap mappings to mangle names + * @returns {ArrayBufferTransform} transform + */ +const rewriteImports = ({ ast, usedDependencyMap }) => bin => { + return editWithAST(ast, bin, { + ModuleImport(path) { + const result = usedDependencyMap.get( + path.node.module + ":" + path.node.name + ); - if (warnings.length > 0) { - const hasAsyncChunks = - compilation.chunks.filter(chunk => !chunk.canBeInitial()).length > - 0; + if (result !== undefined) { + path.node.module = result.module; + path.node.name = result.name; + } + } + }); +}; - if (!hasAsyncChunks) { - warnings.push(new NoAsyncChunksWarning()); - } +/** + * Add an init function. + * + * The init function fills the globals given input arguments. + * + * @param {Object} state transformation state + * @param {Object} state.ast Module's ast + * @param {t.Identifier} state.initFuncId identifier of the init function + * @param {t.Index} state.startAtFuncOffset index of the start function + * @param {t.ModuleImport[]} state.importedGlobals list of imported globals + * @param {t.Instruction[]} state.additionalInitCode list of addition instructions for the init function + * @param {t.Index} state.nextFuncIndex index of the next function + * @param {t.Index} state.nextTypeIndex index of the next type + * @returns {ArrayBufferTransform} transform + */ +const addInitFunction = ({ + ast, + initFuncId, + startAtFuncOffset, + importedGlobals, + additionalInitCode, + nextFuncIndex, + nextTypeIndex +}) => bin => { + const funcParams = importedGlobals.map(importedGlobal => { + // used for debugging + const id = t.identifier(`${importedGlobal.module}.${importedGlobal.name}`); - if (hints === "error") { - compilation.errors.push(...warnings); - } else { - compilation.warnings.push(...warnings); - } - } - } - }); + return t.funcParam(importedGlobal.descr.valtype, id); + }); + + const funcBody = importedGlobals.reduce((acc, importedGlobal, index) => { + const args = [t.indexLiteral(index)]; + const body = [ + t.instruction("get_local", args), + t.instruction("set_global", args) + ]; + + return [...acc, ...body]; + }, []); + + if (typeof startAtFuncOffset === "number") { + funcBody.push(t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset))); } -}; + for (const instr of additionalInitCode) { + funcBody.push(instr); + } -/***/ }), + funcBody.push(t.instruction("end")); -/***/ 52315: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + const funcResults = []; -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + // Code section + const funcSignature = t.signature(funcParams, funcResults); + const func = t.func(initFuncId, funcSignature, funcBody); + // Type section + const functype = t.typeInstruction(undefined, funcSignature); + // Func section + const funcindex = t.indexInFuncSection(nextTypeIndex); -const SortableSet = __webpack_require__(50071); + // Export section + const moduleExport = t.moduleExport( + initFuncId.value, + t.moduleExportDescr("Func", nextFuncIndex) + ); + + return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]); +}; /** - * @template T - * @template K - * Multi layer bucket sorted set - * Supports adding non-existing items (DO NOT ADD ITEM TWICE) - * Supports removing exiting items (DO NOT REMOVE ITEM NOT IN SET) - * Supports popping the first items according to defined order - * Supports iterating all items without order - * Supports updating an item in an efficient way - * Supports size property, which is the number of items - * Items are lazy partially sorted when needed + * Extract mangle mappings from module + * @param {Module} module current module + * @param {boolean} mangle mangle imports + * @returns {Map} mappings to mangled names */ -class LazyBucketSortedSet { - /** - * @param {function(T): K} getKey function to get key from item - * @param {function(K, K): number} comparator comparator to sort keys - * @param {...((function(T): any) | (function(any, any): number))} args more pairs of getKey and comparator plus optional final comparator for the last layer - */ - constructor(getKey, comparator, ...args) { - this._getKey = getKey; - this._innerArgs = args; - this._leaf = args.length <= 1; - this._keys = new SortableSet(undefined, comparator); - /** @type {Map | SortableSet>} */ - this._map = new Map(); - this._unsortedItems = new Set(); - this.size = 0; +const getUsedDependencyMap = (module, mangle) => { + /** @type {Map} */ + const map = new Map(); + for (const usedDep of WebAssemblyUtils.getUsedDependencies(module, mangle)) { + const dep = usedDep.dependency; + const request = dep.request; + const exportName = dep.name; + map.set(request + ":" + exportName, usedDep); } + return map; +}; - /** - * @param {T} item an item - * @returns {void} - */ - add(item) { - this.size++; - this._unsortedItems.add(item); +class WebAssemblyGenerator extends Generator { + constructor(options) { + super(); + this.options = options; } /** - * @param {K} key key of item - * @param {T} item the item - * @returns {void} + * @param {NormalModule} module module for which the code should be generated + * @param {Map} dependencyTemplates mapping from dependencies to templates + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {string} type which kind of code should be generated + * @returns {Source} generated code */ - _addInternal(key, item) { - let entry = this._map.get(key); - if (entry === undefined) { - entry = this._leaf - ? new SortableSet(undefined, this._innerArgs[0]) - : new /** @type {any} */ (LazyBucketSortedSet)(...this._innerArgs); - this._keys.add(key); - this._map.set(key, entry); - } - entry.add(item); - } + generate(module, dependencyTemplates, runtimeTemplate, type) { + let bin = module.originalSource().source(); - /** - * @param {T} item an item - * @returns {void} - */ - delete(item) { - this.size--; - if (this._unsortedItems.has(item)) { - this._unsortedItems.delete(item); - return; - } - const key = this._getKey(item); - const entry = this._map.get(key); - entry.delete(item); - if (entry.size === 0) { - this._deleteKey(key); - } - } + const initFuncId = t.identifier( + Array.isArray(module.usedExports) + ? Template.numberToIdentifer(module.usedExports.length) + : "__webpack_init__" + ); - /** - * @param {K} key key to be removed - * @returns {void} - */ - _deleteKey(key) { - this._keys.delete(key); - this._map.delete(key); - } + // parse it + const ast = decode(bin, { + ignoreDataSection: true, + ignoreCodeSection: true, + ignoreCustomNameSection: true + }); - /** - * @returns {T | undefined} an item - */ - popFirst() { - if (this.size === 0) return undefined; - this.size--; - if (this._unsortedItems.size > 0) { - for (const item of this._unsortedItems) { - const key = this._getKey(item); - this._addInternal(key, item); - } - this._unsortedItems.clear(); - } - this._keys.sort(); - const key = this._keys.values().next().value; - const entry = this._map.get(key); - if (this._leaf) { - const leafEntry = /** @type {SortableSet} */ (entry); - leafEntry.sort(); - const item = leafEntry.values().next().value; - leafEntry.delete(item); - if (leafEntry.size === 0) { - this._deleteKey(key); - } - return item; - } else { - const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); - const item = nodeEntry.popFirst(); - if (nodeEntry.size === 0) { - this._deleteKey(key); - } - return item; - } - } + const moduleContext = moduleContextFromModuleAST(ast.body[0]); - /** - * @param {T} item to be updated item - * @returns {function(true=): void} finish update - */ - startUpdate(item) { - if (this._unsortedItems.has(item)) { - return remove => { - if (remove) { - this._unsortedItems.delete(item); - this.size--; - return; - } - }; - } - const key = this._getKey(item); - if (this._leaf) { - const oldEntry = /** @type {SortableSet} */ (this._map.get(key)); - return remove => { - if (remove) { - this.size--; - oldEntry.delete(item); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - return; - } - const newKey = this._getKey(item); - if (key === newKey) { - // This flags the sortable set as unordered - oldEntry.add(item); - } else { - oldEntry.delete(item); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - this._addInternal(newKey, item); - } - }; - } else { - const oldEntry = /** @type {LazyBucketSortedSet} */ (this._map.get( - key - )); - const finishUpdate = oldEntry.startUpdate(item); - return remove => { - if (remove) { - this.size--; - finishUpdate(true); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - return; - } - const newKey = this._getKey(item); - if (key === newKey) { - finishUpdate(); - } else { - finishUpdate(true); - if (oldEntry.size === 0) { - this._deleteKey(key); - } - this._addInternal(newKey, item); - } - }; - } - } + const importedGlobals = getImportedGlobals(ast); + const countImportedFunc = getCountImportedFunc(ast); + const startAtFuncOffset = moduleContext.getStart(); + const nextFuncIndex = getNextFuncIndex(ast, countImportedFunc); + const nextTypeIndex = getNextTypeIndex(ast); - /** - * @param {Iterator[]} iterators list of iterators to append to - * @returns {void} - */ - _appendIterators(iterators) { - if (this._unsortedItems.size > 0) - iterators.push(this._unsortedItems[Symbol.iterator]()); - for (const key of this._keys) { - const entry = this._map.get(key); - if (this._leaf) { - const leafEntry = /** @type {SortableSet} */ (entry); - const iterator = leafEntry[Symbol.iterator](); - iterators.push(iterator); - } else { - const nodeEntry = /** @type {LazyBucketSortedSet} */ (entry); - nodeEntry._appendIterators(iterators); - } - } - } + const usedDependencyMap = getUsedDependencyMap( + module, + this.options.mangleImports + ); + const externalExports = new Set( + module.dependencies + .filter(d => d instanceof WebAssemblyExportImportedDependency) + .map(d => { + const wasmDep = /** @type {WebAssemblyExportImportedDependency} */ (d); + return wasmDep.exportName; + }) + ); - /** - * @returns {Iterator} the iterator - */ - [Symbol.iterator]() { - const iterators = []; - this._appendIterators(iterators); - iterators.reverse(); - let currentIterator = iterators.pop(); - return { - next: () => { - const res = currentIterator.next(); - if (res.done) { - if (iterators.length === 0) return res; - currentIterator = iterators.pop(); - return currentIterator.next(); - } - return res; - } - }; + /** @type {t.Instruction[]} */ + const additionalInitCode = []; + + const transform = compose( + rewriteExportNames({ + ast, + module, + externalExports + }), + + removeStartFunc({ ast }), + + rewriteImportedGlobals({ ast, additionalInitCode }), + + rewriteImports({ + ast, + usedDependencyMap + }), + + addInitFunction({ + ast, + initFuncId, + importedGlobals, + additionalInitCode, + startAtFuncOffset, + nextFuncIndex, + nextTypeIndex + }) + ); + + const newBin = transform(bin); + + return new RawSource(newBin); } } -module.exports = LazyBucketSortedSet; +module.exports = WebAssemblyGenerator; /***/ }), -/***/ 38637: -/***/ (function(module) { +/***/ 45283: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +const WebpackError = __webpack_require__(97391); + +/** @typedef {import("../Module")} Module */ +/** @typedef {import("../RequestShortener")} RequestShortener */ /** - * @template T + * @param {Module} module module to get chains from + * @param {RequestShortener} requestShortener to make readable identifiers + * @returns {string[]} all chains to the module */ -class Queue { - /** - * @param {Iterable=} items The initial elements. - */ - constructor(items) { - /** @private @type {Set} */ - this.set = new Set(items); - /** @private @type {Iterator} */ - this.iterator = this.set[Symbol.iterator](); - } +const getInitialModuleChains = (module, requestShortener) => { + const queue = [ + { head: module, message: module.readableIdentifier(requestShortener) } + ]; + /** @type {Set} */ + const results = new Set(); + /** @type {Set} */ + const incompleteResults = new Set(); + /** @type {Set} */ + const visitedModules = new Set(); - /** - * Returns the number of elements in this queue. - * @returns {number} The number of elements in this queue. - */ - get length() { - return this.set.size; + for (const chain of queue) { + const { head, message } = chain; + let final = true; + /** @type {Set} */ + const alreadyReferencedModules = new Set(); + for (const reason of head.reasons) { + const newHead = reason.module; + if (newHead) { + if (!newHead.getChunks().some(c => c.canBeInitial())) continue; + final = false; + if (alreadyReferencedModules.has(newHead)) continue; + alreadyReferencedModules.add(newHead); + const moduleName = newHead.readableIdentifier(requestShortener); + const detail = reason.explanation ? ` (${reason.explanation})` : ""; + const newMessage = `${moduleName}${detail} --> ${message}`; + if (visitedModules.has(newHead)) { + incompleteResults.add(`... --> ${newMessage}`); + continue; + } + visitedModules.add(newHead); + queue.push({ + head: newHead, + message: newMessage + }); + } else { + final = false; + const newMessage = reason.explanation + ? `(${reason.explanation}) --> ${message}` + : message; + results.add(newMessage); + } + } + if (final) { + results.add(message); + } } - - /** - * Appends the specified element to this queue. - * @param {T} item The element to add. - * @returns {void} - */ - enqueue(item) { - this.set.add(item); + for (const result of incompleteResults) { + results.add(result); } + return Array.from(results); +}; +module.exports = class WebAssemblyInInitialChunkError extends WebpackError { /** - * Retrieves and removes the head of this queue. - * @returns {T | undefined} The head of the queue of `undefined` if this queue is empty. + * @param {Module} module WASM module + * @param {RequestShortener} requestShortener request shortener */ - dequeue() { - const result = this.iterator.next(); - if (result.done) return undefined; - this.set.delete(result.value); - return result.value; - } -} + constructor(module, requestShortener) { + const moduleChains = getInitialModuleChains(module, requestShortener); + const message = `WebAssembly module is included in initial chunk. +This is not allowed, because WebAssembly download and compilation must happen asynchronous. +Add an async splitpoint (i. e. import()) somewhere between your entrypoint and the WebAssembly module: +${moduleChains.map(s => `* ${s}`).join("\n")}`; -module.exports = Queue; + super(message); + this.name = "WebAssemblyInInitialChunkError"; + this.hideStack = true; + this.module = module; + + Error.captureStackTrace(this, this.constructor); + } +}; /***/ }), -/***/ 33349: -/***/ (function(module) { +/***/ 13411: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -111105,262 +109531,293 @@ module.exports = Queue; */ -class Semaphore { - /** - * Creates an instance of Semaphore. - * - * @param {number} available the amount available number of "tasks" - * in the Semaphore - */ - constructor(available) { - this.available = available; - /** @type {(function(): void)[]} */ - this.waiters = []; - /** @private */ - this._continue = this._continue.bind(this); - } +const Generator = __webpack_require__(39172); +const Template = __webpack_require__(96066); +const { RawSource } = __webpack_require__(53665); +const WebAssemblyImportDependency = __webpack_require__(52959); +const WebAssemblyExportImportedDependency = __webpack_require__(18925); + +/** @typedef {import("../NormalModule")} NormalModule */ +/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../Dependency").DependencyTemplate} DependencyTemplate */ +class WebAssemblyJavascriptGenerator extends Generator { /** - * @param {function(): void} callback function block to capture and run - * @returns {void} + * @param {NormalModule} module module for which the code should be generated + * @param {Map} dependencyTemplates mapping from dependencies to templates + * @param {RuntimeTemplate} runtimeTemplate the runtime template + * @param {string} type which kind of code should be generated + * @returns {Source} generated code */ - acquire(callback) { - if (this.available > 0) { - this.available--; - callback(); - } else { - this.waiters.push(callback); - } - } + generate(module, dependencyTemplates, runtimeTemplate, type) { + const initIdentifer = Array.isArray(module.usedExports) + ? Template.numberToIdentifer(module.usedExports.length) + : "__webpack_init__"; - release() { - this.available++; - if (this.waiters.length > 0) { - process.nextTick(this._continue); - } - } + let needExportsCopy = false; + const importedModules = new Map(); + const initParams = []; + let index = 0; + for (const dep of module.dependencies) { + const depAsAny = /** @type {any} */ (dep); + if (dep.module) { + let importData = importedModules.get(dep.module); + if (importData === undefined) { + importedModules.set( + dep.module, + (importData = { + importVar: `m${index}`, + index, + request: + "userRequest" in depAsAny ? depAsAny.userRequest : undefined, + names: new Set(), + reexports: [] + }) + ); + index++; + } + if (dep instanceof WebAssemblyImportDependency) { + importData.names.add(dep.name); + if (dep.description.type === "GlobalType") { + const exportName = dep.name; + const usedName = dep.module && dep.module.isUsed(exportName); - _continue() { - if (this.available > 0) { - if (this.waiters.length > 0) { - this.available--; - const callback = this.waiters.pop(); - callback(); + if (dep.module) { + if (usedName) { + initParams.push( + runtimeTemplate.exportFromImport({ + module: dep.module, + request: dep.request, + importVar: importData.importVar, + originModule: module, + exportName: dep.name, + asiSafe: true, + isCall: false, + callContext: null + }) + ); + } + } + } + } + if (dep instanceof WebAssemblyExportImportedDependency) { + importData.names.add(dep.name); + const usedName = module.isUsed(dep.exportName); + if (usedName) { + const exportProp = `${module.exportsArgument}[${JSON.stringify( + usedName + )}]`; + const defineStatement = Template.asString([ + `${exportProp} = ${runtimeTemplate.exportFromImport({ + module: dep.module, + request: dep.request, + importVar: importData.importVar, + originModule: module, + exportName: dep.name, + asiSafe: true, + isCall: false, + callContext: null + })};`, + `if(WebAssembly.Global) ${exportProp} = ` + + `new WebAssembly.Global({ value: ${JSON.stringify( + dep.valueType + )} }, ${exportProp});` + ]); + importData.reexports.push(defineStatement); + needExportsCopy = true; + } + } } } + const importsCode = Template.asString( + Array.from( + importedModules, + ([module, { importVar, request, reexports }]) => { + const importStatement = runtimeTemplate.importStatement({ + module, + request, + importVar, + originModule: module + }); + return importStatement + reexports.join("\n"); + } + ) + ); + + // create source + const source = new RawSource( + [ + '"use strict";', + "// Instantiate WebAssembly module", + "var wasmExports = __webpack_require__.w[module.i];", + + !Array.isArray(module.usedExports) + ? `__webpack_require__.r(${module.exportsArgument});` + : "", + + // this must be before import for circular dependencies + "// export exports from WebAssembly module", + Array.isArray(module.usedExports) && !needExportsCopy + ? `${module.moduleArgument}.exports = wasmExports;` + : "for(var name in wasmExports) " + + `if(name != ${JSON.stringify(initIdentifer)}) ` + + `${module.exportsArgument}[name] = wasmExports[name];`, + "// exec imports from WebAssembly module (for esm order)", + importsCode, + "", + "// exec wasm module", + `wasmExports[${JSON.stringify(initIdentifer)}](${initParams.join( + ", " + )})` + ].join("\n") + ); + return source; } } -module.exports = Semaphore; +module.exports = WebAssemblyJavascriptGenerator; /***/ }), -/***/ 54262: -/***/ (function(__unused_webpack_module, exports) { +/***/ 99510: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * intersect creates Set containing the intersection of elements between all sets - * @param {Set[]} sets an array of sets being checked for shared elements - * @returns {Set} returns a new Set containing the intersecting items - */ -const intersect = sets => { - if (sets.length === 0) return new Set(); - if (sets.length === 1) return new Set(sets[0]); - let minSize = Infinity; - let minIndex = -1; - for (let i = 0; i < sets.length; i++) { - const size = sets[i].size; - if (size < minSize) { - minIndex = i; - minSize = size; - } - } - const current = new Set(sets[minIndex]); - for (let i = 0; i < sets.length; i++) { - if (i === minIndex) continue; - const set = sets[i]; - for (const item of current) { - if (!set.has(item)) { - current.delete(item); - } - } - } - return current; -}; - -/** - * Checks if a set is the subset of another set - * @param {Set} bigSet a Set which contains the original elements to compare against - * @param {Set} smallSet the set whos elements might be contained inside of bigSet - * @returns {boolean} returns true if smallSet contains all elements inside of the bigSet - */ -const isSubset = (bigSet, smallSet) => { - if (bigSet.size < smallSet.size) return false; - for (const item of smallSet) { - if (!bigSet.has(item)) return false; - } - return true; -}; - -exports.intersect = intersect; -exports.isSubset = isSubset; +const Generator = __webpack_require__(39172); +const WebAssemblyExportImportedDependency = __webpack_require__(18925); +const WebAssemblyImportDependency = __webpack_require__(52959); +const WebAssemblyInInitialChunkError = __webpack_require__(45283); +/** @typedef {import("../Compiler")} Compiler */ -/***/ }), +let WebAssemblyGenerator; +let WebAssemblyJavascriptGenerator; +let WebAssemblyParser; -/***/ 50071: -/***/ (function(module) { - -"use strict"; - - -/** - * A subset of Set that offers sorting functionality - * @template T item type in set - * @extends {Set} - */ -class SortableSet extends Set { - /** - * Create a new sortable set - * @param {Iterable=} initialIterable The initial iterable value - * @typedef {function(T, T): number} SortFunction - * @param {SortFunction=} defaultSort Default sorting function - */ - constructor(initialIterable, defaultSort) { - super(initialIterable); - /** @private @type {function(T, T): number}} */ - this._sortFn = defaultSort; - /** @private @type {function(T, T): number} | null} */ - this._lastActiveSortFn = null; - /** @private @type {Map | undefined} */ - this._cache = undefined; - /** @private @type {Map | undefined} */ - this._cacheOrderIndependent = undefined; +class WebAssemblyModulesPlugin { + constructor(options) { + this.options = options; } /** - * @param {T} value value to add to set - * @returns {this} returns itself + * @param {Compiler} compiler compiler + * @returns {void} */ - add(value) { - this._lastActiveSortFn = null; - this._invalidateCache(); - this._invalidateOrderedCache(); - super.add(value); - return this; - } + apply(compiler) { + compiler.hooks.compilation.tap( + "WebAssemblyModulesPlugin", + (compilation, { normalModuleFactory }) => { + compilation.dependencyFactories.set( + WebAssemblyImportDependency, + normalModuleFactory + ); - /** - * @param {T} value value to delete - * @returns {boolean} true if value existed in set, false otherwise - */ - delete(value) { - this._invalidateCache(); - this._invalidateOrderedCache(); - return super.delete(value); - } + compilation.dependencyFactories.set( + WebAssemblyExportImportedDependency, + normalModuleFactory + ); - /** - * @returns {void} - */ - clear() { - this._invalidateCache(); - this._invalidateOrderedCache(); - return super.clear(); - } + normalModuleFactory.hooks.createParser + .for("webassembly/experimental") + .tap("WebAssemblyModulesPlugin", () => { + if (WebAssemblyParser === undefined) { + WebAssemblyParser = __webpack_require__(77703); + } + return new WebAssemblyParser(); + }); - /** - * Sort with a comparer function - * @param {SortFunction} sortFn Sorting comparer function - * @returns {void} - */ - sortWith(sortFn) { - if (this.size <= 1 || sortFn === this._lastActiveSortFn) { - // already sorted - nothing to do - return; - } + normalModuleFactory.hooks.createGenerator + .for("webassembly/experimental") + .tap("WebAssemblyModulesPlugin", () => { + if (WebAssemblyGenerator === undefined) { + WebAssemblyGenerator = __webpack_require__(13099); + } + if (WebAssemblyJavascriptGenerator === undefined) { + WebAssemblyJavascriptGenerator = __webpack_require__(13411); + } + return Generator.byType({ + javascript: new WebAssemblyJavascriptGenerator(), + webassembly: new WebAssemblyGenerator(this.options) + }); + }); - const sortedArray = Array.from(this).sort(sortFn); - super.clear(); - for (let i = 0; i < sortedArray.length; i += 1) { - super.add(sortedArray[i]); - } - this._lastActiveSortFn = sortFn; - this._invalidateCache(); - } + compilation.chunkTemplate.hooks.renderManifest.tap( + "WebAssemblyModulesPlugin", + (result, options) => { + const chunk = options.chunk; + const outputOptions = options.outputOptions; + const moduleTemplates = options.moduleTemplates; + const dependencyTemplates = options.dependencyTemplates; - sort() { - this.sortWith(this._sortFn); - } + for (const module of chunk.modulesIterable) { + if (module.type && module.type.startsWith("webassembly")) { + const filenameTemplate = + outputOptions.webassemblyModuleFilename; - /** - * Get data from cache - * @param {function(SortableSet): T[]} fn function to calculate value - * @returns {T[]} returns result of fn(this), cached until set changes - */ - getFromCache(fn) { - if (this._cache === undefined) { - this._cache = new Map(); - } else { - const data = this._cache.get(fn); - if (data !== undefined) { - return data; - } - } - const newData = fn(this); - this._cache.set(fn, newData); - return newData; - } + result.push({ + render: () => + this.renderWebAssembly( + module, + moduleTemplates.webassembly, + dependencyTemplates + ), + filenameTemplate, + pathOptions: { + module + }, + identifier: `webassemblyModule${module.id}`, + hash: module.hash + }); + } + } - /** - * @param {function(SortableSet): string|number|T[]} fn function to calculate value - * @returns {any} returns result of fn(this), cached until set changes - */ - getFromUnorderedCache(fn) { - if (this._cacheOrderIndependent === undefined) { - this._cacheOrderIndependent = new Map(); - } else { - const data = this._cacheOrderIndependent.get(fn); - if (data !== undefined) { - return data; - } - } - const newData = fn(this); - this._cacheOrderIndependent.set(fn, newData); - return newData; - } + return result; + } + ); - /** - * @private - * @returns {void} - */ - _invalidateCache() { - if (this._cache !== undefined) { - this._cache.clear(); - } + compilation.hooks.afterChunks.tap("WebAssemblyModulesPlugin", () => { + const initialWasmModules = new Set(); + for (const chunk of compilation.chunks) { + if (chunk.canBeInitial()) { + for (const module of chunk.modulesIterable) { + if (module.type.startsWith("webassembly")) { + initialWasmModules.add(module); + } + } + } + } + for (const module of initialWasmModules) { + compilation.errors.push( + new WebAssemblyInInitialChunkError( + module, + compilation.requestShortener + ) + ); + } + }); + } + ); } - /** - * @private - * @returns {void} - */ - _invalidateOrderedCache() { - if (this._cacheOrderIndependent !== undefined) { - this._cacheOrderIndependent.clear(); - } + renderWebAssembly(module, moduleTemplate, dependencyTemplates) { + return moduleTemplate.render(module, dependencyTemplates, {}); } } -module.exports = SortableSet; +module.exports = WebAssemblyModulesPlugin; /***/ }), -/***/ 92251: +/***/ 77703: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -111370,148 +109827,181 @@ module.exports = SortableSet; */ -const util = __webpack_require__(31669); +const t = __webpack_require__(81875); +const { decode } = __webpack_require__(27352); +const { + moduleContextFromModuleAST +} = __webpack_require__(71234); -const TOMBSTONE = {}; -const UNDEFINED_MARKER = {}; +const { Tapable } = __webpack_require__(56758); +const WebAssemblyImportDependency = __webpack_require__(52959); +const WebAssemblyExportImportedDependency = __webpack_require__(18925); -class StackedSetMap { - constructor(parentStack) { - this.stack = parentStack === undefined ? [] : parentStack.slice(); - this.map = new Map(); - this.stack.push(this.map); - } +/** @typedef {import("../Module")} Module */ - add(item) { - this.map.set(item, true); - } +const JS_COMPAT_TYPES = new Set(["i32", "f32", "f64"]); - set(item, value) { - this.map.set(item, value === undefined ? UNDEFINED_MARKER : value); +/** + * @param {t.Signature} signature the func signature + * @returns {null | string} the type incompatible with js types + */ +const getJsIncompatibleType = signature => { + for (const param of signature.params) { + if (!JS_COMPAT_TYPES.has(param.valtype)) { + return `${param.valtype} as parameter`; + } } + for (const type of signature.results) { + if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; + } + return null; +}; - delete(item) { - if (this.stack.length > 1) { - this.map.set(item, TOMBSTONE); - } else { - this.map.delete(item); +/** + * TODO why are there two different Signature types? + * @param {t.FuncSignature} signature the func signature + * @returns {null | string} the type incompatible with js types + */ +const getJsIncompatibleTypeOfFuncSignature = signature => { + for (const param of signature.args) { + if (!JS_COMPAT_TYPES.has(param)) { + return `${param} as parameter`; } } + for (const type of signature.result) { + if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; + } + return null; +}; - has(item) { - const topValue = this.map.get(item); - if (topValue !== undefined) return topValue !== TOMBSTONE; - if (this.stack.length > 1) { - for (var i = this.stack.length - 2; i >= 0; i--) { - const value = this.stack[i].get(item); - if (value !== undefined) { - this.map.set(item, value); - return value !== TOMBSTONE; - } - } - this.map.set(item, TOMBSTONE); - } - return false; +const decoderOpts = { + ignoreCodeSection: true, + ignoreDataSection: true, + + // this will avoid having to lookup with identifiers in the ModuleContext + ignoreCustomNameSection: true +}; + +class WebAssemblyParser extends Tapable { + constructor(options) { + super(); + this.hooks = {}; + this.options = options; } - get(item) { - const topValue = this.map.get(item); - if (topValue !== undefined) { - return topValue === TOMBSTONE || topValue === UNDEFINED_MARKER - ? undefined - : topValue; - } - if (this.stack.length > 1) { - for (var i = this.stack.length - 2; i >= 0; i--) { - const value = this.stack[i].get(item); - if (value !== undefined) { - this.map.set(item, value); - return value === TOMBSTONE || value === UNDEFINED_MARKER - ? undefined - : value; + parse(binary, state) { + // flag it as ESM + state.module.buildMeta.exportsType = "namespace"; + + // parse it + const program = decode(binary, decoderOpts); + const module = program.body[0]; + + const moduleContext = moduleContextFromModuleAST(module); + + // extract imports and exports + const exports = (state.module.buildMeta.providedExports = []); + const jsIncompatibleExports = (state.module.buildMeta.jsIncompatibleExports = []); + + const importedGlobals = []; + t.traverse(module, { + ModuleExport({ node }) { + const descriptor = node.descr; + + if (descriptor.exportType === "Func") { + const funcidx = descriptor.id.value; + + /** @type {t.FuncSignature} */ + const funcSignature = moduleContext.getFunction(funcidx); + + const incompatibleType = getJsIncompatibleTypeOfFuncSignature( + funcSignature + ); + + if (incompatibleType) { + jsIncompatibleExports[node.name] = incompatibleType; + } } - } - this.map.set(item, TOMBSTONE); - } - return undefined; - } - _compress() { - if (this.stack.length === 1) return; - this.map = new Map(); - for (const data of this.stack) { - for (const pair of data) { - if (pair[1] === TOMBSTONE) { - this.map.delete(pair[0]); - } else { - this.map.set(pair[0], pair[1]); + exports.push(node.name); + + if (node.descr && node.descr.exportType === "Global") { + const refNode = importedGlobals[node.descr.id.value]; + if (refNode) { + const dep = new WebAssemblyExportImportedDependency( + node.name, + refNode.module, + refNode.name, + refNode.descr.valtype + ); + + state.module.addDependency(dep); + } } - } - } - this.stack = [this.map]; - } + }, - asArray() { - this._compress(); - return Array.from(this.map.entries(), pair => pair[0]); - } + Global({ node }) { + const init = node.init[0]; - asSet() { - return new Set(this.asArray()); - } + let importNode = null; - asPairArray() { - this._compress(); - return Array.from(this.map.entries(), pair => - /** @type {[TODO, TODO]} */ (pair[1] === UNDEFINED_MARKER - ? [pair[0], undefined] - : pair) - ); - } + if (init.id === "get_global") { + const globalIdx = init.args[0].value; - asMap() { - return new Map(this.asPairArray()); - } + if (globalIdx < importedGlobals.length) { + importNode = importedGlobals[globalIdx]; + } + } - get size() { - this._compress(); - return this.map.size; - } + importedGlobals.push(importNode); + }, - createChild() { - return new StackedSetMap(this.stack); - } + ModuleImport({ node }) { + /** @type {false | string} */ + let onlyDirectImport = false; - get length() { - throw new Error("This is no longer an Array"); - } + if (t.isMemory(node.descr) === true) { + onlyDirectImport = "Memory"; + } else if (t.isTable(node.descr) === true) { + onlyDirectImport = "Table"; + } else if (t.isFuncImportDescr(node.descr) === true) { + const incompatibleType = getJsIncompatibleType(node.descr.signature); + if (incompatibleType) { + onlyDirectImport = `Non-JS-compatible Func Sigurature (${incompatibleType})`; + } + } else if (t.isGlobalType(node.descr) === true) { + const type = node.descr.valtype; + if (!JS_COMPAT_TYPES.has(type)) { + onlyDirectImport = `Non-JS-compatible Global Type (${type})`; + } + } - set length(value) { - throw new Error("This is no longer an Array"); + const dep = new WebAssemblyImportDependency( + node.module, + node.name, + node.descr, + onlyDirectImport + ); + + state.module.addDependency(dep); + + if (t.isGlobalType(node.descr)) { + importedGlobals.push(node); + } + } + }); + + return state; } } -// TODO remove in webpack 5 -StackedSetMap.prototype.push = util.deprecate( - /** - * @deprecated - * @this {StackedSetMap} - * @param {any} item Item to add - * @returns {void} - */ - function(item) { - this.add(item); - }, - "This is no longer an Array: Use add instead." -); - -module.exports = StackedSetMap; +module.exports = WebAssemblyParser; /***/ }), -/***/ 67916: -/***/ (function(__unused_webpack_module, exports) { +/***/ 52136: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; /* @@ -111520,83 +110010,65 @@ module.exports = StackedSetMap; */ +const Template = __webpack_require__(96066); +const WebAssemblyImportDependency = __webpack_require__(52959); + +/** @typedef {import("../Module")} Module */ -const mergeCache = new WeakMap(); +/** @typedef {Object} UsedWasmDependency + * @property {WebAssemblyImportDependency} dependency the dependency + * @property {string} name the export name + * @property {string} module the module name + */ + +const MANGLED_MODULE = "a"; /** - * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again. - * @example - * // performs cleverMerge(first, second), stores the result in WeakMap and returns result - * cachedCleverMerge({a: 1}, {a: 2}) - * {a: 2} - * // when same arguments passed, gets the result from WeakMap and returns it. - * cachedCleverMerge({a: 1}, {a: 2}) - * {a: 2} - * @param {object} first first object - * @param {object} second second object - * @returns {object} merged object of first and second object + * @param {Module} module the module + * @param {boolean} mangle mangle module and export names + * @returns {UsedWasmDependency[]} used dependencies and (mangled) name */ -const cachedCleverMerge = (first, second) => { - let innerCache = mergeCache.get(first); - if (innerCache === undefined) { - innerCache = new WeakMap(); - mergeCache.set(first, innerCache); - } - const prevMerge = innerCache.get(second); - if (prevMerge !== undefined) return prevMerge; - const newMerge = cleverMerge(first, second); - innerCache.set(second, newMerge); - return newMerge; -}; +const getUsedDependencies = (module, mangle) => { + /** @type {UsedWasmDependency[]} */ + const array = []; + let importIndex = 0; + for (const dep of module.dependencies) { + if (dep instanceof WebAssemblyImportDependency) { + if (dep.description.type === "GlobalType" || dep.module === null) { + continue; + } -/** - * Merges two objects. Objects are not deeply merged. - * TODO webpack 5: merge objects deeply clever. - * Arrays might reference the old value with "..." - * @param {object} first first object - * @param {object} second second object - * @returns {object} merged object of first and second object - */ -const cleverMerge = (first, second) => { - const newObject = Object.assign({}, first); - for (const key of Object.keys(second)) { - if (!(key in newObject)) { - newObject[key] = second[key]; - continue; - } - const secondValue = second[key]; - if (!Array.isArray(secondValue)) { - newObject[key] = secondValue; - continue; - } - const firstValue = newObject[key]; - if (Array.isArray(firstValue)) { - const newArray = []; - for (const item of secondValue) { - if (item === "...") { - for (const item of firstValue) { - newArray.push(item); - } - } else { - newArray.push(item); - } + const exportName = dep.name; + // TODO add the following 3 lines when removing of ModuleExport is possible + // const importedModule = dep.module; + // const usedName = importedModule && importedModule.isUsed(exportName); + // if (usedName !== false) { + if (mangle) { + array.push({ + dependency: dep, + name: Template.numberToIdentifer(importIndex++), + module: MANGLED_MODULE + }); + } else { + array.push({ + dependency: dep, + name: exportName, + module: dep.request + }); } - newObject[key] = newArray; - } else { - newObject[key] = secondValue; } } - return newObject; + return array; }; -exports.cachedCleverMerge = cachedCleverMerge; -exports.cleverMerge = cleverMerge; +exports.getUsedDependencies = getUsedDependencies; +exports.MANGLED_MODULE = MANGLED_MODULE; /***/ }), -/***/ 15660: -/***/ (function(module, exports, __webpack_require__) { +/***/ 52669: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /* @@ -111605,759 +110077,304 @@ exports.cleverMerge = cleverMerge; */ -const AbstractMethodError = __webpack_require__(36104); - -const BULK_SIZE = 1000; +const WasmMainTemplatePlugin = __webpack_require__(65331); -class Hash { - /** - * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} - * @param {string|Buffer} data data - * @param {string=} inputEncoding data encoding - * @returns {this} updated hash - */ - update(data, inputEncoding) { - throw new AbstractMethodError(); +class FetchCompileWasmTemplatePlugin { + constructor(options) { + this.options = options || {}; } - /** - * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} - * @param {string=} encoding encoding of the return value - * @returns {string|Buffer} digest - */ - digest(encoding) { - throw new AbstractMethodError(); + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "FetchCompileWasmTemplatePlugin", + compilation => { + const mainTemplate = compilation.mainTemplate; + const generateLoadBinaryCode = path => + `fetch(${mainTemplate.requireFn}.p + ${path})`; + + const plugin = new WasmMainTemplatePlugin( + Object.assign( + { + generateLoadBinaryCode, + supportsStreaming: true + }, + this.options + ) + ); + plugin.apply(mainTemplate); + } + ); } } -exports.Hash = Hash; -/** @typedef {typeof Hash} HashConstructor */ +module.exports = FetchCompileWasmTemplatePlugin; -class BulkUpdateDecorator extends Hash { - /** - * @param {Hash} hash hash - */ - constructor(hash) { - super(); - this.hash = hash; - this.buffer = ""; - } - /** - * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} - * @param {string|Buffer} data data - * @param {string=} inputEncoding data encoding - * @returns {this} updated hash - */ - update(data, inputEncoding) { - if ( - inputEncoding !== undefined || - typeof data !== "string" || - data.length > BULK_SIZE - ) { - if (this.buffer.length > 0) { - this.hash.update(this.buffer); - this.buffer = ""; - } - this.hash.update(data, inputEncoding); - } else { - this.buffer += data; - if (this.buffer.length > BULK_SIZE) { - this.hash.update(this.buffer); - this.buffer = ""; - } - } - return this; - } +/***/ }), - /** - * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} - * @param {string=} encoding encoding of the return value - * @returns {string|Buffer} digest - */ - digest(encoding) { - if (this.buffer.length > 0) { - this.hash.update(this.buffer); - } - var digestResult = this.hash.digest(encoding); - return typeof digestResult === "string" - ? digestResult - : digestResult.toString(); - } -} +/***/ 31898: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * istanbul ignore next - */ -class DebugHash extends Hash { - constructor() { - super(); - this.string = ""; - } +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - /** - * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding} - * @param {string|Buffer} data data - * @param {string=} inputEncoding data encoding - * @returns {this} updated hash - */ - update(data, inputEncoding) { - if (typeof data !== "string") data = data.toString("utf-8"); - this.string += data; - return this; - } +const { ConcatSource } = __webpack_require__(53665); + +/** @typedef {import("../ChunkTemplate")} ChunkTemplate */ + +const getEntryInfo = chunk => { + return [chunk.entryModule].filter(Boolean).map(m => + [m.id].concat( + Array.from(chunk.groupsIterable)[0] + .chunks.filter(c => c !== chunk) + .map(c => c.id) + ) + ); +}; + +class JsonpChunkTemplatePlugin { /** - * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding} - * @param {string=} encoding encoding of the return value - * @returns {string|Buffer} digest + * @param {ChunkTemplate} chunkTemplate the chunk template + * @returns {void} */ - digest(encoding) { - return this.string.replace(/[^a-z0-9]+/gi, m => - Buffer.from(m).toString("hex") + apply(chunkTemplate) { + chunkTemplate.hooks.render.tap( + "JsonpChunkTemplatePlugin", + (modules, chunk) => { + const jsonpFunction = chunkTemplate.outputOptions.jsonpFunction; + const globalObject = chunkTemplate.outputOptions.globalObject; + const source = new ConcatSource(); + const prefetchChunks = chunk.getChildIdsByOrders().prefetch; + source.add( + `(${globalObject}[${JSON.stringify( + jsonpFunction + )}] = ${globalObject}[${JSON.stringify( + jsonpFunction + )}] || []).push([${JSON.stringify(chunk.ids)},` + ); + source.add(modules); + const entries = getEntryInfo(chunk); + if (entries.length > 0) { + source.add(`,${JSON.stringify(entries)}`); + } else if (prefetchChunks && prefetchChunks.length) { + source.add(`,0`); + } + + if (prefetchChunks && prefetchChunks.length) { + source.add(`,${JSON.stringify(prefetchChunks)}`); + } + source.add("])"); + return source; + } + ); + chunkTemplate.hooks.hash.tap("JsonpChunkTemplatePlugin", hash => { + hash.update("JsonpChunkTemplatePlugin"); + hash.update("4"); + hash.update(`${chunkTemplate.outputOptions.jsonpFunction}`); + hash.update(`${chunkTemplate.outputOptions.globalObject}`); + }); + chunkTemplate.hooks.hashForChunk.tap( + "JsonpChunkTemplatePlugin", + (hash, chunk) => { + hash.update(JSON.stringify(getEntryInfo(chunk))); + hash.update(JSON.stringify(chunk.getChildIdsByOrders().prefetch) || ""); + } ); } } - -/** - * Creates a hash by name or function - * @param {string | HashConstructor} algorithm the algorithm name or a constructor creating a hash - * @returns {Hash} the hash - */ -module.exports = algorithm => { - if (typeof algorithm === "function") { - return new BulkUpdateDecorator(new algorithm()); - } - switch (algorithm) { - // TODO add non-cryptographic algorithm here - case "debug": - return new DebugHash(); - default: - return new BulkUpdateDecorator(__webpack_require__(76417).createHash(algorithm)); - } -}; +module.exports = JsonpChunkTemplatePlugin; /***/ }), -/***/ 30815: -/***/ (function(module) { +/***/ 13732: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -// Simulations show these probabilities for a single change -// 93.1% that one group is invalidated -// 4.8% that two groups are invalidated -// 1.1% that 3 groups are invalidated -// 0.1% that 4 or more groups are invalidated -// -// And these for removing/adding 10 lexically adjacent files -// 64.5% that one group is invalidated -// 24.8% that two groups are invalidated -// 7.8% that 3 groups are invalidated -// 2.7% that 4 or more groups are invalidated -// -// And these for removing/adding 3 random files -// 0% that one group is invalidated -// 3.7% that two groups are invalidated -// 80.8% that 3 groups are invalidated -// 12.3% that 4 groups are invalidated -// 3.2% that 5 or more groups are invalidated +const { ConcatSource } = __webpack_require__(53665); -/** - * - * @param {string} a key - * @param {string} b key - * @returns {number} the similarity as number - */ -const similarity = (a, b) => { - const l = Math.min(a.length, b.length); - let dist = 0; - for (let i = 0; i < l; i++) { - const ca = a.charCodeAt(i); - const cb = b.charCodeAt(i); - dist += Math.max(0, 10 - Math.abs(ca - cb)); +class JsonpExportMainTemplatePlugin { + /** + * @param {string} name jsonp function name + */ + constructor(name) { + this.name = name; } - return dist; -}; -/** - * @param {string} a key - * @param {string} b key - * @returns {string} the common part and a single char for the difference - */ -const getName = (a, b) => { - const l = Math.min(a.length, b.length); - let r = ""; - for (let i = 0; i < l; i++) { - const ca = a.charAt(i); - const cb = b.charAt(i); - r += ca; - if (ca === cb) { - continue; + apply(compilation) { + const { mainTemplate, chunkTemplate } = compilation; + + const onRenderWithEntry = (source, chunk, hash) => { + const name = mainTemplate.getAssetPath(this.name || "", { + hash, + chunk + }); + return new ConcatSource(`${name}(`, source, ");"); + }; + + for (const template of [mainTemplate, chunkTemplate]) { + template.hooks.renderWithEntry.tap( + "JsonpExportMainTemplatePlugin", + onRenderWithEntry + ); } - return r; - } - return a; -}; -/** - * @template T - */ -class Node { - /** - * @param {T} item item - * @param {string} key key - * @param {number} size size - */ - constructor(item, key, size) { - this.item = item; - this.key = key; - this.size = size; - } -} + mainTemplate.hooks.globalHashPaths.tap( + "JsonpExportMainTemplatePlugin", + paths => { + if (this.name) paths.push(this.name); + return paths; + } + ); -/** - * @template T - */ -class Group { - /** - * @param {Node[]} nodes nodes - * @param {number[]} similarities similarities between the nodes (length = nodes.length - 1) - */ - constructor(nodes, similarities) { - this.nodes = nodes; - this.similarities = similarities; - this.size = nodes.reduce((size, node) => size + node.size, 0); - /** @type {string} */ - this.key = undefined; + mainTemplate.hooks.hash.tap("JsonpExportMainTemplatePlugin", hash => { + hash.update("jsonp export"); + hash.update(`${this.name}`); + }); } } -/** - * @template T - * @typedef {Object} GroupedItems - * @property {string} key - * @property {T[]} items - * @property {number} size - */ +module.exports = JsonpExportMainTemplatePlugin; -/** - * @template T - * @typedef {Object} Options - * @property {number} maxSize maximum size of a group - * @property {number} minSize minimum size of a group (preferred over maximum size) - * @property {Iterable} items a list of items - * @property {function(T): number} getSize function to get size of an item - * @property {function(T): string} getKey function to get the key of an item - */ -/** - * @template T - * @param {Options} options options object - * @returns {GroupedItems[]} grouped items - */ -module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { - /** @type {Group[]} */ - const result = []; +/***/ }), - const nodes = Array.from( - items, - item => new Node(item, getKey(item), getSize(item)) - ); +/***/ 44458: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - /** @type {Node[]} */ - const initialNodes = []; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // lexically ordering of keys - nodes.sort((a, b) => { - if (a.key < b.key) return -1; - if (a.key > b.key) return 1; - return 0; - }); - // return nodes bigger than maxSize directly as group - for (const node of nodes) { - if (node.size >= maxSize) { - result.push(new Group([node], [])); - } else { - initialNodes.push(node); - } +const { ConcatSource } = __webpack_require__(53665); + +class JsonpHotUpdateChunkTemplatePlugin { + apply(hotUpdateChunkTemplate) { + hotUpdateChunkTemplate.hooks.render.tap( + "JsonpHotUpdateChunkTemplatePlugin", + (modulesSource, modules, removedModules, hash, id) => { + const source = new ConcatSource(); + source.add( + `${ + hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + }(${JSON.stringify(id)},` + ); + source.add(modulesSource); + source.add(")"); + return source; + } + ); + hotUpdateChunkTemplate.hooks.hash.tap( + "JsonpHotUpdateChunkTemplatePlugin", + hash => { + hash.update("JsonpHotUpdateChunkTemplatePlugin"); + hash.update("3"); + hash.update( + `${hotUpdateChunkTemplate.outputOptions.hotUpdateFunction}` + ); + hash.update(`${hotUpdateChunkTemplate.outputOptions.library}`); + } + ); } +} - if (initialNodes.length > 0) { - // calculate similarities between lexically adjacent nodes - /** @type {number[]} */ - const similarities = []; - for (let i = 1; i < initialNodes.length; i++) { - const a = initialNodes[i - 1]; - const b = initialNodes[i]; - similarities.push(similarity(a.key, b.key)); - } - - const initialGroup = new Group(initialNodes, similarities); - - if (initialGroup.size < minSize) { - // We hit an edgecase where the working set is already smaller than minSize - // We merge it with the smallest result node to keep minSize intact - if (result.length > 0) { - const smallestGroup = result.reduce((min, group) => - min.size > group.size ? group : min - ); - for (const node of initialGroup.nodes) smallestGroup.nodes.push(node); - smallestGroup.nodes.sort((a, b) => { - if (a.key < b.key) return -1; - if (a.key > b.key) return 1; - return 0; - }); - } else { - // There are no other nodes - // We use all nodes and have to accept that it's smaller than minSize - result.push(initialGroup); - } - } else { - const queue = [initialGroup]; - - while (queue.length) { - const group = queue.pop(); - // only groups bigger than maxSize need to be splitted - if (group.size < maxSize) { - result.push(group); - continue; - } - - // find unsplittable area from left and right - // going minSize from left and right - // at least one node need to be included otherwise we get stuck - let left = 0; - let leftSize = 0; - while (leftSize <= minSize) { - leftSize += group.nodes[left].size; - left++; - } - let right = group.nodes.length - 1; - let rightSize = 0; - while (rightSize <= minSize) { - rightSize += group.nodes[right].size; - right--; - } - - if (left - 1 > right) { - // can't split group while holding minSize - // because minSize is preferred of maxSize we return - // the group here even while it's too big - // To avoid this make sure maxSize > minSize * 3 - result.push(group); - continue; - } - if (left <= right) { - // when there is a area between left and right - // we look for best split point - // we split at the minimum similarity - // here key space is separated the most - let best = left - 1; - let bestSimilarity = group.similarities[best]; - for (let i = left; i <= right; i++) { - const similarity = group.similarities[i]; - if (similarity < bestSimilarity) { - best = i; - bestSimilarity = similarity; - } - } - left = best + 1; - right = best; - } - - // create two new groups for left and right area - // and queue them up - const rightNodes = [group.nodes[right + 1]]; - /** @type {number[]} */ - const rightSimilaries = []; - for (let i = right + 2; i < group.nodes.length; i++) { - rightSimilaries.push(group.similarities[i - 1]); - rightNodes.push(group.nodes[i]); - } - queue.push(new Group(rightNodes, rightSimilaries)); - - const leftNodes = [group.nodes[0]]; - /** @type {number[]} */ - const leftSimilaries = []; - for (let i = 1; i < left; i++) { - leftSimilaries.push(group.similarities[i - 1]); - leftNodes.push(group.nodes[i]); - } - queue.push(new Group(leftNodes, leftSimilaries)); - } - } - } - - // lexically ordering - result.sort((a, b) => { - if (a.nodes[0].key < b.nodes[0].key) return -1; - if (a.nodes[0].key > b.nodes[0].key) return 1; - return 0; - }); - - // give every group a name - for (let i = 0; i < result.length; i++) { - const group = result[i]; - const first = group.nodes[0]; - const last = group.nodes[group.nodes.length - 1]; - let name = getName(first.key, last.key); - group.key = name; - } - - // return the results - return result.map(group => { - /** @type {GroupedItems} */ - return { - key: group.key, - items: group.nodes.map(node => node.item), - size: group.size - }; - }); -}; - - -/***/ }), - -/***/ 94658: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -const path = __webpack_require__(85622); - -/** - * @param {string} context context for relative path - * @param {string} relativePath path - * @returns {string} absolute path - */ -const requestToAbsolute = (context, relativePath) => { - if (relativePath.startsWith("./") || relativePath.startsWith("../")) - return path.join(context, relativePath); - return relativePath; -}; - -/** - * @typedef {Object} MakeRelativePathsCache - * @property {Map>=} relativePaths - */ - -/** - * - * @param {string} maybeAbsolutePath path to check - * @returns {boolean} returns true if path is "Absolute Path"-like - */ -const looksLikeAbsolutePath = maybeAbsolutePath => { - if (/^\/.*\/$/.test(maybeAbsolutePath)) { - // this 'path' is actually a regexp generated by dynamic requires. - // Don't treat it as an absolute path. - return false; - } - return /^(?:[a-z]:\\|\/)/i.test(maybeAbsolutePath); -}; - -/** - * - * @param {string} p path to normalize - * @returns {string} normalized version of path - */ -const normalizePathSeparator = p => p.replace(/\\/g, "/"); - -/** - * - * @param {string} context context for relative path - * @param {string} identifier identifier for path - * @returns {string} a converted relative path - */ -const _makePathsRelative = (context, identifier) => { - return identifier - .split(/([|! ])/) - .map(str => - looksLikeAbsolutePath(str) - ? normalizePathSeparator(path.relative(context, str)) - : str - ) - .join(""); -}; - -/** - * - * @param {string} context context used to create relative path - * @param {string} identifier identifier used to create relative path - * @param {MakeRelativePathsCache=} cache the cache object being set - * @returns {string} the returned relative path - */ -exports.makePathsRelative = (context, identifier, cache) => { - if (!cache) return _makePathsRelative(context, identifier); - - const relativePaths = - cache.relativePaths || (cache.relativePaths = new Map()); - - let cachedResult; - let contextCache = relativePaths.get(context); - if (contextCache === undefined) { - relativePaths.set(context, (contextCache = new Map())); - } else { - cachedResult = contextCache.get(identifier); - } - - if (cachedResult !== undefined) { - return cachedResult; - } else { - const relativePath = _makePathsRelative(context, identifier); - contextCache.set(identifier, relativePath); - return relativePath; - } -}; - -/** - * @param {string} context absolute context path - * @param {string} request any request string may containing absolute paths, query string, etc. - * @returns {string} a new request string avoiding absolute paths when possible - */ -exports.contextify = (context, request) => { - return request - .split("!") - .map(r => { - const splitPath = r.split("?", 2); - if (/^[a-zA-Z]:\\/.test(splitPath[0])) { - splitPath[0] = path.win32.relative(context, splitPath[0]); - if (!/^[a-zA-Z]:\\/.test(splitPath[0])) { - splitPath[0] = splitPath[0].replace(/\\/g, "/"); - } - } - if (/^\//.test(splitPath[0])) { - splitPath[0] = path.posix.relative(context, splitPath[0]); - } - if (!/^(\.\.\/|\/|[a-zA-Z]:\\)/.test(splitPath[0])) { - splitPath[0] = "./" + splitPath[0]; - } - return splitPath.join("?"); - }) - .join("!"); -}; - -/** - * @param {string} context absolute context path - * @param {string} request any request string - * @returns {string} a new request string using absolute paths when possible - */ -const _absolutify = (context, request) => { - return request - .split("!") - .map(r => requestToAbsolute(context, r)) - .join("!"); -}; - -exports.absolutify = _absolutify; +module.exports = JsonpHotUpdateChunkTemplatePlugin; /***/ }), -/***/ 1111: +/***/ 24916: /***/ (function(module) { -/** - * convert an object into its 2D array equivalent to be turned - * into an ES6 map - * - * @param {object} obj any object type that works with Object.keys() - * @returns {Map} an ES6 Map of KV pairs - */ -module.exports = function objectToMap(obj) { - return new Map( - Object.keys(obj).map(key => { - /** @type {[string, string]} */ - const pair = [key, obj[key]]; - return pair; - }) - ); -}; - - -/***/ }), - -/***/ 68935: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php - Author Gajus Kuizinas @gajus + Author Tobias Koppers @sokra */ +// eslint-disable-next-line no-unused-vars +var hotAddUpdateChunk = undefined; +var parentHotUpdateCallback = undefined; +var $require$ = undefined; +var $hotMainFilename$ = undefined; +var $hotChunkFilename$ = undefined; +var $crossOriginLoading$ = undefined; +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function webpackHotUpdateCallback(chunkId, moreModules) { + hotAddUpdateChunk(chunkId, moreModules); + if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); + } //$semicolon -const Ajv = __webpack_require__(21414); -const ajv = new Ajv({ - errorDataPath: "configuration", - allErrors: true, - verbose: true -}); -__webpack_require__(82133)(ajv, ["instanceof"]); -__webpack_require__(51613)(ajv); - -const validateSchema = (schema, options) => { - if (Array.isArray(options)) { - const errors = options.map(options => validateObject(schema, options)); - errors.forEach((list, idx) => { - const applyPrefix = err => { - err.dataPath = `[${idx}]${err.dataPath}`; - if (err.children) { - err.children.forEach(applyPrefix); - } - }; - list.forEach(applyPrefix); - }); - return errors.reduce((arr, items) => { - return arr.concat(items); - }, []); - } else { - return validateObject(schema, options); + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + var script = document.createElement("script"); + script.charset = "utf-8"; + script.src = $require$.p + $hotChunkFilename$; + if ($crossOriginLoading$) script.crossOrigin = $crossOriginLoading$; + document.head.appendChild(script); } -}; -const validateObject = (schema, options) => { - const validate = ajv.compile(schema); - const valid = validate(options); - return valid ? [] : filterErrors(validate.errors); -}; - -const filterErrors = errors => { - let newErrors = []; - for (const err of errors) { - const dataPath = err.dataPath; - let children = []; - newErrors = newErrors.filter(oldError => { - if (oldError.dataPath.includes(dataPath)) { - if (oldError.children) { - children = children.concat(oldError.children.slice(0)); - } - oldError.children = undefined; - children.push(oldError); - return false; + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest(requestTimeout) { + requestTimeout = requestTimeout || 10000; + return new Promise(function(resolve, reject) { + if (typeof XMLHttpRequest === "undefined") { + return reject(new Error("No browser support")); } - return true; - }); - if (children.length) { - err.children = children; - } - newErrors.push(err); - } - - return newErrors; -}; - -module.exports = validateSchema; - - -/***/ }), - -/***/ 43101: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ - - -const WebpackError = __webpack_require__(97391); - -module.exports = class UnsupportedWebAssemblyFeatureError extends WebpackError { - /** @param {string} message Error message */ - constructor(message) { - super(message); - this.name = "UnsupportedWebAssemblyFeatureError"; - this.hideStack = true; - - Error.captureStackTrace(this, this.constructor); - } -}; - - -/***/ }), - -/***/ 10557: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra - */ - - -const UnsupportedWebAssemblyFeatureError = __webpack_require__(43101); - -class WasmFinalizeExportsPlugin { - apply(compiler) { - compiler.hooks.compilation.tap("WasmFinalizeExportsPlugin", compilation => { - compilation.hooks.finishModules.tap( - "WasmFinalizeExportsPlugin", - modules => { - for (const module of modules) { - // 1. if a WebAssembly module - if (module.type.startsWith("webassembly") === true) { - const jsIncompatibleExports = - module.buildMeta.jsIncompatibleExports; - - if (jsIncompatibleExports === undefined) { - continue; - } - - for (const reason of module.reasons) { - // 2. is referenced by a non-WebAssembly module - if (reason.module.type.startsWith("webassembly") === false) { - const ref = compilation.getDependencyReference( - reason.module, - reason.dependency - ); - - if (!ref) continue; - - const importedNames = ref.importedNames; - - if (Array.isArray(importedNames)) { - importedNames.forEach(name => { - // 3. and uses a func with an incompatible JS signature - if ( - Object.prototype.hasOwnProperty.call( - jsIncompatibleExports, - name - ) - ) { - // 4. error - /** @type {any} */ - const error = new UnsupportedWebAssemblyFeatureError( - `Export "${name}" with ${jsIncompatibleExports[name]} can only be used for direct wasm to wasm dependencies` - ); - error.module = module; - error.origin = reason.module; - error.originLoc = reason.dependency.loc; - error.dependencies = [reason.dependency]; - compilation.errors.push(error); - } - }); - } - } - } - } + try { + var request = new XMLHttpRequest(); + var requestPath = $require$.p + $hotMainFilename$; + request.open("GET", requestPath, true); + request.timeout = requestTimeout; + request.send(null); + } catch (err) { + return reject(err); + } + request.onreadystatechange = function() { + if (request.readyState !== 4) return; + if (request.status === 0) { + // timeout + reject( + new Error("Manifest request to " + requestPath + " timed out.") + ); + } else if (request.status === 404) { + // no update available + resolve(); + } else if (request.status !== 200 && request.status !== 304) { + // other failure + reject(new Error("Manifest request to " + requestPath + " failed.")); + } else { + // success + try { + var update = JSON.parse(request.responseText); + } catch (e) { + reject(e); + return; } + resolve(update); } - ); + }; }); } -} - -module.exports = WasmFinalizeExportsPlugin; +}; /***/ }), -/***/ 65331: +/***/ 38017: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; @@ -112367,3034 +110384,4389 @@ module.exports = WasmFinalizeExportsPlugin; */ +const { SyncWaterfallHook } = __webpack_require__(56758); const Template = __webpack_require__(96066); -const WebAssemblyUtils = __webpack_require__(52136); - -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../MainTemplate")} MainTemplate */ -// Get all wasm modules -const getAllWasmModules = chunk => { - const wasmModules = chunk.getAllAsyncChunks(); - const array = []; - for (const chunk of wasmModules) { - for (const m of chunk.modulesIterable) { - if (m.type.startsWith("webassembly")) { - array.push(m); +class JsonpMainTemplatePlugin { + apply(mainTemplate) { + const needChunkOnDemandLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.getNumberOfChildren() > 0) return true; } - } - } - - return array; -}; - -/** - * generates the import object function for a module - * @param {Module} module the module - * @param {boolean} mangle mangle imports - * @returns {string} source code - */ -const generateImportObject = (module, mangle) => { - const waitForInstances = new Map(); - const properties = []; - const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies( - module, - mangle - ); - for (const usedDep of usedWasmDependencies) { - const dep = usedDep.dependency; - const importedModule = dep.module; - const exportName = dep.name; - const usedName = importedModule && importedModule.isUsed(exportName); - const description = dep.description; - const direct = dep.onlyDirectImport; - - const module = usedDep.module; - const name = usedDep.name; - - if (direct) { - const instanceVar = `m${waitForInstances.size}`; - waitForInstances.set(instanceVar, importedModule.id); - properties.push({ - module, - name, - value: `${instanceVar}[${JSON.stringify(usedName)}]` - }); - } else { - const params = description.signature.params.map( - (param, k) => "p" + k + param.valtype - ); - - const mod = `installedModules[${JSON.stringify(importedModule.id)}]`; - const func = `${mod}.exports[${JSON.stringify(usedName)}]`; - - properties.push({ - module, - name, - value: Template.asString([ - (importedModule.type.startsWith("webassembly") - ? `${mod} ? ${func} : ` - : "") + `function(${params}) {`, - Template.indent([`return ${func}(${params});`]), - "}" - ]) - }); - } - } - - let importObject; - if (mangle) { - importObject = [ - "return {", - Template.indent([ - properties.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") - ]), - "};" - ]; - } else { - const propertiesByModule = new Map(); - for (const p of properties) { - let list = propertiesByModule.get(p.module); - if (list === undefined) { - propertiesByModule.set(p.module, (list = [])); + return false; + }; + const needChunkLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.chunks.length > 1) return true; + if (chunkGroup.getNumberOfChildren() > 0) return true; } - list.push(p); - } - importObject = [ - "return {", - Template.indent([ - Array.from(propertiesByModule, ([module, list]) => { - return Template.asString([ - `${JSON.stringify(module)}: {`, - Template.indent([ - list.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n") - ]), - "}" - ]); - }).join(",\n") - ]), - "};" - ]; - } - - if (waitForInstances.size === 1) { - const moduleId = Array.from(waitForInstances.values())[0]; - const promise = `installedWasmModules[${JSON.stringify(moduleId)}]`; - const variable = Array.from(waitForInstances.keys())[0]; - return Template.asString([ - `${JSON.stringify(module.id)}: function() {`, - Template.indent([ - `return promiseResolve().then(function() { return ${promise}; }).then(function(${variable}) {`, - Template.indent(importObject), - "});" - ]), - "}," - ]); - } else if (waitForInstances.size > 0) { - const promises = Array.from( - waitForInstances.values(), - id => `installedWasmModules[${JSON.stringify(id)}]` - ).join(", "); - const variables = Array.from( - waitForInstances.keys(), - (name, i) => `${name} = array[${i}]` - ).join(", "); - return Template.asString([ - `${JSON.stringify(module.id)}: function() {`, - Template.indent([ - `return promiseResolve().then(function() { return Promise.all([${promises}]); }).then(function(array) {`, - Template.indent([`var ${variables};`, ...importObject]), - "});" - ]), - "}," - ]); - } else { - return Template.asString([ - `${JSON.stringify(module.id)}: function() {`, - Template.indent(importObject), - "}," - ]); - } -}; - -class WasmMainTemplatePlugin { - constructor({ generateLoadBinaryCode, supportsStreaming, mangleImports }) { - this.generateLoadBinaryCode = generateLoadBinaryCode; - this.supportsStreaming = supportsStreaming; - this.mangleImports = mangleImports; - } + return false; + }; + const needEntryDeferringCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.chunks.length > 1) return true; + } + return false; + }; + const needPrefetchingCode = chunk => { + const allPrefetchChunks = chunk.getChildIdsByOrdersMap(true).prefetch; + return allPrefetchChunks && Object.keys(allPrefetchChunks).length; + }; - /** - * @param {MainTemplate} mainTemplate main template - * @returns {void} - */ - apply(mainTemplate) { - mainTemplate.hooks.localVars.tap( - "WasmMainTemplatePlugin", - (source, chunk) => { - const wasmModules = getAllWasmModules(chunk); - if (wasmModules.length === 0) return source; - const importObjects = wasmModules.map(module => { - return generateImportObject(module, this.mangleImports); - }); - return Template.asString([ - source, - "", - "// object to store loaded and loading wasm modules", - "var installedWasmModules = {};", - "", - // This function is used to delay reading the installed wasm module promises - // by a microtask. Sorting them doesn't help because there are egdecases where - // sorting is not possible (modules splitted into different chunks). - // So we not even trying and solve this by a microtask delay. - "function promiseResolve() { return Promise.resolve(); }", - "", - "var wasmImportObjects = {", - Template.indent(importObjects), - "};" + // TODO webpack 5, no adding to .hooks, use WeakMap and static methods + ["jsonpScript", "linkPreload", "linkPrefetch"].forEach(hook => { + if (!mainTemplate.hooks[hook]) { + mainTemplate.hooks[hook] = new SyncWaterfallHook([ + "source", + "chunk", + "hash" ]); } - ); - mainTemplate.hooks.requireEnsure.tap( - "WasmMainTemplatePlugin", - (source, chunk, hash) => { - const webassemblyModuleFilename = - mainTemplate.outputOptions.webassemblyModuleFilename; + }); - const chunkModuleMaps = chunk.getChunkModuleMaps(m => - m.type.startsWith("webassembly") - ); - if (Object.keys(chunkModuleMaps.id).length === 0) return source; - const wasmModuleSrcPath = mainTemplate.getAssetPath( - JSON.stringify(webassemblyModuleFilename), - { - hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, - hashWithLength: length => - `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, - module: { - id: '" + wasmModuleId + "', - hash: `" + ${JSON.stringify( - chunkModuleMaps.hash - )}[wasmModuleId] + "`, - hashWithLength(length) { - const shortChunkHashMap = Object.create(null); - for (const wasmModuleId of Object.keys(chunkModuleMaps.hash)) { - if (typeof chunkModuleMaps.hash[wasmModuleId] === "string") { - shortChunkHashMap[wasmModuleId] = chunkModuleMaps.hash[ - wasmModuleId - ].substr(0, length); - } + const getScriptSrcPath = (hash, chunk, chunkIdExpression) => { + const chunkFilename = mainTemplate.outputOptions.chunkFilename; + const chunkMaps = chunk.getChunkMaps(); + return mainTemplate.getAssetPath(JSON.stringify(chunkFilename), { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: `" + ${chunkIdExpression} + "`, + hash: `" + ${JSON.stringify( + chunkMaps.hash + )}[${chunkIdExpression}] + "`, + hashWithLength(length) { + const shortChunkHashMap = Object.create(null); + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( + 0, + length + ); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[${chunkIdExpression}] + "`; + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[${chunkIdExpression}]||${chunkIdExpression}) + "`, + contentHash: { + javascript: `" + ${JSON.stringify( + chunkMaps.contentHash.javascript + )}[${chunkIdExpression}] + "` + }, + contentHashWithLength: { + javascript: length => { + const shortContentHashMap = {}; + const contentHash = chunkMaps.contentHash.javascript; + for (const chunkId of Object.keys(contentHash)) { + if (typeof contentHash[chunkId] === "string") { + shortContentHashMap[chunkId] = contentHash[chunkId].substr( + 0, + length + ); } - return `" + ${JSON.stringify( - shortChunkHashMap - )}[wasmModuleId] + "`; } + return `" + ${JSON.stringify( + shortContentHashMap + )}[${chunkIdExpression}] + "`; } } - ); - const createImportObject = content => - this.mangleImports - ? `{ ${JSON.stringify( - WebAssemblyUtils.MANGLED_MODULE - )}: ${content} }` - : content; + }, + contentHashType: "javascript" + }); + }; + mainTemplate.hooks.localVars.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + const extraCode = []; + if (needChunkLoadingCode(chunk)) { + extraCode.push( + "", + "// object to store loaded and loading chunks", + "// undefined = chunk not loaded, null = chunk preloaded/prefetched", + "// Promise = chunk loading, 0 = chunk loaded", + "var installedChunks = {", + Template.indent( + chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") + ), + "};", + "", + needEntryDeferringCode(chunk) + ? needPrefetchingCode(chunk) + ? "var deferredModules = [], deferredPrefetch = [];" + : "var deferredModules = [];" + : "" + ); + } + if (needChunkOnDemandLoadingCode(chunk)) { + extraCode.push( + "", + "// script path function", + "function jsonpScriptSrc(chunkId) {", + Template.indent([ + `return ${mainTemplate.requireFn}.p + ${getScriptSrcPath( + hash, + chunk, + "chunkId" + )}` + ]), + "}" + ); + } + if (extraCode.length === 0) return source; + return Template.asString([source, ...extraCode]); + } + ); + + mainTemplate.hooks.jsonpScript.tap( + "JsonpMainTemplatePlugin", + (_, chunk, hash) => { + const crossOriginLoading = + mainTemplate.outputOptions.crossOriginLoading; + const chunkLoadTimeout = mainTemplate.outputOptions.chunkLoadTimeout; + const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; + return Template.asString([ - source, - "", - "// Fetch + compile chunk loading for webassembly", - "", - `var wasmModules = ${JSON.stringify( - chunkModuleMaps.id - )}[chunkId] || [];`, - "", - "wasmModules.forEach(function(wasmModuleId) {", + "var script = document.createElement('script');", + "var onScriptComplete;", + jsonpScriptType + ? `script.type = ${JSON.stringify(jsonpScriptType)};` + : "", + "script.charset = 'utf-8';", + `script.timeout = ${chunkLoadTimeout / 1000};`, + `if (${mainTemplate.requireFn}.nc) {`, + Template.indent( + `script.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` + ), + "}", + "script.src = jsonpScriptSrc(chunkId);", + crossOriginLoading + ? Template.asString([ + "if (script.src.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + ), + "}" + ]) + : "", + "// create error before stack unwound to get useful stacktrace later", + "var error = new Error();", + "onScriptComplete = function (event) {", Template.indent([ - "var installedWasmModuleData = installedWasmModules[wasmModuleId];", - "", - '// a Promise means "currently loading" or "already loaded".', - "if(installedWasmModuleData)", - Template.indent(["promises.push(installedWasmModuleData);"]), - "else {", + "// avoid mem leaks in IE.", + "script.onerror = script.onload = null;", + "clearTimeout(timeout);", + "var chunk = installedChunks[chunkId];", + "if(chunk !== 0) {", Template.indent([ - `var importObject = wasmImportObjects[wasmModuleId]();`, - `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, - "var promise;", - this.supportsStreaming - ? Template.asString([ - "if(importObject instanceof Promise && typeof WebAssembly.compileStreaming === 'function') {", - Template.indent([ - "promise = Promise.all([WebAssembly.compileStreaming(req), importObject]).then(function(items) {", - Template.indent([ - `return WebAssembly.instantiate(items[0], ${createImportObject( - "items[1]" - )});` - ]), - "});" - ]), - "} else if(typeof WebAssembly.instantiateStreaming === 'function') {", - Template.indent([ - `promise = WebAssembly.instantiateStreaming(req, ${createImportObject( - "importObject" - )});` - ]) - ]) - : Template.asString([ - "if(importObject instanceof Promise) {", - Template.indent([ - "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", - "promise = Promise.all([", - Template.indent([ - "bytesPromise.then(function(bytes) { return WebAssembly.compile(bytes); }),", - "importObject" - ]), - "]).then(function(items) {", - Template.indent([ - `return WebAssembly.instantiate(items[0], ${createImportObject( - "items[1]" - )});` - ]), - "});" - ]) - ]), - "} else {", + "if(chunk) {", Template.indent([ - "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", - "promise = bytesPromise.then(function(bytes) {", - Template.indent([ - `return WebAssembly.instantiate(bytes, ${createImportObject( - "importObject" - )});` - ]), - "});" + "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", + "var realSrc = event && event.target && event.target.src;", + "error.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", + "error.name = 'ChunkLoadError';", + "error.type = errorType;", + "error.request = realSrc;", + "chunk[1](error);" ]), "}", - "promises.push(installedWasmModules[wasmModuleId] = promise.then(function(res) {", - Template.indent([ - `return ${mainTemplate.requireFn}.w[wasmModuleId] = (res.instance || res).exports;` - ]), - "}));" + "installedChunks[chunkId] = undefined;" ]), "}" ]), - "});" + "};", + "var timeout = setTimeout(function(){", + Template.indent([ + "onScriptComplete({ type: 'timeout', target: script });" + ]), + `}, ${chunkLoadTimeout});`, + "script.onerror = script.onload = onScriptComplete;" ]); } ); - mainTemplate.hooks.requireExtensions.tap( - "WasmMainTemplatePlugin", - (source, chunk) => { - if (!chunk.hasModuleInGraph(m => m.type.startsWith("webassembly"))) { - return source; - } + mainTemplate.hooks.linkPreload.tap( + "JsonpMainTemplatePlugin", + (_, chunk, hash) => { + const crossOriginLoading = + mainTemplate.outputOptions.crossOriginLoading; + const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; + return Template.asString([ - source, - "", - "// object with all WebAssembly.instance exports", - `${mainTemplate.requireFn}.w = {};` + "var link = document.createElement('link');", + jsonpScriptType + ? `link.type = ${JSON.stringify(jsonpScriptType)};` + : "", + "link.charset = 'utf-8';", + `if (${mainTemplate.requireFn}.nc) {`, + Template.indent( + `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` + ), + "}", + 'link.rel = "preload";', + 'link.as = "script";', + "link.href = jsonpScriptSrc(chunkId);", + crossOriginLoading + ? Template.asString([ + "if (link.href.indexOf(window.location.origin + '/') !== 0) {", + Template.indent( + `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + ), + "}" + ]) + : "" ]); } ); - mainTemplate.hooks.hash.tap("WasmMainTemplatePlugin", hash => { - hash.update("WasmMainTemplatePlugin"); - hash.update("2"); - }); - } -} - -module.exports = WasmMainTemplatePlugin; - - -/***/ }), - -/***/ 13099: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ - + mainTemplate.hooks.linkPrefetch.tap( + "JsonpMainTemplatePlugin", + (_, chunk, hash) => { + const crossOriginLoading = + mainTemplate.outputOptions.crossOriginLoading; -const Generator = __webpack_require__(39172); -const Template = __webpack_require__(96066); -const WebAssemblyUtils = __webpack_require__(52136); -const { RawSource } = __webpack_require__(53665); + return Template.asString([ + "var link = document.createElement('link');", + crossOriginLoading + ? `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` + : "", + `if (${mainTemplate.requireFn}.nc) {`, + Template.indent( + `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` + ), + "}", + 'link.rel = "prefetch";', + 'link.as = "script";', + "link.href = jsonpScriptSrc(chunkId);" + ]); + } + ); + mainTemplate.hooks.requireEnsure.tap( + "JsonpMainTemplatePlugin load", + (source, chunk, hash) => { + return Template.asString([ + source, + "", + "// JSONP chunk loading for javascript", + "", + "var installedChunkData = installedChunks[chunkId];", + 'if(installedChunkData !== 0) { // 0 means "already installed".', + Template.indent([ + "", + '// a Promise means "currently loading".', + "if(installedChunkData) {", + Template.indent(["promises.push(installedChunkData[2]);"]), + "} else {", + Template.indent([ + "// setup Promise in chunk cache", + "var promise = new Promise(function(resolve, reject) {", + Template.indent([ + "installedChunkData = installedChunks[chunkId] = [resolve, reject];" + ]), + "});", + "promises.push(installedChunkData[2] = promise);", + "", + "// start chunk loading", + mainTemplate.hooks.jsonpScript.call("", chunk, hash), + "document.head.appendChild(script);" + ]), + "}" + ]), + "}" + ]); + } + ); + mainTemplate.hooks.requireEnsure.tap( + { + name: "JsonpMainTemplatePlugin preload", + stage: 10 + }, + (source, chunk, hash) => { + const chunkMap = chunk.getChildIdsByOrdersMap().preload; + if (!chunkMap || Object.keys(chunkMap).length === 0) return source; + return Template.asString([ + source, + "", + "// chunk preloadng for javascript", + "", + `var chunkPreloadMap = ${JSON.stringify(chunkMap, null, "\t")};`, + "", + "var chunkPreloadData = chunkPreloadMap[chunkId];", + "if(chunkPreloadData) {", + Template.indent([ + "chunkPreloadData.forEach(function(chunkId) {", + Template.indent([ + "if(installedChunks[chunkId] === undefined) {", + Template.indent([ + "installedChunks[chunkId] = null;", + mainTemplate.hooks.linkPreload.call("", chunk, hash), + "document.head.appendChild(link);" + ]), + "}" + ]), + "});" + ]), + "}" + ]); + } + ); + mainTemplate.hooks.requireExtensions.tap( + "JsonpMainTemplatePlugin", + (source, chunk) => { + if (!needChunkOnDemandLoadingCode(chunk)) return source; -const { editWithAST, addWithAST } = __webpack_require__(65584); -const { decode } = __webpack_require__(27352); -const t = __webpack_require__(81875); -const { - moduleContextFromModuleAST -} = __webpack_require__(71234); + return Template.asString([ + source, + "", + "// on error function for async loading", + `${mainTemplate.requireFn}.oe = function(err) { console.error(err); throw err; };` + ]); + } + ); + mainTemplate.hooks.bootstrap.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + if (needChunkLoadingCode(chunk)) { + const withDefer = needEntryDeferringCode(chunk); + const withPrefetch = needPrefetchingCode(chunk); + return Template.asString([ + source, + "", + "// install a JSONP callback for chunk loading", + "function webpackJsonpCallback(data) {", + Template.indent([ + "var chunkIds = data[0];", + "var moreModules = data[1];", + withDefer ? "var executeModules = data[2];" : "", + withPrefetch ? "var prefetchChunks = data[3] || [];" : "", + '// add "moreModules" to the modules object,', + '// then flag all "chunkIds" as loaded and fire callback', + "var moduleId, chunkId, i = 0, resolves = [];", + "for(;i < chunkIds.length; i++) {", + Template.indent([ + "chunkId = chunkIds[i];", + "if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {", + Template.indent("resolves.push(installedChunks[chunkId][0]);"), + "}", + "installedChunks[chunkId] = 0;" + ]), + "}", + "for(moduleId in moreModules) {", + Template.indent([ + "if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {", + Template.indent( + mainTemplate.renderAddModule( + hash, + chunk, + "moduleId", + "moreModules[moduleId]" + ) + ), + "}" + ]), + "}", + "if(parentJsonpFunction) parentJsonpFunction(data);", + withPrefetch + ? withDefer + ? "deferredPrefetch.push.apply(deferredPrefetch, prefetchChunks);" + : Template.asString([ + "// chunk prefetching for javascript", + "prefetchChunks.forEach(function(chunkId) {", + Template.indent([ + "if(installedChunks[chunkId] === undefined) {", + Template.indent([ + "installedChunks[chunkId] = null;", + mainTemplate.hooks.linkPrefetch.call("", chunk, hash), + "document.head.appendChild(link);" + ]), + "}" + ]), + "});" + ]) + : "", + "while(resolves.length) {", + Template.indent("resolves.shift()();"), + "}", + withDefer + ? Template.asString([ + "", + "// add entry modules from loaded chunk to deferred list", + "deferredModules.push.apply(deferredModules, executeModules || []);", + "", + "// run deferred modules when all chunks ready", + "return checkDeferredModules();" + ]) + : "" + ]), + "};", + withDefer + ? Template.asString([ + "function checkDeferredModules() {", + Template.indent([ + "var result;", + "for(var i = 0; i < deferredModules.length; i++) {", + Template.indent([ + "var deferredModule = deferredModules[i];", + "var fulfilled = true;", + "for(var j = 1; j < deferredModule.length; j++) {", + Template.indent([ + "var depId = deferredModule[j];", + "if(installedChunks[depId] !== 0) fulfilled = false;" + ]), + "}", + "if(fulfilled) {", + Template.indent([ + "deferredModules.splice(i--, 1);", + "result = " + + mainTemplate.requireFn + + "(" + + mainTemplate.requireFn + + ".s = deferredModule[0]);" + ]), + "}" + ]), + "}", + withPrefetch + ? Template.asString([ + "if(deferredModules.length === 0) {", + Template.indent([ + "// chunk prefetching for javascript", + "deferredPrefetch.forEach(function(chunkId) {", + Template.indent([ + "if(installedChunks[chunkId] === undefined) {", + Template.indent([ + "installedChunks[chunkId] = null;", + mainTemplate.hooks.linkPrefetch.call( + "", + chunk, + hash + ), + "document.head.appendChild(link);" + ]), + "}" + ]), + "});", + "deferredPrefetch.length = 0;" + ]), + "}" + ]) + : "", + "return result;" + ]), + "}" + ]) + : "" + ]); + } + return source; + } + ); + mainTemplate.hooks.beforeStartup.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + if (needChunkLoadingCode(chunk)) { + var jsonpFunction = mainTemplate.outputOptions.jsonpFunction; + var globalObject = mainTemplate.outputOptions.globalObject; + return Template.asString([ + `var jsonpArray = ${globalObject}[${JSON.stringify( + jsonpFunction + )}] = ${globalObject}[${JSON.stringify(jsonpFunction)}] || [];`, + "var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);", + "jsonpArray.push = webpackJsonpCallback;", + "jsonpArray = jsonpArray.slice();", + "for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);", + "var parentJsonpFunction = oldJsonpFunction;", + "", + source + ]); + } + return source; + } + ); + mainTemplate.hooks.afterStartup.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + const prefetchChunks = chunk.getChildIdsByOrders().prefetch; + if ( + needChunkLoadingCode(chunk) && + prefetchChunks && + prefetchChunks.length + ) { + return Template.asString([ + source, + `webpackJsonpCallback([[], {}, 0, ${JSON.stringify( + prefetchChunks + )}]);` + ]); + } + return source; + } + ); + mainTemplate.hooks.startup.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + if (needEntryDeferringCode(chunk)) { + if (chunk.hasEntryModule()) { + const entries = [chunk.entryModule].filter(Boolean).map(m => + [m.id].concat( + Array.from(chunk.groupsIterable)[0] + .chunks.filter(c => c !== chunk) + .map(c => c.id) + ) + ); + return Template.asString([ + "// add entry module to deferred list", + `deferredModules.push(${entries + .map(e => JSON.stringify(e)) + .join(", ")});`, + "// run deferred modules when ready", + "return checkDeferredModules();" + ]); + } else { + return Template.asString([ + "// run deferred modules from other chunks", + "checkDeferredModules();" + ]); + } + } + return source; + } + ); + mainTemplate.hooks.hotBootstrap.tap( + "JsonpMainTemplatePlugin", + (source, chunk, hash) => { + const globalObject = mainTemplate.outputOptions.globalObject; + const hotUpdateChunkFilename = + mainTemplate.outputOptions.hotUpdateChunkFilename; + const hotUpdateMainFilename = + mainTemplate.outputOptions.hotUpdateMainFilename; + const crossOriginLoading = + mainTemplate.outputOptions.crossOriginLoading; + const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction; + const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateChunkFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: '" + chunkId + "' + } + } + ); + const currentHotUpdateMainFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateMainFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` + } + ); + const runtimeSource = Template.getFunctionContent( + __webpack_require__(24916) + ) + .replace(/\/\/\$semicolon/g, ";") + .replace(/\$require\$/g, mainTemplate.requireFn) + .replace( + /\$crossOriginLoading\$/g, + crossOriginLoading ? JSON.stringify(crossOriginLoading) : "null" + ) + .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) + .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) + .replace(/\$hash\$/g, JSON.stringify(hash)); + return `${source} +function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; +} +var parentHotUpdateCallback = ${globalObject}[${JSON.stringify( + hotUpdateFunction + )}]; +${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`; + } + ); + mainTemplate.hooks.hash.tap("JsonpMainTemplatePlugin", hash => { + hash.update("jsonp"); + hash.update("6"); + }); + } +} +module.exports = JsonpMainTemplatePlugin; -const WebAssemblyExportImportedDependency = __webpack_require__(18925); -/** @typedef {import("../Module")} Module */ -/** @typedef {import("./WebAssemblyUtils").UsedWasmDependency} UsedWasmDependency */ -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Dependency").DependencyTemplate} DependencyTemplate */ +/***/ }), -/** - * @typedef {(ArrayBuffer) => ArrayBuffer} ArrayBufferTransform - */ +/***/ 92764: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * @template T - * @param {Function[]} fns transforms - * @returns {Function} composed transform - */ -const compose = (...fns) => { - return fns.reduce( - (prevFn, nextFn) => { - return value => nextFn(prevFn(value)); - }, - value => value - ); -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -// TODO replace with @callback -/** - * Removes the start instruction - * - * @param {Object} state unused state - * @returns {ArrayBufferTransform} transform - */ -const removeStartFunc = state => bin => { - return editWithAST(state.ast, bin, { - Start(path) { - path.remove(); - } - }); -}; +const JsonpMainTemplatePlugin = __webpack_require__(38017); +const JsonpChunkTemplatePlugin = __webpack_require__(31898); +const JsonpHotUpdateChunkTemplatePlugin = __webpack_require__(44458); -/** - * Get imported globals - * - * @param {Object} ast Module's AST - * @returns {Array} - nodes - */ -const getImportedGlobals = ast => { - const importedGlobals = []; +class JsonpTemplatePlugin { + apply(compiler) { + compiler.hooks.thisCompilation.tap("JsonpTemplatePlugin", compilation => { + new JsonpMainTemplatePlugin().apply(compilation.mainTemplate); + new JsonpChunkTemplatePlugin().apply(compilation.chunkTemplate); + new JsonpHotUpdateChunkTemplatePlugin().apply( + compilation.hotUpdateChunkTemplate + ); + }); + } +} - t.traverse(ast, { - ModuleImport({ node }) { - if (t.isGlobalType(node.descr)) { - importedGlobals.push(node); - } - } - }); +module.exports = JsonpTemplatePlugin; - return importedGlobals; -}; -/** - * Get the count for imported func - * - * @param {Object} ast Module's AST - * @returns {Number} - count - */ -const getCountImportedFunc = ast => { - let count = 0; +/***/ }), - t.traverse(ast, { - ModuleImport({ node }) { - if (t.isFuncImportDescr(node.descr)) { - count++; - } - } - }); +/***/ 92929: +/***/ (function(module, exports, __webpack_require__) { - return count; -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * Get next type index - * - * @param {Object} ast Module's AST - * @returns {t.Index} - index - */ -const getNextTypeIndex = ast => { - const typeSectionMetadata = t.getSectionMetadata(ast, "type"); - if (typeSectionMetadata === undefined) { - return t.indexLiteral(0); - } +const Compiler = __webpack_require__(58705); +const MultiCompiler = __webpack_require__(10238); +const NodeEnvironmentPlugin = __webpack_require__(52520); +const WebpackOptionsApply = __webpack_require__(2779); +const WebpackOptionsDefaulter = __webpack_require__(60016); +const validateSchema = __webpack_require__(68935); +const WebpackOptionsValidationError = __webpack_require__(285); +const webpackOptionsSchema = __webpack_require__(37863); +const RemovedPluginError = __webpack_require__(15377); +const version = __webpack_require__(71618)/* .version */ .i8; - return t.indexLiteral(typeSectionMetadata.vectorOfSize.value); -}; +/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ /** - * Get next func index - * - * The Func section metadata provide informations for implemented funcs - * in order to have the correct index we shift the index by number of external - * functions. - * - * @param {Object} ast Module's AST - * @param {Number} countImportedFunc number of imported funcs - * @returns {t.Index} - index + * @param {WebpackOptions} options options object + * @param {function(Error=, Stats=): void=} callback callback + * @returns {Compiler | MultiCompiler} the compiler object */ -const getNextFuncIndex = (ast, countImportedFunc) => { - const funcSectionMetadata = t.getSectionMetadata(ast, "func"); +const webpack = (options, callback) => { + const webpackOptionsValidationErrors = validateSchema( + webpackOptionsSchema, + options + ); + if (webpackOptionsValidationErrors.length) { + throw new WebpackOptionsValidationError(webpackOptionsValidationErrors); + } + let compiler; + if (Array.isArray(options)) { + compiler = new MultiCompiler( + Array.from(options).map(options => webpack(options)) + ); + } else if (typeof options === "object") { + options = new WebpackOptionsDefaulter().process(options); - if (funcSectionMetadata === undefined) { - return t.indexLiteral(0 + countImportedFunc); + compiler = new Compiler(options.context); + compiler.options = options; + new NodeEnvironmentPlugin({ + infrastructureLogging: options.infrastructureLogging + }).apply(compiler); + if (options.plugins && Array.isArray(options.plugins)) { + for (const plugin of options.plugins) { + if (typeof plugin === "function") { + plugin.call(compiler, compiler); + } else { + plugin.apply(compiler); + } + } + } + compiler.hooks.environment.call(); + compiler.hooks.afterEnvironment.call(); + compiler.options = new WebpackOptionsApply().process(options, compiler); + } else { + throw new Error("Invalid argument: options"); + } + if (callback) { + if (typeof callback !== "function") { + throw new Error("Invalid argument: callback"); + } + if ( + options.watch === true || + (Array.isArray(options) && options.some(o => o.watch)) + ) { + const watchOptions = Array.isArray(options) + ? options.map(o => o.watchOptions || {}) + : options.watchOptions || {}; + return compiler.watch(watchOptions, callback); + } + compiler.run(callback); } + return compiler; +}; - const vectorOfSize = funcSectionMetadata.vectorOfSize.value; +exports = module.exports = webpack; +exports.version = version; - return t.indexLiteral(vectorOfSize + countImportedFunc); -}; +webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter; +webpack.WebpackOptionsApply = WebpackOptionsApply; +webpack.Compiler = Compiler; +webpack.MultiCompiler = MultiCompiler; +webpack.NodeEnvironmentPlugin = NodeEnvironmentPlugin; +// @ts-ignore Global @this directive is not supported +webpack.validate = validateSchema.bind(this, webpackOptionsSchema); +webpack.validateSchema = validateSchema; +webpack.WebpackOptionsValidationError = WebpackOptionsValidationError; -/** - * Creates an init instruction for a global type - * @param {t.GlobalType} globalType the global type - * @returns {t.Instruction} init expression - */ -const createDefaultInitForGlobal = globalType => { - if (globalType.valtype[0] === "i") { - // create NumberLiteral global initializer - return t.objectInstruction("const", globalType.valtype, [ - t.numberLiteralFromRaw(66) - ]); - } else if (globalType.valtype[0] === "f") { - // create FloatLiteral global initializer - return t.objectInstruction("const", globalType.valtype, [ - t.floatLiteral(66, false, false, "66") - ]); - } else { - throw new Error("unknown type: " + globalType.valtype); +const exportPlugins = (obj, mappings) => { + for (const name of Object.keys(mappings)) { + Object.defineProperty(obj, name, { + configurable: false, + enumerable: true, + get: mappings[name] + }); } }; -/** - * Rewrite the import globals: - * - removes the ModuleImport instruction - * - injects at the same offset a mutable global of the same type - * - * Since the imported globals are before the other global declarations, our - * indices will be preserved. - * - * Note that globals will become mutable. - * - * @param {Object} state unused state - * @returns {ArrayBufferTransform} transform - */ -const rewriteImportedGlobals = state => bin => { - const additionalInitCode = state.additionalInitCode; - const newGlobals = []; +exportPlugins(exports, { + AutomaticPrefetchPlugin: () => __webpack_require__(51596), + BannerPlugin: () => __webpack_require__(4009), + CachePlugin: () => __webpack_require__(6465), + ContextExclusionPlugin: () => __webpack_require__(10706), + ContextReplacementPlugin: () => __webpack_require__(27295), + DefinePlugin: () => __webpack_require__(97374), + Dependency: () => __webpack_require__(57282), + DllPlugin: () => __webpack_require__(45255), + DllReferencePlugin: () => __webpack_require__(86231), + EnvironmentPlugin: () => __webpack_require__(6098), + EvalDevToolModulePlugin: () => __webpack_require__(65200), + EvalSourceMapDevToolPlugin: () => __webpack_require__(99994), + ExtendedAPIPlugin: () => __webpack_require__(17270), + ExternalsPlugin: () => __webpack_require__(75705), + HashedModuleIdsPlugin: () => __webpack_require__(50268), + HotModuleReplacementPlugin: () => __webpack_require__(69575), + IgnorePlugin: () => __webpack_require__(41364), + LibraryTemplatePlugin: () => __webpack_require__(65237), + LoaderOptionsPlugin: () => __webpack_require__(48775), + LoaderTargetPlugin: () => __webpack_require__(95154), + MemoryOutputFileSystem: () => __webpack_require__(50332), + Module: () => __webpack_require__(75993), + ModuleFilenameHelpers: () => __webpack_require__(71474), + NamedChunksPlugin: () => __webpack_require__(70419), + NamedModulesPlugin: () => __webpack_require__(86707), + NoEmitOnErrorsPlugin: () => __webpack_require__(22615), + NormalModuleReplacementPlugin: () => + __webpack_require__(73253), + PrefetchPlugin: () => __webpack_require__(27850), + ProgressPlugin: () => __webpack_require__(63123), + ProvidePlugin: () => __webpack_require__(72861), + SetVarMainTemplatePlugin: () => __webpack_require__(37098), + SingleEntryPlugin: () => __webpack_require__(19070), + SourceMapDevToolPlugin: () => __webpack_require__(11851), + Stats: () => __webpack_require__(99977), + Template: () => __webpack_require__(96066), + UmdMainTemplatePlugin: () => __webpack_require__(75374), + WatchIgnorePlugin: () => __webpack_require__(88015) +}); +exportPlugins((exports.dependencies = {}), { + DependencyReference: () => __webpack_require__(71722) +}); +exportPlugins((exports.optimize = {}), { + AggressiveMergingPlugin: () => __webpack_require__(88197), + AggressiveSplittingPlugin: () => + __webpack_require__(26688), + ChunkModuleIdRangePlugin: () => + __webpack_require__(30346), + LimitChunkCountPlugin: () => __webpack_require__(3846), + MinChunkSizePlugin: () => __webpack_require__(55607), + ModuleConcatenationPlugin: () => + __webpack_require__(45184), + OccurrenceOrderPlugin: () => __webpack_require__(67340), + OccurrenceModuleOrderPlugin: () => + __webpack_require__(62000), + OccurrenceChunkOrderPlugin: () => + __webpack_require__(83741), + RuntimeChunkPlugin: () => __webpack_require__(76894), + SideEffectsFlagPlugin: () => __webpack_require__(83654), + SplitChunksPlugin: () => __webpack_require__(60474) +}); +exportPlugins((exports.web = {}), { + FetchCompileWasmTemplatePlugin: () => + __webpack_require__(52669), + JsonpTemplatePlugin: () => __webpack_require__(92764) +}); +exportPlugins((exports.webworker = {}), { + WebWorkerTemplatePlugin: () => __webpack_require__(21328) +}); +exportPlugins((exports.node = {}), { + NodeTemplatePlugin: () => __webpack_require__(90010), + ReadFileCompileWasmTemplatePlugin: () => + __webpack_require__(73839) +}); +exportPlugins((exports.debug = {}), { + ProfilingPlugin: () => __webpack_require__(72890) +}); +exportPlugins((exports.util = {}), { + createHash: () => __webpack_require__(15660) +}); - bin = editWithAST(state.ast, bin, { - ModuleImport(path) { - if (t.isGlobalType(path.node.descr)) { - const globalType = path.node.descr; +const defineMissingPluginError = (namespace, pluginName, errorMessage) => { + Object.defineProperty(namespace, pluginName, { + configurable: false, + enumerable: true, + get() { + throw new RemovedPluginError(errorMessage); + } + }); +}; - globalType.mutability = "var"; +// TODO remove in webpack 5 +defineMissingPluginError( + exports.optimize, + "UglifyJsPlugin", + "webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." +); - const init = [ - createDefaultInitForGlobal(globalType), - t.instruction("end") - ]; +// TODO remove in webpack 5 +defineMissingPluginError( + exports.optimize, + "CommonsChunkPlugin", + "webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead." +); - newGlobals.push(t.global(globalType, init)); - path.remove(); - } - }, +/***/ }), - // in order to preserve non-imported global's order we need to re-inject - // those as well - Global(path) { - const { node } = path; - const [init] = node.init; +/***/ 37919: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - if (init.id === "get_global") { - node.globalType.mutability = "var"; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const initialGlobalidx = init.args[0]; - node.init = [ - createDefaultInitForGlobal(node.globalType), - t.instruction("end") - ]; +const { ConcatSource } = __webpack_require__(53665); - additionalInitCode.push( - /** - * get_global in global initializer only works for imported globals. - * They have the same indices as the init params, so use the - * same index. - */ - t.instruction("get_local", [initialGlobalidx]), - t.instruction("set_global", [t.indexLiteral(newGlobals.length)]) +class WebWorkerChunkTemplatePlugin { + apply(chunkTemplate) { + chunkTemplate.hooks.render.tap( + "WebWorkerChunkTemplatePlugin", + (modules, chunk) => { + const chunkCallbackName = chunkTemplate.outputOptions.chunkCallbackName; + const globalObject = chunkTemplate.outputOptions.globalObject; + const source = new ConcatSource(); + source.add( + `${globalObject}[${JSON.stringify( + chunkCallbackName + )}](${JSON.stringify(chunk.ids)},` ); + source.add(modules); + source.add(")"); + return source; } + ); + chunkTemplate.hooks.hash.tap("WebWorkerChunkTemplatePlugin", hash => { + hash.update("webworker"); + hash.update("3"); + hash.update(`${chunkTemplate.outputOptions.chunkCallbackName}`); + hash.update(`${chunkTemplate.outputOptions.globalObject}`); + }); + } +} +module.exports = WebWorkerChunkTemplatePlugin; - newGlobals.push(node); - path.remove(); - } - }); +/***/ }), - // Add global declaration instructions - return addWithAST(state.ast, bin, newGlobals); -}; +/***/ 45493: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -/** - * Rewrite the export names - * @param {Object} state state - * @param {Object} state.ast Module's ast - * @param {Module} state.module Module - * @param {Set} state.externalExports Module - * @returns {ArrayBufferTransform} transform - */ -const rewriteExportNames = ({ ast, module, externalExports }) => bin => { - return editWithAST(ast, bin, { - ModuleExport(path) { - const isExternal = externalExports.has(path.node.name); - if (isExternal) { - path.remove(); - return; - } - const usedName = module.isUsed(path.node.name); - if (!usedName) { - path.remove(); - return; - } - path.node.name = usedName; - } - }); -}; +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ -/** - * Mangle import names and modules - * @param {Object} state state - * @param {Object} state.ast Module's ast - * @param {Map} state.usedDependencyMap mappings to mangle names - * @returns {ArrayBufferTransform} transform - */ -const rewriteImports = ({ ast, usedDependencyMap }) => bin => { - return editWithAST(ast, bin, { - ModuleImport(path) { - const result = usedDependencyMap.get( - path.node.module + ":" + path.node.name - ); +const { ConcatSource } = __webpack_require__(53665); - if (result !== undefined) { - path.node.module = result.module; - path.node.name = result.name; +class WebWorkerHotUpdateChunkTemplatePlugin { + apply(hotUpdateChunkTemplate) { + hotUpdateChunkTemplate.hooks.render.tap( + "WebWorkerHotUpdateChunkTemplatePlugin", + (modulesSource, modules, removedModules, hash, id) => { + const hotUpdateFunction = + hotUpdateChunkTemplate.outputOptions.hotUpdateFunction; + const globalObject = hotUpdateChunkTemplate.outputOptions.globalObject; + const source = new ConcatSource(); + source.add( + `${globalObject}[${JSON.stringify( + hotUpdateFunction + )}](${JSON.stringify(id)},` + ); + source.add(modulesSource); + source.add(")"); + return source; } - } - }); -}; + ); + hotUpdateChunkTemplate.hooks.hash.tap( + "WebWorkerHotUpdateChunkTemplatePlugin", + hash => { + hash.update("WebWorkerHotUpdateChunkTemplatePlugin"); + hash.update("3"); + hash.update( + hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "" + ); + hash.update(hotUpdateChunkTemplate.outputOptions.globalObject + ""); + } + ); + } +} +module.exports = WebWorkerHotUpdateChunkTemplatePlugin; -/** - * Add an init function. - * - * The init function fills the globals given input arguments. - * - * @param {Object} state transformation state - * @param {Object} state.ast Module's ast - * @param {t.Identifier} state.initFuncId identifier of the init function - * @param {t.Index} state.startAtFuncOffset index of the start function - * @param {t.ModuleImport[]} state.importedGlobals list of imported globals - * @param {t.Instruction[]} state.additionalInitCode list of addition instructions for the init function - * @param {t.Index} state.nextFuncIndex index of the next function - * @param {t.Index} state.nextTypeIndex index of the next type - * @returns {ArrayBufferTransform} transform - */ -const addInitFunction = ({ - ast, - initFuncId, - startAtFuncOffset, - importedGlobals, - additionalInitCode, - nextFuncIndex, - nextTypeIndex -}) => bin => { - const funcParams = importedGlobals.map(importedGlobal => { - // used for debugging - const id = t.identifier(`${importedGlobal.module}.${importedGlobal.name}`); - return t.funcParam(importedGlobal.descr.valtype, id); - }); +/***/ }), - const funcBody = importedGlobals.reduce((acc, importedGlobal, index) => { - const args = [t.indexLiteral(index)]; - const body = [ - t.instruction("get_local", args), - t.instruction("set_global", args) - ]; +/***/ 72337: +/***/ (function(module) { - return [...acc, ...body]; - }, []); +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +// eslint-disable-next-line no-unused-vars +var hotAddUpdateChunk = undefined; +var parentHotUpdateCallback = undefined; +var $require$ = undefined; +var $hotChunkFilename$ = undefined; +var $hotMainFilename$ = undefined; +var installedChunks = undefined; +var importScripts = undefined; - if (typeof startAtFuncOffset === "number") { - funcBody.push(t.callInstruction(t.numberLiteralFromRaw(startAtFuncOffset))); +module.exports = function() { + // eslint-disable-next-line no-unused-vars + function webpackHotUpdateCallback(chunkId, moreModules) { + hotAddUpdateChunk(chunkId, moreModules); + if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); + } //$semicolon + + // eslint-disable-next-line no-unused-vars + function hotDownloadUpdateChunk(chunkId) { + importScripts($require$.p + $hotChunkFilename$); } - for (const instr of additionalInitCode) { - funcBody.push(instr); + // eslint-disable-next-line no-unused-vars + function hotDownloadManifest(requestTimeout) { + requestTimeout = requestTimeout || 10000; + return new Promise(function(resolve, reject) { + if (typeof XMLHttpRequest === "undefined") { + return reject(new Error("No browser support")); + } + try { + var request = new XMLHttpRequest(); + var requestPath = $require$.p + $hotMainFilename$; + request.open("GET", requestPath, true); + request.timeout = requestTimeout; + request.send(null); + } catch (err) { + return reject(err); + } + request.onreadystatechange = function() { + if (request.readyState !== 4) return; + if (request.status === 0) { + // timeout + reject( + new Error("Manifest request to " + requestPath + " timed out.") + ); + } else if (request.status === 404) { + // no update available + resolve(); + } else if (request.status !== 200 && request.status !== 304) { + // other failure + reject(new Error("Manifest request to " + requestPath + " failed.")); + } else { + // success + try { + var update = JSON.parse(request.responseText); + } catch (e) { + reject(e); + return; + } + resolve(update); + } + }; + }); } - funcBody.push(t.instruction("end")); + //eslint-disable-next-line no-unused-vars + function hotDisposeChunk(chunkId) { + delete installedChunks[chunkId]; + } +}; - const funcResults = []; - // Code section - const funcSignature = t.signature(funcParams, funcResults); - const func = t.func(initFuncId, funcSignature, funcBody); +/***/ }), - // Type section - const functype = t.typeInstruction(undefined, funcSignature); +/***/ 20482: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - // Func section - const funcindex = t.indexInFuncSection(nextTypeIndex); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - // Export section - const moduleExport = t.moduleExport( - initFuncId.value, - t.moduleExportDescr("Func", nextFuncIndex) - ); - return addWithAST(ast, bin, [func, moduleExport, funcindex, functype]); -}; +const Template = __webpack_require__(96066); -/** - * Extract mangle mappings from module - * @param {Module} module current module - * @param {boolean} mangle mangle imports - * @returns {Map} mappings to mangled names - */ -const getUsedDependencyMap = (module, mangle) => { - /** @type {Map} */ - const map = new Map(); - for (const usedDep of WebAssemblyUtils.getUsedDependencies(module, mangle)) { - const dep = usedDep.dependency; - const request = dep.request; - const exportName = dep.name; - map.set(request + ":" + exportName, usedDep); - } - return map; -}; +class WebWorkerMainTemplatePlugin { + apply(mainTemplate) { + const needChunkOnDemandLoadingCode = chunk => { + for (const chunkGroup of chunk.groupsIterable) { + if (chunkGroup.getNumberOfChildren() > 0) return true; + } + return false; + }; + mainTemplate.hooks.localVars.tap( + "WebWorkerMainTemplatePlugin", + (source, chunk) => { + if (needChunkOnDemandLoadingCode(chunk)) { + return Template.asString([ + source, + "", + "// object to store loaded chunks", + '// "1" means "already loaded"', + "var installedChunks = {", + Template.indent( + chunk.ids.map(id => `${JSON.stringify(id)}: 1`).join(",\n") + ), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.requireEnsure.tap( + "WebWorkerMainTemplatePlugin", + (_, chunk, hash) => { + const chunkFilename = mainTemplate.outputOptions.chunkFilename; + const chunkMaps = chunk.getChunkMaps(); + return Template.asString([ + "promises.push(Promise.resolve().then(function() {", + Template.indent([ + '// "1" is the signal for "already loaded"', + "if(!installedChunks[chunkId]) {", + Template.indent([ + "importScripts(" + + "__webpack_require__.p + " + + mainTemplate.getAssetPath(JSON.stringify(chunkFilename), { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode( + hash, + length + )} + "`, + chunk: { + id: '" + chunkId + "', + hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, + hashWithLength(length) { + const shortChunkHashMap = Object.create(null); + for (const chunkId of Object.keys(chunkMaps.hash)) { + if (typeof chunkMaps.hash[chunkId] === "string") { + shortChunkHashMap[chunkId] = chunkMaps.hash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortChunkHashMap + )}[chunkId] + "`; + }, + contentHash: { + javascript: `" + ${JSON.stringify( + chunkMaps.contentHash.javascript + )}[chunkId] + "` + }, + contentHashWithLength: { + javascript: length => { + const shortContentHashMap = {}; + const contentHash = chunkMaps.contentHash.javascript; + for (const chunkId of Object.keys(contentHash)) { + if (typeof contentHash[chunkId] === "string") { + shortContentHashMap[chunkId] = contentHash[ + chunkId + ].substr(0, length); + } + } + return `" + ${JSON.stringify( + shortContentHashMap + )}[chunkId] + "`; + } + }, + name: `" + (${JSON.stringify( + chunkMaps.name + )}[chunkId]||chunkId) + "` + }, + contentHashType: "javascript" + }) + + ");" + ]), + "}" + ]), + "}));" + ]); + } + ); + mainTemplate.hooks.bootstrap.tap( + "WebWorkerMainTemplatePlugin", + (source, chunk, hash) => { + if (needChunkOnDemandLoadingCode(chunk)) { + const chunkCallbackName = + mainTemplate.outputOptions.chunkCallbackName; + const globalObject = mainTemplate.outputOptions.globalObject; + return Template.asString([ + source, + `${globalObject}[${JSON.stringify( + chunkCallbackName + )}] = function webpackChunkCallback(chunkIds, moreModules) {`, + Template.indent([ + "for(var moduleId in moreModules) {", + Template.indent( + mainTemplate.renderAddModule( + hash, + chunk, + "moduleId", + "moreModules[moduleId]" + ) + ), + "}", + "while(chunkIds.length)", + Template.indent("installedChunks[chunkIds.pop()] = 1;") + ]), + "};" + ]); + } + return source; + } + ); + mainTemplate.hooks.hotBootstrap.tap( + "WebWorkerMainTemplatePlugin", + (source, chunk, hash) => { + const hotUpdateChunkFilename = + mainTemplate.outputOptions.hotUpdateChunkFilename; + const hotUpdateMainFilename = + mainTemplate.outputOptions.hotUpdateMainFilename; + const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction; + const globalObject = mainTemplate.outputOptions.globalObject; + const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateChunkFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, + chunk: { + id: '" + chunkId + "' + } + } + ); + const currentHotUpdateMainFilename = mainTemplate.getAssetPath( + JSON.stringify(hotUpdateMainFilename), + { + hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, + hashWithLength: length => + `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` + } + ); -class WebAssemblyGenerator extends Generator { - constructor(options) { - super(); - this.options = options; + return ( + source + + "\n" + + `var parentHotUpdateCallback = ${globalObject}[${JSON.stringify( + hotUpdateFunction + )}];\n` + + `${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ` + + Template.getFunctionContent( + __webpack_require__(72337) + ) + .replace(/\/\/\$semicolon/g, ";") + .replace(/\$require\$/g, mainTemplate.requireFn) + .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) + .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) + .replace(/\$hash\$/g, JSON.stringify(hash)) + ); + } + ); + mainTemplate.hooks.hash.tap("WebWorkerMainTemplatePlugin", hash => { + hash.update("webworker"); + hash.update("4"); + }); } +} +module.exports = WebWorkerMainTemplatePlugin; - /** - * @param {NormalModule} module module for which the code should be generated - * @param {Map} dependencyTemplates mapping from dependencies to templates - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {string} type which kind of code should be generated - * @returns {Source} generated code - */ - generate(module, dependencyTemplates, runtimeTemplate, type) { - let bin = module.originalSource().source(); - const initFuncId = t.identifier( - Array.isArray(module.usedExports) - ? Template.numberToIdentifer(module.usedExports.length) - : "__webpack_init__" - ); +/***/ }), - // parse it - const ast = decode(bin, { - ignoreDataSection: true, - ignoreCodeSection: true, - ignoreCustomNameSection: true - }); +/***/ 21328: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { - const moduleContext = moduleContextFromModuleAST(ast.body[0]); +"use strict"; +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ - const importedGlobals = getImportedGlobals(ast); - const countImportedFunc = getCountImportedFunc(ast); - const startAtFuncOffset = moduleContext.getStart(); - const nextFuncIndex = getNextFuncIndex(ast, countImportedFunc); - const nextTypeIndex = getNextTypeIndex(ast); - const usedDependencyMap = getUsedDependencyMap( - module, - this.options.mangleImports - ); - const externalExports = new Set( - module.dependencies - .filter(d => d instanceof WebAssemblyExportImportedDependency) - .map(d => { - const wasmDep = /** @type {WebAssemblyExportImportedDependency} */ (d); - return wasmDep.exportName; - }) - ); +const WebWorkerMainTemplatePlugin = __webpack_require__(20482); +const WebWorkerChunkTemplatePlugin = __webpack_require__(37919); +const WebWorkerHotUpdateChunkTemplatePlugin = __webpack_require__(45493); - /** @type {t.Instruction[]} */ - const additionalInitCode = []; +class WebWorkerTemplatePlugin { + apply(compiler) { + compiler.hooks.thisCompilation.tap( + "WebWorkerTemplatePlugin", + compilation => { + new WebWorkerMainTemplatePlugin().apply(compilation.mainTemplate); + new WebWorkerChunkTemplatePlugin().apply(compilation.chunkTemplate); + new WebWorkerHotUpdateChunkTemplatePlugin().apply( + compilation.hotUpdateChunkTemplate + ); + } + ); + } +} +module.exports = WebWorkerTemplatePlugin; - const transform = compose( - rewriteExportNames({ - ast, - module, - externalExports - }), - removeStartFunc({ ast }), +/***/ }), - rewriteImportedGlobals({ ast, additionalInitCode }), +/***/ 19728: +/***/ (function(__unused_webpack_module, exports) { - rewriteImports({ - ast, - usedDependencyMap - }), +"use strict"; - addInitFunction({ - ast, - initFuncId, - importedGlobals, - additionalInitCode, - startAtFuncOffset, - nextFuncIndex, - nextTypeIndex - }) - ); - const newBin = transform(bin); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.cloneNode = cloneNode; - return new RawSource(newBin); - } -} +function cloneNode(n) { + // $FlowIgnore + var newObj = {}; -module.exports = WebAssemblyGenerator; + for (var k in n) { + newObj[k] = n[k]; + } + return newObj; +} /***/ }), -/***/ 45283: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 81875: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php -*/ -const WebpackError = __webpack_require__(97391); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +var _exportNames = { + numberLiteralFromRaw: true, + withLoc: true, + withRaw: true, + funcParam: true, + indexLiteral: true, + memIndexLiteral: true, + instruction: true, + objectInstruction: true, + traverse: true, + signatures: true, + cloneNode: true +}; +Object.defineProperty(exports, "numberLiteralFromRaw", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.numberLiteralFromRaw; + } +})); +Object.defineProperty(exports, "withLoc", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.withLoc; + } +})); +Object.defineProperty(exports, "withRaw", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.withRaw; + } +})); +Object.defineProperty(exports, "funcParam", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.funcParam; + } +})); +Object.defineProperty(exports, "indexLiteral", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.indexLiteral; + } +})); +Object.defineProperty(exports, "memIndexLiteral", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.memIndexLiteral; + } +})); +Object.defineProperty(exports, "instruction", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.instruction; + } +})); +Object.defineProperty(exports, "objectInstruction", ({ + enumerable: true, + get: function get() { + return _nodeHelpers.objectInstruction; + } +})); +Object.defineProperty(exports, "traverse", ({ + enumerable: true, + get: function get() { + return _traverse.traverse; + } +})); +Object.defineProperty(exports, "signatures", ({ + enumerable: true, + get: function get() { + return _signatures.signatures; + } +})); +Object.defineProperty(exports, "cloneNode", ({ + enumerable: true, + get: function get() { + return _clone.cloneNode; + } +})); -/** @typedef {import("../Module")} Module */ -/** @typedef {import("../RequestShortener")} RequestShortener */ +var _nodes = __webpack_require__(94841); -/** - * @param {Module} module module to get chains from - * @param {RequestShortener} requestShortener to make readable identifiers - * @returns {string[]} all chains to the module - */ -const getInitialModuleChains = (module, requestShortener) => { - const queue = [ - { head: module, message: module.readableIdentifier(requestShortener) } - ]; - /** @type {Set} */ - const results = new Set(); - /** @type {Set} */ - const incompleteResults = new Set(); - /** @type {Set} */ - const visitedModules = new Set(); +Object.keys(_nodes).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _nodes[key]; + } + }); +}); - for (const chain of queue) { - const { head, message } = chain; - let final = true; - /** @type {Set} */ - const alreadyReferencedModules = new Set(); - for (const reason of head.reasons) { - const newHead = reason.module; - if (newHead) { - if (!newHead.getChunks().some(c => c.canBeInitial())) continue; - final = false; - if (alreadyReferencedModules.has(newHead)) continue; - alreadyReferencedModules.add(newHead); - const moduleName = newHead.readableIdentifier(requestShortener); - const detail = reason.explanation ? ` (${reason.explanation})` : ""; - const newMessage = `${moduleName}${detail} --> ${message}`; - if (visitedModules.has(newHead)) { - incompleteResults.add(`... --> ${newMessage}`); - continue; - } - visitedModules.add(newHead); - queue.push({ - head: newHead, - message: newMessage - }); - } else { - final = false; - const newMessage = reason.explanation - ? `(${reason.explanation}) --> ${message}` - : message; - results.add(newMessage); - } - } - if (final) { - results.add(message); - } - } - for (const result of incompleteResults) { - results.add(result); - } - return Array.from(results); -}; +var _nodeHelpers = __webpack_require__(1004); -module.exports = class WebAssemblyInInitialChunkError extends WebpackError { - /** - * @param {Module} module WASM module - * @param {RequestShortener} requestShortener request shortener - */ - constructor(module, requestShortener) { - const moduleChains = getInitialModuleChains(module, requestShortener); - const message = `WebAssembly module is included in initial chunk. -This is not allowed, because WebAssembly download and compilation must happen asynchronous. -Add an async splitpoint (i. e. import()) somewhere between your entrypoint and the WebAssembly module: -${moduleChains.map(s => `* ${s}`).join("\n")}`; +var _traverse = __webpack_require__(29436); - super(message); - this.name = "WebAssemblyInInitialChunkError"; - this.hideStack = true; - this.module = module; +var _signatures = __webpack_require__(77392); - Error.captureStackTrace(this, this.constructor); - } -}; +var _utils = __webpack_require__(38456); + +Object.keys(_utils).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _utils[key]; + } + }); +}); +var _clone = __webpack_require__(19728); /***/ }), -/***/ 13411: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +/***/ 1004: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -const Generator = __webpack_require__(39172); -const Template = __webpack_require__(96066); -const { RawSource } = __webpack_require__(53665); -const WebAssemblyImportDependency = __webpack_require__(52959); -const WebAssemblyExportImportedDependency = __webpack_require__(18925); - -/** @typedef {import("../NormalModule")} NormalModule */ -/** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ -/** @typedef {import("webpack-sources").Source} Source */ -/** @typedef {import("../Dependency").DependencyTemplate} DependencyTemplate */ +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.numberLiteralFromRaw = numberLiteralFromRaw; +exports.instruction = instruction; +exports.objectInstruction = objectInstruction; +exports.withLoc = withLoc; +exports.withRaw = withRaw; +exports.funcParam = funcParam; +exports.indexLiteral = indexLiteral; +exports.memIndexLiteral = memIndexLiteral; -class WebAssemblyJavascriptGenerator extends Generator { - /** - * @param {NormalModule} module module for which the code should be generated - * @param {Map} dependencyTemplates mapping from dependencies to templates - * @param {RuntimeTemplate} runtimeTemplate the runtime template - * @param {string} type which kind of code should be generated - * @returns {Source} generated code - */ - generate(module, dependencyTemplates, runtimeTemplate, type) { - const initIdentifer = Array.isArray(module.usedExports) - ? Template.numberToIdentifer(module.usedExports.length) - : "__webpack_init__"; +var _wastParser = __webpack_require__(9016); - let needExportsCopy = false; - const importedModules = new Map(); - const initParams = []; - let index = 0; - for (const dep of module.dependencies) { - const depAsAny = /** @type {any} */ (dep); - if (dep.module) { - let importData = importedModules.get(dep.module); - if (importData === undefined) { - importedModules.set( - dep.module, - (importData = { - importVar: `m${index}`, - index, - request: - "userRequest" in depAsAny ? depAsAny.userRequest : undefined, - names: new Set(), - reexports: [] - }) - ); - index++; - } - if (dep instanceof WebAssemblyImportDependency) { - importData.names.add(dep.name); - if (dep.description.type === "GlobalType") { - const exportName = dep.name; - const usedName = dep.module && dep.module.isUsed(exportName); +var _nodes = __webpack_require__(94841); - if (dep.module) { - if (usedName) { - initParams.push( - runtimeTemplate.exportFromImport({ - module: dep.module, - request: dep.request, - importVar: importData.importVar, - originModule: module, - exportName: dep.name, - asiSafe: true, - isCall: false, - callContext: null - }) - ); - } - } - } - } - if (dep instanceof WebAssemblyExportImportedDependency) { - importData.names.add(dep.name); - const usedName = module.isUsed(dep.exportName); - if (usedName) { - const exportProp = `${module.exportsArgument}[${JSON.stringify( - usedName - )}]`; - const defineStatement = Template.asString([ - `${exportProp} = ${runtimeTemplate.exportFromImport({ - module: dep.module, - request: dep.request, - importVar: importData.importVar, - originModule: module, - exportName: dep.name, - asiSafe: true, - isCall: false, - callContext: null - })};`, - `if(WebAssembly.Global) ${exportProp} = ` + - `new WebAssembly.Global({ value: ${JSON.stringify( - dep.valueType - )} }, ${exportProp});` - ]); - importData.reexports.push(defineStatement); - needExportsCopy = true; - } - } - } - } - const importsCode = Template.asString( - Array.from( - importedModules, - ([module, { importVar, request, reexports }]) => { - const importStatement = runtimeTemplate.importStatement({ - module, - request, - importVar, - originModule: module - }); - return importStatement + reexports.join("\n"); - } - ) - ); +function numberLiteralFromRaw(rawValue) { + var instructionType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "i32"; + var original = rawValue; // Remove numeric separators _ - // create source - const source = new RawSource( - [ - '"use strict";', - "// Instantiate WebAssembly module", - "var wasmExports = __webpack_require__.w[module.i];", + if (typeof rawValue === "string") { + rawValue = rawValue.replace(/_/g, ""); + } - !Array.isArray(module.usedExports) - ? `__webpack_require__.r(${module.exportsArgument});` - : "", + if (typeof rawValue === "number") { + return (0, _nodes.numberLiteral)(rawValue, String(original)); + } else { + switch (instructionType) { + case "i32": + { + return (0, _nodes.numberLiteral)((0, _wastParser.parse32I)(rawValue), String(original)); + } - // this must be before import for circular dependencies - "// export exports from WebAssembly module", - Array.isArray(module.usedExports) && !needExportsCopy - ? `${module.moduleArgument}.exports = wasmExports;` - : "for(var name in wasmExports) " + - `if(name != ${JSON.stringify(initIdentifer)}) ` + - `${module.exportsArgument}[name] = wasmExports[name];`, - "// exec imports from WebAssembly module (for esm order)", - importsCode, - "", - "// exec wasm module", - `wasmExports[${JSON.stringify(initIdentifer)}](${initParams.join( - ", " - )})` - ].join("\n") - ); - return source; - } -} + case "u32": + { + return (0, _nodes.numberLiteral)((0, _wastParser.parseU32)(rawValue), String(original)); + } -module.exports = WebAssemblyJavascriptGenerator; + case "i64": + { + return (0, _nodes.longNumberLiteral)((0, _wastParser.parse64I)(rawValue), String(original)); + } + case "f32": + { + return (0, _nodes.floatLiteral)((0, _wastParser.parse32F)(rawValue), (0, _wastParser.isNanLiteral)(rawValue), (0, _wastParser.isInfLiteral)(rawValue), String(original)); + } + // f64 -/***/ }), + default: + { + return (0, _nodes.floatLiteral)((0, _wastParser.parse64F)(rawValue), (0, _wastParser.isNanLiteral)(rawValue), (0, _wastParser.isInfLiteral)(rawValue), String(original)); + } + } + } +} -/***/ 99510: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +function instruction(id) { + var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var namedArgs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + return (0, _nodes.instr)(id, undefined, args, namedArgs); +} -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +function objectInstruction(id, object) { + var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var namedArgs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + return (0, _nodes.instr)(id, object, args, namedArgs); +} +/** + * Decorators + */ -const Generator = __webpack_require__(39172); -const WebAssemblyExportImportedDependency = __webpack_require__(18925); -const WebAssemblyImportDependency = __webpack_require__(52959); -const WebAssemblyInInitialChunkError = __webpack_require__(45283); +function withLoc(n, end, start) { + var loc = { + start: start, + end: end + }; + n.loc = loc; + return n; +} -/** @typedef {import("../Compiler")} Compiler */ +function withRaw(n, raw) { + n.raw = raw; + return n; +} -let WebAssemblyGenerator; -let WebAssemblyJavascriptGenerator; -let WebAssemblyParser; +function funcParam(valtype, id) { + return { + id: id, + valtype: valtype + }; +} -class WebAssemblyModulesPlugin { - constructor(options) { - this.options = options; - } +function indexLiteral(value) { + // $FlowIgnore + var x = numberLiteralFromRaw(value, "u32"); + return x; +} - /** - * @param {Compiler} compiler compiler - * @returns {void} - */ - apply(compiler) { - compiler.hooks.compilation.tap( - "WebAssemblyModulesPlugin", - (compilation, { normalModuleFactory }) => { - compilation.dependencyFactories.set( - WebAssemblyImportDependency, - normalModuleFactory - ); +function memIndexLiteral(value) { + // $FlowIgnore + var x = numberLiteralFromRaw(value, "u32"); + return x; +} - compilation.dependencyFactories.set( - WebAssemblyExportImportedDependency, - normalModuleFactory - ); +/***/ }), - normalModuleFactory.hooks.createParser - .for("webassembly/experimental") - .tap("WebAssemblyModulesPlugin", () => { - if (WebAssemblyParser === undefined) { - WebAssemblyParser = __webpack_require__(77703); - } - return new WebAssemblyParser(); - }); +/***/ 89231: +/***/ (function(__unused_webpack_module, exports) { - normalModuleFactory.hooks.createGenerator - .for("webassembly/experimental") - .tap("WebAssemblyModulesPlugin", () => { - if (WebAssemblyGenerator === undefined) { - WebAssemblyGenerator = __webpack_require__(13099); - } - if (WebAssemblyJavascriptGenerator === undefined) { - WebAssemblyJavascriptGenerator = __webpack_require__(13411); - } - return Generator.byType({ - javascript: new WebAssemblyJavascriptGenerator(), - webassembly: new WebAssemblyGenerator(this.options) - }); - }); +"use strict"; - compilation.chunkTemplate.hooks.renderManifest.tap( - "WebAssemblyModulesPlugin", - (result, options) => { - const chunk = options.chunk; - const outputOptions = options.outputOptions; - const moduleTemplates = options.moduleTemplates; - const dependencyTemplates = options.dependencyTemplates; - for (const module of chunk.modulesIterable) { - if (module.type && module.type.startsWith("webassembly")) { - const filenameTemplate = - outputOptions.webassemblyModuleFilename; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createPath = createPath; - result.push({ - render: () => - this.renderWebAssembly( - module, - moduleTemplates.webassembly, - dependencyTemplates - ), - filenameTemplate, - pathOptions: { - module - }, - identifier: `webassemblyModule${module.id}`, - hash: module.hash - }); - } - } +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } - return result; - } - ); +function findParent(_ref, cb) { + var parentPath = _ref.parentPath; - compilation.hooks.afterChunks.tap("WebAssemblyModulesPlugin", () => { - const initialWasmModules = new Set(); - for (const chunk of compilation.chunks) { - if (chunk.canBeInitial()) { - for (const module of chunk.modulesIterable) { - if (module.type.startsWith("webassembly")) { - initialWasmModules.add(module); - } - } - } - } - for (const module of initialWasmModules) { - compilation.errors.push( - new WebAssemblyInInitialChunkError( - module, - compilation.requestShortener - ) - ); - } - }); - } - ); - } + if (parentPath == null) { + throw new Error("node is root"); + } - renderWebAssembly(module, moduleTemplate, dependencyTemplates) { - return moduleTemplate.render(module, dependencyTemplates, {}); - } -} + var currentPath = parentPath; -module.exports = WebAssemblyModulesPlugin; + while (cb(currentPath) !== false) { + // Hit the root node, stop + // $FlowIgnore + if (currentPath.parentPath == null) { + return null; + } // $FlowIgnore -/***/ }), + currentPath = currentPath.parentPath; + } -/***/ 77703: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return currentPath.node; +} -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +function insertBefore(context, newNode) { + return insert(context, newNode); +} +function insertAfter(context, newNode) { + return insert(context, newNode, 1); +} -const t = __webpack_require__(81875); -const { decode } = __webpack_require__(27352); -const { - moduleContextFromModuleAST -} = __webpack_require__(71234); +function insert(_ref2, newNode) { + var node = _ref2.node, + inList = _ref2.inList, + parentPath = _ref2.parentPath, + parentKey = _ref2.parentKey; + var indexOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; -const { Tapable } = __webpack_require__(56758); -const WebAssemblyImportDependency = __webpack_require__(52959); -const WebAssemblyExportImportedDependency = __webpack_require__(18925); + if (!inList) { + throw new Error('inList' + " error: " + ("insert can only be used for nodes that are within lists" || 0)); + } -/** @typedef {import("../Module")} Module */ + if (!(parentPath != null)) { + throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || 0)); + } -const JS_COMPAT_TYPES = new Set(["i32", "f32", "f64"]); + // $FlowIgnore + var parentList = parentPath.node[parentKey]; + var indexInList = parentList.findIndex(function (n) { + return n === node; + }); + parentList.splice(indexInList + indexOffset, 0, newNode); +} -/** - * @param {t.Signature} signature the func signature - * @returns {null | string} the type incompatible with js types - */ -const getJsIncompatibleType = signature => { - for (const param of signature.params) { - if (!JS_COMPAT_TYPES.has(param.valtype)) { - return `${param.valtype} as parameter`; - } - } - for (const type of signature.results) { - if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; - } - return null; -}; +function remove(_ref3) { + var node = _ref3.node, + parentKey = _ref3.parentKey, + parentPath = _ref3.parentPath; -/** - * TODO why are there two different Signature types? - * @param {t.FuncSignature} signature the func signature - * @returns {null | string} the type incompatible with js types - */ -const getJsIncompatibleTypeOfFuncSignature = signature => { - for (const param of signature.args) { - if (!JS_COMPAT_TYPES.has(param)) { - return `${param} as parameter`; - } - } - for (const type of signature.result) { - if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`; - } - return null; -}; + if (!(parentPath != null)) { + throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || 0)); + } -const decoderOpts = { - ignoreCodeSection: true, - ignoreDataSection: true, + // $FlowIgnore + var parentNode = parentPath.node; // $FlowIgnore - // this will avoid having to lookup with identifiers in the ModuleContext - ignoreCustomNameSection: true -}; + var parentProperty = parentNode[parentKey]; -class WebAssemblyParser extends Tapable { - constructor(options) { - super(); - this.hooks = {}; - this.options = options; - } + if (Array.isArray(parentProperty)) { + // $FlowIgnore + parentNode[parentKey] = parentProperty.filter(function (n) { + return n !== node; + }); + } else { + // $FlowIgnore + delete parentNode[parentKey]; + } - parse(binary, state) { - // flag it as ESM - state.module.buildMeta.exportsType = "namespace"; + node._deleted = true; +} - // parse it - const program = decode(binary, decoderOpts); - const module = program.body[0]; +function stop(context) { + context.shouldStop = true; +} - const moduleContext = moduleContextFromModuleAST(module); +function replaceWith(context, newNode) { + // $FlowIgnore + var parentNode = context.parentPath.node; // $FlowIgnore - // extract imports and exports - const exports = (state.module.buildMeta.providedExports = []); - const jsIncompatibleExports = (state.module.buildMeta.jsIncompatibleExports = []); + var parentProperty = parentNode[context.parentKey]; - const importedGlobals = []; - t.traverse(module, { - ModuleExport({ node }) { - const descriptor = node.descr; + if (Array.isArray(parentProperty)) { + var indexInList = parentProperty.findIndex(function (n) { + return n === context.node; + }); + parentProperty.splice(indexInList, 1, newNode); + } else { + // $FlowIgnore + parentNode[context.parentKey] = newNode; + } - if (descriptor.exportType === "Func") { - const funcidx = descriptor.id.value; + context.node._deleted = true; + context.node = newNode; +} // bind the context to the first argument of node operations - /** @type {t.FuncSignature} */ - const funcSignature = moduleContext.getFunction(funcidx); - const incompatibleType = getJsIncompatibleTypeOfFuncSignature( - funcSignature - ); - - if (incompatibleType) { - jsIncompatibleExports[node.name] = incompatibleType; - } - } - - exports.push(node.name); - - if (node.descr && node.descr.exportType === "Global") { - const refNode = importedGlobals[node.descr.id.value]; - if (refNode) { - const dep = new WebAssemblyExportImportedDependency( - node.name, - refNode.module, - refNode.name, - refNode.descr.valtype - ); +function bindNodeOperations(operations, context) { + var keys = Object.keys(operations); + var boundOperations = {}; + keys.forEach(function (key) { + boundOperations[key] = operations[key].bind(null, context); + }); + return boundOperations; +} - state.module.addDependency(dep); - } - } - }, +function createPathOperations(context) { + // $FlowIgnore + return bindNodeOperations({ + findParent: findParent, + replaceWith: replaceWith, + remove: remove, + insertBefore: insertBefore, + insertAfter: insertAfter, + stop: stop + }, context); +} - Global({ node }) { - const init = node.init[0]; +function createPath(context) { + var path = _extends({}, context); // $FlowIgnore - let importNode = null; - if (init.id === "get_global") { - const globalIdx = init.args[0].value; + Object.assign(path, createPathOperations(path)); // $FlowIgnore - if (globalIdx < importedGlobals.length) { - importNode = importedGlobals[globalIdx]; - } - } + return path; +} - importedGlobals.push(importNode); - }, +/***/ }), - ModuleImport({ node }) { - /** @type {false | string} */ - let onlyDirectImport = false; +/***/ 94841: +/***/ (function(__unused_webpack_module, exports) { - if (t.isMemory(node.descr) === true) { - onlyDirectImport = "Memory"; - } else if (t.isTable(node.descr) === true) { - onlyDirectImport = "Table"; - } else if (t.isFuncImportDescr(node.descr) === true) { - const incompatibleType = getJsIncompatibleType(node.descr.signature); - if (incompatibleType) { - onlyDirectImport = `Non-JS-compatible Func Sigurature (${incompatibleType})`; - } - } else if (t.isGlobalType(node.descr) === true) { - const type = node.descr.valtype; - if (!JS_COMPAT_TYPES.has(type)) { - onlyDirectImport = `Non-JS-compatible Global Type (${type})`; - } - } +"use strict"; - const dep = new WebAssemblyImportDependency( - node.module, - node.name, - node.descr, - onlyDirectImport - ); - state.module.addDependency(dep); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.module = _module; +exports.moduleMetadata = moduleMetadata; +exports.moduleNameMetadata = moduleNameMetadata; +exports.functionNameMetadata = functionNameMetadata; +exports.localNameMetadata = localNameMetadata; +exports.binaryModule = binaryModule; +exports.quoteModule = quoteModule; +exports.sectionMetadata = sectionMetadata; +exports.producersSectionMetadata = producersSectionMetadata; +exports.producerMetadata = producerMetadata; +exports.producerMetadataVersionedName = producerMetadataVersionedName; +exports.loopInstruction = loopInstruction; +exports.instr = instr; +exports.ifInstruction = ifInstruction; +exports.stringLiteral = stringLiteral; +exports.numberLiteral = numberLiteral; +exports.longNumberLiteral = longNumberLiteral; +exports.floatLiteral = floatLiteral; +exports.elem = elem; +exports.indexInFuncSection = indexInFuncSection; +exports.valtypeLiteral = valtypeLiteral; +exports.typeInstruction = typeInstruction; +exports.start = start; +exports.globalType = globalType; +exports.leadingComment = leadingComment; +exports.blockComment = blockComment; +exports.data = data; +exports.global = global; +exports.table = table; +exports.memory = memory; +exports.funcImportDescr = funcImportDescr; +exports.moduleImport = moduleImport; +exports.moduleExportDescr = moduleExportDescr; +exports.moduleExport = moduleExport; +exports.limit = limit; +exports.signature = signature; +exports.program = program; +exports.identifier = identifier; +exports.blockInstruction = blockInstruction; +exports.callInstruction = callInstruction; +exports.callIndirectInstruction = callIndirectInstruction; +exports.byteArray = byteArray; +exports.func = func; +exports.internalBrUnless = internalBrUnless; +exports.internalGoto = internalGoto; +exports.internalCallExtern = internalCallExtern; +exports.internalEndAndReturn = internalEndAndReturn; +exports.assertInternalCallExtern = exports.assertInternalGoto = exports.assertInternalBrUnless = exports.assertFunc = exports.assertByteArray = exports.assertCallIndirectInstruction = exports.assertCallInstruction = exports.assertBlockInstruction = exports.assertIdentifier = exports.assertProgram = exports.assertSignature = exports.assertLimit = exports.assertModuleExport = exports.assertModuleExportDescr = exports.assertModuleImport = exports.assertFuncImportDescr = exports.assertMemory = exports.assertTable = exports.assertGlobal = exports.assertData = exports.assertBlockComment = exports.assertLeadingComment = exports.assertGlobalType = exports.assertStart = exports.assertTypeInstruction = exports.assertValtypeLiteral = exports.assertIndexInFuncSection = exports.assertElem = exports.assertFloatLiteral = exports.assertLongNumberLiteral = exports.assertNumberLiteral = exports.assertStringLiteral = exports.assertIfInstruction = exports.assertInstr = exports.assertLoopInstruction = exports.assertProducerMetadataVersionedName = exports.assertProducerMetadata = exports.assertProducersSectionMetadata = exports.assertSectionMetadata = exports.assertQuoteModule = exports.assertBinaryModule = exports.assertLocalNameMetadata = exports.assertFunctionNameMetadata = exports.assertModuleNameMetadata = exports.assertModuleMetadata = exports.assertModule = exports.isIntrinsic = exports.isImportDescr = exports.isNumericLiteral = exports.isExpression = exports.isInstruction = exports.isBlock = exports.isNode = exports.isInternalEndAndReturn = exports.isInternalCallExtern = exports.isInternalGoto = exports.isInternalBrUnless = exports.isFunc = exports.isByteArray = exports.isCallIndirectInstruction = exports.isCallInstruction = exports.isBlockInstruction = exports.isIdentifier = exports.isProgram = exports.isSignature = exports.isLimit = exports.isModuleExport = exports.isModuleExportDescr = exports.isModuleImport = exports.isFuncImportDescr = exports.isMemory = exports.isTable = exports.isGlobal = exports.isData = exports.isBlockComment = exports.isLeadingComment = exports.isGlobalType = exports.isStart = exports.isTypeInstruction = exports.isValtypeLiteral = exports.isIndexInFuncSection = exports.isElem = exports.isFloatLiteral = exports.isLongNumberLiteral = exports.isNumberLiteral = exports.isStringLiteral = exports.isIfInstruction = exports.isInstr = exports.isLoopInstruction = exports.isProducerMetadataVersionedName = exports.isProducerMetadata = exports.isProducersSectionMetadata = exports.isSectionMetadata = exports.isQuoteModule = exports.isBinaryModule = exports.isLocalNameMetadata = exports.isFunctionNameMetadata = exports.isModuleNameMetadata = exports.isModuleMetadata = exports.isModule = void 0; +exports.nodeAndUnionTypes = exports.unionTypesMap = exports.assertInternalEndAndReturn = void 0; - if (t.isGlobalType(node.descr)) { - importedGlobals.push(node); - } - } - }); +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - return state; - } +// THIS FILE IS AUTOGENERATED +// see scripts/generateNodeUtils.js +function isTypeOf(t) { + return function (n) { + return n.type === t; + }; } -module.exports = WebAssemblyParser; - - -/***/ }), +function assertTypeOf(t) { + return function (n) { + return function () { + if (!(n.type === t)) { + throw new Error('n.type === t' + " error: " + (undefined || "unknown")); + } + }(); + }; +} -/***/ 52136: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { +function _module(id, fields, metadata) { + if (id !== null && id !== undefined) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (!(_typeof(fields) === "object" && typeof fields.length !== "undefined")) { + throw new Error('typeof fields === "object" && typeof fields.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + var node = { + type: "Module", + id: id, + fields: fields + }; -const Template = __webpack_require__(96066); -const WebAssemblyImportDependency = __webpack_require__(52959); + if (typeof metadata !== "undefined") { + node.metadata = metadata; + } -/** @typedef {import("../Module")} Module */ + return node; +} -/** @typedef {Object} UsedWasmDependency - * @property {WebAssemblyImportDependency} dependency the dependency - * @property {string} name the export name - * @property {string} module the module name - */ +function moduleMetadata(sections, functionNames, localNames, producers) { + if (!(_typeof(sections) === "object" && typeof sections.length !== "undefined")) { + throw new Error('typeof sections === "object" && typeof sections.length !== "undefined"' + " error: " + (undefined || "unknown")); + } -const MANGLED_MODULE = "a"; + if (functionNames !== null && functionNames !== undefined) { + if (!(_typeof(functionNames) === "object" && typeof functionNames.length !== "undefined")) { + throw new Error('typeof functionNames === "object" && typeof functionNames.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } -/** - * @param {Module} module the module - * @param {boolean} mangle mangle module and export names - * @returns {UsedWasmDependency[]} used dependencies and (mangled) name - */ -const getUsedDependencies = (module, mangle) => { - /** @type {UsedWasmDependency[]} */ - const array = []; - let importIndex = 0; - for (const dep of module.dependencies) { - if (dep instanceof WebAssemblyImportDependency) { - if (dep.description.type === "GlobalType" || dep.module === null) { - continue; - } + if (localNames !== null && localNames !== undefined) { + if (!(_typeof(localNames) === "object" && typeof localNames.length !== "undefined")) { + throw new Error('typeof localNames === "object" && typeof localNames.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } - const exportName = dep.name; - // TODO add the following 3 lines when removing of ModuleExport is possible - // const importedModule = dep.module; - // const usedName = importedModule && importedModule.isUsed(exportName); - // if (usedName !== false) { - if (mangle) { - array.push({ - dependency: dep, - name: Template.numberToIdentifer(importIndex++), - module: MANGLED_MODULE - }); - } else { - array.push({ - dependency: dep, - name: exportName, - module: dep.request - }); - } - } - } - return array; -}; + if (producers !== null && producers !== undefined) { + if (!(_typeof(producers) === "object" && typeof producers.length !== "undefined")) { + throw new Error('typeof producers === "object" && typeof producers.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } -exports.getUsedDependencies = getUsedDependencies; -exports.MANGLED_MODULE = MANGLED_MODULE; + var node = { + type: "ModuleMetadata", + sections: sections + }; + if (typeof functionNames !== "undefined" && functionNames.length > 0) { + node.functionNames = functionNames; + } -/***/ }), + if (typeof localNames !== "undefined" && localNames.length > 0) { + node.localNames = localNames; + } -/***/ 52669: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (typeof producers !== "undefined" && producers.length > 0) { + node.producers = producers; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + return node; +} +function moduleNameMetadata(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } -const WasmMainTemplatePlugin = __webpack_require__(65331); + var node = { + type: "ModuleNameMetadata", + value: value + }; + return node; +} -class FetchCompileWasmTemplatePlugin { - constructor(options) { - this.options = options || {}; - } +function functionNameMetadata(value, index) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "FetchCompileWasmTemplatePlugin", - compilation => { - const mainTemplate = compilation.mainTemplate; - const generateLoadBinaryCode = path => - `fetch(${mainTemplate.requireFn}.p + ${path})`; + if (!(typeof index === "number")) { + throw new Error('typeof index === "number"' + " error: " + ("Argument index must be of type number, given: " + _typeof(index) || 0)); + } - const plugin = new WasmMainTemplatePlugin( - Object.assign( - { - generateLoadBinaryCode, - supportsStreaming: true - }, - this.options - ) - ); - plugin.apply(mainTemplate); - } - ); - } + var node = { + type: "FunctionNameMetadata", + value: value, + index: index + }; + return node; } -module.exports = FetchCompileWasmTemplatePlugin; +function localNameMetadata(value, localIndex, functionIndex) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + if (!(typeof localIndex === "number")) { + throw new Error('typeof localIndex === "number"' + " error: " + ("Argument localIndex must be of type number, given: " + _typeof(localIndex) || 0)); + } -/***/ }), + if (!(typeof functionIndex === "number")) { + throw new Error('typeof functionIndex === "number"' + " error: " + ("Argument functionIndex must be of type number, given: " + _typeof(functionIndex) || 0)); + } -/***/ 31898: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + var node = { + type: "LocalNameMetadata", + value: value, + localIndex: localIndex, + functionIndex: functionIndex + }; + return node; +} -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +function binaryModule(id, blob) { + if (id !== null && id !== undefined) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + } + if (!(_typeof(blob) === "object" && typeof blob.length !== "undefined")) { + throw new Error('typeof blob === "object" && typeof blob.length !== "undefined"' + " error: " + (undefined || "unknown")); + } -const { ConcatSource } = __webpack_require__(53665); + var node = { + type: "BinaryModule", + id: id, + blob: blob + }; + return node; +} -/** @typedef {import("../ChunkTemplate")} ChunkTemplate */ +function quoteModule(id, string) { + if (id !== null && id !== undefined) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + } -const getEntryInfo = chunk => { - return [chunk.entryModule].filter(Boolean).map(m => - [m.id].concat( - Array.from(chunk.groupsIterable)[0] - .chunks.filter(c => c !== chunk) - .map(c => c.id) - ) - ); -}; + if (!(_typeof(string) === "object" && typeof string.length !== "undefined")) { + throw new Error('typeof string === "object" && typeof string.length !== "undefined"' + " error: " + (undefined || "unknown")); + } -class JsonpChunkTemplatePlugin { - /** - * @param {ChunkTemplate} chunkTemplate the chunk template - * @returns {void} - */ - apply(chunkTemplate) { - chunkTemplate.hooks.render.tap( - "JsonpChunkTemplatePlugin", - (modules, chunk) => { - const jsonpFunction = chunkTemplate.outputOptions.jsonpFunction; - const globalObject = chunkTemplate.outputOptions.globalObject; - const source = new ConcatSource(); - const prefetchChunks = chunk.getChildIdsByOrders().prefetch; - source.add( - `(${globalObject}[${JSON.stringify( - jsonpFunction - )}] = ${globalObject}[${JSON.stringify( - jsonpFunction - )}] || []).push([${JSON.stringify(chunk.ids)},` - ); - source.add(modules); - const entries = getEntryInfo(chunk); - if (entries.length > 0) { - source.add(`,${JSON.stringify(entries)}`); - } else if (prefetchChunks && prefetchChunks.length) { - source.add(`,0`); - } + var node = { + type: "QuoteModule", + id: id, + string: string + }; + return node; +} - if (prefetchChunks && prefetchChunks.length) { - source.add(`,${JSON.stringify(prefetchChunks)}`); - } - source.add("])"); - return source; - } - ); - chunkTemplate.hooks.hash.tap("JsonpChunkTemplatePlugin", hash => { - hash.update("JsonpChunkTemplatePlugin"); - hash.update("4"); - hash.update(`${chunkTemplate.outputOptions.jsonpFunction}`); - hash.update(`${chunkTemplate.outputOptions.globalObject}`); - }); - chunkTemplate.hooks.hashForChunk.tap( - "JsonpChunkTemplatePlugin", - (hash, chunk) => { - hash.update(JSON.stringify(getEntryInfo(chunk))); - hash.update(JSON.stringify(chunk.getChildIdsByOrders().prefetch) || ""); - } - ); - } +function sectionMetadata(section, startOffset, size, vectorOfSize) { + if (!(typeof startOffset === "number")) { + throw new Error('typeof startOffset === "number"' + " error: " + ("Argument startOffset must be of type number, given: " + _typeof(startOffset) || 0)); + } + + var node = { + type: "SectionMetadata", + section: section, + startOffset: startOffset, + size: size, + vectorOfSize: vectorOfSize + }; + return node; } -module.exports = JsonpChunkTemplatePlugin; +function producersSectionMetadata(producers) { + if (!(_typeof(producers) === "object" && typeof producers.length !== "undefined")) { + throw new Error('typeof producers === "object" && typeof producers.length !== "undefined"' + " error: " + (undefined || "unknown")); + } -/***/ }), + var node = { + type: "ProducersSectionMetadata", + producers: producers + }; + return node; +} -/***/ 13732: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +function producerMetadata(language, processedBy, sdk) { + if (!(_typeof(language) === "object" && typeof language.length !== "undefined")) { + throw new Error('typeof language === "object" && typeof language.length !== "undefined"' + " error: " + (undefined || "unknown")); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (!(_typeof(processedBy) === "object" && typeof processedBy.length !== "undefined")) { + throw new Error('typeof processedBy === "object" && typeof processedBy.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + if (!(_typeof(sdk) === "object" && typeof sdk.length !== "undefined")) { + throw new Error('typeof sdk === "object" && typeof sdk.length !== "undefined"' + " error: " + (undefined || "unknown")); + } -const { ConcatSource } = __webpack_require__(53665); + var node = { + type: "ProducerMetadata", + language: language, + processedBy: processedBy, + sdk: sdk + }; + return node; +} -class JsonpExportMainTemplatePlugin { - /** - * @param {string} name jsonp function name - */ - constructor(name) { - this.name = name; - } +function producerMetadataVersionedName(name, version) { + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); + } - apply(compilation) { - const { mainTemplate, chunkTemplate } = compilation; + if (!(typeof version === "string")) { + throw new Error('typeof version === "string"' + " error: " + ("Argument version must be of type string, given: " + _typeof(version) || 0)); + } - const onRenderWithEntry = (source, chunk, hash) => { - const name = mainTemplate.getAssetPath(this.name || "", { - hash, - chunk - }); - return new ConcatSource(`${name}(`, source, ");"); - }; - - for (const template of [mainTemplate, chunkTemplate]) { - template.hooks.renderWithEntry.tap( - "JsonpExportMainTemplatePlugin", - onRenderWithEntry - ); - } + var node = { + type: "ProducerMetadataVersionedName", + name: name, + version: version + }; + return node; +} - mainTemplate.hooks.globalHashPaths.tap( - "JsonpExportMainTemplatePlugin", - paths => { - if (this.name) paths.push(this.name); - return paths; - } - ); +function loopInstruction(label, resulttype, instr) { + if (!(_typeof(instr) === "object" && typeof instr.length !== "undefined")) { + throw new Error('typeof instr === "object" && typeof instr.length !== "undefined"' + " error: " + (undefined || "unknown")); + } - mainTemplate.hooks.hash.tap("JsonpExportMainTemplatePlugin", hash => { - hash.update("jsonp export"); - hash.update(`${this.name}`); - }); - } + var node = { + type: "LoopInstruction", + id: "loop", + label: label, + resulttype: resulttype, + instr: instr + }; + return node; } -module.exports = JsonpExportMainTemplatePlugin; +function instr(id, object, args, namedArgs) { + if (!(typeof id === "string")) { + throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + } + if (!(_typeof(args) === "object" && typeof args.length !== "undefined")) { + throw new Error('typeof args === "object" && typeof args.length !== "undefined"' + " error: " + (undefined || "unknown")); + } -/***/ }), + var node = { + type: "Instr", + id: id, + args: args + }; -/***/ 44458: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (typeof object !== "undefined") { + node.object = object; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + if (typeof namedArgs !== "undefined" && Object.keys(namedArgs).length !== 0) { + node.namedArgs = namedArgs; + } + return node; +} -const { ConcatSource } = __webpack_require__(53665); +function ifInstruction(testLabel, test, result, consequent, alternate) { + if (!(_typeof(test) === "object" && typeof test.length !== "undefined")) { + throw new Error('typeof test === "object" && typeof test.length !== "undefined"' + " error: " + (undefined || "unknown")); + } -class JsonpHotUpdateChunkTemplatePlugin { - apply(hotUpdateChunkTemplate) { - hotUpdateChunkTemplate.hooks.render.tap( - "JsonpHotUpdateChunkTemplatePlugin", - (modulesSource, modules, removedModules, hash, id) => { - const source = new ConcatSource(); - source.add( - `${ - hotUpdateChunkTemplate.outputOptions.hotUpdateFunction - }(${JSON.stringify(id)},` - ); - source.add(modulesSource); - source.add(")"); - return source; - } - ); - hotUpdateChunkTemplate.hooks.hash.tap( - "JsonpHotUpdateChunkTemplatePlugin", - hash => { - hash.update("JsonpHotUpdateChunkTemplatePlugin"); - hash.update("3"); - hash.update( - `${hotUpdateChunkTemplate.outputOptions.hotUpdateFunction}` - ); - hash.update(`${hotUpdateChunkTemplate.outputOptions.library}`); - } - ); - } + if (!(_typeof(consequent) === "object" && typeof consequent.length !== "undefined")) { + throw new Error('typeof consequent === "object" && typeof consequent.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(alternate) === "object" && typeof alternate.length !== "undefined")) { + throw new Error('typeof alternate === "object" && typeof alternate.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "IfInstruction", + id: "if", + testLabel: testLabel, + test: test, + result: result, + consequent: consequent, + alternate: alternate + }; + return node; } -module.exports = JsonpHotUpdateChunkTemplatePlugin; +function stringLiteral(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + var node = { + type: "StringLiteral", + value: value + }; + return node; +} -/***/ }), +function numberLiteral(value, raw) { + if (!(typeof value === "number")) { + throw new Error('typeof value === "number"' + " error: " + ("Argument value must be of type number, given: " + _typeof(value) || 0)); + } -/***/ 24916: -/***/ (function(module) { + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -// eslint-disable-next-line no-unused-vars -var hotAddUpdateChunk = undefined; -var parentHotUpdateCallback = undefined; -var $require$ = undefined; -var $hotMainFilename$ = undefined; -var $hotChunkFilename$ = undefined; -var $crossOriginLoading$ = undefined; + var node = { + type: "NumberLiteral", + value: value, + raw: raw + }; + return node; +} -module.exports = function() { - // eslint-disable-next-line no-unused-vars - function webpackHotUpdateCallback(chunkId, moreModules) { - hotAddUpdateChunk(chunkId, moreModules); - if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); - } //$semicolon +function longNumberLiteral(value, raw) { + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } - // eslint-disable-next-line no-unused-vars - function hotDownloadUpdateChunk(chunkId) { - var script = document.createElement("script"); - script.charset = "utf-8"; - script.src = $require$.p + $hotChunkFilename$; - if ($crossOriginLoading$) script.crossOrigin = $crossOriginLoading$; - document.head.appendChild(script); - } + var node = { + type: "LongNumberLiteral", + value: value, + raw: raw + }; + return node; +} - // eslint-disable-next-line no-unused-vars - function hotDownloadManifest(requestTimeout) { - requestTimeout = requestTimeout || 10000; - return new Promise(function(resolve, reject) { - if (typeof XMLHttpRequest === "undefined") { - return reject(new Error("No browser support")); - } - try { - var request = new XMLHttpRequest(); - var requestPath = $require$.p + $hotMainFilename$; - request.open("GET", requestPath, true); - request.timeout = requestTimeout; - request.send(null); - } catch (err) { - return reject(err); - } - request.onreadystatechange = function() { - if (request.readyState !== 4) return; - if (request.status === 0) { - // timeout - reject( - new Error("Manifest request to " + requestPath + " timed out.") - ); - } else if (request.status === 404) { - // no update available - resolve(); - } else if (request.status !== 200 && request.status !== 304) { - // other failure - reject(new Error("Manifest request to " + requestPath + " failed.")); - } else { - // success - try { - var update = JSON.parse(request.responseText); - } catch (e) { - reject(e); - return; - } - resolve(update); - } - }; - }); - } -}; +function floatLiteral(value, nan, inf, raw) { + if (!(typeof value === "number")) { + throw new Error('typeof value === "number"' + " error: " + ("Argument value must be of type number, given: " + _typeof(value) || 0)); + } + if (nan !== null && nan !== undefined) { + if (!(typeof nan === "boolean")) { + throw new Error('typeof nan === "boolean"' + " error: " + ("Argument nan must be of type boolean, given: " + _typeof(nan) || 0)); + } + } -/***/ }), + if (inf !== null && inf !== undefined) { + if (!(typeof inf === "boolean")) { + throw new Error('typeof inf === "boolean"' + " error: " + ("Argument inf must be of type boolean, given: " + _typeof(inf) || 0)); + } + } -/***/ 38017: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + var node = { + type: "FloatLiteral", + value: value, + raw: raw + }; + if (nan === true) { + node.nan = true; + } -const { SyncWaterfallHook } = __webpack_require__(56758); -const Template = __webpack_require__(96066); + if (inf === true) { + node.inf = true; + } -class JsonpMainTemplatePlugin { - apply(mainTemplate) { - const needChunkOnDemandLoadingCode = chunk => { - for (const chunkGroup of chunk.groupsIterable) { - if (chunkGroup.getNumberOfChildren() > 0) return true; - } - return false; - }; - const needChunkLoadingCode = chunk => { - for (const chunkGroup of chunk.groupsIterable) { - if (chunkGroup.chunks.length > 1) return true; - if (chunkGroup.getNumberOfChildren() > 0) return true; - } - return false; - }; - const needEntryDeferringCode = chunk => { - for (const chunkGroup of chunk.groupsIterable) { - if (chunkGroup.chunks.length > 1) return true; - } - return false; - }; - const needPrefetchingCode = chunk => { - const allPrefetchChunks = chunk.getChildIdsByOrdersMap(true).prefetch; - return allPrefetchChunks && Object.keys(allPrefetchChunks).length; - }; + return node; +} - // TODO webpack 5, no adding to .hooks, use WeakMap and static methods - ["jsonpScript", "linkPreload", "linkPrefetch"].forEach(hook => { - if (!mainTemplate.hooks[hook]) { - mainTemplate.hooks[hook] = new SyncWaterfallHook([ - "source", - "chunk", - "hash" - ]); - } - }); +function elem(table, offset, funcs) { + if (!(_typeof(offset) === "object" && typeof offset.length !== "undefined")) { + throw new Error('typeof offset === "object" && typeof offset.length !== "undefined"' + " error: " + (undefined || "unknown")); + } - const getScriptSrcPath = (hash, chunk, chunkIdExpression) => { - const chunkFilename = mainTemplate.outputOptions.chunkFilename; - const chunkMaps = chunk.getChunkMaps(); - return mainTemplate.getAssetPath(JSON.stringify(chunkFilename), { - hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, - hashWithLength: length => - `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, - chunk: { - id: `" + ${chunkIdExpression} + "`, - hash: `" + ${JSON.stringify( - chunkMaps.hash - )}[${chunkIdExpression}] + "`, - hashWithLength(length) { - const shortChunkHashMap = Object.create(null); - for (const chunkId of Object.keys(chunkMaps.hash)) { - if (typeof chunkMaps.hash[chunkId] === "string") { - shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( - 0, - length - ); - } - } - return `" + ${JSON.stringify( - shortChunkHashMap - )}[${chunkIdExpression}] + "`; - }, - name: `" + (${JSON.stringify( - chunkMaps.name - )}[${chunkIdExpression}]||${chunkIdExpression}) + "`, - contentHash: { - javascript: `" + ${JSON.stringify( - chunkMaps.contentHash.javascript - )}[${chunkIdExpression}] + "` - }, - contentHashWithLength: { - javascript: length => { - const shortContentHashMap = {}; - const contentHash = chunkMaps.contentHash.javascript; - for (const chunkId of Object.keys(contentHash)) { - if (typeof contentHash[chunkId] === "string") { - shortContentHashMap[chunkId] = contentHash[chunkId].substr( - 0, - length - ); - } - } - return `" + ${JSON.stringify( - shortContentHashMap - )}[${chunkIdExpression}] + "`; - } - } - }, - contentHashType: "javascript" - }); - }; - mainTemplate.hooks.localVars.tap( - "JsonpMainTemplatePlugin", - (source, chunk, hash) => { - const extraCode = []; - if (needChunkLoadingCode(chunk)) { - extraCode.push( - "", - "// object to store loaded and loading chunks", - "// undefined = chunk not loaded, null = chunk preloaded/prefetched", - "// Promise = chunk loading, 0 = chunk loaded", - "var installedChunks = {", - Template.indent( - chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n") - ), - "};", - "", - needEntryDeferringCode(chunk) - ? needPrefetchingCode(chunk) - ? "var deferredModules = [], deferredPrefetch = [];" - : "var deferredModules = [];" - : "" - ); - } - if (needChunkOnDemandLoadingCode(chunk)) { - extraCode.push( - "", - "// script path function", - "function jsonpScriptSrc(chunkId) {", - Template.indent([ - `return ${mainTemplate.requireFn}.p + ${getScriptSrcPath( - hash, - chunk, - "chunkId" - )}` - ]), - "}" - ); - } - if (extraCode.length === 0) return source; - return Template.asString([source, ...extraCode]); - } - ); + if (!(_typeof(funcs) === "object" && typeof funcs.length !== "undefined")) { + throw new Error('typeof funcs === "object" && typeof funcs.length !== "undefined"' + " error: " + (undefined || "unknown")); + } - mainTemplate.hooks.jsonpScript.tap( - "JsonpMainTemplatePlugin", - (_, chunk, hash) => { - const crossOriginLoading = - mainTemplate.outputOptions.crossOriginLoading; - const chunkLoadTimeout = mainTemplate.outputOptions.chunkLoadTimeout; - const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; + var node = { + type: "Elem", + table: table, + offset: offset, + funcs: funcs + }; + return node; +} - return Template.asString([ - "var script = document.createElement('script');", - "var onScriptComplete;", - jsonpScriptType - ? `script.type = ${JSON.stringify(jsonpScriptType)};` - : "", - "script.charset = 'utf-8';", - `script.timeout = ${chunkLoadTimeout / 1000};`, - `if (${mainTemplate.requireFn}.nc) {`, - Template.indent( - `script.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` - ), - "}", - "script.src = jsonpScriptSrc(chunkId);", - crossOriginLoading - ? Template.asString([ - "if (script.src.indexOf(window.location.origin + '/') !== 0) {", - Template.indent( - `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` - ), - "}" - ]) - : "", - "// create error before stack unwound to get useful stacktrace later", - "var error = new Error();", - "onScriptComplete = function (event) {", - Template.indent([ - "// avoid mem leaks in IE.", - "script.onerror = script.onload = null;", - "clearTimeout(timeout);", - "var chunk = installedChunks[chunkId];", - "if(chunk !== 0) {", - Template.indent([ - "if(chunk) {", - Template.indent([ - "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", - "var realSrc = event && event.target && event.target.src;", - "error.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';", - "error.name = 'ChunkLoadError';", - "error.type = errorType;", - "error.request = realSrc;", - "chunk[1](error);" - ]), - "}", - "installedChunks[chunkId] = undefined;" - ]), - "}" - ]), - "};", - "var timeout = setTimeout(function(){", - Template.indent([ - "onScriptComplete({ type: 'timeout', target: script });" - ]), - `}, ${chunkLoadTimeout});`, - "script.onerror = script.onload = onScriptComplete;" - ]); - } - ); - mainTemplate.hooks.linkPreload.tap( - "JsonpMainTemplatePlugin", - (_, chunk, hash) => { - const crossOriginLoading = - mainTemplate.outputOptions.crossOriginLoading; - const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; +function indexInFuncSection(index) { + var node = { + type: "IndexInFuncSection", + index: index + }; + return node; +} - return Template.asString([ - "var link = document.createElement('link');", - jsonpScriptType - ? `link.type = ${JSON.stringify(jsonpScriptType)};` - : "", - "link.charset = 'utf-8';", - `if (${mainTemplate.requireFn}.nc) {`, - Template.indent( - `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` - ), - "}", - 'link.rel = "preload";', - 'link.as = "script";', - "link.href = jsonpScriptSrc(chunkId);", - crossOriginLoading - ? Template.asString([ - "if (link.href.indexOf(window.location.origin + '/') !== 0) {", - Template.indent( - `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` - ), - "}" - ]) - : "" - ]); - } - ); - mainTemplate.hooks.linkPrefetch.tap( - "JsonpMainTemplatePlugin", - (_, chunk, hash) => { - const crossOriginLoading = - mainTemplate.outputOptions.crossOriginLoading; +function valtypeLiteral(name) { + var node = { + type: "ValtypeLiteral", + name: name + }; + return node; +} + +function typeInstruction(id, functype) { + var node = { + type: "TypeInstruction", + id: id, + functype: functype + }; + return node; +} + +function start(index) { + var node = { + type: "Start", + index: index + }; + return node; +} + +function globalType(valtype, mutability) { + var node = { + type: "GlobalType", + valtype: valtype, + mutability: mutability + }; + return node; +} + +function leadingComment(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + var node = { + type: "LeadingComment", + value: value + }; + return node; +} + +function blockComment(value) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + var node = { + type: "BlockComment", + value: value + }; + return node; +} + +function data(memoryIndex, offset, init) { + var node = { + type: "Data", + memoryIndex: memoryIndex, + offset: offset, + init: init + }; + return node; +} + +function global(globalType, init, name) { + if (!(_typeof(init) === "object" && typeof init.length !== "undefined")) { + throw new Error('typeof init === "object" && typeof init.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Global", + globalType: globalType, + init: init, + name: name + }; + return node; +} + +function table(elementType, limits, name, elements) { + if (!(limits.type === "Limit")) { + throw new Error('limits.type === "Limit"' + " error: " + ("Argument limits must be of type Limit, given: " + limits.type || 0)); + } + + if (elements !== null && elements !== undefined) { + if (!(_typeof(elements) === "object" && typeof elements.length !== "undefined")) { + throw new Error('typeof elements === "object" && typeof elements.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + var node = { + type: "Table", + elementType: elementType, + limits: limits, + name: name + }; + + if (typeof elements !== "undefined" && elements.length > 0) { + node.elements = elements; + } + + return node; +} + +function memory(limits, id) { + var node = { + type: "Memory", + limits: limits, + id: id + }; + return node; +} + +function funcImportDescr(id, signature) { + var node = { + type: "FuncImportDescr", + id: id, + signature: signature + }; + return node; +} + +function moduleImport(module, name, descr) { + if (!(typeof module === "string")) { + throw new Error('typeof module === "string"' + " error: " + ("Argument module must be of type string, given: " + _typeof(module) || 0)); + } + + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); + } + + var node = { + type: "ModuleImport", + module: module, + name: name, + descr: descr + }; + return node; +} + +function moduleExportDescr(exportType, id) { + var node = { + type: "ModuleExportDescr", + exportType: exportType, + id: id + }; + return node; +} + +function moduleExport(name, descr) { + if (!(typeof name === "string")) { + throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); + } + + var node = { + type: "ModuleExport", + name: name, + descr: descr + }; + return node; +} + +function limit(min, max) { + if (!(typeof min === "number")) { + throw new Error('typeof min === "number"' + " error: " + ("Argument min must be of type number, given: " + _typeof(min) || 0)); + } + + if (max !== null && max !== undefined) { + if (!(typeof max === "number")) { + throw new Error('typeof max === "number"' + " error: " + ("Argument max must be of type number, given: " + _typeof(max) || 0)); + } + } + + var node = { + type: "Limit", + min: min + }; + + if (typeof max !== "undefined") { + node.max = max; + } + + return node; +} + +function signature(params, results) { + if (!(_typeof(params) === "object" && typeof params.length !== "undefined")) { + throw new Error('typeof params === "object" && typeof params.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (!(_typeof(results) === "object" && typeof results.length !== "undefined")) { + throw new Error('typeof results === "object" && typeof results.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Signature", + params: params, + results: results + }; + return node; +} + +function program(body) { + if (!(_typeof(body) === "object" && typeof body.length !== "undefined")) { + throw new Error('typeof body === "object" && typeof body.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "Program", + body: body + }; + return node; +} + +function identifier(value, raw) { + if (!(typeof value === "string")) { + throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + } + + if (raw !== null && raw !== undefined) { + if (!(typeof raw === "string")) { + throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + } + } + + var node = { + type: "Identifier", + value: value + }; + + if (typeof raw !== "undefined") { + node.raw = raw; + } + + return node; +} + +function blockInstruction(label, instr, result) { + if (!(_typeof(instr) === "object" && typeof instr.length !== "undefined")) { + throw new Error('typeof instr === "object" && typeof instr.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "BlockInstruction", + id: "block", + label: label, + instr: instr, + result: result + }; + return node; +} + +function callInstruction(index, instrArgs, numeric) { + if (instrArgs !== null && instrArgs !== undefined) { + if (!(_typeof(instrArgs) === "object" && typeof instrArgs.length !== "undefined")) { + throw new Error('typeof instrArgs === "object" && typeof instrArgs.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + var node = { + type: "CallInstruction", + id: "call", + index: index + }; + + if (typeof instrArgs !== "undefined" && instrArgs.length > 0) { + node.instrArgs = instrArgs; + } + + if (typeof numeric !== "undefined") { + node.numeric = numeric; + } + + return node; +} + +function callIndirectInstruction(signature, intrs) { + if (intrs !== null && intrs !== undefined) { + if (!(_typeof(intrs) === "object" && typeof intrs.length !== "undefined")) { + throw new Error('typeof intrs === "object" && typeof intrs.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + } + + var node = { + type: "CallIndirectInstruction", + id: "call_indirect", + signature: signature + }; + + if (typeof intrs !== "undefined" && intrs.length > 0) { + node.intrs = intrs; + } + + return node; +} + +function byteArray(values) { + if (!(_typeof(values) === "object" && typeof values.length !== "undefined")) { + throw new Error('typeof values === "object" && typeof values.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + var node = { + type: "ByteArray", + values: values + }; + return node; +} + +function func(name, signature, body, isExternal, metadata) { + if (!(_typeof(body) === "object" && typeof body.length !== "undefined")) { + throw new Error('typeof body === "object" && typeof body.length !== "undefined"' + " error: " + (undefined || "unknown")); + } + + if (isExternal !== null && isExternal !== undefined) { + if (!(typeof isExternal === "boolean")) { + throw new Error('typeof isExternal === "boolean"' + " error: " + ("Argument isExternal must be of type boolean, given: " + _typeof(isExternal) || 0)); + } + } + + var node = { + type: "Func", + name: name, + signature: signature, + body: body + }; + + if (isExternal === true) { + node.isExternal = true; + } + + if (typeof metadata !== "undefined") { + node.metadata = metadata; + } + + return node; +} + +function internalBrUnless(target) { + if (!(typeof target === "number")) { + throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); + } + + var node = { + type: "InternalBrUnless", + target: target + }; + return node; +} + +function internalGoto(target) { + if (!(typeof target === "number")) { + throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); + } + + var node = { + type: "InternalGoto", + target: target + }; + return node; +} + +function internalCallExtern(target) { + if (!(typeof target === "number")) { + throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); + } + + var node = { + type: "InternalCallExtern", + target: target + }; + return node; +} + +function internalEndAndReturn() { + var node = { + type: "InternalEndAndReturn" + }; + return node; +} + +var isModule = isTypeOf("Module"); +exports.isModule = isModule; +var isModuleMetadata = isTypeOf("ModuleMetadata"); +exports.isModuleMetadata = isModuleMetadata; +var isModuleNameMetadata = isTypeOf("ModuleNameMetadata"); +exports.isModuleNameMetadata = isModuleNameMetadata; +var isFunctionNameMetadata = isTypeOf("FunctionNameMetadata"); +exports.isFunctionNameMetadata = isFunctionNameMetadata; +var isLocalNameMetadata = isTypeOf("LocalNameMetadata"); +exports.isLocalNameMetadata = isLocalNameMetadata; +var isBinaryModule = isTypeOf("BinaryModule"); +exports.isBinaryModule = isBinaryModule; +var isQuoteModule = isTypeOf("QuoteModule"); +exports.isQuoteModule = isQuoteModule; +var isSectionMetadata = isTypeOf("SectionMetadata"); +exports.isSectionMetadata = isSectionMetadata; +var isProducersSectionMetadata = isTypeOf("ProducersSectionMetadata"); +exports.isProducersSectionMetadata = isProducersSectionMetadata; +var isProducerMetadata = isTypeOf("ProducerMetadata"); +exports.isProducerMetadata = isProducerMetadata; +var isProducerMetadataVersionedName = isTypeOf("ProducerMetadataVersionedName"); +exports.isProducerMetadataVersionedName = isProducerMetadataVersionedName; +var isLoopInstruction = isTypeOf("LoopInstruction"); +exports.isLoopInstruction = isLoopInstruction; +var isInstr = isTypeOf("Instr"); +exports.isInstr = isInstr; +var isIfInstruction = isTypeOf("IfInstruction"); +exports.isIfInstruction = isIfInstruction; +var isStringLiteral = isTypeOf("StringLiteral"); +exports.isStringLiteral = isStringLiteral; +var isNumberLiteral = isTypeOf("NumberLiteral"); +exports.isNumberLiteral = isNumberLiteral; +var isLongNumberLiteral = isTypeOf("LongNumberLiteral"); +exports.isLongNumberLiteral = isLongNumberLiteral; +var isFloatLiteral = isTypeOf("FloatLiteral"); +exports.isFloatLiteral = isFloatLiteral; +var isElem = isTypeOf("Elem"); +exports.isElem = isElem; +var isIndexInFuncSection = isTypeOf("IndexInFuncSection"); +exports.isIndexInFuncSection = isIndexInFuncSection; +var isValtypeLiteral = isTypeOf("ValtypeLiteral"); +exports.isValtypeLiteral = isValtypeLiteral; +var isTypeInstruction = isTypeOf("TypeInstruction"); +exports.isTypeInstruction = isTypeInstruction; +var isStart = isTypeOf("Start"); +exports.isStart = isStart; +var isGlobalType = isTypeOf("GlobalType"); +exports.isGlobalType = isGlobalType; +var isLeadingComment = isTypeOf("LeadingComment"); +exports.isLeadingComment = isLeadingComment; +var isBlockComment = isTypeOf("BlockComment"); +exports.isBlockComment = isBlockComment; +var isData = isTypeOf("Data"); +exports.isData = isData; +var isGlobal = isTypeOf("Global"); +exports.isGlobal = isGlobal; +var isTable = isTypeOf("Table"); +exports.isTable = isTable; +var isMemory = isTypeOf("Memory"); +exports.isMemory = isMemory; +var isFuncImportDescr = isTypeOf("FuncImportDescr"); +exports.isFuncImportDescr = isFuncImportDescr; +var isModuleImport = isTypeOf("ModuleImport"); +exports.isModuleImport = isModuleImport; +var isModuleExportDescr = isTypeOf("ModuleExportDescr"); +exports.isModuleExportDescr = isModuleExportDescr; +var isModuleExport = isTypeOf("ModuleExport"); +exports.isModuleExport = isModuleExport; +var isLimit = isTypeOf("Limit"); +exports.isLimit = isLimit; +var isSignature = isTypeOf("Signature"); +exports.isSignature = isSignature; +var isProgram = isTypeOf("Program"); +exports.isProgram = isProgram; +var isIdentifier = isTypeOf("Identifier"); +exports.isIdentifier = isIdentifier; +var isBlockInstruction = isTypeOf("BlockInstruction"); +exports.isBlockInstruction = isBlockInstruction; +var isCallInstruction = isTypeOf("CallInstruction"); +exports.isCallInstruction = isCallInstruction; +var isCallIndirectInstruction = isTypeOf("CallIndirectInstruction"); +exports.isCallIndirectInstruction = isCallIndirectInstruction; +var isByteArray = isTypeOf("ByteArray"); +exports.isByteArray = isByteArray; +var isFunc = isTypeOf("Func"); +exports.isFunc = isFunc; +var isInternalBrUnless = isTypeOf("InternalBrUnless"); +exports.isInternalBrUnless = isInternalBrUnless; +var isInternalGoto = isTypeOf("InternalGoto"); +exports.isInternalGoto = isInternalGoto; +var isInternalCallExtern = isTypeOf("InternalCallExtern"); +exports.isInternalCallExtern = isInternalCallExtern; +var isInternalEndAndReturn = isTypeOf("InternalEndAndReturn"); +exports.isInternalEndAndReturn = isInternalEndAndReturn; + +var isNode = function isNode(node) { + return isModule(node) || isModuleMetadata(node) || isModuleNameMetadata(node) || isFunctionNameMetadata(node) || isLocalNameMetadata(node) || isBinaryModule(node) || isQuoteModule(node) || isSectionMetadata(node) || isProducersSectionMetadata(node) || isProducerMetadata(node) || isProducerMetadataVersionedName(node) || isLoopInstruction(node) || isInstr(node) || isIfInstruction(node) || isStringLiteral(node) || isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node) || isElem(node) || isIndexInFuncSection(node) || isValtypeLiteral(node) || isTypeInstruction(node) || isStart(node) || isGlobalType(node) || isLeadingComment(node) || isBlockComment(node) || isData(node) || isGlobal(node) || isTable(node) || isMemory(node) || isFuncImportDescr(node) || isModuleImport(node) || isModuleExportDescr(node) || isModuleExport(node) || isLimit(node) || isSignature(node) || isProgram(node) || isIdentifier(node) || isBlockInstruction(node) || isCallInstruction(node) || isCallIndirectInstruction(node) || isByteArray(node) || isFunc(node) || isInternalBrUnless(node) || isInternalGoto(node) || isInternalCallExtern(node) || isInternalEndAndReturn(node); +}; + +exports.isNode = isNode; + +var isBlock = function isBlock(node) { + return isLoopInstruction(node) || isBlockInstruction(node) || isFunc(node); +}; + +exports.isBlock = isBlock; + +var isInstruction = function isInstruction(node) { + return isLoopInstruction(node) || isInstr(node) || isIfInstruction(node) || isTypeInstruction(node) || isBlockInstruction(node) || isCallInstruction(node) || isCallIndirectInstruction(node); +}; + +exports.isInstruction = isInstruction; + +var isExpression = function isExpression(node) { + return isInstr(node) || isStringLiteral(node) || isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node) || isValtypeLiteral(node) || isIdentifier(node); +}; + +exports.isExpression = isExpression; + +var isNumericLiteral = function isNumericLiteral(node) { + return isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node); +}; + +exports.isNumericLiteral = isNumericLiteral; + +var isImportDescr = function isImportDescr(node) { + return isGlobalType(node) || isTable(node) || isMemory(node) || isFuncImportDescr(node); +}; + +exports.isImportDescr = isImportDescr; + +var isIntrinsic = function isIntrinsic(node) { + return isInternalBrUnless(node) || isInternalGoto(node) || isInternalCallExtern(node) || isInternalEndAndReturn(node); +}; + +exports.isIntrinsic = isIntrinsic; +var assertModule = assertTypeOf("Module"); +exports.assertModule = assertModule; +var assertModuleMetadata = assertTypeOf("ModuleMetadata"); +exports.assertModuleMetadata = assertModuleMetadata; +var assertModuleNameMetadata = assertTypeOf("ModuleNameMetadata"); +exports.assertModuleNameMetadata = assertModuleNameMetadata; +var assertFunctionNameMetadata = assertTypeOf("FunctionNameMetadata"); +exports.assertFunctionNameMetadata = assertFunctionNameMetadata; +var assertLocalNameMetadata = assertTypeOf("LocalNameMetadata"); +exports.assertLocalNameMetadata = assertLocalNameMetadata; +var assertBinaryModule = assertTypeOf("BinaryModule"); +exports.assertBinaryModule = assertBinaryModule; +var assertQuoteModule = assertTypeOf("QuoteModule"); +exports.assertQuoteModule = assertQuoteModule; +var assertSectionMetadata = assertTypeOf("SectionMetadata"); +exports.assertSectionMetadata = assertSectionMetadata; +var assertProducersSectionMetadata = assertTypeOf("ProducersSectionMetadata"); +exports.assertProducersSectionMetadata = assertProducersSectionMetadata; +var assertProducerMetadata = assertTypeOf("ProducerMetadata"); +exports.assertProducerMetadata = assertProducerMetadata; +var assertProducerMetadataVersionedName = assertTypeOf("ProducerMetadataVersionedName"); +exports.assertProducerMetadataVersionedName = assertProducerMetadataVersionedName; +var assertLoopInstruction = assertTypeOf("LoopInstruction"); +exports.assertLoopInstruction = assertLoopInstruction; +var assertInstr = assertTypeOf("Instr"); +exports.assertInstr = assertInstr; +var assertIfInstruction = assertTypeOf("IfInstruction"); +exports.assertIfInstruction = assertIfInstruction; +var assertStringLiteral = assertTypeOf("StringLiteral"); +exports.assertStringLiteral = assertStringLiteral; +var assertNumberLiteral = assertTypeOf("NumberLiteral"); +exports.assertNumberLiteral = assertNumberLiteral; +var assertLongNumberLiteral = assertTypeOf("LongNumberLiteral"); +exports.assertLongNumberLiteral = assertLongNumberLiteral; +var assertFloatLiteral = assertTypeOf("FloatLiteral"); +exports.assertFloatLiteral = assertFloatLiteral; +var assertElem = assertTypeOf("Elem"); +exports.assertElem = assertElem; +var assertIndexInFuncSection = assertTypeOf("IndexInFuncSection"); +exports.assertIndexInFuncSection = assertIndexInFuncSection; +var assertValtypeLiteral = assertTypeOf("ValtypeLiteral"); +exports.assertValtypeLiteral = assertValtypeLiteral; +var assertTypeInstruction = assertTypeOf("TypeInstruction"); +exports.assertTypeInstruction = assertTypeInstruction; +var assertStart = assertTypeOf("Start"); +exports.assertStart = assertStart; +var assertGlobalType = assertTypeOf("GlobalType"); +exports.assertGlobalType = assertGlobalType; +var assertLeadingComment = assertTypeOf("LeadingComment"); +exports.assertLeadingComment = assertLeadingComment; +var assertBlockComment = assertTypeOf("BlockComment"); +exports.assertBlockComment = assertBlockComment; +var assertData = assertTypeOf("Data"); +exports.assertData = assertData; +var assertGlobal = assertTypeOf("Global"); +exports.assertGlobal = assertGlobal; +var assertTable = assertTypeOf("Table"); +exports.assertTable = assertTable; +var assertMemory = assertTypeOf("Memory"); +exports.assertMemory = assertMemory; +var assertFuncImportDescr = assertTypeOf("FuncImportDescr"); +exports.assertFuncImportDescr = assertFuncImportDescr; +var assertModuleImport = assertTypeOf("ModuleImport"); +exports.assertModuleImport = assertModuleImport; +var assertModuleExportDescr = assertTypeOf("ModuleExportDescr"); +exports.assertModuleExportDescr = assertModuleExportDescr; +var assertModuleExport = assertTypeOf("ModuleExport"); +exports.assertModuleExport = assertModuleExport; +var assertLimit = assertTypeOf("Limit"); +exports.assertLimit = assertLimit; +var assertSignature = assertTypeOf("Signature"); +exports.assertSignature = assertSignature; +var assertProgram = assertTypeOf("Program"); +exports.assertProgram = assertProgram; +var assertIdentifier = assertTypeOf("Identifier"); +exports.assertIdentifier = assertIdentifier; +var assertBlockInstruction = assertTypeOf("BlockInstruction"); +exports.assertBlockInstruction = assertBlockInstruction; +var assertCallInstruction = assertTypeOf("CallInstruction"); +exports.assertCallInstruction = assertCallInstruction; +var assertCallIndirectInstruction = assertTypeOf("CallIndirectInstruction"); +exports.assertCallIndirectInstruction = assertCallIndirectInstruction; +var assertByteArray = assertTypeOf("ByteArray"); +exports.assertByteArray = assertByteArray; +var assertFunc = assertTypeOf("Func"); +exports.assertFunc = assertFunc; +var assertInternalBrUnless = assertTypeOf("InternalBrUnless"); +exports.assertInternalBrUnless = assertInternalBrUnless; +var assertInternalGoto = assertTypeOf("InternalGoto"); +exports.assertInternalGoto = assertInternalGoto; +var assertInternalCallExtern = assertTypeOf("InternalCallExtern"); +exports.assertInternalCallExtern = assertInternalCallExtern; +var assertInternalEndAndReturn = assertTypeOf("InternalEndAndReturn"); +exports.assertInternalEndAndReturn = assertInternalEndAndReturn; +var unionTypesMap = { + Module: ["Node"], + ModuleMetadata: ["Node"], + ModuleNameMetadata: ["Node"], + FunctionNameMetadata: ["Node"], + LocalNameMetadata: ["Node"], + BinaryModule: ["Node"], + QuoteModule: ["Node"], + SectionMetadata: ["Node"], + ProducersSectionMetadata: ["Node"], + ProducerMetadata: ["Node"], + ProducerMetadataVersionedName: ["Node"], + LoopInstruction: ["Node", "Block", "Instruction"], + Instr: ["Node", "Expression", "Instruction"], + IfInstruction: ["Node", "Instruction"], + StringLiteral: ["Node", "Expression"], + NumberLiteral: ["Node", "NumericLiteral", "Expression"], + LongNumberLiteral: ["Node", "NumericLiteral", "Expression"], + FloatLiteral: ["Node", "NumericLiteral", "Expression"], + Elem: ["Node"], + IndexInFuncSection: ["Node"], + ValtypeLiteral: ["Node", "Expression"], + TypeInstruction: ["Node", "Instruction"], + Start: ["Node"], + GlobalType: ["Node", "ImportDescr"], + LeadingComment: ["Node"], + BlockComment: ["Node"], + Data: ["Node"], + Global: ["Node"], + Table: ["Node", "ImportDescr"], + Memory: ["Node", "ImportDescr"], + FuncImportDescr: ["Node", "ImportDescr"], + ModuleImport: ["Node"], + ModuleExportDescr: ["Node"], + ModuleExport: ["Node"], + Limit: ["Node"], + Signature: ["Node"], + Program: ["Node"], + Identifier: ["Node", "Expression"], + BlockInstruction: ["Node", "Block", "Instruction"], + CallInstruction: ["Node", "Instruction"], + CallIndirectInstruction: ["Node", "Instruction"], + ByteArray: ["Node"], + Func: ["Node", "Block"], + InternalBrUnless: ["Node", "Intrinsic"], + InternalGoto: ["Node", "Intrinsic"], + InternalCallExtern: ["Node", "Intrinsic"], + InternalEndAndReturn: ["Node", "Intrinsic"] +}; +exports.unionTypesMap = unionTypesMap; +var nodeAndUnionTypes = ["Module", "ModuleMetadata", "ModuleNameMetadata", "FunctionNameMetadata", "LocalNameMetadata", "BinaryModule", "QuoteModule", "SectionMetadata", "ProducersSectionMetadata", "ProducerMetadata", "ProducerMetadataVersionedName", "LoopInstruction", "Instr", "IfInstruction", "StringLiteral", "NumberLiteral", "LongNumberLiteral", "FloatLiteral", "Elem", "IndexInFuncSection", "ValtypeLiteral", "TypeInstruction", "Start", "GlobalType", "LeadingComment", "BlockComment", "Data", "Global", "Table", "Memory", "FuncImportDescr", "ModuleImport", "ModuleExportDescr", "ModuleExport", "Limit", "Signature", "Program", "Identifier", "BlockInstruction", "CallInstruction", "CallIndirectInstruction", "ByteArray", "Func", "InternalBrUnless", "InternalGoto", "InternalCallExtern", "InternalEndAndReturn", "Node", "Block", "Instruction", "Expression", "NumericLiteral", "ImportDescr", "Intrinsic"]; +exports.nodeAndUnionTypes = nodeAndUnionTypes; + +/***/ }), + +/***/ 77392: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.signatures = void 0; + +function sign(input, output) { + return [input, output]; +} + +var u32 = "u32"; +var i32 = "i32"; +var i64 = "i64"; +var f32 = "f32"; +var f64 = "f64"; + +var vector = function vector(t) { + var vecType = [t]; // $FlowIgnore + + vecType.vector = true; + return vecType; +}; + +var controlInstructions = { + unreachable: sign([], []), + nop: sign([], []), + // block ? + // loop ? + // if ? + // if else ? + br: sign([u32], []), + br_if: sign([u32], []), + br_table: sign(vector(u32), []), + return: sign([], []), + call: sign([u32], []), + call_indirect: sign([u32], []) +}; +var parametricInstructions = { + drop: sign([], []), + select: sign([], []) +}; +var variableInstructions = { + get_local: sign([u32], []), + set_local: sign([u32], []), + tee_local: sign([u32], []), + get_global: sign([u32], []), + set_global: sign([u32], []) +}; +var memoryInstructions = { + "i32.load": sign([u32, u32], [i32]), + "i64.load": sign([u32, u32], []), + "f32.load": sign([u32, u32], []), + "f64.load": sign([u32, u32], []), + "i32.load8_s": sign([u32, u32], [i32]), + "i32.load8_u": sign([u32, u32], [i32]), + "i32.load16_s": sign([u32, u32], [i32]), + "i32.load16_u": sign([u32, u32], [i32]), + "i64.load8_s": sign([u32, u32], [i64]), + "i64.load8_u": sign([u32, u32], [i64]), + "i64.load16_s": sign([u32, u32], [i64]), + "i64.load16_u": sign([u32, u32], [i64]), + "i64.load32_s": sign([u32, u32], [i64]), + "i64.load32_u": sign([u32, u32], [i64]), + "i32.store": sign([u32, u32], []), + "i64.store": sign([u32, u32], []), + "f32.store": sign([u32, u32], []), + "f64.store": sign([u32, u32], []), + "i32.store8": sign([u32, u32], []), + "i32.store16": sign([u32, u32], []), + "i64.store8": sign([u32, u32], []), + "i64.store16": sign([u32, u32], []), + "i64.store32": sign([u32, u32], []), + current_memory: sign([], []), + grow_memory: sign([], []) +}; +var numericInstructions = { + "i32.const": sign([i32], [i32]), + "i64.const": sign([i64], [i64]), + "f32.const": sign([f32], [f32]), + "f64.const": sign([f64], [f64]), + "i32.eqz": sign([i32], [i32]), + "i32.eq": sign([i32, i32], [i32]), + "i32.ne": sign([i32, i32], [i32]), + "i32.lt_s": sign([i32, i32], [i32]), + "i32.lt_u": sign([i32, i32], [i32]), + "i32.gt_s": sign([i32, i32], [i32]), + "i32.gt_u": sign([i32, i32], [i32]), + "i32.le_s": sign([i32, i32], [i32]), + "i32.le_u": sign([i32, i32], [i32]), + "i32.ge_s": sign([i32, i32], [i32]), + "i32.ge_u": sign([i32, i32], [i32]), + "i64.eqz": sign([i64], [i64]), + "i64.eq": sign([i64, i64], [i32]), + "i64.ne": sign([i64, i64], [i32]), + "i64.lt_s": sign([i64, i64], [i32]), + "i64.lt_u": sign([i64, i64], [i32]), + "i64.gt_s": sign([i64, i64], [i32]), + "i64.gt_u": sign([i64, i64], [i32]), + "i64.le_s": sign([i64, i64], [i32]), + "i64.le_u": sign([i64, i64], [i32]), + "i64.ge_s": sign([i64, i64], [i32]), + "i64.ge_u": sign([i64, i64], [i32]), + "f32.eq": sign([f32, f32], [i32]), + "f32.ne": sign([f32, f32], [i32]), + "f32.lt": sign([f32, f32], [i32]), + "f32.gt": sign([f32, f32], [i32]), + "f32.le": sign([f32, f32], [i32]), + "f32.ge": sign([f32, f32], [i32]), + "f64.eq": sign([f64, f64], [i32]), + "f64.ne": sign([f64, f64], [i32]), + "f64.lt": sign([f64, f64], [i32]), + "f64.gt": sign([f64, f64], [i32]), + "f64.le": sign([f64, f64], [i32]), + "f64.ge": sign([f64, f64], [i32]), + "i32.clz": sign([i32], [i32]), + "i32.ctz": sign([i32], [i32]), + "i32.popcnt": sign([i32], [i32]), + "i32.add": sign([i32, i32], [i32]), + "i32.sub": sign([i32, i32], [i32]), + "i32.mul": sign([i32, i32], [i32]), + "i32.div_s": sign([i32, i32], [i32]), + "i32.div_u": sign([i32, i32], [i32]), + "i32.rem_s": sign([i32, i32], [i32]), + "i32.rem_u": sign([i32, i32], [i32]), + "i32.and": sign([i32, i32], [i32]), + "i32.or": sign([i32, i32], [i32]), + "i32.xor": sign([i32, i32], [i32]), + "i32.shl": sign([i32, i32], [i32]), + "i32.shr_s": sign([i32, i32], [i32]), + "i32.shr_u": sign([i32, i32], [i32]), + "i32.rotl": sign([i32, i32], [i32]), + "i32.rotr": sign([i32, i32], [i32]), + "i64.clz": sign([i64], [i64]), + "i64.ctz": sign([i64], [i64]), + "i64.popcnt": sign([i64], [i64]), + "i64.add": sign([i64, i64], [i64]), + "i64.sub": sign([i64, i64], [i64]), + "i64.mul": sign([i64, i64], [i64]), + "i64.div_s": sign([i64, i64], [i64]), + "i64.div_u": sign([i64, i64], [i64]), + "i64.rem_s": sign([i64, i64], [i64]), + "i64.rem_u": sign([i64, i64], [i64]), + "i64.and": sign([i64, i64], [i64]), + "i64.or": sign([i64, i64], [i64]), + "i64.xor": sign([i64, i64], [i64]), + "i64.shl": sign([i64, i64], [i64]), + "i64.shr_s": sign([i64, i64], [i64]), + "i64.shr_u": sign([i64, i64], [i64]), + "i64.rotl": sign([i64, i64], [i64]), + "i64.rotr": sign([i64, i64], [i64]), + "f32.abs": sign([f32], [f32]), + "f32.neg": sign([f32], [f32]), + "f32.ceil": sign([f32], [f32]), + "f32.floor": sign([f32], [f32]), + "f32.trunc": sign([f32], [f32]), + "f32.nearest": sign([f32], [f32]), + "f32.sqrt": sign([f32], [f32]), + "f32.add": sign([f32, f32], [f32]), + "f32.sub": sign([f32, f32], [f32]), + "f32.mul": sign([f32, f32], [f32]), + "f32.div": sign([f32, f32], [f32]), + "f32.min": sign([f32, f32], [f32]), + "f32.max": sign([f32, f32], [f32]), + "f32.copysign": sign([f32, f32], [f32]), + "f64.abs": sign([f64], [f64]), + "f64.neg": sign([f64], [f64]), + "f64.ceil": sign([f64], [f64]), + "f64.floor": sign([f64], [f64]), + "f64.trunc": sign([f64], [f64]), + "f64.nearest": sign([f64], [f64]), + "f64.sqrt": sign([f64], [f64]), + "f64.add": sign([f64, f64], [f64]), + "f64.sub": sign([f64, f64], [f64]), + "f64.mul": sign([f64, f64], [f64]), + "f64.div": sign([f64, f64], [f64]), + "f64.min": sign([f64, f64], [f64]), + "f64.max": sign([f64, f64], [f64]), + "f64.copysign": sign([f64, f64], [f64]), + "i32.wrap/i64": sign([i64], [i32]), + "i32.trunc_s/f32": sign([f32], [i32]), + "i32.trunc_u/f32": sign([f32], [i32]), + "i32.trunc_s/f64": sign([f32], [i32]), + "i32.trunc_u/f64": sign([f64], [i32]), + "i64.extend_s/i32": sign([i32], [i64]), + "i64.extend_u/i32": sign([i32], [i64]), + "i64.trunc_s/f32": sign([f32], [i64]), + "i64.trunc_u/f32": sign([f32], [i64]), + "i64.trunc_s/f64": sign([f64], [i64]), + "i64.trunc_u/f64": sign([f64], [i64]), + "f32.convert_s/i32": sign([i32], [f32]), + "f32.convert_u/i32": sign([i32], [f32]), + "f32.convert_s/i64": sign([i64], [f32]), + "f32.convert_u/i64": sign([i64], [f32]), + "f32.demote/f64": sign([f64], [f32]), + "f64.convert_s/i32": sign([i32], [f64]), + "f64.convert_u/i32": sign([i32], [f64]), + "f64.convert_s/i64": sign([i64], [f64]), + "f64.convert_u/i64": sign([i64], [f64]), + "f64.promote/f32": sign([f32], [f64]), + "i32.reinterpret/f32": sign([f32], [i32]), + "i64.reinterpret/f64": sign([f64], [i64]), + "f32.reinterpret/i32": sign([i32], [f32]), + "f64.reinterpret/i64": sign([i64], [f64]) +}; +var signatures = Object.assign({}, controlInstructions, parametricInstructions, variableInstructions, memoryInstructions, numericInstructions); +exports.signatures = signatures; + +/***/ }), + +/***/ 29436: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.traverse = traverse; + +var _nodePath = __webpack_require__(89231); + +var _nodes = __webpack_require__(94841); + +// recursively walks the AST starting at the given node. The callback is invoked for +// and object that has a 'type' property. +function walk(context, callback) { + var stop = false; + + function innerWalk(context, callback) { + if (stop) { + return; + } + + var node = context.node; + + if (node === undefined) { + console.warn("traversing with an empty context"); + return; + } + + if (node._deleted === true) { + return; + } + + var path = (0, _nodePath.createPath)(context); + callback(node.type, path); + + if (path.shouldStop) { + stop = true; + return; + } + + Object.keys(node).forEach(function (prop) { + var value = node[prop]; + + if (value === null || value === undefined) { + return; + } + + var valueAsArray = Array.isArray(value) ? value : [value]; + valueAsArray.forEach(function (childNode) { + if (typeof childNode.type === "string") { + var childContext = { + node: childNode, + parentKey: prop, + parentPath: path, + shouldStop: false, + inList: Array.isArray(value) + }; + innerWalk(childContext, callback); + } + }); + }); + } + + innerWalk(context, callback); +} + +var noop = function noop() {}; + +function traverse(node, visitors) { + var before = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : noop; + var after = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : noop; + Object.keys(visitors).forEach(function (visitor) { + if (!_nodes.nodeAndUnionTypes.includes(visitor)) { + throw new Error("Unexpected visitor ".concat(visitor)); + } + }); + var context = { + node: node, + inList: false, + shouldStop: false, + parentPath: null, + parentKey: null + }; + walk(context, function (type, path) { + if (typeof visitors[type] === "function") { + before(type, path); + visitors[type](path); + after(type, path); + } + + var unionTypes = _nodes.unionTypesMap[type]; + + if (!unionTypes) { + throw new Error("Unexpected node type ".concat(type)); + } + + unionTypes.forEach(function (unionType) { + if (typeof visitors[unionType] === "function") { + before(unionType, path); + visitors[unionType](path); + after(unionType, path); + } + }); + }); +} + +/***/ }), + +/***/ 38456: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.isAnonymous = isAnonymous; +exports.getSectionMetadata = getSectionMetadata; +exports.getSectionMetadatas = getSectionMetadatas; +exports.sortSectionMetadata = sortSectionMetadata; +exports.orderedInsertNode = orderedInsertNode; +exports.assertHasLoc = assertHasLoc; +exports.getEndOfSection = getEndOfSection; +exports.shiftLoc = shiftLoc; +exports.shiftSection = shiftSection; +exports.signatureForOpcode = signatureForOpcode; +exports.getUniqueNameGenerator = getUniqueNameGenerator; +exports.getStartByteOffset = getStartByteOffset; +exports.getEndByteOffset = getEndByteOffset; +exports.getFunctionBeginingByteOffset = getFunctionBeginingByteOffset; +exports.getEndBlockByteOffset = getEndBlockByteOffset; +exports.getStartBlockByteOffset = getStartBlockByteOffset; + +var _signatures = __webpack_require__(77392); + +var _traverse = __webpack_require__(29436); + +var _helperWasmBytecode = _interopRequireWildcard(__webpack_require__(66921)); + +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 _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function isAnonymous(ident) { + return ident.raw === ""; +} + +function getSectionMetadata(ast, name) { + var section; + (0, _traverse.traverse)(ast, { + SectionMetadata: function (_SectionMetadata) { + function SectionMetadata(_x) { + return _SectionMetadata.apply(this, arguments); + } + + SectionMetadata.toString = function () { + return _SectionMetadata.toString(); + }; + + return SectionMetadata; + }(function (_ref) { + var node = _ref.node; + + if (node.section === name) { + section = node; + } + }) + }); + return section; +} + +function getSectionMetadatas(ast, name) { + var sections = []; + (0, _traverse.traverse)(ast, { + SectionMetadata: function (_SectionMetadata2) { + function SectionMetadata(_x2) { + return _SectionMetadata2.apply(this, arguments); + } + + SectionMetadata.toString = function () { + return _SectionMetadata2.toString(); + }; + + return SectionMetadata; + }(function (_ref2) { + var node = _ref2.node; + + if (node.section === name) { + sections.push(node); + } + }) + }); + return sections; +} + +function sortSectionMetadata(m) { + if (m.metadata == null) { + console.warn("sortSectionMetadata: no metadata to sort"); + return; + } // $FlowIgnore + + + m.metadata.sections.sort(function (a, b) { + var aId = _helperWasmBytecode.default.sections[a.section]; + var bId = _helperWasmBytecode.default.sections[b.section]; + + if (typeof aId !== "number" || typeof bId !== "number") { + throw new Error("Section id not found"); + } + + return aId - bId; + }); +} + +function orderedInsertNode(m, n) { + assertHasLoc(n); + var didInsert = false; + + if (n.type === "ModuleExport") { + m.fields.push(n); + return; + } + + m.fields = m.fields.reduce(function (acc, field) { + var fieldEndCol = Infinity; + + if (field.loc != null) { + // $FlowIgnore + fieldEndCol = field.loc.end.column; + } // $FlowIgnore: assertHasLoc ensures that + + + if (didInsert === false && n.loc.start.column < fieldEndCol) { + didInsert = true; + acc.push(n); + } + + acc.push(field); + return acc; + }, []); // Handles empty modules or n is the last element + + if (didInsert === false) { + m.fields.push(n); + } +} + +function assertHasLoc(n) { + if (n.loc == null || n.loc.start == null || n.loc.end == null) { + throw new Error("Internal failure: node (".concat(JSON.stringify(n.type), ") has no location information")); + } +} + +function getEndOfSection(s) { + assertHasLoc(s.size); + return s.startOffset + s.size.value + ( // $FlowIgnore + s.size.loc.end.column - s.size.loc.start.column); +} + +function shiftLoc(node, delta) { + // $FlowIgnore + node.loc.start.column += delta; // $FlowIgnore + + node.loc.end.column += delta; +} + +function shiftSection(ast, node, delta) { + if (node.type !== "SectionMetadata") { + throw new Error("Can not shift node " + JSON.stringify(node.type)); + } + + node.startOffset += delta; + + if (_typeof(node.size.loc) === "object") { + shiftLoc(node.size, delta); + } // Custom sections doesn't have vectorOfSize + + + if (_typeof(node.vectorOfSize) === "object" && _typeof(node.vectorOfSize.loc) === "object") { + shiftLoc(node.vectorOfSize, delta); + } + + var sectionName = node.section; // shift node locations within that section + + (0, _traverse.traverse)(ast, { + Node: function Node(_ref3) { + var node = _ref3.node; + var section = (0, _helperWasmBytecode.getSectionForNode)(node); + + if (section === sectionName && _typeof(node.loc) === "object") { + shiftLoc(node, delta); + } + } + }); +} + +function signatureForOpcode(object, name) { + var opcodeName = name; + + if (object !== undefined && object !== "") { + opcodeName = object + "." + name; + } + + var sign = _signatures.signatures[opcodeName]; + + if (sign == undefined) { + // TODO: Uncomment this when br_table and others has been done + //throw new Error("Invalid opcode: "+opcodeName); + return [object, object]; + } + + return sign[0]; +} + +function getUniqueNameGenerator() { + var inc = {}; + return function () { + var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; + + if (!(prefix in inc)) { + inc[prefix] = 0; + } else { + inc[prefix] = inc[prefix] + 1; + } + + return prefix + "_" + inc[prefix]; + }; +} + +function getStartByteOffset(n) { + // $FlowIgnore + if (typeof n.loc === "undefined" || typeof n.loc.start === "undefined") { + throw new Error( // $FlowIgnore + "Can not get byte offset without loc informations, node: " + String(n.id)); + } + + return n.loc.start.column; +} + +function getEndByteOffset(n) { + // $FlowIgnore + if (typeof n.loc === "undefined" || typeof n.loc.end === "undefined") { + throw new Error("Can not get byte offset without loc informations, node: " + n.type); + } + + return n.loc.end.column; +} + +function getFunctionBeginingByteOffset(n) { + if (!(n.body.length > 0)) { + throw new Error('n.body.length > 0' + " error: " + (undefined || "unknown")); + } + + var _n$body = _slicedToArray(n.body, 1), + firstInstruction = _n$body[0]; + + return getStartByteOffset(firstInstruction); +} + +function getEndBlockByteOffset(n) { + // $FlowIgnore + if (!(n.instr.length > 0 || n.body.length > 0)) { + throw new Error('n.instr.length > 0 || n.body.length > 0' + " error: " + (undefined || "unknown")); + } + + var lastInstruction; + + if (n.instr) { + // $FlowIgnore + lastInstruction = n.instr[n.instr.length - 1]; + } + + if (n.body) { + // $FlowIgnore + lastInstruction = n.body[n.body.length - 1]; + } + + if (!(_typeof(lastInstruction) === "object")) { + throw new Error('typeof lastInstruction === "object"' + " error: " + (undefined || "unknown")); + } + + // $FlowIgnore + return getStartByteOffset(lastInstruction); +} + +function getStartBlockByteOffset(n) { + // $FlowIgnore + if (!(n.instr.length > 0 || n.body.length > 0)) { + throw new Error('n.instr.length > 0 || n.body.length > 0' + " error: " + (undefined || "unknown")); + } + + var fistInstruction; + + if (n.instr) { + // $FlowIgnore + var _n$instr = _slicedToArray(n.instr, 1); + + fistInstruction = _n$instr[0]; + } + + if (n.body) { + // $FlowIgnore + var _n$body2 = _slicedToArray(n.body, 1); + + fistInstruction = _n$body2[0]; + } + + if (!(_typeof(fistInstruction) === "object")) { + throw new Error('typeof fistInstruction === "object"' + " error: " + (undefined || "unknown")); + } + + // $FlowIgnore + return getStartByteOffset(fistInstruction); +} + +/***/ }), + +/***/ 20193: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LinkError = exports.CompileError = exports.RuntimeError = void 0; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var RuntimeError = +/*#__PURE__*/ +function (_Error) { + _inherits(RuntimeError, _Error); + + function RuntimeError() { + _classCallCheck(this, RuntimeError); + + return _possibleConstructorReturn(this, (RuntimeError.__proto__ || Object.getPrototypeOf(RuntimeError)).apply(this, arguments)); + } + + return RuntimeError; +}(Error); + +exports.RuntimeError = RuntimeError; + +var CompileError = +/*#__PURE__*/ +function (_Error2) { + _inherits(CompileError, _Error2); + + function CompileError() { + _classCallCheck(this, CompileError); + + return _possibleConstructorReturn(this, (CompileError.__proto__ || Object.getPrototypeOf(CompileError)).apply(this, arguments)); + } + + return CompileError; +}(Error); + +exports.CompileError = CompileError; + +var LinkError = +/*#__PURE__*/ +function (_Error3) { + _inherits(LinkError, _Error3); + + function LinkError() { + _classCallCheck(this, LinkError); + + return _possibleConstructorReturn(this, (LinkError.__proto__ || Object.getPrototypeOf(LinkError)).apply(this, arguments)); + } + + return LinkError; +}(Error); + +exports.LinkError = LinkError; + +/***/ }), + +/***/ 66921: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "getSectionForNode", ({ + enumerable: true, + get: function get() { + return _section.getSectionForNode; + } +})); +exports.default = void 0; + +var _section = __webpack_require__(79348); + +var illegalop = "illegal"; +var magicModuleHeader = [0x00, 0x61, 0x73, 0x6d]; +var moduleVersion = [0x01, 0x00, 0x00, 0x00]; + +function invertMap(obj) { + var keyModifierFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (k) { + return k; + }; + var result = {}; + var keys = Object.keys(obj); + + for (var i = 0, length = keys.length; i < length; i++) { + result[keyModifierFn(obj[keys[i]])] = keys[i]; + } + + return result; +} + +function createSymbolObject(name +/*: string */ +, object +/*: string */ +) +/*: Symbol*/ +{ + var numberOfArgs + /*: number*/ + = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + return { + name: name, + object: object, + numberOfArgs: numberOfArgs + }; +} + +function createSymbol(name +/*: string */ +) +/*: Symbol*/ +{ + var numberOfArgs + /*: number*/ + = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + return { + name: name, + numberOfArgs: numberOfArgs + }; +} + +var types = { + func: 0x60, + result: 0x40 +}; +var exportTypes = { + 0x00: "Func", + 0x01: "Table", + 0x02: "Mem", + 0x03: "Global" +}; +var exportTypesByName = invertMap(exportTypes); +var valtypes = { + 0x7f: "i32", + 0x7e: "i64", + 0x7d: "f32", + 0x7c: "f64", + 0x7b: "v128" +}; +var valtypesByString = invertMap(valtypes); +var tableTypes = { + 0x70: "anyfunc" +}; +var blockTypes = Object.assign({}, valtypes, { + // https://webassembly.github.io/spec/core/binary/types.html#binary-blocktype + 0x40: null, + // https://webassembly.github.io/spec/core/binary/types.html#binary-valtype + 0x7f: "i32", + 0x7e: "i64", + 0x7d: "f32", + 0x7c: "f64" +}); +var globalTypes = { + 0x00: "const", + 0x01: "var" +}; +var globalTypesByString = invertMap(globalTypes); +var importTypes = { + 0x00: "func", + 0x01: "table", + 0x02: "mem", + 0x03: "global" +}; +var sections = { + custom: 0, + type: 1, + import: 2, + func: 3, + table: 4, + memory: 5, + global: 6, + export: 7, + start: 8, + element: 9, + code: 10, + data: 11 +}; +var symbolsByByte = { + 0x00: createSymbol("unreachable"), + 0x01: createSymbol("nop"), + 0x02: createSymbol("block"), + 0x03: createSymbol("loop"), + 0x04: createSymbol("if"), + 0x05: createSymbol("else"), + 0x06: illegalop, + 0x07: illegalop, + 0x08: illegalop, + 0x09: illegalop, + 0x0a: illegalop, + 0x0b: createSymbol("end"), + 0x0c: createSymbol("br", 1), + 0x0d: createSymbol("br_if", 1), + 0x0e: createSymbol("br_table"), + 0x0f: createSymbol("return"), + 0x10: createSymbol("call", 1), + 0x11: createSymbol("call_indirect", 2), + 0x12: illegalop, + 0x13: illegalop, + 0x14: illegalop, + 0x15: illegalop, + 0x16: illegalop, + 0x17: illegalop, + 0x18: illegalop, + 0x19: illegalop, + 0x1a: createSymbol("drop"), + 0x1b: createSymbol("select"), + 0x1c: illegalop, + 0x1d: illegalop, + 0x1e: illegalop, + 0x1f: illegalop, + 0x20: createSymbol("get_local", 1), + 0x21: createSymbol("set_local", 1), + 0x22: createSymbol("tee_local", 1), + 0x23: createSymbol("get_global", 1), + 0x24: createSymbol("set_global", 1), + 0x25: illegalop, + 0x26: illegalop, + 0x27: illegalop, + 0x28: createSymbolObject("load", "u32", 1), + 0x29: createSymbolObject("load", "u64", 1), + 0x2a: createSymbolObject("load", "f32", 1), + 0x2b: createSymbolObject("load", "f64", 1), + 0x2c: createSymbolObject("load8_s", "u32", 1), + 0x2d: createSymbolObject("load8_u", "u32", 1), + 0x2e: createSymbolObject("load16_s", "u32", 1), + 0x2f: createSymbolObject("load16_u", "u32", 1), + 0x30: createSymbolObject("load8_s", "u64", 1), + 0x31: createSymbolObject("load8_u", "u64", 1), + 0x32: createSymbolObject("load16_s", "u64", 1), + 0x33: createSymbolObject("load16_u", "u64", 1), + 0x34: createSymbolObject("load32_s", "u64", 1), + 0x35: createSymbolObject("load32_u", "u64", 1), + 0x36: createSymbolObject("store", "u32", 1), + 0x37: createSymbolObject("store", "u64", 1), + 0x38: createSymbolObject("store", "f32", 1), + 0x39: createSymbolObject("store", "f64", 1), + 0x3a: createSymbolObject("store8", "u32", 1), + 0x3b: createSymbolObject("store16", "u32", 1), + 0x3c: createSymbolObject("store8", "u64", 1), + 0x3d: createSymbolObject("store16", "u64", 1), + 0x3e: createSymbolObject("store32", "u64", 1), + 0x3f: createSymbolObject("current_memory"), + 0x40: createSymbolObject("grow_memory"), + 0x41: createSymbolObject("const", "i32", 1), + 0x42: createSymbolObject("const", "i64", 1), + 0x43: createSymbolObject("const", "f32", 1), + 0x44: createSymbolObject("const", "f64", 1), + 0x45: createSymbolObject("eqz", "i32"), + 0x46: createSymbolObject("eq", "i32"), + 0x47: createSymbolObject("ne", "i32"), + 0x48: createSymbolObject("lt_s", "i32"), + 0x49: createSymbolObject("lt_u", "i32"), + 0x4a: createSymbolObject("gt_s", "i32"), + 0x4b: createSymbolObject("gt_u", "i32"), + 0x4c: createSymbolObject("le_s", "i32"), + 0x4d: createSymbolObject("le_u", "i32"), + 0x4e: createSymbolObject("ge_s", "i32"), + 0x4f: createSymbolObject("ge_u", "i32"), + 0x50: createSymbolObject("eqz", "i64"), + 0x51: createSymbolObject("eq", "i64"), + 0x52: createSymbolObject("ne", "i64"), + 0x53: createSymbolObject("lt_s", "i64"), + 0x54: createSymbolObject("lt_u", "i64"), + 0x55: createSymbolObject("gt_s", "i64"), + 0x56: createSymbolObject("gt_u", "i64"), + 0x57: createSymbolObject("le_s", "i64"), + 0x58: createSymbolObject("le_u", "i64"), + 0x59: createSymbolObject("ge_s", "i64"), + 0x5a: createSymbolObject("ge_u", "i64"), + 0x5b: createSymbolObject("eq", "f32"), + 0x5c: createSymbolObject("ne", "f32"), + 0x5d: createSymbolObject("lt", "f32"), + 0x5e: createSymbolObject("gt", "f32"), + 0x5f: createSymbolObject("le", "f32"), + 0x60: createSymbolObject("ge", "f32"), + 0x61: createSymbolObject("eq", "f64"), + 0x62: createSymbolObject("ne", "f64"), + 0x63: createSymbolObject("lt", "f64"), + 0x64: createSymbolObject("gt", "f64"), + 0x65: createSymbolObject("le", "f64"), + 0x66: createSymbolObject("ge", "f64"), + 0x67: createSymbolObject("clz", "i32"), + 0x68: createSymbolObject("ctz", "i32"), + 0x69: createSymbolObject("popcnt", "i32"), + 0x6a: createSymbolObject("add", "i32"), + 0x6b: createSymbolObject("sub", "i32"), + 0x6c: createSymbolObject("mul", "i32"), + 0x6d: createSymbolObject("div_s", "i32"), + 0x6e: createSymbolObject("div_u", "i32"), + 0x6f: createSymbolObject("rem_s", "i32"), + 0x70: createSymbolObject("rem_u", "i32"), + 0x71: createSymbolObject("and", "i32"), + 0x72: createSymbolObject("or", "i32"), + 0x73: createSymbolObject("xor", "i32"), + 0x74: createSymbolObject("shl", "i32"), + 0x75: createSymbolObject("shr_s", "i32"), + 0x76: createSymbolObject("shr_u", "i32"), + 0x77: createSymbolObject("rotl", "i32"), + 0x78: createSymbolObject("rotr", "i32"), + 0x79: createSymbolObject("clz", "i64"), + 0x7a: createSymbolObject("ctz", "i64"), + 0x7b: createSymbolObject("popcnt", "i64"), + 0x7c: createSymbolObject("add", "i64"), + 0x7d: createSymbolObject("sub", "i64"), + 0x7e: createSymbolObject("mul", "i64"), + 0x7f: createSymbolObject("div_s", "i64"), + 0x80: createSymbolObject("div_u", "i64"), + 0x81: createSymbolObject("rem_s", "i64"), + 0x82: createSymbolObject("rem_u", "i64"), + 0x83: createSymbolObject("and", "i64"), + 0x84: createSymbolObject("or", "i64"), + 0x85: createSymbolObject("xor", "i64"), + 0x86: createSymbolObject("shl", "i64"), + 0x87: createSymbolObject("shr_s", "i64"), + 0x88: createSymbolObject("shr_u", "i64"), + 0x89: createSymbolObject("rotl", "i64"), + 0x8a: createSymbolObject("rotr", "i64"), + 0x8b: createSymbolObject("abs", "f32"), + 0x8c: createSymbolObject("neg", "f32"), + 0x8d: createSymbolObject("ceil", "f32"), + 0x8e: createSymbolObject("floor", "f32"), + 0x8f: createSymbolObject("trunc", "f32"), + 0x90: createSymbolObject("nearest", "f32"), + 0x91: createSymbolObject("sqrt", "f32"), + 0x92: createSymbolObject("add", "f32"), + 0x93: createSymbolObject("sub", "f32"), + 0x94: createSymbolObject("mul", "f32"), + 0x95: createSymbolObject("div", "f32"), + 0x96: createSymbolObject("min", "f32"), + 0x97: createSymbolObject("max", "f32"), + 0x98: createSymbolObject("copysign", "f32"), + 0x99: createSymbolObject("abs", "f64"), + 0x9a: createSymbolObject("neg", "f64"), + 0x9b: createSymbolObject("ceil", "f64"), + 0x9c: createSymbolObject("floor", "f64"), + 0x9d: createSymbolObject("trunc", "f64"), + 0x9e: createSymbolObject("nearest", "f64"), + 0x9f: createSymbolObject("sqrt", "f64"), + 0xa0: createSymbolObject("add", "f64"), + 0xa1: createSymbolObject("sub", "f64"), + 0xa2: createSymbolObject("mul", "f64"), + 0xa3: createSymbolObject("div", "f64"), + 0xa4: createSymbolObject("min", "f64"), + 0xa5: createSymbolObject("max", "f64"), + 0xa6: createSymbolObject("copysign", "f64"), + 0xa7: createSymbolObject("wrap/i64", "i32"), + 0xa8: createSymbolObject("trunc_s/f32", "i32"), + 0xa9: createSymbolObject("trunc_u/f32", "i32"), + 0xaa: createSymbolObject("trunc_s/f64", "i32"), + 0xab: createSymbolObject("trunc_u/f64", "i32"), + 0xac: createSymbolObject("extend_s/i32", "i64"), + 0xad: createSymbolObject("extend_u/i32", "i64"), + 0xae: createSymbolObject("trunc_s/f32", "i64"), + 0xaf: createSymbolObject("trunc_u/f32", "i64"), + 0xb0: createSymbolObject("trunc_s/f64", "i64"), + 0xb1: createSymbolObject("trunc_u/f64", "i64"), + 0xb2: createSymbolObject("convert_s/i32", "f32"), + 0xb3: createSymbolObject("convert_u/i32", "f32"), + 0xb4: createSymbolObject("convert_s/i64", "f32"), + 0xb5: createSymbolObject("convert_u/i64", "f32"), + 0xb6: createSymbolObject("demote/f64", "f32"), + 0xb7: createSymbolObject("convert_s/i32", "f64"), + 0xb8: createSymbolObject("convert_u/i32", "f64"), + 0xb9: createSymbolObject("convert_s/i64", "f64"), + 0xba: createSymbolObject("convert_u/i64", "f64"), + 0xbb: createSymbolObject("promote/f32", "f64"), + 0xbc: createSymbolObject("reinterpret/f32", "i32"), + 0xbd: createSymbolObject("reinterpret/f64", "i64"), + 0xbe: createSymbolObject("reinterpret/i32", "f32"), + 0xbf: createSymbolObject("reinterpret/i64", "f64") +}; +var symbolsByName = invertMap(symbolsByByte, function (obj) { + if (typeof obj.object === "string") { + return "".concat(obj.object, ".").concat(obj.name); + } + + return obj.name; +}); +var _default = { + symbolsByByte: symbolsByByte, + sections: sections, + magicModuleHeader: magicModuleHeader, + moduleVersion: moduleVersion, + types: types, + valtypes: valtypes, + exportTypes: exportTypes, + blockTypes: blockTypes, + tableTypes: tableTypes, + globalTypes: globalTypes, + importTypes: importTypes, + valtypesByString: valtypesByString, + globalTypesByString: globalTypesByString, + exportTypesByName: exportTypesByName, + symbolsByName: symbolsByName +}; +exports.default = _default; + +/***/ }), + +/***/ 79348: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.getSectionForNode = getSectionForNode; + +function getSectionForNode(n) { + switch (n.type) { + case "ModuleImport": + return "import"; + + case "CallInstruction": + case "CallIndirectInstruction": + case "Func": + case "Instr": + return "code"; + + case "ModuleExport": + return "export"; + + case "Start": + return "start"; + + case "TypeInstruction": + return "type"; + + case "IndexInFuncSection": + return "func"; + + case "Global": + return "global"; + // No section + + default: + return; + } +} + +/***/ }), + +/***/ 57732: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encodeF32 = encodeF32; +exports.encodeF64 = encodeF64; +exports.decodeF32 = decodeF32; +exports.decodeF64 = decodeF64; +exports.DOUBLE_PRECISION_MANTISSA = exports.SINGLE_PRECISION_MANTISSA = exports.NUMBER_OF_BYTE_F64 = exports.NUMBER_OF_BYTE_F32 = void 0; + +var _ieee = __webpack_require__(30848); - return Template.asString([ - "var link = document.createElement('link');", - crossOriginLoading - ? `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};` - : "", - `if (${mainTemplate.requireFn}.nc) {`, - Template.indent( - `link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);` - ), - "}", - 'link.rel = "prefetch";', - 'link.as = "script";', - "link.href = jsonpScriptSrc(chunkId);" - ]); - } - ); - mainTemplate.hooks.requireEnsure.tap( - "JsonpMainTemplatePlugin load", - (source, chunk, hash) => { - return Template.asString([ - source, - "", - "// JSONP chunk loading for javascript", - "", - "var installedChunkData = installedChunks[chunkId];", - 'if(installedChunkData !== 0) { // 0 means "already installed".', - Template.indent([ - "", - '// a Promise means "currently loading".', - "if(installedChunkData) {", - Template.indent(["promises.push(installedChunkData[2]);"]), - "} else {", - Template.indent([ - "// setup Promise in chunk cache", - "var promise = new Promise(function(resolve, reject) {", - Template.indent([ - "installedChunkData = installedChunks[chunkId] = [resolve, reject];" - ]), - "});", - "promises.push(installedChunkData[2] = promise);", - "", - "// start chunk loading", - mainTemplate.hooks.jsonpScript.call("", chunk, hash), - "document.head.appendChild(script);" - ]), - "}" - ]), - "}" - ]); - } - ); - mainTemplate.hooks.requireEnsure.tap( - { - name: "JsonpMainTemplatePlugin preload", - stage: 10 - }, - (source, chunk, hash) => { - const chunkMap = chunk.getChildIdsByOrdersMap().preload; - if (!chunkMap || Object.keys(chunkMap).length === 0) return source; - return Template.asString([ - source, - "", - "// chunk preloadng for javascript", - "", - `var chunkPreloadMap = ${JSON.stringify(chunkMap, null, "\t")};`, - "", - "var chunkPreloadData = chunkPreloadMap[chunkId];", - "if(chunkPreloadData) {", - Template.indent([ - "chunkPreloadData.forEach(function(chunkId) {", - Template.indent([ - "if(installedChunks[chunkId] === undefined) {", - Template.indent([ - "installedChunks[chunkId] = null;", - mainTemplate.hooks.linkPreload.call("", chunk, hash), - "document.head.appendChild(link);" - ]), - "}" - ]), - "});" - ]), - "}" - ]); - } - ); - mainTemplate.hooks.requireExtensions.tap( - "JsonpMainTemplatePlugin", - (source, chunk) => { - if (!needChunkOnDemandLoadingCode(chunk)) return source; +/** + * According to https://webassembly.github.io/spec/binary/values.html#binary-float + * n = 32/8 + */ +var NUMBER_OF_BYTE_F32 = 4; +/** + * According to https://webassembly.github.io/spec/binary/values.html#binary-float + * n = 64/8 + */ - return Template.asString([ - source, - "", - "// on error function for async loading", - `${mainTemplate.requireFn}.oe = function(err) { console.error(err); throw err; };` - ]); - } - ); - mainTemplate.hooks.bootstrap.tap( - "JsonpMainTemplatePlugin", - (source, chunk, hash) => { - if (needChunkLoadingCode(chunk)) { - const withDefer = needEntryDeferringCode(chunk); - const withPrefetch = needPrefetchingCode(chunk); - return Template.asString([ - source, - "", - "// install a JSONP callback for chunk loading", - "function webpackJsonpCallback(data) {", - Template.indent([ - "var chunkIds = data[0];", - "var moreModules = data[1];", - withDefer ? "var executeModules = data[2];" : "", - withPrefetch ? "var prefetchChunks = data[3] || [];" : "", - '// add "moreModules" to the modules object,', - '// then flag all "chunkIds" as loaded and fire callback', - "var moduleId, chunkId, i = 0, resolves = [];", - "for(;i < chunkIds.length; i++) {", - Template.indent([ - "chunkId = chunkIds[i];", - "if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {", - Template.indent("resolves.push(installedChunks[chunkId][0]);"), - "}", - "installedChunks[chunkId] = 0;" - ]), - "}", - "for(moduleId in moreModules) {", - Template.indent([ - "if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {", - Template.indent( - mainTemplate.renderAddModule( - hash, - chunk, - "moduleId", - "moreModules[moduleId]" - ) - ), - "}" - ]), - "}", - "if(parentJsonpFunction) parentJsonpFunction(data);", - withPrefetch - ? withDefer - ? "deferredPrefetch.push.apply(deferredPrefetch, prefetchChunks);" - : Template.asString([ - "// chunk prefetching for javascript", - "prefetchChunks.forEach(function(chunkId) {", - Template.indent([ - "if(installedChunks[chunkId] === undefined) {", - Template.indent([ - "installedChunks[chunkId] = null;", - mainTemplate.hooks.linkPrefetch.call("", chunk, hash), - "document.head.appendChild(link);" - ]), - "}" - ]), - "});" - ]) - : "", - "while(resolves.length) {", - Template.indent("resolves.shift()();"), - "}", - withDefer - ? Template.asString([ - "", - "// add entry modules from loaded chunk to deferred list", - "deferredModules.push.apply(deferredModules, executeModules || []);", - "", - "// run deferred modules when all chunks ready", - "return checkDeferredModules();" - ]) - : "" - ]), - "};", - withDefer - ? Template.asString([ - "function checkDeferredModules() {", - Template.indent([ - "var result;", - "for(var i = 0; i < deferredModules.length; i++) {", - Template.indent([ - "var deferredModule = deferredModules[i];", - "var fulfilled = true;", - "for(var j = 1; j < deferredModule.length; j++) {", - Template.indent([ - "var depId = deferredModule[j];", - "if(installedChunks[depId] !== 0) fulfilled = false;" - ]), - "}", - "if(fulfilled) {", - Template.indent([ - "deferredModules.splice(i--, 1);", - "result = " + - mainTemplate.requireFn + - "(" + - mainTemplate.requireFn + - ".s = deferredModule[0]);" - ]), - "}" - ]), - "}", - withPrefetch - ? Template.asString([ - "if(deferredModules.length === 0) {", - Template.indent([ - "// chunk prefetching for javascript", - "deferredPrefetch.forEach(function(chunkId) {", - Template.indent([ - "if(installedChunks[chunkId] === undefined) {", - Template.indent([ - "installedChunks[chunkId] = null;", - mainTemplate.hooks.linkPrefetch.call( - "", - chunk, - hash - ), - "document.head.appendChild(link);" - ]), - "}" - ]), - "});", - "deferredPrefetch.length = 0;" - ]), - "}" - ]) - : "", - "return result;" - ]), - "}" - ]) - : "" - ]); - } - return source; - } - ); - mainTemplate.hooks.beforeStartup.tap( - "JsonpMainTemplatePlugin", - (source, chunk, hash) => { - if (needChunkLoadingCode(chunk)) { - var jsonpFunction = mainTemplate.outputOptions.jsonpFunction; - var globalObject = mainTemplate.outputOptions.globalObject; - return Template.asString([ - `var jsonpArray = ${globalObject}[${JSON.stringify( - jsonpFunction - )}] = ${globalObject}[${JSON.stringify(jsonpFunction)}] || [];`, - "var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);", - "jsonpArray.push = webpackJsonpCallback;", - "jsonpArray = jsonpArray.slice();", - "for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);", - "var parentJsonpFunction = oldJsonpFunction;", - "", - source - ]); - } - return source; - } - ); - mainTemplate.hooks.afterStartup.tap( - "JsonpMainTemplatePlugin", - (source, chunk, hash) => { - const prefetchChunks = chunk.getChildIdsByOrders().prefetch; - if ( - needChunkLoadingCode(chunk) && - prefetchChunks && - prefetchChunks.length - ) { - return Template.asString([ - source, - `webpackJsonpCallback([[], {}, 0, ${JSON.stringify( - prefetchChunks - )}]);` - ]); - } - return source; - } - ); - mainTemplate.hooks.startup.tap( - "JsonpMainTemplatePlugin", - (source, chunk, hash) => { - if (needEntryDeferringCode(chunk)) { - if (chunk.hasEntryModule()) { - const entries = [chunk.entryModule].filter(Boolean).map(m => - [m.id].concat( - Array.from(chunk.groupsIterable)[0] - .chunks.filter(c => c !== chunk) - .map(c => c.id) - ) - ); - return Template.asString([ - "// add entry module to deferred list", - `deferredModules.push(${entries - .map(e => JSON.stringify(e)) - .join(", ")});`, - "// run deferred modules when ready", - "return checkDeferredModules();" - ]); - } else { - return Template.asString([ - "// run deferred modules from other chunks", - "checkDeferredModules();" - ]); - } - } - return source; - } - ); - mainTemplate.hooks.hotBootstrap.tap( - "JsonpMainTemplatePlugin", - (source, chunk, hash) => { - const globalObject = mainTemplate.outputOptions.globalObject; - const hotUpdateChunkFilename = - mainTemplate.outputOptions.hotUpdateChunkFilename; - const hotUpdateMainFilename = - mainTemplate.outputOptions.hotUpdateMainFilename; - const crossOriginLoading = - mainTemplate.outputOptions.crossOriginLoading; - const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction; - const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( - JSON.stringify(hotUpdateChunkFilename), - { - hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, - hashWithLength: length => - `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, - chunk: { - id: '" + chunkId + "' - } - } - ); - const currentHotUpdateMainFilename = mainTemplate.getAssetPath( - JSON.stringify(hotUpdateMainFilename), - { - hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, - hashWithLength: length => - `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` - } - ); - const runtimeSource = Template.getFunctionContent( - __webpack_require__(24916) - ) - .replace(/\/\/\$semicolon/g, ";") - .replace(/\$require\$/g, mainTemplate.requireFn) - .replace( - /\$crossOriginLoading\$/g, - crossOriginLoading ? JSON.stringify(crossOriginLoading) : "null" - ) - .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) - .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) - .replace(/\$hash\$/g, JSON.stringify(hash)); - return `${source} -function hotDisposeChunk(chunkId) { - delete installedChunks[chunkId]; +exports.NUMBER_OF_BYTE_F32 = NUMBER_OF_BYTE_F32; +var NUMBER_OF_BYTE_F64 = 8; +exports.NUMBER_OF_BYTE_F64 = NUMBER_OF_BYTE_F64; +var SINGLE_PRECISION_MANTISSA = 23; +exports.SINGLE_PRECISION_MANTISSA = SINGLE_PRECISION_MANTISSA; +var DOUBLE_PRECISION_MANTISSA = 52; +exports.DOUBLE_PRECISION_MANTISSA = DOUBLE_PRECISION_MANTISSA; + +function encodeF32(v) { + var buffer = []; + (0, _ieee.write)(buffer, v, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); + return buffer; } -var parentHotUpdateCallback = ${globalObject}[${JSON.stringify( - hotUpdateFunction - )}]; -${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`; - } - ); - mainTemplate.hooks.hash.tap("JsonpMainTemplatePlugin", hash => { - hash.update("jsonp"); - hash.update("6"); - }); - } + +function encodeF64(v) { + var buffer = []; + (0, _ieee.write)(buffer, v, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); + return buffer; +} + +function decodeF32(bytes) { + var buffer = Buffer.from(bytes); + return (0, _ieee.read)(buffer, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); +} + +function decodeF64(bytes) { + var buffer = Buffer.from(bytes); + return (0, _ieee.read)(buffer, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); +} + +/***/ }), + +/***/ 62904: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +// Copyright 2012 The Obvious Corporation. + +/* + * bits: Bitwise buffer utilities. The utilities here treat a buffer + * as a little-endian bigint, so the lowest-order bit is bit #0 of + * `buffer[0]`, and the highest-order bit is bit #7 of + * `buffer[buffer.length - 1]`. + */ + +/* + * Modules used + */ + +/* + * Exported bindings + */ + +/** + * Extracts the given number of bits from the buffer at the indicated + * index, returning a simple number as the result. If bits are requested + * that aren't covered by the buffer, the `defaultBit` is used as their + * value. + * + * The `bitLength` must be no more than 32. The `defaultBit` if not + * specified is taken to be `0`. + */ + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.extract = extract; +exports.inject = inject; +exports.getSign = getSign; +exports.highOrder = highOrder; + +function extract(buffer, bitIndex, bitLength, defaultBit) { + if (bitLength < 0 || bitLength > 32) { + throw new Error("Bad value for bitLength."); + } + + if (defaultBit === undefined) { + defaultBit = 0; + } else if (defaultBit !== 0 && defaultBit !== 1) { + throw new Error("Bad value for defaultBit."); + } + + var defaultByte = defaultBit * 0xff; + var result = 0; // All starts are inclusive. The {endByte, endBit} pair is exclusive, but + // if endBit !== 0, then endByte is inclusive. + + var lastBit = bitIndex + bitLength; + var startByte = Math.floor(bitIndex / 8); + var startBit = bitIndex % 8; + var endByte = Math.floor(lastBit / 8); + var endBit = lastBit % 8; + + if (endBit !== 0) { + // `(1 << endBit) - 1` is the mask of all bits up to but not including + // the endBit. + result = get(endByte) & (1 << endBit) - 1; + } + + while (endByte > startByte) { + endByte--; + result = result << 8 | get(endByte); + } + + result >>>= startBit; + return result; + + function get(index) { + var result = buffer[index]; + return result === undefined ? defaultByte : result; + } +} +/** + * Injects the given bits into the given buffer at the given index. Any + * bits in the value beyond the length to set are ignored. + */ + + +function inject(buffer, bitIndex, bitLength, value) { + if (bitLength < 0 || bitLength > 32) { + throw new Error("Bad value for bitLength."); + } + + var lastByte = Math.floor((bitIndex + bitLength - 1) / 8); + + if (bitIndex < 0 || lastByte >= buffer.length) { + throw new Error("Index out of range."); + } // Just keeping it simple, until / unless profiling shows that this + // is a problem. + + + var atByte = Math.floor(bitIndex / 8); + var atBit = bitIndex % 8; + + while (bitLength > 0) { + if (value & 1) { + buffer[atByte] |= 1 << atBit; + } else { + buffer[atByte] &= ~(1 << atBit); + } + + value >>= 1; + bitLength--; + atBit = (atBit + 1) % 8; + + if (atBit === 0) { + atByte++; + } + } } -module.exports = JsonpMainTemplatePlugin; +/** + * Gets the sign bit of the given buffer. + */ -/***/ }), +function getSign(buffer) { + return buffer[buffer.length - 1] >>> 7; +} +/** + * Gets the zero-based bit number of the highest-order bit with the + * given value in the given buffer. + * + * If the buffer consists entirely of the other bit value, then this returns + * `-1`. + */ -/***/ 92764: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +function highOrder(bit, buffer) { + var length = buffer.length; + var fullyWrongByte = (bit ^ 1) * 0xff; // the other-bit extended to a full byte + + while (length > 0 && buffer[length - 1] === fullyWrongByte) { + length--; + } + if (length === 0) { + // Degenerate case. The buffer consists entirely of ~bit. + return -1; + } -const JsonpMainTemplatePlugin = __webpack_require__(38017); -const JsonpChunkTemplatePlugin = __webpack_require__(31898); -const JsonpHotUpdateChunkTemplatePlugin = __webpack_require__(44458); + var byteToCheck = buffer[length - 1]; + var result = length * 8 - 1; -class JsonpTemplatePlugin { - apply(compiler) { - compiler.hooks.thisCompilation.tap("JsonpTemplatePlugin", compilation => { - new JsonpMainTemplatePlugin().apply(compilation.mainTemplate); - new JsonpChunkTemplatePlugin().apply(compilation.chunkTemplate); - new JsonpHotUpdateChunkTemplatePlugin().apply( - compilation.hotUpdateChunkTemplate - ); - }); - } -} + for (var i = 7; i > 0; i--) { + if ((byteToCheck >> i & 1) === bit) { + break; + } -module.exports = JsonpTemplatePlugin; + result--; + } + return result; +} /***/ }), -/***/ 92929: -/***/ (function(module, exports, __webpack_require__) { +/***/ 7276: +/***/ (function(__unused_webpack_module, exports) { "use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -const Compiler = __webpack_require__(58705); -const MultiCompiler = __webpack_require__(10238); -const NodeEnvironmentPlugin = __webpack_require__(52520); -const WebpackOptionsApply = __webpack_require__(2779); -const WebpackOptionsDefaulter = __webpack_require__(60016); -const validateSchema = __webpack_require__(68935); -const WebpackOptionsValidationError = __webpack_require__(285); -const webpackOptionsSchema = __webpack_require__(37863); -const RemovedPluginError = __webpack_require__(15377); -const version = __webpack_require__(71618)/* .version */ .i8; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.alloc = alloc; +exports.free = free; +exports.resize = resize; +exports.readInt = readInt; +exports.readUInt = readUInt; +exports.writeInt64 = writeInt64; +exports.writeUInt64 = writeUInt64; +// Copyright 2012 The Obvious Corporation. -/** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */ +/* + * bufs: Buffer utilities. + */ -/** - * @param {WebpackOptions} options options object - * @param {function(Error=, Stats=): void=} callback callback - * @returns {Compiler | MultiCompiler} the compiler object +/* + * Module variables */ -const webpack = (options, callback) => { - const webpackOptionsValidationErrors = validateSchema( - webpackOptionsSchema, - options - ); - if (webpackOptionsValidationErrors.length) { - throw new WebpackOptionsValidationError(webpackOptionsValidationErrors); - } - let compiler; - if (Array.isArray(options)) { - compiler = new MultiCompiler( - Array.from(options).map(options => webpack(options)) - ); - } else if (typeof options === "object") { - options = new WebpackOptionsDefaulter().process(options); - compiler = new Compiler(options.context); - compiler.options = options; - new NodeEnvironmentPlugin({ - infrastructureLogging: options.infrastructureLogging - }).apply(compiler); - if (options.plugins && Array.isArray(options.plugins)) { - for (const plugin of options.plugins) { - if (typeof plugin === "function") { - plugin.call(compiler, compiler); - } else { - plugin.apply(compiler); - } - } - } - compiler.hooks.environment.call(); - compiler.hooks.afterEnvironment.call(); - compiler.options = new WebpackOptionsApply().process(options, compiler); - } else { - throw new Error("Invalid argument: options"); - } - if (callback) { - if (typeof callback !== "function") { - throw new Error("Invalid argument: callback"); - } - if ( - options.watch === true || - (Array.isArray(options) && options.some(o => o.watch)) - ) { - const watchOptions = Array.isArray(options) - ? options.map(o => o.watchOptions || {}) - : options.watchOptions || {}; - return compiler.watch(watchOptions, callback); - } - compiler.run(callback); - } - return compiler; -}; +/** Pool of buffers, where `bufPool[x].length === x`. */ +var bufPool = []; +/** Maximum length of kept temporary buffers. */ -exports = module.exports = webpack; -exports.version = version; +var TEMP_BUF_MAXIMUM_LENGTH = 20; +/** Minimum exactly-representable 64-bit int. */ -webpack.WebpackOptionsDefaulter = WebpackOptionsDefaulter; -webpack.WebpackOptionsApply = WebpackOptionsApply; -webpack.Compiler = Compiler; -webpack.MultiCompiler = MultiCompiler; -webpack.NodeEnvironmentPlugin = NodeEnvironmentPlugin; -// @ts-ignore Global @this directive is not supported -webpack.validate = validateSchema.bind(this, webpackOptionsSchema); -webpack.validateSchema = validateSchema; -webpack.WebpackOptionsValidationError = WebpackOptionsValidationError; +var MIN_EXACT_INT64 = -0x8000000000000000; +/** Maximum exactly-representable 64-bit int. */ -const exportPlugins = (obj, mappings) => { - for (const name of Object.keys(mappings)) { - Object.defineProperty(obj, name, { - configurable: false, - enumerable: true, - get: mappings[name] - }); - } -}; +var MAX_EXACT_INT64 = 0x7ffffffffffffc00; +/** Maximum exactly-representable 64-bit uint. */ -exportPlugins(exports, { - AutomaticPrefetchPlugin: () => __webpack_require__(51596), - BannerPlugin: () => __webpack_require__(4009), - CachePlugin: () => __webpack_require__(6465), - ContextExclusionPlugin: () => __webpack_require__(10706), - ContextReplacementPlugin: () => __webpack_require__(27295), - DefinePlugin: () => __webpack_require__(97374), - Dependency: () => __webpack_require__(57282), - DllPlugin: () => __webpack_require__(45255), - DllReferencePlugin: () => __webpack_require__(86231), - EnvironmentPlugin: () => __webpack_require__(6098), - EvalDevToolModulePlugin: () => __webpack_require__(65200), - EvalSourceMapDevToolPlugin: () => __webpack_require__(99994), - ExtendedAPIPlugin: () => __webpack_require__(17270), - ExternalsPlugin: () => __webpack_require__(75705), - HashedModuleIdsPlugin: () => __webpack_require__(50268), - HotModuleReplacementPlugin: () => __webpack_require__(69575), - IgnorePlugin: () => __webpack_require__(41364), - LibraryTemplatePlugin: () => __webpack_require__(65237), - LoaderOptionsPlugin: () => __webpack_require__(48775), - LoaderTargetPlugin: () => __webpack_require__(95154), - MemoryOutputFileSystem: () => __webpack_require__(50332), - Module: () => __webpack_require__(75993), - ModuleFilenameHelpers: () => __webpack_require__(71474), - NamedChunksPlugin: () => __webpack_require__(70419), - NamedModulesPlugin: () => __webpack_require__(86707), - NoEmitOnErrorsPlugin: () => __webpack_require__(22615), - NormalModuleReplacementPlugin: () => - __webpack_require__(73253), - PrefetchPlugin: () => __webpack_require__(27850), - ProgressPlugin: () => __webpack_require__(63123), - ProvidePlugin: () => __webpack_require__(72861), - SetVarMainTemplatePlugin: () => __webpack_require__(37098), - SingleEntryPlugin: () => __webpack_require__(19070), - SourceMapDevToolPlugin: () => __webpack_require__(11851), - Stats: () => __webpack_require__(99977), - Template: () => __webpack_require__(96066), - UmdMainTemplatePlugin: () => __webpack_require__(75374), - WatchIgnorePlugin: () => __webpack_require__(88015) -}); -exportPlugins((exports.dependencies = {}), { - DependencyReference: () => __webpack_require__(71722) -}); -exportPlugins((exports.optimize = {}), { - AggressiveMergingPlugin: () => __webpack_require__(88197), - AggressiveSplittingPlugin: () => - __webpack_require__(26688), - ChunkModuleIdRangePlugin: () => - __webpack_require__(30346), - LimitChunkCountPlugin: () => __webpack_require__(3846), - MinChunkSizePlugin: () => __webpack_require__(55607), - ModuleConcatenationPlugin: () => - __webpack_require__(45184), - OccurrenceOrderPlugin: () => __webpack_require__(67340), - OccurrenceModuleOrderPlugin: () => - __webpack_require__(62000), - OccurrenceChunkOrderPlugin: () => - __webpack_require__(83741), - RuntimeChunkPlugin: () => __webpack_require__(76894), - SideEffectsFlagPlugin: () => __webpack_require__(83654), - SplitChunksPlugin: () => __webpack_require__(60474) -}); -exportPlugins((exports.web = {}), { - FetchCompileWasmTemplatePlugin: () => - __webpack_require__(52669), - JsonpTemplatePlugin: () => __webpack_require__(92764) -}); -exportPlugins((exports.webworker = {}), { - WebWorkerTemplatePlugin: () => __webpack_require__(21328) -}); -exportPlugins((exports.node = {}), { - NodeTemplatePlugin: () => __webpack_require__(90010), - ReadFileCompileWasmTemplatePlugin: () => - __webpack_require__(73839) -}); -exportPlugins((exports.debug = {}), { - ProfilingPlugin: () => __webpack_require__(72890) -}); -exportPlugins((exports.util = {}), { - createHash: () => __webpack_require__(15660) -}); +var MAX_EXACT_UINT64 = 0xfffffffffffff800; +/** + * The int value consisting just of a 1 in bit #32 (that is, one more + * than the maximum 32-bit unsigned value). + */ -const defineMissingPluginError = (namespace, pluginName, errorMessage) => { - Object.defineProperty(namespace, pluginName, { - configurable: false, - enumerable: true, - get() { - throw new RemovedPluginError(errorMessage); - } - }); -}; +var BIT_32 = 0x100000000; +/** + * The int value consisting just of a 1 in bit #64 (that is, one more + * than the maximum 64-bit unsigned value). + */ -// TODO remove in webpack 5 -defineMissingPluginError( - exports.optimize, - "UglifyJsPlugin", - "webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." -); +var BIT_64 = 0x10000000000000000; +/* + * Helper functions + */ -// TODO remove in webpack 5 -defineMissingPluginError( - exports.optimize, - "CommonsChunkPlugin", - "webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead." -); +/** + * Masks off all but the lowest bit set of the given number. + */ +function lowestBit(num) { + return num & -num; +} +/** + * Gets whether trying to add the second number to the first is lossy + * (inexact). The first number is meant to be an accumulated result. + */ -/***/ }), -/***/ 37919: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { +function isLossyToAdd(accum, num) { + if (num === 0) { + return false; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + var lowBit = lowestBit(num); + var added = accum + lowBit; + if (added === accum) { + return true; + } -const { ConcatSource } = __webpack_require__(53665); + if (added - lowBit !== accum) { + return true; + } -class WebWorkerChunkTemplatePlugin { - apply(chunkTemplate) { - chunkTemplate.hooks.render.tap( - "WebWorkerChunkTemplatePlugin", - (modules, chunk) => { - const chunkCallbackName = chunkTemplate.outputOptions.chunkCallbackName; - const globalObject = chunkTemplate.outputOptions.globalObject; - const source = new ConcatSource(); - source.add( - `${globalObject}[${JSON.stringify( - chunkCallbackName - )}](${JSON.stringify(chunk.ids)},` - ); - source.add(modules); - source.add(")"); - return source; - } - ); - chunkTemplate.hooks.hash.tap("WebWorkerChunkTemplatePlugin", hash => { - hash.update("webworker"); - hash.update("3"); - hash.update(`${chunkTemplate.outputOptions.chunkCallbackName}`); - hash.update(`${chunkTemplate.outputOptions.globalObject}`); - }); - } + return false; } -module.exports = WebWorkerChunkTemplatePlugin; - +/* + * Exported functions + */ -/***/ }), +/** + * Allocates a buffer of the given length, which is initialized + * with all zeroes. This returns a buffer from the pool if it is + * available, or a freshly-allocated buffer if not. + */ -/***/ 45493: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +function alloc(length) { + var result = bufPool[length]; -const { ConcatSource } = __webpack_require__(53665); + if (result) { + bufPool[length] = undefined; + } else { + result = new Buffer(length); + } -class WebWorkerHotUpdateChunkTemplatePlugin { - apply(hotUpdateChunkTemplate) { - hotUpdateChunkTemplate.hooks.render.tap( - "WebWorkerHotUpdateChunkTemplatePlugin", - (modulesSource, modules, removedModules, hash, id) => { - const hotUpdateFunction = - hotUpdateChunkTemplate.outputOptions.hotUpdateFunction; - const globalObject = hotUpdateChunkTemplate.outputOptions.globalObject; - const source = new ConcatSource(); - source.add( - `${globalObject}[${JSON.stringify( - hotUpdateFunction - )}](${JSON.stringify(id)},` - ); - source.add(modulesSource); - source.add(")"); - return source; - } - ); - hotUpdateChunkTemplate.hooks.hash.tap( - "WebWorkerHotUpdateChunkTemplatePlugin", - hash => { - hash.update("WebWorkerHotUpdateChunkTemplatePlugin"); - hash.update("3"); - hash.update( - hotUpdateChunkTemplate.outputOptions.hotUpdateFunction + "" - ); - hash.update(hotUpdateChunkTemplate.outputOptions.globalObject + ""); - } - ); - } + result.fill(0); + return result; } -module.exports = WebWorkerHotUpdateChunkTemplatePlugin; +/** + * Releases a buffer back to the pool. + */ -/***/ }), +function free(buffer) { + var length = buffer.length; -/***/ 72337: -/***/ (function(module) { + if (length < TEMP_BUF_MAXIMUM_LENGTH) { + bufPool[length] = buffer; + } +} +/** + * Resizes a buffer, returning a new buffer. Returns the argument if + * the length wouldn't actually change. This function is only safe to + * use if the given buffer was allocated within this module (since + * otherwise the buffer might possibly be shared externally). + */ -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ -// eslint-disable-next-line no-unused-vars -var hotAddUpdateChunk = undefined; -var parentHotUpdateCallback = undefined; -var $require$ = undefined; -var $hotChunkFilename$ = undefined; -var $hotMainFilename$ = undefined; -var installedChunks = undefined; -var importScripts = undefined; -module.exports = function() { - // eslint-disable-next-line no-unused-vars - function webpackHotUpdateCallback(chunkId, moreModules) { - hotAddUpdateChunk(chunkId, moreModules); - if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); - } //$semicolon +function resize(buffer, length) { + if (length === buffer.length) { + return buffer; + } - // eslint-disable-next-line no-unused-vars - function hotDownloadUpdateChunk(chunkId) { - importScripts($require$.p + $hotChunkFilename$); - } + var newBuf = alloc(length); + buffer.copy(newBuf); + free(buffer); + return newBuf; +} +/** + * Reads an arbitrary signed int from a buffer. + */ - // eslint-disable-next-line no-unused-vars - function hotDownloadManifest(requestTimeout) { - requestTimeout = requestTimeout || 10000; - return new Promise(function(resolve, reject) { - if (typeof XMLHttpRequest === "undefined") { - return reject(new Error("No browser support")); - } - try { - var request = new XMLHttpRequest(); - var requestPath = $require$.p + $hotMainFilename$; - request.open("GET", requestPath, true); - request.timeout = requestTimeout; - request.send(null); - } catch (err) { - return reject(err); - } - request.onreadystatechange = function() { - if (request.readyState !== 4) return; - if (request.status === 0) { - // timeout - reject( - new Error("Manifest request to " + requestPath + " timed out.") - ); - } else if (request.status === 404) { - // no update available - resolve(); - } else if (request.status !== 200 && request.status !== 304) { - // other failure - reject(new Error("Manifest request to " + requestPath + " failed.")); - } else { - // success - try { - var update = JSON.parse(request.responseText); - } catch (e) { - reject(e); - return; - } - resolve(update); - } - }; - }); - } - //eslint-disable-next-line no-unused-vars - function hotDisposeChunk(chunkId) { - delete installedChunks[chunkId]; - } -}; +function readInt(buffer) { + var length = buffer.length; + var positive = buffer[length - 1] < 0x80; + var result = positive ? 0 : -1; + var lossy = false; // Note: We can't use bit manipulation here, since that stops + // working if the result won't fit in a 32-bit int. + + if (length < 7) { + // Common case which can't possibly be lossy (because the result has + // no more than 48 bits, and loss only happens with 54 or more). + for (var i = length - 1; i >= 0; i--) { + result = result * 0x100 + buffer[i]; + } + } else { + for (var _i = length - 1; _i >= 0; _i--) { + var one = buffer[_i]; + result *= 0x100; + if (isLossyToAdd(result, one)) { + lossy = true; + } -/***/ }), + result += one; + } + } -/***/ 20482: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + return { + value: result, + lossy: lossy + }; +} +/** + * Reads an arbitrary unsigned int from a buffer. + */ -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ +function readUInt(buffer) { + var length = buffer.length; + var result = 0; + var lossy = false; // Note: See above in re bit manipulation. -const Template = __webpack_require__(96066); + if (length < 7) { + // Common case which can't possibly be lossy (see above). + for (var i = length - 1; i >= 0; i--) { + result = result * 0x100 + buffer[i]; + } + } else { + for (var _i2 = length - 1; _i2 >= 0; _i2--) { + var one = buffer[_i2]; + result *= 0x100; -class WebWorkerMainTemplatePlugin { - apply(mainTemplate) { - const needChunkOnDemandLoadingCode = chunk => { - for (const chunkGroup of chunk.groupsIterable) { - if (chunkGroup.getNumberOfChildren() > 0) return true; - } - return false; - }; - mainTemplate.hooks.localVars.tap( - "WebWorkerMainTemplatePlugin", - (source, chunk) => { - if (needChunkOnDemandLoadingCode(chunk)) { - return Template.asString([ - source, - "", - "// object to store loaded chunks", - '// "1" means "already loaded"', - "var installedChunks = {", - Template.indent( - chunk.ids.map(id => `${JSON.stringify(id)}: 1`).join(",\n") - ), - "};" - ]); - } - return source; - } - ); - mainTemplate.hooks.requireEnsure.tap( - "WebWorkerMainTemplatePlugin", - (_, chunk, hash) => { - const chunkFilename = mainTemplate.outputOptions.chunkFilename; - const chunkMaps = chunk.getChunkMaps(); - return Template.asString([ - "promises.push(Promise.resolve().then(function() {", - Template.indent([ - '// "1" is the signal for "already loaded"', - "if(!installedChunks[chunkId]) {", - Template.indent([ - "importScripts(" + - "__webpack_require__.p + " + - mainTemplate.getAssetPath(JSON.stringify(chunkFilename), { - hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, - hashWithLength: length => - `" + ${mainTemplate.renderCurrentHashCode( - hash, - length - )} + "`, - chunk: { - id: '" + chunkId + "', - hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, - hashWithLength(length) { - const shortChunkHashMap = Object.create(null); - for (const chunkId of Object.keys(chunkMaps.hash)) { - if (typeof chunkMaps.hash[chunkId] === "string") { - shortChunkHashMap[chunkId] = chunkMaps.hash[ - chunkId - ].substr(0, length); - } - } - return `" + ${JSON.stringify( - shortChunkHashMap - )}[chunkId] + "`; - }, - contentHash: { - javascript: `" + ${JSON.stringify( - chunkMaps.contentHash.javascript - )}[chunkId] + "` - }, - contentHashWithLength: { - javascript: length => { - const shortContentHashMap = {}; - const contentHash = chunkMaps.contentHash.javascript; - for (const chunkId of Object.keys(contentHash)) { - if (typeof contentHash[chunkId] === "string") { - shortContentHashMap[chunkId] = contentHash[ - chunkId - ].substr(0, length); - } - } - return `" + ${JSON.stringify( - shortContentHashMap - )}[chunkId] + "`; - } - }, - name: `" + (${JSON.stringify( - chunkMaps.name - )}[chunkId]||chunkId) + "` - }, - contentHashType: "javascript" - }) + - ");" - ]), - "}" - ]), - "}));" - ]); - } - ); - mainTemplate.hooks.bootstrap.tap( - "WebWorkerMainTemplatePlugin", - (source, chunk, hash) => { - if (needChunkOnDemandLoadingCode(chunk)) { - const chunkCallbackName = - mainTemplate.outputOptions.chunkCallbackName; - const globalObject = mainTemplate.outputOptions.globalObject; - return Template.asString([ - source, - `${globalObject}[${JSON.stringify( - chunkCallbackName - )}] = function webpackChunkCallback(chunkIds, moreModules) {`, - Template.indent([ - "for(var moduleId in moreModules) {", - Template.indent( - mainTemplate.renderAddModule( - hash, - chunk, - "moduleId", - "moreModules[moduleId]" - ) - ), - "}", - "while(chunkIds.length)", - Template.indent("installedChunks[chunkIds.pop()] = 1;") - ]), - "};" - ]); - } - return source; - } - ); - mainTemplate.hooks.hotBootstrap.tap( - "WebWorkerMainTemplatePlugin", - (source, chunk, hash) => { - const hotUpdateChunkFilename = - mainTemplate.outputOptions.hotUpdateChunkFilename; - const hotUpdateMainFilename = - mainTemplate.outputOptions.hotUpdateMainFilename; - const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction; - const globalObject = mainTemplate.outputOptions.globalObject; - const currentHotUpdateChunkFilename = mainTemplate.getAssetPath( - JSON.stringify(hotUpdateChunkFilename), - { - hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, - hashWithLength: length => - `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`, - chunk: { - id: '" + chunkId + "' - } - } - ); - const currentHotUpdateMainFilename = mainTemplate.getAssetPath( - JSON.stringify(hotUpdateMainFilename), - { - hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, - hashWithLength: length => - `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "` - } - ); + if (isLossyToAdd(result, one)) { + lossy = true; + } - return ( - source + - "\n" + - `var parentHotUpdateCallback = ${globalObject}[${JSON.stringify( - hotUpdateFunction - )}];\n` + - `${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ` + - Template.getFunctionContent( - __webpack_require__(72337) - ) - .replace(/\/\/\$semicolon/g, ";") - .replace(/\$require\$/g, mainTemplate.requireFn) - .replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename) - .replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename) - .replace(/\$hash\$/g, JSON.stringify(hash)) - ); - } - ); - mainTemplate.hooks.hash.tap("WebWorkerMainTemplatePlugin", hash => { - hash.update("webworker"); - hash.update("4"); - }); - } + result += one; + } + } + + return { + value: result, + lossy: lossy + }; } -module.exports = WebWorkerMainTemplatePlugin; +/** + * Writes a little-endian 64-bit signed int into a buffer. + */ -/***/ }), +function writeInt64(value, buffer) { + if (value < MIN_EXACT_INT64 || value > MAX_EXACT_INT64) { + throw new Error("Value out of range."); + } -/***/ 21328: -/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + if (value < 0) { + value += BIT_64; + } -"use strict"; -/* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra -*/ + writeUInt64(value, buffer); +} +/** + * Writes a little-endian 64-bit unsigned int into a buffer. + */ -const WebWorkerMainTemplatePlugin = __webpack_require__(20482); -const WebWorkerChunkTemplatePlugin = __webpack_require__(37919); -const WebWorkerHotUpdateChunkTemplatePlugin = __webpack_require__(45493); +function writeUInt64(value, buffer) { + if (value < 0 || value > MAX_EXACT_UINT64) { + throw new Error("Value out of range."); + } -class WebWorkerTemplatePlugin { - apply(compiler) { - compiler.hooks.thisCompilation.tap( - "WebWorkerTemplatePlugin", - compilation => { - new WebWorkerMainTemplatePlugin().apply(compilation.mainTemplate); - new WebWorkerChunkTemplatePlugin().apply(compilation.chunkTemplate); - new WebWorkerHotUpdateChunkTemplatePlugin().apply( - compilation.hotUpdateChunkTemplate - ); - } - ); - } + var lowWord = value % BIT_32; + var highWord = Math.floor(value / BIT_32); + buffer.writeUInt32LE(lowWord, 0); + buffer.writeUInt32LE(highWord, 4); } -module.exports = WebWorkerTemplatePlugin; - /***/ }), -/***/ 19728: -/***/ (function(__unused_webpack_module, exports) { +/***/ 89943: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; @@ -115402,261 +114774,403 @@ module.exports = WebWorkerTemplatePlugin; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.cloneNode = cloneNode; +exports.decodeInt64 = decodeInt64; +exports.decodeUInt64 = decodeUInt64; +exports.decodeInt32 = decodeInt32; +exports.decodeUInt32 = decodeUInt32; +exports.encodeU32 = encodeU32; +exports.encodeI32 = encodeI32; +exports.encodeI64 = encodeI64; +exports.MAX_NUMBER_OF_BYTE_U64 = exports.MAX_NUMBER_OF_BYTE_U32 = void 0; -function cloneNode(n) { - // $FlowIgnore - var newObj = {}; +var _leb = _interopRequireDefault(__webpack_require__(80881)); - for (var k in n) { - newObj[k] = n[k]; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return newObj; +/** + * According to https://webassembly.github.io/spec/core/binary/values.html#binary-int + * max = ceil(32/7) + */ +var MAX_NUMBER_OF_BYTE_U32 = 5; +/** + * According to https://webassembly.github.io/spec/core/binary/values.html#binary-int + * max = ceil(64/7) + */ + +exports.MAX_NUMBER_OF_BYTE_U32 = MAX_NUMBER_OF_BYTE_U32; +var MAX_NUMBER_OF_BYTE_U64 = 10; +exports.MAX_NUMBER_OF_BYTE_U64 = MAX_NUMBER_OF_BYTE_U64; + +function decodeInt64(encodedBuffer, index) { + return _leb.default.decodeInt64(encodedBuffer, index); +} + +function decodeUInt64(encodedBuffer, index) { + return _leb.default.decodeUInt64(encodedBuffer, index); +} + +function decodeInt32(encodedBuffer, index) { + return _leb.default.decodeInt32(encodedBuffer, index); +} + +function decodeUInt32(encodedBuffer, index) { + return _leb.default.decodeUInt32(encodedBuffer, index); +} + +function encodeU32(v) { + return _leb.default.encodeUInt32(v); +} + +function encodeI32(v) { + return _leb.default.encodeInt32(v); +} + +function encodeI64(v) { + return _leb.default.encodeInt64(v); } /***/ }), -/***/ 81875: +/***/ 80881: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; +// Copyright 2012 The Obvious Corporation. + +/* + * leb: LEB128 utilities. + */ + +/* + * Modules used + */ Object.defineProperty(exports, "__esModule", ({ value: true })); -var _exportNames = { - numberLiteralFromRaw: true, - withLoc: true, - withRaw: true, - funcParam: true, - indexLiteral: true, - memIndexLiteral: true, - instruction: true, - objectInstruction: true, - traverse: true, - signatures: true, - cloneNode: true -}; -Object.defineProperty(exports, "numberLiteralFromRaw", ({ - enumerable: true, - get: function get() { - return _nodeHelpers.numberLiteralFromRaw; - } -})); -Object.defineProperty(exports, "withLoc", ({ - enumerable: true, - get: function get() { - return _nodeHelpers.withLoc; - } -})); -Object.defineProperty(exports, "withRaw", ({ - enumerable: true, - get: function get() { - return _nodeHelpers.withRaw; - } -})); -Object.defineProperty(exports, "funcParam", ({ - enumerable: true, - get: function get() { - return _nodeHelpers.funcParam; - } -})); -Object.defineProperty(exports, "indexLiteral", ({ - enumerable: true, - get: function get() { - return _nodeHelpers.indexLiteral; - } -})); -Object.defineProperty(exports, "memIndexLiteral", ({ - enumerable: true, - get: function get() { - return _nodeHelpers.memIndexLiteral; - } -})); -Object.defineProperty(exports, "instruction", ({ - enumerable: true, - get: function get() { - return _nodeHelpers.instruction; - } -})); -Object.defineProperty(exports, "objectInstruction", ({ - enumerable: true, - get: function get() { - return _nodeHelpers.objectInstruction; - } -})); -Object.defineProperty(exports, "traverse", ({ - enumerable: true, - get: function get() { - return _traverse.traverse; - } -})); -Object.defineProperty(exports, "signatures", ({ - enumerable: true, - get: function get() { - return _signatures.signatures; - } -})); -Object.defineProperty(exports, "cloneNode", ({ - enumerable: true, - get: function get() { - return _clone.cloneNode; - } -})); +exports.default = void 0; + +var _long = _interopRequireDefault(__webpack_require__(77960)); + +var bits = _interopRequireWildcard(__webpack_require__(62904)); + +var bufs = _interopRequireWildcard(__webpack_require__(7276)); + +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 }; } + +/* + * Module variables + */ + +/** The minimum possible 32-bit signed int. */ +var MIN_INT32 = -0x80000000; +/** The maximum possible 32-bit signed int. */ + +var MAX_INT32 = 0x7fffffff; +/** The maximum possible 32-bit unsigned int. */ + +var MAX_UINT32 = 0xffffffff; +/** The minimum possible 64-bit signed int. */ +// const MIN_INT64 = -0x8000000000000000; + +/** + * The maximum possible 64-bit signed int that is representable as a + * JavaScript number. + */ +// const MAX_INT64 = 0x7ffffffffffffc00; + +/** + * The maximum possible 64-bit unsigned int that is representable as a + * JavaScript number. + */ +// const MAX_UINT64 = 0xfffffffffffff800; + +/* + * Helper functions + */ + +/** + * Determines the number of bits required to encode the number + * represented in the given buffer as a signed value. The buffer is + * taken to represent a signed number in little-endian form. + * + * The number of bits to encode is the (zero-based) bit number of the + * highest-order non-sign-matching bit, plus two. For example: + * + * 11111011 01110101 + * high low + * + * The sign bit here is 1 (that is, it's a negative number). The highest + * bit number that doesn't match the sign is bit #10 (where the lowest-order + * bit is bit #0). So, we have to encode at least 12 bits total. + * + * As a special degenerate case, the numbers 0 and -1 each require just one bit. + */ + +function signedBitCount(buffer) { + return bits.highOrder(bits.getSign(buffer) ^ 1, buffer) + 2; +} +/** + * Determines the number of bits required to encode the number + * represented in the given buffer as an unsigned value. The buffer is + * taken to represent an unsigned number in little-endian form. + * + * The number of bits to encode is the (zero-based) bit number of the + * highest-order 1 bit, plus one. For example: + * + * 00011000 01010011 + * high low + * + * The highest-order 1 bit here is bit #12 (where the lowest-order bit + * is bit #0). So, we have to encode at least 13 bits total. + * + * As a special degenerate case, the number 0 requires 1 bit. + */ -var _nodes = __webpack_require__(94841); -Object.keys(_nodes).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _nodes[key]; - } - }); -}); +function unsignedBitCount(buffer) { + var result = bits.highOrder(1, buffer) + 1; + return result ? result : 1; +} +/** + * Common encoder for both signed and unsigned ints. This takes a + * bigint-ish buffer, returning an LEB128-encoded buffer. + */ -var _nodeHelpers = __webpack_require__(1004); -var _traverse = __webpack_require__(29436); +function encodeBufferCommon(buffer, signed) { + var signBit; + var bitCount; -var _signatures = __webpack_require__(77392); + if (signed) { + signBit = bits.getSign(buffer); + bitCount = signedBitCount(buffer); + } else { + signBit = 0; + bitCount = unsignedBitCount(buffer); + } -var _utils = __webpack_require__(38456); + var byteCount = Math.ceil(bitCount / 7); + var result = bufs.alloc(byteCount); -Object.keys(_utils).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _utils[key]; - } - }); -}); + for (var i = 0; i < byteCount; i++) { + var payload = bits.extract(buffer, i * 7, 7, signBit); + result[i] = payload | 0x80; + } // Mask off the top bit of the last byte, to indicate the end of the + // encoding. -var _clone = __webpack_require__(19728); -/***/ }), + result[byteCount - 1] &= 0x7f; + return result; +} +/** + * Gets the byte-length of the value encoded in the given buffer at + * the given index. + */ -/***/ 1004: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { -"use strict"; +function encodedLength(encodedBuffer, index) { + var result = 0; + while (encodedBuffer[index + result] >= 0x80) { + result++; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.numberLiteralFromRaw = numberLiteralFromRaw; -exports.instruction = instruction; -exports.objectInstruction = objectInstruction; -exports.withLoc = withLoc; -exports.withRaw = withRaw; -exports.funcParam = funcParam; -exports.indexLiteral = indexLiteral; -exports.memIndexLiteral = memIndexLiteral; + result++; // to account for the last byte -var _wastParser = __webpack_require__(9016); + if (index + result > encodedBuffer.length) {// FIXME(sven): seems to cause false positives + // throw new Error("integer representation too long"); + } -var _nodes = __webpack_require__(94841); + return result; +} +/** + * Common decoder for both signed and unsigned ints. This takes an + * LEB128-encoded buffer, returning a bigint-ish buffer. + */ -function numberLiteralFromRaw(rawValue) { - var instructionType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "i32"; - var original = rawValue; // Remove numeric separators _ - if (typeof rawValue === "string") { - rawValue = rawValue.replace(/_/g, ""); - } +function decodeBufferCommon(encodedBuffer, index, signed) { + index = index === undefined ? 0 : index; + var length = encodedLength(encodedBuffer, index); + var bitLength = length * 7; + var byteLength = Math.ceil(bitLength / 8); + var result = bufs.alloc(byteLength); + var outIndex = 0; - if (typeof rawValue === "number") { - return (0, _nodes.numberLiteral)(rawValue, String(original)); - } else { - switch (instructionType) { - case "i32": - { - return (0, _nodes.numberLiteral)((0, _wastParser.parse32I)(rawValue), String(original)); - } + while (length > 0) { + bits.inject(result, outIndex, 7, encodedBuffer[index]); + outIndex += 7; + index++; + length--; + } - case "u32": - { - return (0, _nodes.numberLiteral)((0, _wastParser.parseU32)(rawValue), String(original)); - } + var signBit; + var signByte; - case "i64": - { - return (0, _nodes.longNumberLiteral)((0, _wastParser.parse64I)(rawValue), String(original)); - } + if (signed) { + // Sign-extend the last byte. + var lastByte = result[byteLength - 1]; + var endBit = outIndex % 8; - case "f32": - { - return (0, _nodes.floatLiteral)((0, _wastParser.parse32F)(rawValue), (0, _wastParser.isNanLiteral)(rawValue), (0, _wastParser.isInfLiteral)(rawValue), String(original)); - } - // f64 + if (endBit !== 0) { + var shift = 32 - endBit; // 32 because JS bit ops work on 32-bit ints. - default: - { - return (0, _nodes.floatLiteral)((0, _wastParser.parse64F)(rawValue), (0, _wastParser.isNanLiteral)(rawValue), (0, _wastParser.isInfLiteral)(rawValue), String(original)); - } + lastByte = result[byteLength - 1] = lastByte << shift >> shift & 0xff; } + + signBit = lastByte >> 7; + signByte = signBit * 0xff; + } else { + signBit = 0; + signByte = 0; + } // Slice off any superfluous bytes, that is, ones that add no meaningful + // bits (because the value would be the same if they were removed). + + + while (byteLength > 1 && result[byteLength - 1] === signByte && (!signed || result[byteLength - 2] >> 7 === signBit)) { + byteLength--; } + + result = bufs.resize(result, byteLength); + return { + value: result, + nextIndex: index + }; } +/* + * Exported bindings + */ -function instruction(id) { - var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var namedArgs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - return (0, _nodes.instr)(id, undefined, args, namedArgs); + +function encodeIntBuffer(buffer) { + return encodeBufferCommon(buffer, true); } -function objectInstruction(id, object) { - var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var namedArgs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - return (0, _nodes.instr)(id, object, args, namedArgs); +function decodeIntBuffer(encodedBuffer, index) { + return decodeBufferCommon(encodedBuffer, index, true); } -/** - * Decorators - */ +function encodeInt32(num) { + var buf = bufs.alloc(4); + buf.writeInt32LE(num, 0); + var result = encodeIntBuffer(buf); + bufs.free(buf); + return result; +} -function withLoc(n, end, start) { - var loc = { - start: start, - end: end +function decodeInt32(encodedBuffer, index) { + var result = decodeIntBuffer(encodedBuffer, index); + var parsed = bufs.readInt(result.value); + var value = parsed.value; + bufs.free(result.value); + + if (value < MIN_INT32 || value > MAX_INT32) { + throw new Error("integer too large"); + } + + return { + value: value, + nextIndex: result.nextIndex }; - n.loc = loc; - return n; } -function withRaw(n, raw) { - n.raw = raw; - return n; +function encodeInt64(num) { + var buf = bufs.alloc(8); + bufs.writeInt64(num, buf); + var result = encodeIntBuffer(buf); + bufs.free(buf); + return result; } -function funcParam(valtype, id) { +function decodeInt64(encodedBuffer, index) { + var result = decodeIntBuffer(encodedBuffer, index); + + var value = _long.default.fromBytesLE(result.value, false); + + bufs.free(result.value); return { - id: id, - valtype: valtype + value: value, + nextIndex: result.nextIndex, + lossy: false }; } -function indexLiteral(value) { - // $FlowIgnore - var x = numberLiteralFromRaw(value, "u32"); - return x; +function encodeUIntBuffer(buffer) { + return encodeBufferCommon(buffer, false); } -function memIndexLiteral(value) { - // $FlowIgnore - var x = numberLiteralFromRaw(value, "u32"); - return x; +function decodeUIntBuffer(encodedBuffer, index) { + return decodeBufferCommon(encodedBuffer, index, false); +} + +function encodeUInt32(num) { + var buf = bufs.alloc(4); + buf.writeUInt32LE(num, 0); + var result = encodeUIntBuffer(buf); + bufs.free(buf); + return result; +} + +function decodeUInt32(encodedBuffer, index) { + var result = decodeUIntBuffer(encodedBuffer, index); + var parsed = bufs.readUInt(result.value); + var value = parsed.value; + bufs.free(result.value); + + if (value > MAX_UINT32) { + throw new Error("integer too large"); + } + + return { + value: value, + nextIndex: result.nextIndex + }; +} + +function encodeUInt64(num) { + var buf = bufs.alloc(8); + bufs.writeUInt64(num, buf); + var result = encodeUIntBuffer(buf); + bufs.free(buf); + return result; +} + +function decodeUInt64(encodedBuffer, index) { + var result = decodeUIntBuffer(encodedBuffer, index); + + var value = _long.default.fromBytesLE(result.value, true); + + bufs.free(result.value); + return { + value: value, + nextIndex: result.nextIndex, + lossy: false + }; } +var _default = { + decodeInt32: decodeInt32, + decodeInt64: decodeInt64, + decodeIntBuffer: decodeIntBuffer, + decodeUInt32: decodeUInt32, + decodeUInt64: decodeUInt64, + decodeUIntBuffer: decodeUIntBuffer, + encodeInt32: encodeInt32, + encodeInt64: encodeInt64, + encodeIntBuffer: encodeIntBuffer, + encodeUInt32: encodeUInt32, + encodeUInt64: encodeUInt64, + encodeUIntBuffer: encodeUIntBuffer +}; +exports.default = _default; + /***/ }), -/***/ 89231: +/***/ 19418: /***/ (function(__unused_webpack_module, exports) { "use strict"; @@ -115665,150 +115179,168 @@ function memIndexLiteral(value) { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createPath = createPath; - -function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } - -function findParent(_ref, cb) { - var parentPath = _ref.parentPath; - - if (parentPath == null) { - throw new Error("node is root"); - } - - var currentPath = parentPath; +exports.decode = decode; - while (cb(currentPath) !== false) { - // Hit the root node, stop - // $FlowIgnore - if (currentPath.parentPath == null) { - return null; - } // $FlowIgnore +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } +function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } - currentPath = currentPath.parentPath; +function con(b) { + if ((b & 0xc0) === 0x80) { + return b & 0x3f; + } else { + throw new Error("invalid UTF-8 encoding"); } - - return currentPath.node; } -function insertBefore(context, newNode) { - return insert(context, newNode); +function code(min, n) { + if (n < min || 0xd800 <= n && n < 0xe000 || n >= 0x10000) { + throw new Error("invalid UTF-8 encoding"); + } else { + return n; + } } -function insertAfter(context, newNode) { - return insert(context, newNode, 1); +function decode(bytes) { + return _decode(bytes).map(function (x) { + return String.fromCharCode(x); + }).join(""); } -function insert(_ref2, newNode) { - var node = _ref2.node, - inList = _ref2.inList, - parentPath = _ref2.parentPath, - parentKey = _ref2.parentKey; - var indexOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - - if (!inList) { - throw new Error('inList' + " error: " + ("insert can only be used for nodes that are within lists" || 0)); +function _decode(bytes) { + if (bytes.length === 0) { + return []; } + /** + * 1 byte + */ - if (!(parentPath != null)) { - throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || 0)); - } - // $FlowIgnore - var parentList = parentPath.node[parentKey]; - var indexInList = parentList.findIndex(function (n) { - return n === node; - }); - parentList.splice(indexInList + indexOffset, 0, newNode); -} + { + var _bytes = _toArray(bytes), + b1 = _bytes[0], + bs = _bytes.slice(1); -function remove(_ref3) { - var node = _ref3.node, - parentKey = _ref3.parentKey, - parentPath = _ref3.parentPath; + if (b1 < 0x80) { + return [code(0x0, b1)].concat(_toConsumableArray(_decode(bs))); + } - if (!(parentPath != null)) { - throw new Error('parentPath != null' + " error: " + ("Can not remove root node" || 0)); + if (b1 < 0xc0) { + throw new Error("invalid UTF-8 encoding"); + } } + /** + * 2 bytes + */ - // $FlowIgnore - var parentNode = parentPath.node; // $FlowIgnore + { + var _bytes2 = _toArray(bytes), + _b = _bytes2[0], + b2 = _bytes2[1], + _bs = _bytes2.slice(2); - var parentProperty = parentNode[parentKey]; + if (_b < 0xe0) { + return [code(0x80, ((_b & 0x1f) << 6) + con(b2))].concat(_toConsumableArray(_decode(_bs))); + } + } + /** + * 3 bytes + */ - if (Array.isArray(parentProperty)) { - // $FlowIgnore - parentNode[parentKey] = parentProperty.filter(function (n) { - return n !== node; - }); - } else { - // $FlowIgnore - delete parentNode[parentKey]; + { + var _bytes3 = _toArray(bytes), + _b2 = _bytes3[0], + _b3 = _bytes3[1], + b3 = _bytes3[2], + _bs2 = _bytes3.slice(3); + + if (_b2 < 0xf0) { + return [code(0x800, ((_b2 & 0x0f) << 12) + (con(_b3) << 6) + con(b3))].concat(_toConsumableArray(_decode(_bs2))); + } } + /** + * 4 bytes + */ - node._deleted = true; -} + { + var _bytes4 = _toArray(bytes), + _b4 = _bytes4[0], + _b5 = _bytes4[1], + _b6 = _bytes4[2], + b4 = _bytes4[3], + _bs3 = _bytes4.slice(4); -function stop(context) { - context.shouldStop = true; + if (_b4 < 0xf8) { + return [code(0x10000, (((_b4 & 0x07) << 18) + con(_b5) << 12) + (con(_b6) << 6) + con(b4))].concat(_toConsumableArray(_decode(_bs3))); + } + } + throw new Error("invalid UTF-8 encoding"); } -function replaceWith(context, newNode) { - // $FlowIgnore - var parentNode = context.parentPath.node; // $FlowIgnore +/***/ }), - var parentProperty = parentNode[context.parentKey]; +/***/ 43882: +/***/ (function(__unused_webpack_module, exports) { - if (Array.isArray(parentProperty)) { - var indexInList = parentProperty.findIndex(function (n) { - return n === context.node; - }); - parentProperty.splice(indexInList, 1, newNode); - } else { - // $FlowIgnore - parentNode[context.parentKey] = newNode; - } +"use strict"; - context.node._deleted = true; - context.node = newNode; -} // bind the context to the first argument of node operations +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.encode = encode; -function bindNodeOperations(operations, context) { - var keys = Object.keys(operations); - var boundOperations = {}; - keys.forEach(function (key) { - boundOperations[key] = operations[key].bind(null, context); - }); - return boundOperations; +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } + +function con(n) { + return 0x80 | n & 0x3f; } -function createPathOperations(context) { - // $FlowIgnore - return bindNodeOperations({ - findParent: findParent, - replaceWith: replaceWith, - remove: remove, - insertBefore: insertBefore, - insertAfter: insertAfter, - stop: stop - }, context); +function encode(str) { + var arr = str.split("").map(function (x) { + return x.charCodeAt(0); + }); + return _encode(arr); } -function createPath(context) { - var path = _extends({}, context); // $FlowIgnore +function _encode(arr) { + if (arr.length === 0) { + return []; + } + var _arr = _toArray(arr), + n = _arr[0], + ns = _arr.slice(1); - Object.assign(path, createPathOperations(path)); // $FlowIgnore + if (n < 0) { + throw new Error("utf8"); + } - return path; + if (n < 0x80) { + return [n].concat(_toConsumableArray(_encode(ns))); + } + + if (n < 0x800) { + return [0xc0 | n >>> 6, con(n)].concat(_toConsumableArray(_encode(ns))); + } + + if (n < 0x10000) { + return [0xe0 | n >>> 12, con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); + } + + if (n < 0x110000) { + return [0xf0 | n >>> 18, con(n >>> 12), con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); + } + + throw new Error("utf8"); } /***/ }), -/***/ 94841: -/***/ (function(__unused_webpack_module, exports) { +/***/ 81637: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; @@ -115816,2461 +115348,1810 @@ function createPath(context) { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.module = _module; -exports.moduleMetadata = moduleMetadata; -exports.moduleNameMetadata = moduleNameMetadata; -exports.functionNameMetadata = functionNameMetadata; -exports.localNameMetadata = localNameMetadata; -exports.binaryModule = binaryModule; -exports.quoteModule = quoteModule; -exports.sectionMetadata = sectionMetadata; -exports.producersSectionMetadata = producersSectionMetadata; -exports.producerMetadata = producerMetadata; -exports.producerMetadataVersionedName = producerMetadataVersionedName; -exports.loopInstruction = loopInstruction; -exports.instr = instr; -exports.ifInstruction = ifInstruction; -exports.stringLiteral = stringLiteral; -exports.numberLiteral = numberLiteral; -exports.longNumberLiteral = longNumberLiteral; -exports.floatLiteral = floatLiteral; -exports.elem = elem; -exports.indexInFuncSection = indexInFuncSection; -exports.valtypeLiteral = valtypeLiteral; -exports.typeInstruction = typeInstruction; -exports.start = start; -exports.globalType = globalType; -exports.leadingComment = leadingComment; -exports.blockComment = blockComment; -exports.data = data; -exports.global = global; -exports.table = table; -exports.memory = memory; -exports.funcImportDescr = funcImportDescr; -exports.moduleImport = moduleImport; -exports.moduleExportDescr = moduleExportDescr; -exports.moduleExport = moduleExport; -exports.limit = limit; -exports.signature = signature; -exports.program = program; -exports.identifier = identifier; -exports.blockInstruction = blockInstruction; -exports.callInstruction = callInstruction; -exports.callIndirectInstruction = callIndirectInstruction; -exports.byteArray = byteArray; -exports.func = func; -exports.internalBrUnless = internalBrUnless; -exports.internalGoto = internalGoto; -exports.internalCallExtern = internalCallExtern; -exports.internalEndAndReturn = internalEndAndReturn; -exports.assertInternalCallExtern = exports.assertInternalGoto = exports.assertInternalBrUnless = exports.assertFunc = exports.assertByteArray = exports.assertCallIndirectInstruction = exports.assertCallInstruction = exports.assertBlockInstruction = exports.assertIdentifier = exports.assertProgram = exports.assertSignature = exports.assertLimit = exports.assertModuleExport = exports.assertModuleExportDescr = exports.assertModuleImport = exports.assertFuncImportDescr = exports.assertMemory = exports.assertTable = exports.assertGlobal = exports.assertData = exports.assertBlockComment = exports.assertLeadingComment = exports.assertGlobalType = exports.assertStart = exports.assertTypeInstruction = exports.assertValtypeLiteral = exports.assertIndexInFuncSection = exports.assertElem = exports.assertFloatLiteral = exports.assertLongNumberLiteral = exports.assertNumberLiteral = exports.assertStringLiteral = exports.assertIfInstruction = exports.assertInstr = exports.assertLoopInstruction = exports.assertProducerMetadataVersionedName = exports.assertProducerMetadata = exports.assertProducersSectionMetadata = exports.assertSectionMetadata = exports.assertQuoteModule = exports.assertBinaryModule = exports.assertLocalNameMetadata = exports.assertFunctionNameMetadata = exports.assertModuleNameMetadata = exports.assertModuleMetadata = exports.assertModule = exports.isIntrinsic = exports.isImportDescr = exports.isNumericLiteral = exports.isExpression = exports.isInstruction = exports.isBlock = exports.isNode = exports.isInternalEndAndReturn = exports.isInternalCallExtern = exports.isInternalGoto = exports.isInternalBrUnless = exports.isFunc = exports.isByteArray = exports.isCallIndirectInstruction = exports.isCallInstruction = exports.isBlockInstruction = exports.isIdentifier = exports.isProgram = exports.isSignature = exports.isLimit = exports.isModuleExport = exports.isModuleExportDescr = exports.isModuleImport = exports.isFuncImportDescr = exports.isMemory = exports.isTable = exports.isGlobal = exports.isData = exports.isBlockComment = exports.isLeadingComment = exports.isGlobalType = exports.isStart = exports.isTypeInstruction = exports.isValtypeLiteral = exports.isIndexInFuncSection = exports.isElem = exports.isFloatLiteral = exports.isLongNumberLiteral = exports.isNumberLiteral = exports.isStringLiteral = exports.isIfInstruction = exports.isInstr = exports.isLoopInstruction = exports.isProducerMetadataVersionedName = exports.isProducerMetadata = exports.isProducersSectionMetadata = exports.isSectionMetadata = exports.isQuoteModule = exports.isBinaryModule = exports.isLocalNameMetadata = exports.isFunctionNameMetadata = exports.isModuleNameMetadata = exports.isModuleMetadata = exports.isModule = void 0; -exports.nodeAndUnionTypes = exports.unionTypesMap = exports.assertInternalEndAndReturn = void 0; - -function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -// THIS FILE IS AUTOGENERATED -// see scripts/generateNodeUtils.js -function isTypeOf(t) { - return function (n) { - return n.type === t; - }; -} - -function assertTypeOf(t) { - return function (n) { - return function () { - if (!(n.type === t)) { - throw new Error('n.type === t' + " error: " + (undefined || "unknown")); - } - }(); - }; -} - -function _module(id, fields, metadata) { - if (id !== null && id !== undefined) { - if (!(typeof id === "string")) { - throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); - } +Object.defineProperty(exports, "decode", ({ + enumerable: true, + get: function get() { + return _decoder.decode; } - - if (!(_typeof(fields) === "object" && typeof fields.length !== "undefined")) { - throw new Error('typeof fields === "object" && typeof fields.length !== "undefined"' + " error: " + (undefined || "unknown")); +})); +Object.defineProperty(exports, "encode", ({ + enumerable: true, + get: function get() { + return _encoder.encode; } +})); - var node = { - type: "Module", - id: id, - fields: fields - }; +var _decoder = __webpack_require__(19418); - if (typeof metadata !== "undefined") { - node.metadata = metadata; - } +var _encoder = __webpack_require__(43882); - return node; -} +/***/ }), -function moduleMetadata(sections, functionNames, localNames, producers) { - if (!(_typeof(sections) === "object" && typeof sections.length !== "undefined")) { - throw new Error('typeof sections === "object" && typeof sections.length !== "undefined"' + " error: " + (undefined || "unknown")); - } +/***/ 28458: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - if (functionNames !== null && functionNames !== undefined) { - if (!(_typeof(functionNames) === "object" && typeof functionNames.length !== "undefined")) { - throw new Error('typeof functionNames === "object" && typeof functionNames.length !== "undefined"' + " error: " + (undefined || "unknown")); - } - } +"use strict"; - if (localNames !== null && localNames !== undefined) { - if (!(_typeof(localNames) === "object" && typeof localNames.length !== "undefined")) { - throw new Error('typeof localNames === "object" && typeof localNames.length !== "undefined"' + " error: " + (undefined || "unknown")); - } - } - if (producers !== null && producers !== undefined) { - if (!(_typeof(producers) === "object" && typeof producers.length !== "undefined")) { - throw new Error('typeof producers === "object" && typeof producers.length !== "undefined"' + " error: " + (undefined || "unknown")); - } - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.decode = decode; - var node = { - type: "ModuleMetadata", - sections: sections - }; +var _helperApiError = __webpack_require__(20193); - if (typeof functionNames !== "undefined" && functionNames.length > 0) { - node.functionNames = functionNames; - } +var ieee754 = _interopRequireWildcard(__webpack_require__(57732)); - if (typeof localNames !== "undefined" && localNames.length > 0) { - node.localNames = localNames; - } +var utf8 = _interopRequireWildcard(__webpack_require__(81637)); - if (typeof producers !== "undefined" && producers.length > 0) { - node.producers = producers; - } +var t = _interopRequireWildcard(__webpack_require__(81875)); - return node; -} +var _leb = __webpack_require__(89943); -function moduleNameMetadata(value) { - if (!(typeof value === "string")) { - throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); - } +var _helperWasmBytecode = _interopRequireDefault(__webpack_require__(66921)); - var node = { - type: "ModuleNameMetadata", - value: value - }; - return node; -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function functionNameMetadata(value, index) { - if (!(typeof value === "string")) { - throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); - } +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; } } - if (!(typeof index === "number")) { - throw new Error('typeof index === "number"' + " error: " + ("Argument index must be of type number, given: " + _typeof(index) || 0)); - } +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } - var node = { - type: "FunctionNameMetadata", - value: value, - index: index - }; - return node; +function toHex(n) { + return "0x" + Number(n).toString(16); } -function localNameMetadata(value, localIndex, functionIndex) { - if (!(typeof value === "string")) { - throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); - } - - if (!(typeof localIndex === "number")) { - throw new Error('typeof localIndex === "number"' + " error: " + ("Argument localIndex must be of type number, given: " + _typeof(localIndex) || 0)); +function byteArrayEq(l, r) { + if (l.length !== r.length) { + return false; } - if (!(typeof functionIndex === "number")) { - throw new Error('typeof functionIndex === "number"' + " error: " + ("Argument functionIndex must be of type number, given: " + _typeof(functionIndex) || 0)); + for (var i = 0; i < l.length; i++) { + if (l[i] !== r[i]) { + return false; + } } - var node = { - type: "LocalNameMetadata", - value: value, - localIndex: localIndex, - functionIndex: functionIndex - }; - return node; + return true; } -function binaryModule(id, blob) { - if (id !== null && id !== undefined) { - if (!(typeof id === "string")) { - throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); - } - } +function decode(ab, opts) { + var buf = new Uint8Array(ab); + var getUniqueName = t.getUniqueNameGenerator(); + var offset = 0; - if (!(_typeof(blob) === "object" && typeof blob.length !== "undefined")) { - throw new Error('typeof blob === "object" && typeof blob.length !== "undefined"' + " error: " + (undefined || "unknown")); + function getPosition() { + return { + line: -1, + column: offset + }; } - var node = { - type: "BinaryModule", - id: id, - blob: blob - }; - return node; -} + function dump(b, msg) { + if (opts.dump === false) return; + var pad = "\t\t\t\t\t\t\t\t\t\t"; + var str = ""; -function quoteModule(id, string) { - if (id !== null && id !== undefined) { - if (!(typeof id === "string")) { - throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); + if (b.length < 5) { + str = b.map(toHex).join(" "); + } else { + str = "..."; } + + console.log(toHex(offset) + ":\t", str, pad, ";", msg); } - if (!(_typeof(string) === "object" && typeof string.length !== "undefined")) { - throw new Error('typeof string === "object" && typeof string.length !== "undefined"' + " error: " + (undefined || "unknown")); + function dumpSep(msg) { + if (opts.dump === false) return; + console.log(";", msg); } + /** + * TODO(sven): we can atually use a same structure + * we are adding incrementally new features + */ - var node = { - type: "QuoteModule", - id: id, - string: string - }; - return node; -} -function sectionMetadata(section, startOffset, size, vectorOfSize) { - if (!(typeof startOffset === "number")) { - throw new Error('typeof startOffset === "number"' + " error: " + ("Argument startOffset must be of type number, given: " + _typeof(startOffset) || 0)); - } + var state = { + elementsInFuncSection: [], + elementsInExportSection: [], + elementsInCodeSection: [], - var node = { - type: "SectionMetadata", - section: section, - startOffset: startOffset, - size: size, - vectorOfSize: vectorOfSize - }; - return node; -} + /** + * Decode memory from: + * - Memory section + */ + memoriesInModule: [], -function producersSectionMetadata(producers) { - if (!(_typeof(producers) === "object" && typeof producers.length !== "undefined")) { - throw new Error('typeof producers === "object" && typeof producers.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + /** + * Decoded types from: + * - Type section + */ + typesInModule: [], - var node = { - type: "ProducersSectionMetadata", - producers: producers + /** + * Decoded functions from: + * - Function section + * - Import section + */ + functionsInModule: [], + + /** + * Decoded tables from: + * - Table section + */ + tablesInModule: [], + + /** + * Decoded globals from: + * - Global section + */ + globalsInModule: [] }; - return node; -} -function producerMetadata(language, processedBy, sdk) { - if (!(_typeof(language) === "object" && typeof language.length !== "undefined")) { - throw new Error('typeof language === "object" && typeof language.length !== "undefined"' + " error: " + (undefined || "unknown")); + function isEOF() { + return offset >= buf.length; } - if (!(_typeof(processedBy) === "object" && typeof processedBy.length !== "undefined")) { - throw new Error('typeof processedBy === "object" && typeof processedBy.length !== "undefined"' + " error: " + (undefined || "unknown")); + function eatBytes(n) { + offset = offset + n; } - if (!(_typeof(sdk) === "object" && typeof sdk.length !== "undefined")) { - throw new Error('typeof sdk === "object" && typeof sdk.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + function readBytesAtOffset(_offset, numberOfBytes) { + var arr = []; - var node = { - type: "ProducerMetadata", - language: language, - processedBy: processedBy, - sdk: sdk - }; - return node; -} + for (var i = 0; i < numberOfBytes; i++) { + arr.push(buf[_offset + i]); + } -function producerMetadataVersionedName(name, version) { - if (!(typeof name === "string")) { - throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); + return arr; } - if (!(typeof version === "string")) { - throw new Error('typeof version === "string"' + " error: " + ("Argument version must be of type string, given: " + _typeof(version) || 0)); + function readBytes(numberOfBytes) { + return readBytesAtOffset(offset, numberOfBytes); } - var node = { - type: "ProducerMetadataVersionedName", - name: name, - version: version - }; - return node; -} + function readF64() { + var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F64); + var value = ieee754.decodeF64(bytes); -function loopInstruction(label, resulttype, instr) { - if (!(_typeof(instr) === "object" && typeof instr.length !== "undefined")) { - throw new Error('typeof instr === "object" && typeof instr.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + if (Math.sign(value) * value === Infinity) { + return { + value: Math.sign(value), + inf: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; + } - var node = { - type: "LoopInstruction", - id: "loop", - label: label, - resulttype: resulttype, - instr: instr - }; - return node; -} + if (isNaN(value)) { + var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1; + var mantissa = 0; -function instr(id, object, args, namedArgs) { - if (!(typeof id === "string")) { - throw new Error('typeof id === "string"' + " error: " + ("Argument id must be of type string, given: " + _typeof(id) || 0)); - } + for (var i = 0; i < bytes.length - 2; ++i) { + mantissa += bytes[i] * Math.pow(256, i); + } - if (!(_typeof(args) === "object" && typeof args.length !== "undefined")) { - throw new Error('typeof args === "object" && typeof args.length !== "undefined"' + " error: " + (undefined || "unknown")); + mantissa += bytes[bytes.length - 2] % 16 * Math.pow(256, bytes.length - 2); + return { + value: sign * mantissa, + nan: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; + } + + return { + value: value, + nextIndex: ieee754.NUMBER_OF_BYTE_F64 + }; } - var node = { - type: "Instr", - id: id, - args: args - }; + function readF32() { + var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F32); + var value = ieee754.decodeF32(bytes); - if (typeof object !== "undefined") { - node.object = object; - } + if (Math.sign(value) * value === Infinity) { + return { + value: Math.sign(value), + inf: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; + } - if (typeof namedArgs !== "undefined" && Object.keys(namedArgs).length !== 0) { - node.namedArgs = namedArgs; - } + if (isNaN(value)) { + var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1; + var mantissa = 0; - return node; -} + for (var i = 0; i < bytes.length - 2; ++i) { + mantissa += bytes[i] * Math.pow(256, i); + } -function ifInstruction(testLabel, test, result, consequent, alternate) { - if (!(_typeof(test) === "object" && typeof test.length !== "undefined")) { - throw new Error('typeof test === "object" && typeof test.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + mantissa += bytes[bytes.length - 2] % 128 * Math.pow(256, bytes.length - 2); + return { + value: sign * mantissa, + nan: true, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; + } - if (!(_typeof(consequent) === "object" && typeof consequent.length !== "undefined")) { - throw new Error('typeof consequent === "object" && typeof consequent.length !== "undefined"' + " error: " + (undefined || "unknown")); + return { + value: value, + nextIndex: ieee754.NUMBER_OF_BYTE_F32 + }; } - if (!(_typeof(alternate) === "object" && typeof alternate.length !== "undefined")) { - throw new Error('typeof alternate === "object" && typeof alternate.length !== "undefined"' + " error: " + (undefined || "unknown")); + function readUTF8String() { + var lenu32 = readU32(); // Don't eat any bytes. Instead, peek ahead of the current offset using + // readBytesAtOffset below. This keeps readUTF8String neutral with respect + // to the current offset, just like the other readX functions. + + var strlen = lenu32.value; + dump([strlen], "string length"); + var bytes = readBytesAtOffset(offset + lenu32.nextIndex, strlen); + var value = utf8.decode(bytes); + return { + value: value, + nextIndex: strlen + lenu32.nextIndex + }; } + /** + * Decode an unsigned 32bits integer + * + * The length will be handled by the leb librairy, we pass the max number of + * byte. + */ - var node = { - type: "IfInstruction", - id: "if", - testLabel: testLabel, - test: test, - result: result, - consequent: consequent, - alternate: alternate - }; - return node; -} -function stringLiteral(value) { - if (!(typeof value === "string")) { - throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); + function readU32() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt32)(buffer); } - var node = { - type: "StringLiteral", - value: value - }; - return node; -} - -function numberLiteral(value, raw) { - if (!(typeof value === "number")) { - throw new Error('typeof value === "number"' + " error: " + ("Argument value must be of type number, given: " + _typeof(value) || 0)); + function readVaruint32() { + // where 32 bits = max 4 bytes + var bytes = readBytes(4); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt32)(buffer); } - if (!(typeof raw === "string")) { - throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + function readVaruint7() { + // where 7 bits = max 1 bytes + var bytes = readBytes(1); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt32)(buffer); } + /** + * Decode a signed 32bits interger + */ - var node = { - type: "NumberLiteral", - value: value, - raw: raw - }; - return node; -} -function longNumberLiteral(value, raw) { - if (!(typeof raw === "string")) { - throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); + function read32() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeInt32)(buffer); } + /** + * Decode a signed 64bits integer + */ - var node = { - type: "LongNumberLiteral", - value: value, - raw: raw - }; - return node; -} -function floatLiteral(value, nan, inf, raw) { - if (!(typeof value === "number")) { - throw new Error('typeof value === "number"' + " error: " + ("Argument value must be of type number, given: " + _typeof(value) || 0)); + function read64() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeInt64)(buffer); } - if (nan !== null && nan !== undefined) { - if (!(typeof nan === "boolean")) { - throw new Error('typeof nan === "boolean"' + " error: " + ("Argument nan must be of type boolean, given: " + _typeof(nan) || 0)); - } + function readU64() { + var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); + var buffer = Buffer.from(bytes); + return (0, _leb.decodeUInt64)(buffer); } - if (inf !== null && inf !== undefined) { - if (!(typeof inf === "boolean")) { - throw new Error('typeof inf === "boolean"' + " error: " + ("Argument inf must be of type boolean, given: " + _typeof(inf) || 0)); - } + function readByte() { + return readBytes(1)[0]; } - if (!(typeof raw === "string")) { - throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); - } + function parseModuleHeader() { + if (isEOF() === true || offset + 4 > buf.length) { + throw new Error("unexpected end"); + } - var node = { - type: "FloatLiteral", - value: value, - raw: raw - }; + var header = readBytes(4); - if (nan === true) { - node.nan = true; - } + if (byteArrayEq(_helperWasmBytecode.default.magicModuleHeader, header) === false) { + throw new _helperApiError.CompileError("magic header not detected"); + } - if (inf === true) { - node.inf = true; + dump(header, "wasm magic header"); + eatBytes(4); } - return node; -} + function parseVersion() { + if (isEOF() === true || offset + 4 > buf.length) { + throw new Error("unexpected end"); + } -function elem(table, offset, funcs) { - if (!(_typeof(offset) === "object" && typeof offset.length !== "undefined")) { - throw new Error('typeof offset === "object" && typeof offset.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + var version = readBytes(4); - if (!(_typeof(funcs) === "object" && typeof funcs.length !== "undefined")) { - throw new Error('typeof funcs === "object" && typeof funcs.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + if (byteArrayEq(_helperWasmBytecode.default.moduleVersion, version) === false) { + throw new _helperApiError.CompileError("unknown binary version"); + } - var node = { - type: "Elem", - table: table, - offset: offset, - funcs: funcs - }; - return node; -} + dump(version, "wasm version"); + eatBytes(4); + } -function indexInFuncSection(index) { - var node = { - type: "IndexInFuncSection", - index: index - }; - return node; -} + function parseVec(cast) { + var u32 = readU32(); + var length = u32.value; + eatBytes(u32.nextIndex); + dump([length], "number"); -function valtypeLiteral(name) { - var node = { - type: "ValtypeLiteral", - name: name - }; - return node; -} + if (length === 0) { + return []; + } -function typeInstruction(id, functype) { - var node = { - type: "TypeInstruction", - id: id, - functype: functype - }; - return node; -} + var elements = []; -function start(index) { - var node = { - type: "Start", - index: index - }; - return node; -} + for (var i = 0; i < length; i++) { + var byte = readByte(); + eatBytes(1); + var value = cast(byte); + dump([byte], value); -function globalType(valtype, mutability) { - var node = { - type: "GlobalType", - valtype: valtype, - mutability: mutability - }; - return node; -} + if (typeof value === "undefined") { + throw new _helperApiError.CompileError("Internal failure: parseVec could not cast the value"); + } -function leadingComment(value) { - if (!(typeof value === "string")) { - throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); - } + elements.push(value); + } - var node = { - type: "LeadingComment", - value: value - }; - return node; -} + return elements; + } // Type section + // https://webassembly.github.io/spec/binary/modules.html#binary-typesec -function blockComment(value) { - if (!(typeof value === "string")) { - throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); - } - var node = { - type: "BlockComment", - value: value - }; - return node; -} + function parseTypeSection(numberOfTypes) { + var typeInstructionNodes = []; + dump([numberOfTypes], "num types"); -function data(memoryIndex, offset, init) { - var node = { - type: "Data", - memoryIndex: memoryIndex, - offset: offset, - init: init - }; - return node; -} + for (var i = 0; i < numberOfTypes; i++) { + var _startLoc = getPosition(); -function global(globalType, init, name) { - if (!(_typeof(init) === "object" && typeof init.length !== "undefined")) { - throw new Error('typeof init === "object" && typeof init.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + dumpSep("type " + i); + var type = readByte(); + eatBytes(1); - var node = { - type: "Global", - globalType: globalType, - init: init, - name: name - }; - return node; -} + if (type == _helperWasmBytecode.default.types.func) { + dump([type], "func"); + var paramValtypes = parseVec(function (b) { + return _helperWasmBytecode.default.valtypes[b]; + }); + var params = paramValtypes.map(function (v) { + return t.funcParam( + /*valtype*/ + v); + }); + var result = parseVec(function (b) { + return _helperWasmBytecode.default.valtypes[b]; + }); + typeInstructionNodes.push(function () { + var endLoc = getPosition(); + return t.withLoc(t.typeInstruction(undefined, t.signature(params, result)), endLoc, _startLoc); + }()); + state.typesInModule.push({ + params: params, + result: result + }); + } else { + throw new Error("Unsupported type: " + toHex(type)); + } + } -function table(elementType, limits, name, elements) { - if (!(limits.type === "Limit")) { - throw new Error('limits.type === "Limit"' + " error: " + ("Argument limits must be of type Limit, given: " + limits.type || 0)); - } + return typeInstructionNodes; + } // Import section + // https://webassembly.github.io/spec/binary/modules.html#binary-importsec - if (elements !== null && elements !== undefined) { - if (!(_typeof(elements) === "object" && typeof elements.length !== "undefined")) { - throw new Error('typeof elements === "object" && typeof elements.length !== "undefined"' + " error: " + (undefined || "unknown")); - } - } - var node = { - type: "Table", - elementType: elementType, - limits: limits, - name: name - }; + function parseImportSection(numberOfImports) { + var imports = []; - if (typeof elements !== "undefined" && elements.length > 0) { - node.elements = elements; - } + for (var i = 0; i < numberOfImports; i++) { + dumpSep("import header " + i); - return node; -} + var _startLoc2 = getPosition(); + /** + * Module name + */ -function memory(limits, id) { - var node = { - type: "Memory", - limits: limits, - id: id - }; - return node; -} -function funcImportDescr(id, signature) { - var node = { - type: "FuncImportDescr", - id: id, - signature: signature - }; - return node; -} + var moduleName = readUTF8String(); + eatBytes(moduleName.nextIndex); + dump([], "module name (".concat(moduleName.value, ")")); + /** + * Name + */ -function moduleImport(module, name, descr) { - if (!(typeof module === "string")) { - throw new Error('typeof module === "string"' + " error: " + ("Argument module must be of type string, given: " + _typeof(module) || 0)); - } + var name = readUTF8String(); + eatBytes(name.nextIndex); + dump([], "name (".concat(name.value, ")")); + /** + * Import descr + */ - if (!(typeof name === "string")) { - throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); - } + var descrTypeByte = readByte(); + eatBytes(1); + var descrType = _helperWasmBytecode.default.importTypes[descrTypeByte]; + dump([descrTypeByte], "import kind"); - var node = { - type: "ModuleImport", - module: module, - name: name, - descr: descr - }; - return node; -} + if (typeof descrType === "undefined") { + throw new _helperApiError.CompileError("Unknown import description type: " + toHex(descrTypeByte)); + } -function moduleExportDescr(exportType, id) { - var node = { - type: "ModuleExportDescr", - exportType: exportType, - id: id - }; - return node; -} + var importDescr = void 0; -function moduleExport(name, descr) { - if (!(typeof name === "string")) { - throw new Error('typeof name === "string"' + " error: " + ("Argument name must be of type string, given: " + _typeof(name) || 0)); - } + if (descrType === "func") { + var indexU32 = readU32(); + var typeindex = indexU32.value; + eatBytes(indexU32.nextIndex); + dump([typeindex], "type index"); + var signature = state.typesInModule[typeindex]; - var node = { - type: "ModuleExport", - name: name, - descr: descr - }; - return node; -} + if (typeof signature === "undefined") { + throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")")); + } -function limit(min, max) { - if (!(typeof min === "number")) { - throw new Error('typeof min === "number"' + " error: " + ("Argument min must be of type number, given: " + _typeof(min) || 0)); - } + var id = getUniqueName("func"); + importDescr = t.funcImportDescr(id, t.signature(signature.params, signature.result)); + state.functionsInModule.push({ + id: t.identifier(name.value), + signature: signature, + isExternal: true + }); + } else if (descrType === "global") { + importDescr = parseGlobalType(); + var globalNode = t.global(importDescr, []); + state.globalsInModule.push(globalNode); + } else if (descrType === "table") { + importDescr = parseTableType(i); + } else if (descrType === "mem") { + var memoryNode = parseMemoryType(0); + state.memoriesInModule.push(memoryNode); + importDescr = memoryNode; + } else { + throw new _helperApiError.CompileError("Unsupported import of type: " + descrType); + } - if (max !== null && max !== undefined) { - if (!(typeof max === "number")) { - throw new Error('typeof max === "number"' + " error: " + ("Argument max must be of type number, given: " + _typeof(max) || 0)); + imports.push(function () { + var endLoc = getPosition(); + return t.withLoc(t.moduleImport(moduleName.value, name.value, importDescr), endLoc, _startLoc2); + }()); } - } - var node = { - type: "Limit", - min: min - }; + return imports; + } // Function section + // https://webassembly.github.io/spec/binary/modules.html#function-section - if (typeof max !== "undefined") { - node.max = max; - } - return node; -} + function parseFuncSection(numberOfFunctions) { + dump([numberOfFunctions], "num funcs"); -function signature(params, results) { - if (!(_typeof(params) === "object" && typeof params.length !== "undefined")) { - throw new Error('typeof params === "object" && typeof params.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + for (var i = 0; i < numberOfFunctions; i++) { + var indexU32 = readU32(); + var typeindex = indexU32.value; + eatBytes(indexU32.nextIndex); + dump([typeindex], "type index"); + var signature = state.typesInModule[typeindex]; - if (!(_typeof(results) === "object" && typeof results.length !== "undefined")) { - throw new Error('typeof results === "object" && typeof results.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + if (typeof signature === "undefined") { + throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")")); + } // preserve anonymous, a name might be resolved later - var node = { - type: "Signature", - params: params, - results: results - }; - return node; -} -function program(body) { - if (!(_typeof(body) === "object" && typeof body.length !== "undefined")) { - throw new Error('typeof body === "object" && typeof body.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + var id = t.withRaw(t.identifier(getUniqueName("func")), ""); + state.functionsInModule.push({ + id: id, + signature: signature, + isExternal: false + }); + } + } // Export section + // https://webassembly.github.io/spec/binary/modules.html#export-section - var node = { - type: "Program", - body: body - }; - return node; -} -function identifier(value, raw) { - if (!(typeof value === "string")) { - throw new Error('typeof value === "string"' + " error: " + ("Argument value must be of type string, given: " + _typeof(value) || 0)); - } + function parseExportSection(numberOfExport) { + dump([numberOfExport], "num exports"); // Parse vector of exports - if (raw !== null && raw !== undefined) { - if (!(typeof raw === "string")) { - throw new Error('typeof raw === "string"' + " error: " + ("Argument raw must be of type string, given: " + _typeof(raw) || 0)); - } - } + for (var i = 0; i < numberOfExport; i++) { + var _startLoc3 = getPosition(); + /** + * Name + */ - var node = { - type: "Identifier", - value: value - }; - if (typeof raw !== "undefined") { - node.raw = raw; - } + var name = readUTF8String(); + eatBytes(name.nextIndex); + dump([], "export name (".concat(name.value, ")")); + /** + * exportdescr + */ - return node; -} + var typeIndex = readByte(); + eatBytes(1); + dump([typeIndex], "export kind"); + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + dump([index], "export index"); + var id = void 0, + signature = void 0; -function blockInstruction(label, instr, result) { - if (!(_typeof(instr) === "object" && typeof instr.length !== "undefined")) { - throw new Error('typeof instr === "object" && typeof instr.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Func") { + var func = state.functionsInModule[index]; - var node = { - type: "BlockInstruction", - id: "block", - label: label, - instr: instr, - result: result - }; - return node; -} + if (typeof func === "undefined") { + throw new _helperApiError.CompileError("unknown function (".concat(index, ")")); + } -function callInstruction(index, instrArgs, numeric) { - if (instrArgs !== null && instrArgs !== undefined) { - if (!(_typeof(instrArgs) === "object" && typeof instrArgs.length !== "undefined")) { - throw new Error('typeof instrArgs === "object" && typeof instrArgs.length !== "undefined"' + " error: " + (undefined || "unknown")); - } - } + id = t.numberLiteralFromRaw(index, String(index)); + signature = func.signature; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Table") { + var table = state.tablesInModule[index]; - var node = { - type: "CallInstruction", - id: "call", - index: index - }; + if (typeof table === "undefined") { + throw new _helperApiError.CompileError("unknown table ".concat(index)); + } - if (typeof instrArgs !== "undefined" && instrArgs.length > 0) { - node.instrArgs = instrArgs; - } + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Mem") { + var memNode = state.memoriesInModule[index]; - if (typeof numeric !== "undefined") { - node.numeric = numeric; - } + if (typeof memNode === "undefined") { + throw new _helperApiError.CompileError("unknown memory ".concat(index)); + } - return node; -} + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Global") { + var global = state.globalsInModule[index]; -function callIndirectInstruction(signature, intrs) { - if (intrs !== null && intrs !== undefined) { - if (!(_typeof(intrs) === "object" && typeof intrs.length !== "undefined")) { - throw new Error('typeof intrs === "object" && typeof intrs.length !== "undefined"' + " error: " + (undefined || "unknown")); - } - } + if (typeof global === "undefined") { + throw new _helperApiError.CompileError("unknown global ".concat(index)); + } - var node = { - type: "CallIndirectInstruction", - id: "call_indirect", - signature: signature - }; + id = t.numberLiteralFromRaw(index, String(index)); + signature = null; + } else { + console.warn("Unsupported export type: " + toHex(typeIndex)); + return; + } - if (typeof intrs !== "undefined" && intrs.length > 0) { - node.intrs = intrs; - } + var endLoc = getPosition(); + state.elementsInExportSection.push({ + name: name.value, + type: _helperWasmBytecode.default.exportTypes[typeIndex], + signature: signature, + id: id, + index: index, + endLoc: endLoc, + startLoc: _startLoc3 + }); + } + } // Code section + // https://webassembly.github.io/spec/binary/modules.html#code-section - return node; -} -function byteArray(values) { - if (!(_typeof(values) === "object" && typeof values.length !== "undefined")) { - throw new Error('typeof values === "object" && typeof values.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + function parseCodeSection(numberOfFuncs) { + dump([numberOfFuncs], "number functions"); // Parse vector of function - var node = { - type: "ByteArray", - values: values - }; - return node; -} + for (var i = 0; i < numberOfFuncs; i++) { + var _startLoc4 = getPosition(); -function func(name, signature, body, isExternal, metadata) { - if (!(_typeof(body) === "object" && typeof body.length !== "undefined")) { - throw new Error('typeof body === "object" && typeof body.length !== "undefined"' + " error: " + (undefined || "unknown")); - } + dumpSep("function body " + i); // the u32 size of the function code in bytes + // Ignore it for now - if (isExternal !== null && isExternal !== undefined) { - if (!(typeof isExternal === "boolean")) { - throw new Error('typeof isExternal === "boolean"' + " error: " + ("Argument isExternal must be of type boolean, given: " + _typeof(isExternal) || 0)); - } - } + var bodySizeU32 = readU32(); + eatBytes(bodySizeU32.nextIndex); + dump([bodySizeU32.value], "function body size"); + var code = []; + /** + * Parse locals + */ - var node = { - type: "Func", - name: name, - signature: signature, - body: body - }; + var funcLocalNumU32 = readU32(); + var funcLocalNum = funcLocalNumU32.value; + eatBytes(funcLocalNumU32.nextIndex); + dump([funcLocalNum], "num locals"); + var locals = []; - if (isExternal === true) { - node.isExternal = true; - } + for (var _i = 0; _i < funcLocalNum; _i++) { + var _startLoc5 = getPosition(); - if (typeof metadata !== "undefined") { - node.metadata = metadata; - } + var localCountU32 = readU32(); + var localCount = localCountU32.value; + eatBytes(localCountU32.nextIndex); + dump([localCount], "num local"); + var valtypeByte = readByte(); + eatBytes(1); + var type = _helperWasmBytecode.default.valtypes[valtypeByte]; + var args = []; - return node; -} + for (var _i2 = 0; _i2 < localCount; _i2++) { + args.push(t.valtypeLiteral(type)); + } -function internalBrUnless(target) { - if (!(typeof target === "number")) { - throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); - } + var localNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction("local", args), endLoc, _startLoc5); + }(); - var node = { - type: "InternalBrUnless", - target: target - }; - return node; -} + locals.push(localNode); + dump([valtypeByte], type); -function internalGoto(target) { - if (!(typeof target === "number")) { - throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); - } + if (typeof type === "undefined") { + throw new _helperApiError.CompileError("Unexpected valtype: " + toHex(valtypeByte)); + } + } - var node = { - type: "InternalGoto", - target: target - }; - return node; -} + code.push.apply(code, locals); // Decode instructions until the end -function internalCallExtern(target) { - if (!(typeof target === "number")) { - throw new Error('typeof target === "number"' + " error: " + ("Argument target must be of type number, given: " + _typeof(target) || 0)); + parseInstructionBlock(code); + var endLoc = getPosition(); + state.elementsInCodeSection.push({ + code: code, + locals: locals, + endLoc: endLoc, + startLoc: _startLoc4, + bodySize: bodySizeU32.value + }); + } } - var node = { - type: "InternalCallExtern", - target: target - }; - return node; -} + function parseInstructionBlock(code) { + while (true) { + var _startLoc6 = getPosition(); -function internalEndAndReturn() { - var node = { - type: "InternalEndAndReturn" - }; - return node; -} + var instructionAlreadyCreated = false; + var instructionByte = readByte(); + eatBytes(1); -var isModule = isTypeOf("Module"); -exports.isModule = isModule; -var isModuleMetadata = isTypeOf("ModuleMetadata"); -exports.isModuleMetadata = isModuleMetadata; -var isModuleNameMetadata = isTypeOf("ModuleNameMetadata"); -exports.isModuleNameMetadata = isModuleNameMetadata; -var isFunctionNameMetadata = isTypeOf("FunctionNameMetadata"); -exports.isFunctionNameMetadata = isFunctionNameMetadata; -var isLocalNameMetadata = isTypeOf("LocalNameMetadata"); -exports.isLocalNameMetadata = isLocalNameMetadata; -var isBinaryModule = isTypeOf("BinaryModule"); -exports.isBinaryModule = isBinaryModule; -var isQuoteModule = isTypeOf("QuoteModule"); -exports.isQuoteModule = isQuoteModule; -var isSectionMetadata = isTypeOf("SectionMetadata"); -exports.isSectionMetadata = isSectionMetadata; -var isProducersSectionMetadata = isTypeOf("ProducersSectionMetadata"); -exports.isProducersSectionMetadata = isProducersSectionMetadata; -var isProducerMetadata = isTypeOf("ProducerMetadata"); -exports.isProducerMetadata = isProducerMetadata; -var isProducerMetadataVersionedName = isTypeOf("ProducerMetadataVersionedName"); -exports.isProducerMetadataVersionedName = isProducerMetadataVersionedName; -var isLoopInstruction = isTypeOf("LoopInstruction"); -exports.isLoopInstruction = isLoopInstruction; -var isInstr = isTypeOf("Instr"); -exports.isInstr = isInstr; -var isIfInstruction = isTypeOf("IfInstruction"); -exports.isIfInstruction = isIfInstruction; -var isStringLiteral = isTypeOf("StringLiteral"); -exports.isStringLiteral = isStringLiteral; -var isNumberLiteral = isTypeOf("NumberLiteral"); -exports.isNumberLiteral = isNumberLiteral; -var isLongNumberLiteral = isTypeOf("LongNumberLiteral"); -exports.isLongNumberLiteral = isLongNumberLiteral; -var isFloatLiteral = isTypeOf("FloatLiteral"); -exports.isFloatLiteral = isFloatLiteral; -var isElem = isTypeOf("Elem"); -exports.isElem = isElem; -var isIndexInFuncSection = isTypeOf("IndexInFuncSection"); -exports.isIndexInFuncSection = isIndexInFuncSection; -var isValtypeLiteral = isTypeOf("ValtypeLiteral"); -exports.isValtypeLiteral = isValtypeLiteral; -var isTypeInstruction = isTypeOf("TypeInstruction"); -exports.isTypeInstruction = isTypeInstruction; -var isStart = isTypeOf("Start"); -exports.isStart = isStart; -var isGlobalType = isTypeOf("GlobalType"); -exports.isGlobalType = isGlobalType; -var isLeadingComment = isTypeOf("LeadingComment"); -exports.isLeadingComment = isLeadingComment; -var isBlockComment = isTypeOf("BlockComment"); -exports.isBlockComment = isBlockComment; -var isData = isTypeOf("Data"); -exports.isData = isData; -var isGlobal = isTypeOf("Global"); -exports.isGlobal = isGlobal; -var isTable = isTypeOf("Table"); -exports.isTable = isTable; -var isMemory = isTypeOf("Memory"); -exports.isMemory = isMemory; -var isFuncImportDescr = isTypeOf("FuncImportDescr"); -exports.isFuncImportDescr = isFuncImportDescr; -var isModuleImport = isTypeOf("ModuleImport"); -exports.isModuleImport = isModuleImport; -var isModuleExportDescr = isTypeOf("ModuleExportDescr"); -exports.isModuleExportDescr = isModuleExportDescr; -var isModuleExport = isTypeOf("ModuleExport"); -exports.isModuleExport = isModuleExport; -var isLimit = isTypeOf("Limit"); -exports.isLimit = isLimit; -var isSignature = isTypeOf("Signature"); -exports.isSignature = isSignature; -var isProgram = isTypeOf("Program"); -exports.isProgram = isProgram; -var isIdentifier = isTypeOf("Identifier"); -exports.isIdentifier = isIdentifier; -var isBlockInstruction = isTypeOf("BlockInstruction"); -exports.isBlockInstruction = isBlockInstruction; -var isCallInstruction = isTypeOf("CallInstruction"); -exports.isCallInstruction = isCallInstruction; -var isCallIndirectInstruction = isTypeOf("CallIndirectInstruction"); -exports.isCallIndirectInstruction = isCallIndirectInstruction; -var isByteArray = isTypeOf("ByteArray"); -exports.isByteArray = isByteArray; -var isFunc = isTypeOf("Func"); -exports.isFunc = isFunc; -var isInternalBrUnless = isTypeOf("InternalBrUnless"); -exports.isInternalBrUnless = isInternalBrUnless; -var isInternalGoto = isTypeOf("InternalGoto"); -exports.isInternalGoto = isInternalGoto; -var isInternalCallExtern = isTypeOf("InternalCallExtern"); -exports.isInternalCallExtern = isInternalCallExtern; -var isInternalEndAndReturn = isTypeOf("InternalEndAndReturn"); -exports.isInternalEndAndReturn = isInternalEndAndReturn; + if (instructionByte === 0xfe) { + throw new _helperApiError.CompileError("Atomic instructions are not implemented"); + } -var isNode = function isNode(node) { - return isModule(node) || isModuleMetadata(node) || isModuleNameMetadata(node) || isFunctionNameMetadata(node) || isLocalNameMetadata(node) || isBinaryModule(node) || isQuoteModule(node) || isSectionMetadata(node) || isProducersSectionMetadata(node) || isProducerMetadata(node) || isProducerMetadataVersionedName(node) || isLoopInstruction(node) || isInstr(node) || isIfInstruction(node) || isStringLiteral(node) || isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node) || isElem(node) || isIndexInFuncSection(node) || isValtypeLiteral(node) || isTypeInstruction(node) || isStart(node) || isGlobalType(node) || isLeadingComment(node) || isBlockComment(node) || isData(node) || isGlobal(node) || isTable(node) || isMemory(node) || isFuncImportDescr(node) || isModuleImport(node) || isModuleExportDescr(node) || isModuleExport(node) || isLimit(node) || isSignature(node) || isProgram(node) || isIdentifier(node) || isBlockInstruction(node) || isCallInstruction(node) || isCallIndirectInstruction(node) || isByteArray(node) || isFunc(node) || isInternalBrUnless(node) || isInternalGoto(node) || isInternalCallExtern(node) || isInternalEndAndReturn(node); -}; + var instruction = _helperWasmBytecode.default.symbolsByByte[instructionByte]; -exports.isNode = isNode; + if (typeof instruction === "undefined") { + throw new _helperApiError.CompileError("Unexpected instruction: " + toHex(instructionByte)); + } -var isBlock = function isBlock(node) { - return isLoopInstruction(node) || isBlockInstruction(node) || isFunc(node); -}; + if (typeof instruction.object === "string") { + dump([instructionByte], "".concat(instruction.object, ".").concat(instruction.name)); + } else { + dump([instructionByte], instruction.name); + } + /** + * End of the function + */ -exports.isBlock = isBlock; -var isInstruction = function isInstruction(node) { - return isLoopInstruction(node) || isInstr(node) || isIfInstruction(node) || isTypeInstruction(node) || isBlockInstruction(node) || isCallInstruction(node) || isCallIndirectInstruction(node); -}; + if (instruction.name === "end") { + var node = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction(instruction.name), endLoc, _startLoc6); + }(); -exports.isInstruction = isInstruction; + code.push(node); + break; + } -var isExpression = function isExpression(node) { - return isInstr(node) || isStringLiteral(node) || isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node) || isValtypeLiteral(node) || isIdentifier(node); -}; + var args = []; -exports.isExpression = isExpression; + if (instruction.name === "loop") { + var _startLoc7 = getPosition(); -var isNumericLiteral = function isNumericLiteral(node) { - return isNumberLiteral(node) || isLongNumberLiteral(node) || isFloatLiteral(node); -}; + var blocktypeByte = readByte(); + eatBytes(1); + var blocktype = _helperWasmBytecode.default.blockTypes[blocktypeByte]; + dump([blocktypeByte], "blocktype"); -exports.isNumericLiteral = isNumericLiteral; + if (typeof blocktype === "undefined") { + throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(blocktypeByte)); + } -var isImportDescr = function isImportDescr(node) { - return isGlobalType(node) || isTable(node) || isMemory(node) || isFuncImportDescr(node); -}; + var instr = []; + parseInstructionBlock(instr); // preserve anonymous -exports.isImportDescr = isImportDescr; + var label = t.withRaw(t.identifier(getUniqueName("loop")), ""); -var isIntrinsic = function isIntrinsic(node) { - return isInternalBrUnless(node) || isInternalGoto(node) || isInternalCallExtern(node) || isInternalEndAndReturn(node); -}; + var loopNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.loopInstruction(label, blocktype, instr), endLoc, _startLoc7); + }(); -exports.isIntrinsic = isIntrinsic; -var assertModule = assertTypeOf("Module"); -exports.assertModule = assertModule; -var assertModuleMetadata = assertTypeOf("ModuleMetadata"); -exports.assertModuleMetadata = assertModuleMetadata; -var assertModuleNameMetadata = assertTypeOf("ModuleNameMetadata"); -exports.assertModuleNameMetadata = assertModuleNameMetadata; -var assertFunctionNameMetadata = assertTypeOf("FunctionNameMetadata"); -exports.assertFunctionNameMetadata = assertFunctionNameMetadata; -var assertLocalNameMetadata = assertTypeOf("LocalNameMetadata"); -exports.assertLocalNameMetadata = assertLocalNameMetadata; -var assertBinaryModule = assertTypeOf("BinaryModule"); -exports.assertBinaryModule = assertBinaryModule; -var assertQuoteModule = assertTypeOf("QuoteModule"); -exports.assertQuoteModule = assertQuoteModule; -var assertSectionMetadata = assertTypeOf("SectionMetadata"); -exports.assertSectionMetadata = assertSectionMetadata; -var assertProducersSectionMetadata = assertTypeOf("ProducersSectionMetadata"); -exports.assertProducersSectionMetadata = assertProducersSectionMetadata; -var assertProducerMetadata = assertTypeOf("ProducerMetadata"); -exports.assertProducerMetadata = assertProducerMetadata; -var assertProducerMetadataVersionedName = assertTypeOf("ProducerMetadataVersionedName"); -exports.assertProducerMetadataVersionedName = assertProducerMetadataVersionedName; -var assertLoopInstruction = assertTypeOf("LoopInstruction"); -exports.assertLoopInstruction = assertLoopInstruction; -var assertInstr = assertTypeOf("Instr"); -exports.assertInstr = assertInstr; -var assertIfInstruction = assertTypeOf("IfInstruction"); -exports.assertIfInstruction = assertIfInstruction; -var assertStringLiteral = assertTypeOf("StringLiteral"); -exports.assertStringLiteral = assertStringLiteral; -var assertNumberLiteral = assertTypeOf("NumberLiteral"); -exports.assertNumberLiteral = assertNumberLiteral; -var assertLongNumberLiteral = assertTypeOf("LongNumberLiteral"); -exports.assertLongNumberLiteral = assertLongNumberLiteral; -var assertFloatLiteral = assertTypeOf("FloatLiteral"); -exports.assertFloatLiteral = assertFloatLiteral; -var assertElem = assertTypeOf("Elem"); -exports.assertElem = assertElem; -var assertIndexInFuncSection = assertTypeOf("IndexInFuncSection"); -exports.assertIndexInFuncSection = assertIndexInFuncSection; -var assertValtypeLiteral = assertTypeOf("ValtypeLiteral"); -exports.assertValtypeLiteral = assertValtypeLiteral; -var assertTypeInstruction = assertTypeOf("TypeInstruction"); -exports.assertTypeInstruction = assertTypeInstruction; -var assertStart = assertTypeOf("Start"); -exports.assertStart = assertStart; -var assertGlobalType = assertTypeOf("GlobalType"); -exports.assertGlobalType = assertGlobalType; -var assertLeadingComment = assertTypeOf("LeadingComment"); -exports.assertLeadingComment = assertLeadingComment; -var assertBlockComment = assertTypeOf("BlockComment"); -exports.assertBlockComment = assertBlockComment; -var assertData = assertTypeOf("Data"); -exports.assertData = assertData; -var assertGlobal = assertTypeOf("Global"); -exports.assertGlobal = assertGlobal; -var assertTable = assertTypeOf("Table"); -exports.assertTable = assertTable; -var assertMemory = assertTypeOf("Memory"); -exports.assertMemory = assertMemory; -var assertFuncImportDescr = assertTypeOf("FuncImportDescr"); -exports.assertFuncImportDescr = assertFuncImportDescr; -var assertModuleImport = assertTypeOf("ModuleImport"); -exports.assertModuleImport = assertModuleImport; -var assertModuleExportDescr = assertTypeOf("ModuleExportDescr"); -exports.assertModuleExportDescr = assertModuleExportDescr; -var assertModuleExport = assertTypeOf("ModuleExport"); -exports.assertModuleExport = assertModuleExport; -var assertLimit = assertTypeOf("Limit"); -exports.assertLimit = assertLimit; -var assertSignature = assertTypeOf("Signature"); -exports.assertSignature = assertSignature; -var assertProgram = assertTypeOf("Program"); -exports.assertProgram = assertProgram; -var assertIdentifier = assertTypeOf("Identifier"); -exports.assertIdentifier = assertIdentifier; -var assertBlockInstruction = assertTypeOf("BlockInstruction"); -exports.assertBlockInstruction = assertBlockInstruction; -var assertCallInstruction = assertTypeOf("CallInstruction"); -exports.assertCallInstruction = assertCallInstruction; -var assertCallIndirectInstruction = assertTypeOf("CallIndirectInstruction"); -exports.assertCallIndirectInstruction = assertCallIndirectInstruction; -var assertByteArray = assertTypeOf("ByteArray"); -exports.assertByteArray = assertByteArray; -var assertFunc = assertTypeOf("Func"); -exports.assertFunc = assertFunc; -var assertInternalBrUnless = assertTypeOf("InternalBrUnless"); -exports.assertInternalBrUnless = assertInternalBrUnless; -var assertInternalGoto = assertTypeOf("InternalGoto"); -exports.assertInternalGoto = assertInternalGoto; -var assertInternalCallExtern = assertTypeOf("InternalCallExtern"); -exports.assertInternalCallExtern = assertInternalCallExtern; -var assertInternalEndAndReturn = assertTypeOf("InternalEndAndReturn"); -exports.assertInternalEndAndReturn = assertInternalEndAndReturn; -var unionTypesMap = { - Module: ["Node"], - ModuleMetadata: ["Node"], - ModuleNameMetadata: ["Node"], - FunctionNameMetadata: ["Node"], - LocalNameMetadata: ["Node"], - BinaryModule: ["Node"], - QuoteModule: ["Node"], - SectionMetadata: ["Node"], - ProducersSectionMetadata: ["Node"], - ProducerMetadata: ["Node"], - ProducerMetadataVersionedName: ["Node"], - LoopInstruction: ["Node", "Block", "Instruction"], - Instr: ["Node", "Expression", "Instruction"], - IfInstruction: ["Node", "Instruction"], - StringLiteral: ["Node", "Expression"], - NumberLiteral: ["Node", "NumericLiteral", "Expression"], - LongNumberLiteral: ["Node", "NumericLiteral", "Expression"], - FloatLiteral: ["Node", "NumericLiteral", "Expression"], - Elem: ["Node"], - IndexInFuncSection: ["Node"], - ValtypeLiteral: ["Node", "Expression"], - TypeInstruction: ["Node", "Instruction"], - Start: ["Node"], - GlobalType: ["Node", "ImportDescr"], - LeadingComment: ["Node"], - BlockComment: ["Node"], - Data: ["Node"], - Global: ["Node"], - Table: ["Node", "ImportDescr"], - Memory: ["Node", "ImportDescr"], - FuncImportDescr: ["Node", "ImportDescr"], - ModuleImport: ["Node"], - ModuleExportDescr: ["Node"], - ModuleExport: ["Node"], - Limit: ["Node"], - Signature: ["Node"], - Program: ["Node"], - Identifier: ["Node", "Expression"], - BlockInstruction: ["Node", "Block", "Instruction"], - CallInstruction: ["Node", "Instruction"], - CallIndirectInstruction: ["Node", "Instruction"], - ByteArray: ["Node"], - Func: ["Node", "Block"], - InternalBrUnless: ["Node", "Intrinsic"], - InternalGoto: ["Node", "Intrinsic"], - InternalCallExtern: ["Node", "Intrinsic"], - InternalEndAndReturn: ["Node", "Intrinsic"] -}; -exports.unionTypesMap = unionTypesMap; -var nodeAndUnionTypes = ["Module", "ModuleMetadata", "ModuleNameMetadata", "FunctionNameMetadata", "LocalNameMetadata", "BinaryModule", "QuoteModule", "SectionMetadata", "ProducersSectionMetadata", "ProducerMetadata", "ProducerMetadataVersionedName", "LoopInstruction", "Instr", "IfInstruction", "StringLiteral", "NumberLiteral", "LongNumberLiteral", "FloatLiteral", "Elem", "IndexInFuncSection", "ValtypeLiteral", "TypeInstruction", "Start", "GlobalType", "LeadingComment", "BlockComment", "Data", "Global", "Table", "Memory", "FuncImportDescr", "ModuleImport", "ModuleExportDescr", "ModuleExport", "Limit", "Signature", "Program", "Identifier", "BlockInstruction", "CallInstruction", "CallIndirectInstruction", "ByteArray", "Func", "InternalBrUnless", "InternalGoto", "InternalCallExtern", "InternalEndAndReturn", "Node", "Block", "Instruction", "Expression", "NumericLiteral", "ImportDescr", "Intrinsic"]; -exports.nodeAndUnionTypes = nodeAndUnionTypes; + code.push(loopNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "if") { + var _startLoc8 = getPosition(); -/***/ }), + var _blocktypeByte = readByte(); -/***/ 77392: -/***/ (function(__unused_webpack_module, exports) { + eatBytes(1); + var _blocktype = _helperWasmBytecode.default.blockTypes[_blocktypeByte]; + dump([_blocktypeByte], "blocktype"); -"use strict"; + if (typeof _blocktype === "undefined") { + throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte)); + } + var testIndex = t.withRaw(t.identifier(getUniqueName("if")), ""); + var ifBody = []; + parseInstructionBlock(ifBody); // Defaults to no alternate -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.signatures = void 0; + var elseIndex = 0; -function sign(input, output) { - return [input, output]; -} + for (elseIndex = 0; elseIndex < ifBody.length; ++elseIndex) { + var _instr = ifBody[elseIndex]; -var u32 = "u32"; -var i32 = "i32"; -var i64 = "i64"; -var f32 = "f32"; -var f64 = "f64"; + if (_instr.type === "Instr" && _instr.id === "else") { + break; + } + } -var vector = function vector(t) { - var vecType = [t]; // $FlowIgnore + var consequentInstr = ifBody.slice(0, elseIndex); + var alternate = ifBody.slice(elseIndex + 1); // wast sugar - vecType.vector = true; - return vecType; -}; + var testInstrs = []; -var controlInstructions = { - unreachable: sign([], []), - nop: sign([], []), - // block ? - // loop ? - // if ? - // if else ? - br: sign([u32], []), - br_if: sign([u32], []), - br_table: sign(vector(u32), []), - return: sign([], []), - call: sign([u32], []), - call_indirect: sign([u32], []) -}; -var parametricInstructions = { - drop: sign([], []), - select: sign([], []) -}; -var variableInstructions = { - get_local: sign([u32], []), - set_local: sign([u32], []), - tee_local: sign([u32], []), - get_global: sign([u32], []), - set_global: sign([u32], []) -}; -var memoryInstructions = { - "i32.load": sign([u32, u32], [i32]), - "i64.load": sign([u32, u32], []), - "f32.load": sign([u32, u32], []), - "f64.load": sign([u32, u32], []), - "i32.load8_s": sign([u32, u32], [i32]), - "i32.load8_u": sign([u32, u32], [i32]), - "i32.load16_s": sign([u32, u32], [i32]), - "i32.load16_u": sign([u32, u32], [i32]), - "i64.load8_s": sign([u32, u32], [i64]), - "i64.load8_u": sign([u32, u32], [i64]), - "i64.load16_s": sign([u32, u32], [i64]), - "i64.load16_u": sign([u32, u32], [i64]), - "i64.load32_s": sign([u32, u32], [i64]), - "i64.load32_u": sign([u32, u32], [i64]), - "i32.store": sign([u32, u32], []), - "i64.store": sign([u32, u32], []), - "f32.store": sign([u32, u32], []), - "f64.store": sign([u32, u32], []), - "i32.store8": sign([u32, u32], []), - "i32.store16": sign([u32, u32], []), - "i64.store8": sign([u32, u32], []), - "i64.store16": sign([u32, u32], []), - "i64.store32": sign([u32, u32], []), - current_memory: sign([], []), - grow_memory: sign([], []) -}; -var numericInstructions = { - "i32.const": sign([i32], [i32]), - "i64.const": sign([i64], [i64]), - "f32.const": sign([f32], [f32]), - "f64.const": sign([f64], [f64]), - "i32.eqz": sign([i32], [i32]), - "i32.eq": sign([i32, i32], [i32]), - "i32.ne": sign([i32, i32], [i32]), - "i32.lt_s": sign([i32, i32], [i32]), - "i32.lt_u": sign([i32, i32], [i32]), - "i32.gt_s": sign([i32, i32], [i32]), - "i32.gt_u": sign([i32, i32], [i32]), - "i32.le_s": sign([i32, i32], [i32]), - "i32.le_u": sign([i32, i32], [i32]), - "i32.ge_s": sign([i32, i32], [i32]), - "i32.ge_u": sign([i32, i32], [i32]), - "i64.eqz": sign([i64], [i64]), - "i64.eq": sign([i64, i64], [i32]), - "i64.ne": sign([i64, i64], [i32]), - "i64.lt_s": sign([i64, i64], [i32]), - "i64.lt_u": sign([i64, i64], [i32]), - "i64.gt_s": sign([i64, i64], [i32]), - "i64.gt_u": sign([i64, i64], [i32]), - "i64.le_s": sign([i64, i64], [i32]), - "i64.le_u": sign([i64, i64], [i32]), - "i64.ge_s": sign([i64, i64], [i32]), - "i64.ge_u": sign([i64, i64], [i32]), - "f32.eq": sign([f32, f32], [i32]), - "f32.ne": sign([f32, f32], [i32]), - "f32.lt": sign([f32, f32], [i32]), - "f32.gt": sign([f32, f32], [i32]), - "f32.le": sign([f32, f32], [i32]), - "f32.ge": sign([f32, f32], [i32]), - "f64.eq": sign([f64, f64], [i32]), - "f64.ne": sign([f64, f64], [i32]), - "f64.lt": sign([f64, f64], [i32]), - "f64.gt": sign([f64, f64], [i32]), - "f64.le": sign([f64, f64], [i32]), - "f64.ge": sign([f64, f64], [i32]), - "i32.clz": sign([i32], [i32]), - "i32.ctz": sign([i32], [i32]), - "i32.popcnt": sign([i32], [i32]), - "i32.add": sign([i32, i32], [i32]), - "i32.sub": sign([i32, i32], [i32]), - "i32.mul": sign([i32, i32], [i32]), - "i32.div_s": sign([i32, i32], [i32]), - "i32.div_u": sign([i32, i32], [i32]), - "i32.rem_s": sign([i32, i32], [i32]), - "i32.rem_u": sign([i32, i32], [i32]), - "i32.and": sign([i32, i32], [i32]), - "i32.or": sign([i32, i32], [i32]), - "i32.xor": sign([i32, i32], [i32]), - "i32.shl": sign([i32, i32], [i32]), - "i32.shr_s": sign([i32, i32], [i32]), - "i32.shr_u": sign([i32, i32], [i32]), - "i32.rotl": sign([i32, i32], [i32]), - "i32.rotr": sign([i32, i32], [i32]), - "i64.clz": sign([i64], [i64]), - "i64.ctz": sign([i64], [i64]), - "i64.popcnt": sign([i64], [i64]), - "i64.add": sign([i64, i64], [i64]), - "i64.sub": sign([i64, i64], [i64]), - "i64.mul": sign([i64, i64], [i64]), - "i64.div_s": sign([i64, i64], [i64]), - "i64.div_u": sign([i64, i64], [i64]), - "i64.rem_s": sign([i64, i64], [i64]), - "i64.rem_u": sign([i64, i64], [i64]), - "i64.and": sign([i64, i64], [i64]), - "i64.or": sign([i64, i64], [i64]), - "i64.xor": sign([i64, i64], [i64]), - "i64.shl": sign([i64, i64], [i64]), - "i64.shr_s": sign([i64, i64], [i64]), - "i64.shr_u": sign([i64, i64], [i64]), - "i64.rotl": sign([i64, i64], [i64]), - "i64.rotr": sign([i64, i64], [i64]), - "f32.abs": sign([f32], [f32]), - "f32.neg": sign([f32], [f32]), - "f32.ceil": sign([f32], [f32]), - "f32.floor": sign([f32], [f32]), - "f32.trunc": sign([f32], [f32]), - "f32.nearest": sign([f32], [f32]), - "f32.sqrt": sign([f32], [f32]), - "f32.add": sign([f32, f32], [f32]), - "f32.sub": sign([f32, f32], [f32]), - "f32.mul": sign([f32, f32], [f32]), - "f32.div": sign([f32, f32], [f32]), - "f32.min": sign([f32, f32], [f32]), - "f32.max": sign([f32, f32], [f32]), - "f32.copysign": sign([f32, f32], [f32]), - "f64.abs": sign([f64], [f64]), - "f64.neg": sign([f64], [f64]), - "f64.ceil": sign([f64], [f64]), - "f64.floor": sign([f64], [f64]), - "f64.trunc": sign([f64], [f64]), - "f64.nearest": sign([f64], [f64]), - "f64.sqrt": sign([f64], [f64]), - "f64.add": sign([f64, f64], [f64]), - "f64.sub": sign([f64, f64], [f64]), - "f64.mul": sign([f64, f64], [f64]), - "f64.div": sign([f64, f64], [f64]), - "f64.min": sign([f64, f64], [f64]), - "f64.max": sign([f64, f64], [f64]), - "f64.copysign": sign([f64, f64], [f64]), - "i32.wrap/i64": sign([i64], [i32]), - "i32.trunc_s/f32": sign([f32], [i32]), - "i32.trunc_u/f32": sign([f32], [i32]), - "i32.trunc_s/f64": sign([f32], [i32]), - "i32.trunc_u/f64": sign([f64], [i32]), - "i64.extend_s/i32": sign([i32], [i64]), - "i64.extend_u/i32": sign([i32], [i64]), - "i64.trunc_s/f32": sign([f32], [i64]), - "i64.trunc_u/f32": sign([f32], [i64]), - "i64.trunc_s/f64": sign([f64], [i64]), - "i64.trunc_u/f64": sign([f64], [i64]), - "f32.convert_s/i32": sign([i32], [f32]), - "f32.convert_u/i32": sign([i32], [f32]), - "f32.convert_s/i64": sign([i64], [f32]), - "f32.convert_u/i64": sign([i64], [f32]), - "f32.demote/f64": sign([f64], [f32]), - "f64.convert_s/i32": sign([i32], [f64]), - "f64.convert_u/i32": sign([i32], [f64]), - "f64.convert_s/i64": sign([i64], [f64]), - "f64.convert_u/i64": sign([i64], [f64]), - "f64.promote/f32": sign([f32], [f64]), - "i32.reinterpret/f32": sign([f32], [i32]), - "i64.reinterpret/f64": sign([f64], [i64]), - "f32.reinterpret/i32": sign([i32], [f32]), - "f64.reinterpret/i64": sign([i64], [f64]) -}; -var signatures = Object.assign({}, controlInstructions, parametricInstructions, variableInstructions, memoryInstructions, numericInstructions); -exports.signatures = signatures; + var ifNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.ifInstruction(testIndex, testInstrs, _blocktype, consequentInstr, alternate), endLoc, _startLoc8); + }(); -/***/ }), + code.push(ifNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "block") { + var _startLoc9 = getPosition(); -/***/ 29436: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + var _blocktypeByte2 = readByte(); -"use strict"; + eatBytes(1); + var _blocktype2 = _helperWasmBytecode.default.blockTypes[_blocktypeByte2]; + dump([_blocktypeByte2], "blocktype"); + if (typeof _blocktype2 === "undefined") { + throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte2)); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.traverse = traverse; + var _instr2 = []; + parseInstructionBlock(_instr2); // preserve anonymous -var _nodePath = __webpack_require__(89231); + var _label = t.withRaw(t.identifier(getUniqueName("block")), ""); -var _nodes = __webpack_require__(94841); + var blockNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.blockInstruction(_label, _instr2, _blocktype2), endLoc, _startLoc9); + }(); -// recursively walks the AST starting at the given node. The callback is invoked for -// and object that has a 'type' property. -function walk(context, callback) { - var stop = false; + code.push(blockNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "call") { + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + dump([index], "index"); - function innerWalk(context, callback) { - if (stop) { - return; - } + var callNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.callInstruction(t.indexLiteral(index)), endLoc, _startLoc6); + }(); - var node = context.node; + code.push(callNode); + instructionAlreadyCreated = true; + } else if (instruction.name === "call_indirect") { + var _startLoc10 = getPosition(); - if (node === undefined) { - console.warn("traversing with an empty context"); - return; - } + var indexU32 = readU32(); + var typeindex = indexU32.value; + eatBytes(indexU32.nextIndex); + dump([typeindex], "type index"); + var signature = state.typesInModule[typeindex]; - if (node._deleted === true) { - return; - } + if (typeof signature === "undefined") { + throw new _helperApiError.CompileError("call_indirect signature not found (".concat(typeindex, ")")); + } - var path = (0, _nodePath.createPath)(context); - callback(node.type, path); + var _callNode = t.callIndirectInstruction(t.signature(signature.params, signature.result), []); - if (path.shouldStop) { - stop = true; - return; - } + var flagU32 = readU32(); + var flag = flagU32.value; // 0x00 - reserved byte - Object.keys(node).forEach(function (prop) { - var value = node[prop]; + eatBytes(flagU32.nextIndex); - if (value === null || value === undefined) { - return; - } + if (flag !== 0) { + throw new _helperApiError.CompileError("zero flag expected"); + } - var valueAsArray = Array.isArray(value) ? value : [value]; - valueAsArray.forEach(function (childNode) { - if (typeof childNode.type === "string") { - var childContext = { - node: childNode, - parentKey: prop, - parentPath: path, - shouldStop: false, - inList: Array.isArray(value) + code.push(function () { + var endLoc = getPosition(); + return t.withLoc(_callNode, endLoc, _startLoc10); + }()); + instructionAlreadyCreated = true; + } else if (instruction.name === "br_table") { + var indicesu32 = readU32(); + var indices = indicesu32.value; + eatBytes(indicesu32.nextIndex); + dump([indices], "num indices"); + + for (var i = 0; i <= indices; i++) { + var _indexu = readU32(); + + var _index = _indexu.value; + eatBytes(_indexu.nextIndex); + dump([_index], "index"); + args.push(t.numberLiteralFromRaw(_indexu.value.toString(), "u32")); + } + } else if (instructionByte >= 0x28 && instructionByte <= 0x40) { + /** + * Memory instructions + */ + if (instruction.name === "grow_memory" || instruction.name === "current_memory") { + var _indexU = readU32(); + + var _index2 = _indexU.value; + eatBytes(_indexU.nextIndex); + + if (_index2 !== 0) { + throw new Error("zero flag expected"); + } + + dump([_index2], "index"); + } else { + var aligun32 = readU32(); + var align = aligun32.value; + eatBytes(aligun32.nextIndex); + dump([align], "align"); + var offsetu32 = readU32(); + var _offset2 = offsetu32.value; + eatBytes(offsetu32.nextIndex); + dump([_offset2], "offset"); + } + } else if (instructionByte >= 0x41 && instructionByte <= 0x44) { + /** + * Numeric instructions + */ + if (instruction.object === "i32") { + var value32 = read32(); + var value = value32.value; + eatBytes(value32.nextIndex); + dump([value], "i32 value"); + args.push(t.numberLiteralFromRaw(value)); + } + + if (instruction.object === "u32") { + var valueu32 = readU32(); + var _value = valueu32.value; + eatBytes(valueu32.nextIndex); + dump([_value], "u32 value"); + args.push(t.numberLiteralFromRaw(_value)); + } + + if (instruction.object === "i64") { + var value64 = read64(); + var _value2 = value64.value; + eatBytes(value64.nextIndex); + dump([Number(_value2.toString())], "i64 value"); + var high = _value2.high, + low = _value2.low; + var _node = { + type: "LongNumberLiteral", + value: { + high: high, + low: low + } }; - innerWalk(childContext, callback); + args.push(_node); } - }); - }); - } - innerWalk(context, callback); -} + if (instruction.object === "u64") { + var valueu64 = readU64(); + var _value3 = valueu64.value; + eatBytes(valueu64.nextIndex); + dump([Number(_value3.toString())], "u64 value"); + var _high = _value3.high, + _low = _value3.low; + var _node2 = { + type: "LongNumberLiteral", + value: { + high: _high, + low: _low + } + }; + args.push(_node2); + } -var noop = function noop() {}; + if (instruction.object === "f32") { + var valuef32 = readF32(); + var _value4 = valuef32.value; + eatBytes(valuef32.nextIndex); + dump([_value4], "f32 value"); + args.push( // $FlowIgnore + t.floatLiteral(_value4, valuef32.nan, valuef32.inf, String(_value4))); + } -function traverse(node, visitors) { - var before = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : noop; - var after = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : noop; - Object.keys(visitors).forEach(function (visitor) { - if (!_nodes.nodeAndUnionTypes.includes(visitor)) { - throw new Error("Unexpected visitor ".concat(visitor)); - } - }); - var context = { - node: node, - inList: false, - shouldStop: false, - parentPath: null, - parentKey: null - }; - walk(context, function (type, path) { - if (typeof visitors[type] === "function") { - before(type, path); - visitors[type](path); - after(type, path); - } + if (instruction.object === "f64") { + var valuef64 = readF64(); + var _value5 = valuef64.value; + eatBytes(valuef64.nextIndex); + dump([_value5], "f64 value"); + args.push( // $FlowIgnore + t.floatLiteral(_value5, valuef64.nan, valuef64.inf, String(_value5))); + } + } else { + for (var _i3 = 0; _i3 < instruction.numberOfArgs; _i3++) { + var u32 = readU32(); + eatBytes(u32.nextIndex); + dump([u32.value], "argument " + _i3); + args.push(t.numberLiteralFromRaw(u32.value)); + } + } - var unionTypes = _nodes.unionTypesMap[type]; + if (instructionAlreadyCreated === false) { + if (typeof instruction.object === "string") { + var _node3 = function () { + var endLoc = getPosition(); + return t.withLoc(t.objectInstruction(instruction.name, instruction.object, args), endLoc, _startLoc6); + }(); - if (!unionTypes) { - throw new Error("Unexpected node type ".concat(type)); + code.push(_node3); + } else { + var _node4 = function () { + var endLoc = getPosition(); + return t.withLoc(t.instruction(instruction.name, args), endLoc, _startLoc6); + }(); + + code.push(_node4); + } + } } + } // https://webassembly.github.io/spec/core/binary/types.html#limits - unionTypes.forEach(function (unionType) { - if (typeof visitors[unionType] === "function") { - before(unionType, path); - visitors[unionType](path); - after(unionType, path); + + function parseLimits() { + var limitType = readByte(); + eatBytes(1); + dump([limitType], "limit type"); + var min, max; + + if (limitType === 0x01 || limitType === 0x03 // shared limits + ) { + var u32min = readU32(); + min = parseInt(u32min.value); + eatBytes(u32min.nextIndex); + dump([min], "min"); + var u32max = readU32(); + max = parseInt(u32max.value); + eatBytes(u32max.nextIndex); + dump([max], "max"); } - }); - }); -} - -/***/ }), -/***/ 38456: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + if (limitType === 0x00) { + var _u32min = readU32(); -"use strict"; + min = parseInt(_u32min.value); + eatBytes(_u32min.nextIndex); + dump([min], "min"); + } + return t.limit(min, max); + } // https://webassembly.github.io/spec/core/binary/types.html#binary-tabletype -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.isAnonymous = isAnonymous; -exports.getSectionMetadata = getSectionMetadata; -exports.getSectionMetadatas = getSectionMetadatas; -exports.sortSectionMetadata = sortSectionMetadata; -exports.orderedInsertNode = orderedInsertNode; -exports.assertHasLoc = assertHasLoc; -exports.getEndOfSection = getEndOfSection; -exports.shiftLoc = shiftLoc; -exports.shiftSection = shiftSection; -exports.signatureForOpcode = signatureForOpcode; -exports.getUniqueNameGenerator = getUniqueNameGenerator; -exports.getStartByteOffset = getStartByteOffset; -exports.getEndByteOffset = getEndByteOffset; -exports.getFunctionBeginingByteOffset = getFunctionBeginingByteOffset; -exports.getEndBlockByteOffset = getEndBlockByteOffset; -exports.getStartBlockByteOffset = getStartBlockByteOffset; -var _signatures = __webpack_require__(77392); + function parseTableType(index) { + var name = t.withRaw(t.identifier(getUniqueName("table")), String(index)); + var elementTypeByte = readByte(); + eatBytes(1); + dump([elementTypeByte], "element type"); + var elementType = _helperWasmBytecode.default.tableTypes[elementTypeByte]; -var _traverse = __webpack_require__(29436); + if (typeof elementType === "undefined") { + throw new _helperApiError.CompileError("Unknown element type in table: " + toHex(elementType)); + } -var _helperWasmBytecode = _interopRequireWildcard(__webpack_require__(66921)); + var limits = parseLimits(); + return t.table(elementType, limits, name); + } // https://webassembly.github.io/spec/binary/types.html#global-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 _sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + function parseGlobalType() { + var valtypeByte = readByte(); + eatBytes(1); + var type = _helperWasmBytecode.default.valtypes[valtypeByte]; + dump([valtypeByte], type); -function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return _sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } } + if (typeof type === "undefined") { + throw new _helperApiError.CompileError("Unknown valtype: " + toHex(valtypeByte)); + } -function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + var globalTypeByte = readByte(); + eatBytes(1); + var globalType = _helperWasmBytecode.default.globalTypes[globalTypeByte]; + dump([globalTypeByte], "global type (".concat(globalType, ")")); -function isAnonymous(ident) { - return ident.raw === ""; -} + if (typeof globalType === "undefined") { + throw new _helperApiError.CompileError("Invalid mutability: " + toHex(globalTypeByte)); + } -function getSectionMetadata(ast, name) { - var section; - (0, _traverse.traverse)(ast, { - SectionMetadata: function (_SectionMetadata) { - function SectionMetadata(_x) { - return _SectionMetadata.apply(this, arguments); - } + return t.globalType(type, globalType); + } // function parseNameModule() { + // const lenu32 = readVaruint32(); + // eatBytes(lenu32.nextIndex); + // console.log("len", lenu32); + // const strlen = lenu32.value; + // dump([strlen], "string length"); + // const bytes = readBytes(strlen); + // eatBytes(strlen); + // const value = utf8.decode(bytes); + // return [t.moduleNameMetadata(value)]; + // } + // this section contains an array of function names and indices - SectionMetadata.toString = function () { - return _SectionMetadata.toString(); - }; - return SectionMetadata; - }(function (_ref) { - var node = _ref.node; + function parseNameSectionFunctions() { + var functionNames = []; + var numberOfFunctionsu32 = readU32(); + var numbeOfFunctions = numberOfFunctionsu32.value; + eatBytes(numberOfFunctionsu32.nextIndex); - if (node.section === name) { - section = node; - } - }) - }); - return section; -} + for (var i = 0; i < numbeOfFunctions; i++) { + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + var name = readUTF8String(); + eatBytes(name.nextIndex); + functionNames.push(t.functionNameMetadata(name.value, index)); + } -function getSectionMetadatas(ast, name) { - var sections = []; - (0, _traverse.traverse)(ast, { - SectionMetadata: function (_SectionMetadata2) { - function SectionMetadata(_x2) { - return _SectionMetadata2.apply(this, arguments); - } + return functionNames; + } - SectionMetadata.toString = function () { - return _SectionMetadata2.toString(); - }; + function parseNameSectionLocals() { + var localNames = []; + var numbeOfFunctionsu32 = readU32(); + var numbeOfFunctions = numbeOfFunctionsu32.value; + eatBytes(numbeOfFunctionsu32.nextIndex); - return SectionMetadata; - }(function (_ref2) { - var node = _ref2.node; + for (var i = 0; i < numbeOfFunctions; i++) { + var functionIndexu32 = readU32(); + var functionIndex = functionIndexu32.value; + eatBytes(functionIndexu32.nextIndex); + var numLocalsu32 = readU32(); + var numLocals = numLocalsu32.value; + eatBytes(numLocalsu32.nextIndex); - if (node.section === name) { - sections.push(node); + for (var _i4 = 0; _i4 < numLocals; _i4++) { + var localIndexu32 = readU32(); + var localIndex = localIndexu32.value; + eatBytes(localIndexu32.nextIndex); + var name = readUTF8String(); + eatBytes(name.nextIndex); + localNames.push(t.localNameMetadata(name.value, localIndex, functionIndex)); } - }) - }); - return sections; -} - -function sortSectionMetadata(m) { - if (m.metadata == null) { - console.warn("sortSectionMetadata: no metadata to sort"); - return; - } // $FlowIgnore + } + return localNames; + } // this is a custom section used for name resolution + // https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section - m.metadata.sections.sort(function (a, b) { - var aId = _helperWasmBytecode.default.sections[a.section]; - var bId = _helperWasmBytecode.default.sections[b.section]; - if (typeof aId !== "number" || typeof bId !== "number") { - throw new Error("Section id not found"); - } + function parseNameSection(remainingBytes) { + var nameMetadata = []; + var initialOffset = offset; - return aId - bId; - }); -} + while (offset - initialOffset < remainingBytes) { + // name_type + var sectionTypeByte = readVaruint7(); + eatBytes(sectionTypeByte.nextIndex); // name_payload_len -function orderedInsertNode(m, n) { - assertHasLoc(n); - var didInsert = false; + var subSectionSizeInBytesu32 = readVaruint32(); + eatBytes(subSectionSizeInBytesu32.nextIndex); - if (n.type === "ModuleExport") { - m.fields.push(n); - return; - } + switch (sectionTypeByte.value) { + // case 0: { + // TODO(sven): re-enable that + // Current status: it seems that when we decode the module's name + // no name_payload_len is used. + // + // See https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section + // + // nameMetadata.push(...parseNameModule()); + // break; + // } + case 1: + { + nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionFunctions())); + break; + } - m.fields = m.fields.reduce(function (acc, field) { - var fieldEndCol = Infinity; + case 2: + { + nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionLocals())); + break; + } - if (field.loc != null) { - // $FlowIgnore - fieldEndCol = field.loc.end.column; - } // $FlowIgnore: assertHasLoc ensures that + default: + { + // skip unknown subsection + eatBytes(subSectionSizeInBytesu32.value); + } + } + } + return nameMetadata; + } // this is a custom section used for information about the producers + // https://github.com/WebAssembly/tool-conventions/blob/master/ProducersSection.md - if (didInsert === false && n.loc.start.column < fieldEndCol) { - didInsert = true; - acc.push(n); - } - acc.push(field); - return acc; - }, []); // Handles empty modules or n is the last element + function parseProducersSection() { + var metadata = t.producersSectionMetadata([]); // field_count - if (didInsert === false) { - m.fields.push(n); - } -} + var sectionTypeByte = readVaruint32(); + eatBytes(sectionTypeByte.nextIndex); + dump([sectionTypeByte.value], "num of producers"); + var fields = { + language: [], + "processed-by": [], + sdk: [] + }; // fields -function assertHasLoc(n) { - if (n.loc == null || n.loc.start == null || n.loc.end == null) { - throw new Error("Internal failure: node (".concat(JSON.stringify(n.type), ") has no location information")); - } -} + for (var fieldI = 0; fieldI < sectionTypeByte.value; fieldI++) { + // field_name + var fieldName = readUTF8String(); + eatBytes(fieldName.nextIndex); // field_value_count -function getEndOfSection(s) { - assertHasLoc(s.size); - return s.startOffset + s.size.value + ( // $FlowIgnore - s.size.loc.end.column - s.size.loc.start.column); -} + var valueCount = readVaruint32(); + eatBytes(valueCount.nextIndex); // field_values -function shiftLoc(node, delta) { - // $FlowIgnore - node.loc.start.column += delta; // $FlowIgnore + for (var producerI = 0; producerI < valueCount.value; producerI++) { + var producerName = readUTF8String(); + eatBytes(producerName.nextIndex); + var producerVersion = readUTF8String(); + eatBytes(producerVersion.nextIndex); + fields[fieldName.value].push(t.producerMetadataVersionedName(producerName.value, producerVersion.value)); + } - node.loc.end.column += delta; -} + metadata.producers.push(fields[fieldName.value]); + } -function shiftSection(ast, node, delta) { - if (node.type !== "SectionMetadata") { - throw new Error("Can not shift node " + JSON.stringify(node.type)); + return metadata; } - node.startOffset += delta; - - if (_typeof(node.size.loc) === "object") { - shiftLoc(node.size, delta); - } // Custom sections doesn't have vectorOfSize + function parseGlobalSection(numberOfGlobals) { + var globals = []; + dump([numberOfGlobals], "num globals"); + for (var i = 0; i < numberOfGlobals; i++) { + var _startLoc11 = getPosition(); - if (_typeof(node.vectorOfSize) === "object" && _typeof(node.vectorOfSize.loc) === "object") { - shiftLoc(node.vectorOfSize, delta); - } + var globalType = parseGlobalType(); + /** + * Global expressions + */ - var sectionName = node.section; // shift node locations within that section + var init = []; + parseInstructionBlock(init); - (0, _traverse.traverse)(ast, { - Node: function Node(_ref3) { - var node = _ref3.node; - var section = (0, _helperWasmBytecode.getSectionForNode)(node); + var node = function () { + var endLoc = getPosition(); + return t.withLoc(t.global(globalType, init), endLoc, _startLoc11); + }(); - if (section === sectionName && _typeof(node.loc) === "object") { - shiftLoc(node, delta); - } + globals.push(node); + state.globalsInModule.push(node); } - }); -} -function signatureForOpcode(object, name) { - var opcodeName = name; - - if (object !== undefined && object !== "") { - opcodeName = object + "." + name; + return globals; } - var sign = _signatures.signatures[opcodeName]; + function parseElemSection(numberOfElements) { + var elems = []; + dump([numberOfElements], "num elements"); - if (sign == undefined) { - // TODO: Uncomment this when br_table and others has been done - //throw new Error("Invalid opcode: "+opcodeName); - return [object, object]; - } + for (var i = 0; i < numberOfElements; i++) { + var _startLoc12 = getPosition(); - return sign[0]; -} + var tableindexu32 = readU32(); + var tableindex = tableindexu32.value; + eatBytes(tableindexu32.nextIndex); + dump([tableindex], "table index"); + /** + * Parse instructions + */ -function getUniqueNameGenerator() { - var inc = {}; - return function () { - var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp"; + var instr = []; + parseInstructionBlock(instr); + /** + * Parse ( vector function index ) * + */ - if (!(prefix in inc)) { - inc[prefix] = 0; - } else { - inc[prefix] = inc[prefix] + 1; - } + var indicesu32 = readU32(); + var indices = indicesu32.value; + eatBytes(indicesu32.nextIndex); + dump([indices], "num indices"); + var indexValues = []; - return prefix + "_" + inc[prefix]; - }; -} + for (var _i5 = 0; _i5 < indices; _i5++) { + var indexu32 = readU32(); + var index = indexu32.value; + eatBytes(indexu32.nextIndex); + dump([index], "index"); + indexValues.push(t.indexLiteral(index)); + } -function getStartByteOffset(n) { - // $FlowIgnore - if (typeof n.loc === "undefined" || typeof n.loc.start === "undefined") { - throw new Error( // $FlowIgnore - "Can not get byte offset without loc informations, node: " + String(n.id)); - } + var elemNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.elem(t.indexLiteral(tableindex), instr, indexValues), endLoc, _startLoc12); + }(); - return n.loc.start.column; -} + elems.push(elemNode); + } -function getEndByteOffset(n) { - // $FlowIgnore - if (typeof n.loc === "undefined" || typeof n.loc.end === "undefined") { - throw new Error("Can not get byte offset without loc informations, node: " + n.type); - } + return elems; + } // https://webassembly.github.io/spec/core/binary/types.html#memory-types - return n.loc.end.column; -} -function getFunctionBeginingByteOffset(n) { - if (!(n.body.length > 0)) { - throw new Error('n.body.length > 0' + " error: " + (undefined || "unknown")); - } + function parseMemoryType(i) { + var limits = parseLimits(); + return t.memory(limits, t.indexLiteral(i)); + } // https://webassembly.github.io/spec/binary/modules.html#table-section - var _n$body = _slicedToArray(n.body, 1), - firstInstruction = _n$body[0]; - return getStartByteOffset(firstInstruction); -} + function parseTableSection(numberOfElements) { + var tables = []; + dump([numberOfElements], "num elements"); -function getEndBlockByteOffset(n) { - // $FlowIgnore - if (!(n.instr.length > 0 || n.body.length > 0)) { - throw new Error('n.instr.length > 0 || n.body.length > 0' + " error: " + (undefined || "unknown")); - } + for (var i = 0; i < numberOfElements; i++) { + var tablesNode = parseTableType(i); + state.tablesInModule.push(tablesNode); + tables.push(tablesNode); + } - var lastInstruction; + return tables; + } // https://webassembly.github.io/spec/binary/modules.html#memory-section - if (n.instr) { - // $FlowIgnore - lastInstruction = n.instr[n.instr.length - 1]; - } - if (n.body) { - // $FlowIgnore - lastInstruction = n.body[n.body.length - 1]; - } + function parseMemorySection(numberOfElements) { + var memories = []; + dump([numberOfElements], "num elements"); - if (!(_typeof(lastInstruction) === "object")) { - throw new Error('typeof lastInstruction === "object"' + " error: " + (undefined || "unknown")); - } + for (var i = 0; i < numberOfElements; i++) { + var memoryNode = parseMemoryType(i); + state.memoriesInModule.push(memoryNode); + memories.push(memoryNode); + } - // $FlowIgnore - return getStartByteOffset(lastInstruction); -} + return memories; + } // https://webassembly.github.io/spec/binary/modules.html#binary-startsec -function getStartBlockByteOffset(n) { - // $FlowIgnore - if (!(n.instr.length > 0 || n.body.length > 0)) { - throw new Error('n.instr.length > 0 || n.body.length > 0' + " error: " + (undefined || "unknown")); - } - var fistInstruction; + function parseStartSection() { + var startLoc = getPosition(); + var u32 = readU32(); + var startFuncIndex = u32.value; + eatBytes(u32.nextIndex); + dump([startFuncIndex], "index"); + return function () { + var endLoc = getPosition(); + return t.withLoc(t.start(t.indexLiteral(startFuncIndex)), endLoc, startLoc); + }(); + } // https://webassembly.github.io/spec/binary/modules.html#data-section - if (n.instr) { - // $FlowIgnore - var _n$instr = _slicedToArray(n.instr, 1); - fistInstruction = _n$instr[0]; - } + function parseDataSection(numberOfElements) { + var dataEntries = []; + dump([numberOfElements], "num elements"); - if (n.body) { - // $FlowIgnore - var _n$body2 = _slicedToArray(n.body, 1); + for (var i = 0; i < numberOfElements; i++) { + var memoryIndexu32 = readU32(); + var memoryIndex = memoryIndexu32.value; + eatBytes(memoryIndexu32.nextIndex); + dump([memoryIndex], "memory index"); + var instrs = []; + parseInstructionBlock(instrs); + var hasExtraInstrs = instrs.filter(function (i) { + return i.id !== "end"; + }).length !== 1; - fistInstruction = _n$body2[0]; - } + if (hasExtraInstrs) { + throw new _helperApiError.CompileError("data section offset must be a single instruction"); + } - if (!(_typeof(fistInstruction) === "object")) { - throw new Error('typeof fistInstruction === "object"' + " error: " + (undefined || "unknown")); - } + var bytes = parseVec(function (b) { + return b; + }); + dump([], "init"); + dataEntries.push(t.data(t.memIndexLiteral(memoryIndex), instrs[0], t.byteArray(bytes))); + } - // $FlowIgnore - return getStartByteOffset(fistInstruction); -} + return dataEntries; + } // https://webassembly.github.io/spec/binary/modules.html#binary-section -/***/ }), -/***/ 20193: -/***/ (function(__unused_webpack_module, exports) { + function parseSection(sectionIndex) { + var sectionId = readByte(); + eatBytes(1); + + if (sectionId >= sectionIndex || sectionIndex === _helperWasmBytecode.default.sections.custom) { + sectionIndex = sectionId + 1; + } else { + if (sectionId !== _helperWasmBytecode.default.sections.custom) throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId)); + } -"use strict"; + var nextSectionIndex = sectionIndex; + var startOffset = offset; + var startLoc = getPosition(); + var u32 = readU32(); + var sectionSizeInBytes = u32.value; + eatBytes(u32.nextIndex); + var sectionSizeInBytesNode = function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(sectionSizeInBytes), endLoc, startLoc); + }(); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.LinkError = exports.CompileError = exports.RuntimeError = void 0; + switch (sectionId) { + case _helperWasmBytecode.default.sections.type: + { + dumpSep("section Type"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); -function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + var _startLoc13 = getPosition(); -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + var _u = readU32(); -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + var numberOfTypes = _u.value; + eatBytes(_u.nextIndex); -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + var _metadata = t.sectionMetadata("type", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfTypes), endLoc, _startLoc13); + }()); -var RuntimeError = -/*#__PURE__*/ -function (_Error) { - _inherits(RuntimeError, _Error); + var _nodes = parseTypeSection(numberOfTypes); - function RuntimeError() { - _classCallCheck(this, RuntimeError); + return { + nodes: _nodes, + metadata: _metadata, + nextSectionIndex: nextSectionIndex + }; + } - return _possibleConstructorReturn(this, (RuntimeError.__proto__ || Object.getPrototypeOf(RuntimeError)).apply(this, arguments)); - } + case _helperWasmBytecode.default.sections.table: + { + dumpSep("section Table"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); - return RuntimeError; -}(Error); + var _startLoc14 = getPosition(); -exports.RuntimeError = RuntimeError; + var _u2 = readU32(); -var CompileError = -/*#__PURE__*/ -function (_Error2) { - _inherits(CompileError, _Error2); + var numberOfTable = _u2.value; + eatBytes(_u2.nextIndex); + dump([numberOfTable], "num tables"); - function CompileError() { - _classCallCheck(this, CompileError); + var _metadata2 = t.sectionMetadata("table", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfTable), endLoc, _startLoc14); + }()); - return _possibleConstructorReturn(this, (CompileError.__proto__ || Object.getPrototypeOf(CompileError)).apply(this, arguments)); - } + var _nodes2 = parseTableSection(numberOfTable); - return CompileError; -}(Error); + return { + nodes: _nodes2, + metadata: _metadata2, + nextSectionIndex: nextSectionIndex + }; + } -exports.CompileError = CompileError; + case _helperWasmBytecode.default.sections.import: + { + dumpSep("section Import"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); -var LinkError = -/*#__PURE__*/ -function (_Error3) { - _inherits(LinkError, _Error3); + var _startLoc15 = getPosition(); - function LinkError() { - _classCallCheck(this, LinkError); + var numberOfImportsu32 = readU32(); + var numberOfImports = numberOfImportsu32.value; + eatBytes(numberOfImportsu32.nextIndex); + dump([numberOfImports], "number of imports"); - return _possibleConstructorReturn(this, (LinkError.__proto__ || Object.getPrototypeOf(LinkError)).apply(this, arguments)); - } + var _metadata3 = t.sectionMetadata("import", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfImports), endLoc, _startLoc15); + }()); - return LinkError; -}(Error); + var _nodes3 = parseImportSection(numberOfImports); -exports.LinkError = LinkError; + return { + nodes: _nodes3, + metadata: _metadata3, + nextSectionIndex: nextSectionIndex + }; + } -/***/ }), + case _helperWasmBytecode.default.sections.func: + { + dumpSep("section Function"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); -/***/ 66921: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + var _startLoc16 = getPosition(); -"use strict"; + var numberOfFunctionsu32 = readU32(); + var numberOfFunctions = numberOfFunctionsu32.value; + eatBytes(numberOfFunctionsu32.nextIndex); + var _metadata4 = t.sectionMetadata("func", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfFunctions), endLoc, _startLoc16); + }()); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "getSectionForNode", ({ - enumerable: true, - get: function get() { - return _section.getSectionForNode; - } -})); -exports.default = void 0; + parseFuncSection(numberOfFunctions); + var _nodes4 = []; + return { + nodes: _nodes4, + metadata: _metadata4, + nextSectionIndex: nextSectionIndex + }; + } -var _section = __webpack_require__(79348); + case _helperWasmBytecode.default.sections.export: + { + dumpSep("section Export"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); -var illegalop = "illegal"; -var magicModuleHeader = [0x00, 0x61, 0x73, 0x6d]; -var moduleVersion = [0x01, 0x00, 0x00, 0x00]; + var _startLoc17 = getPosition(); -function invertMap(obj) { - var keyModifierFn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (k) { - return k; - }; - var result = {}; - var keys = Object.keys(obj); + var _u3 = readU32(); - for (var i = 0, length = keys.length; i < length; i++) { - result[keyModifierFn(obj[keys[i]])] = keys[i]; - } + var numberOfExport = _u3.value; + eatBytes(_u3.nextIndex); - return result; -} + var _metadata5 = t.sectionMetadata("export", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfExport), endLoc, _startLoc17); + }()); -function createSymbolObject(name -/*: string */ -, object -/*: string */ -) -/*: Symbol*/ -{ - var numberOfArgs - /*: number*/ - = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - return { - name: name, - object: object, - numberOfArgs: numberOfArgs - }; -} + parseExportSection(numberOfExport); + var _nodes5 = []; + return { + nodes: _nodes5, + metadata: _metadata5, + nextSectionIndex: nextSectionIndex + }; + } -function createSymbol(name -/*: string */ -) -/*: Symbol*/ -{ - var numberOfArgs - /*: number*/ - = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - return { - name: name, - numberOfArgs: numberOfArgs - }; -} + case _helperWasmBytecode.default.sections.code: + { + dumpSep("section Code"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); -var types = { - func: 0x60, - result: 0x40 -}; -var exportTypes = { - 0x00: "Func", - 0x01: "Table", - 0x02: "Mem", - 0x03: "Global" -}; -var exportTypesByName = invertMap(exportTypes); -var valtypes = { - 0x7f: "i32", - 0x7e: "i64", - 0x7d: "f32", - 0x7c: "f64", - 0x7b: "v128" -}; -var valtypesByString = invertMap(valtypes); -var tableTypes = { - 0x70: "anyfunc" -}; -var blockTypes = Object.assign({}, valtypes, { - // https://webassembly.github.io/spec/core/binary/types.html#binary-blocktype - 0x40: null, - // https://webassembly.github.io/spec/core/binary/types.html#binary-valtype - 0x7f: "i32", - 0x7e: "i64", - 0x7d: "f32", - 0x7c: "f64" -}); -var globalTypes = { - 0x00: "const", - 0x01: "var" -}; -var globalTypesByString = invertMap(globalTypes); -var importTypes = { - 0x00: "func", - 0x01: "table", - 0x02: "mem", - 0x03: "global" -}; -var sections = { - custom: 0, - type: 1, - import: 2, - func: 3, - table: 4, - memory: 5, - global: 6, - export: 7, - start: 8, - element: 9, - code: 10, - data: 11 -}; -var symbolsByByte = { - 0x00: createSymbol("unreachable"), - 0x01: createSymbol("nop"), - 0x02: createSymbol("block"), - 0x03: createSymbol("loop"), - 0x04: createSymbol("if"), - 0x05: createSymbol("else"), - 0x06: illegalop, - 0x07: illegalop, - 0x08: illegalop, - 0x09: illegalop, - 0x0a: illegalop, - 0x0b: createSymbol("end"), - 0x0c: createSymbol("br", 1), - 0x0d: createSymbol("br_if", 1), - 0x0e: createSymbol("br_table"), - 0x0f: createSymbol("return"), - 0x10: createSymbol("call", 1), - 0x11: createSymbol("call_indirect", 2), - 0x12: illegalop, - 0x13: illegalop, - 0x14: illegalop, - 0x15: illegalop, - 0x16: illegalop, - 0x17: illegalop, - 0x18: illegalop, - 0x19: illegalop, - 0x1a: createSymbol("drop"), - 0x1b: createSymbol("select"), - 0x1c: illegalop, - 0x1d: illegalop, - 0x1e: illegalop, - 0x1f: illegalop, - 0x20: createSymbol("get_local", 1), - 0x21: createSymbol("set_local", 1), - 0x22: createSymbol("tee_local", 1), - 0x23: createSymbol("get_global", 1), - 0x24: createSymbol("set_global", 1), - 0x25: illegalop, - 0x26: illegalop, - 0x27: illegalop, - 0x28: createSymbolObject("load", "u32", 1), - 0x29: createSymbolObject("load", "u64", 1), - 0x2a: createSymbolObject("load", "f32", 1), - 0x2b: createSymbolObject("load", "f64", 1), - 0x2c: createSymbolObject("load8_s", "u32", 1), - 0x2d: createSymbolObject("load8_u", "u32", 1), - 0x2e: createSymbolObject("load16_s", "u32", 1), - 0x2f: createSymbolObject("load16_u", "u32", 1), - 0x30: createSymbolObject("load8_s", "u64", 1), - 0x31: createSymbolObject("load8_u", "u64", 1), - 0x32: createSymbolObject("load16_s", "u64", 1), - 0x33: createSymbolObject("load16_u", "u64", 1), - 0x34: createSymbolObject("load32_s", "u64", 1), - 0x35: createSymbolObject("load32_u", "u64", 1), - 0x36: createSymbolObject("store", "u32", 1), - 0x37: createSymbolObject("store", "u64", 1), - 0x38: createSymbolObject("store", "f32", 1), - 0x39: createSymbolObject("store", "f64", 1), - 0x3a: createSymbolObject("store8", "u32", 1), - 0x3b: createSymbolObject("store16", "u32", 1), - 0x3c: createSymbolObject("store8", "u64", 1), - 0x3d: createSymbolObject("store16", "u64", 1), - 0x3e: createSymbolObject("store32", "u64", 1), - 0x3f: createSymbolObject("current_memory"), - 0x40: createSymbolObject("grow_memory"), - 0x41: createSymbolObject("const", "i32", 1), - 0x42: createSymbolObject("const", "i64", 1), - 0x43: createSymbolObject("const", "f32", 1), - 0x44: createSymbolObject("const", "f64", 1), - 0x45: createSymbolObject("eqz", "i32"), - 0x46: createSymbolObject("eq", "i32"), - 0x47: createSymbolObject("ne", "i32"), - 0x48: createSymbolObject("lt_s", "i32"), - 0x49: createSymbolObject("lt_u", "i32"), - 0x4a: createSymbolObject("gt_s", "i32"), - 0x4b: createSymbolObject("gt_u", "i32"), - 0x4c: createSymbolObject("le_s", "i32"), - 0x4d: createSymbolObject("le_u", "i32"), - 0x4e: createSymbolObject("ge_s", "i32"), - 0x4f: createSymbolObject("ge_u", "i32"), - 0x50: createSymbolObject("eqz", "i64"), - 0x51: createSymbolObject("eq", "i64"), - 0x52: createSymbolObject("ne", "i64"), - 0x53: createSymbolObject("lt_s", "i64"), - 0x54: createSymbolObject("lt_u", "i64"), - 0x55: createSymbolObject("gt_s", "i64"), - 0x56: createSymbolObject("gt_u", "i64"), - 0x57: createSymbolObject("le_s", "i64"), - 0x58: createSymbolObject("le_u", "i64"), - 0x59: createSymbolObject("ge_s", "i64"), - 0x5a: createSymbolObject("ge_u", "i64"), - 0x5b: createSymbolObject("eq", "f32"), - 0x5c: createSymbolObject("ne", "f32"), - 0x5d: createSymbolObject("lt", "f32"), - 0x5e: createSymbolObject("gt", "f32"), - 0x5f: createSymbolObject("le", "f32"), - 0x60: createSymbolObject("ge", "f32"), - 0x61: createSymbolObject("eq", "f64"), - 0x62: createSymbolObject("ne", "f64"), - 0x63: createSymbolObject("lt", "f64"), - 0x64: createSymbolObject("gt", "f64"), - 0x65: createSymbolObject("le", "f64"), - 0x66: createSymbolObject("ge", "f64"), - 0x67: createSymbolObject("clz", "i32"), - 0x68: createSymbolObject("ctz", "i32"), - 0x69: createSymbolObject("popcnt", "i32"), - 0x6a: createSymbolObject("add", "i32"), - 0x6b: createSymbolObject("sub", "i32"), - 0x6c: createSymbolObject("mul", "i32"), - 0x6d: createSymbolObject("div_s", "i32"), - 0x6e: createSymbolObject("div_u", "i32"), - 0x6f: createSymbolObject("rem_s", "i32"), - 0x70: createSymbolObject("rem_u", "i32"), - 0x71: createSymbolObject("and", "i32"), - 0x72: createSymbolObject("or", "i32"), - 0x73: createSymbolObject("xor", "i32"), - 0x74: createSymbolObject("shl", "i32"), - 0x75: createSymbolObject("shr_s", "i32"), - 0x76: createSymbolObject("shr_u", "i32"), - 0x77: createSymbolObject("rotl", "i32"), - 0x78: createSymbolObject("rotr", "i32"), - 0x79: createSymbolObject("clz", "i64"), - 0x7a: createSymbolObject("ctz", "i64"), - 0x7b: createSymbolObject("popcnt", "i64"), - 0x7c: createSymbolObject("add", "i64"), - 0x7d: createSymbolObject("sub", "i64"), - 0x7e: createSymbolObject("mul", "i64"), - 0x7f: createSymbolObject("div_s", "i64"), - 0x80: createSymbolObject("div_u", "i64"), - 0x81: createSymbolObject("rem_s", "i64"), - 0x82: createSymbolObject("rem_u", "i64"), - 0x83: createSymbolObject("and", "i64"), - 0x84: createSymbolObject("or", "i64"), - 0x85: createSymbolObject("xor", "i64"), - 0x86: createSymbolObject("shl", "i64"), - 0x87: createSymbolObject("shr_s", "i64"), - 0x88: createSymbolObject("shr_u", "i64"), - 0x89: createSymbolObject("rotl", "i64"), - 0x8a: createSymbolObject("rotr", "i64"), - 0x8b: createSymbolObject("abs", "f32"), - 0x8c: createSymbolObject("neg", "f32"), - 0x8d: createSymbolObject("ceil", "f32"), - 0x8e: createSymbolObject("floor", "f32"), - 0x8f: createSymbolObject("trunc", "f32"), - 0x90: createSymbolObject("nearest", "f32"), - 0x91: createSymbolObject("sqrt", "f32"), - 0x92: createSymbolObject("add", "f32"), - 0x93: createSymbolObject("sub", "f32"), - 0x94: createSymbolObject("mul", "f32"), - 0x95: createSymbolObject("div", "f32"), - 0x96: createSymbolObject("min", "f32"), - 0x97: createSymbolObject("max", "f32"), - 0x98: createSymbolObject("copysign", "f32"), - 0x99: createSymbolObject("abs", "f64"), - 0x9a: createSymbolObject("neg", "f64"), - 0x9b: createSymbolObject("ceil", "f64"), - 0x9c: createSymbolObject("floor", "f64"), - 0x9d: createSymbolObject("trunc", "f64"), - 0x9e: createSymbolObject("nearest", "f64"), - 0x9f: createSymbolObject("sqrt", "f64"), - 0xa0: createSymbolObject("add", "f64"), - 0xa1: createSymbolObject("sub", "f64"), - 0xa2: createSymbolObject("mul", "f64"), - 0xa3: createSymbolObject("div", "f64"), - 0xa4: createSymbolObject("min", "f64"), - 0xa5: createSymbolObject("max", "f64"), - 0xa6: createSymbolObject("copysign", "f64"), - 0xa7: createSymbolObject("wrap/i64", "i32"), - 0xa8: createSymbolObject("trunc_s/f32", "i32"), - 0xa9: createSymbolObject("trunc_u/f32", "i32"), - 0xaa: createSymbolObject("trunc_s/f64", "i32"), - 0xab: createSymbolObject("trunc_u/f64", "i32"), - 0xac: createSymbolObject("extend_s/i32", "i64"), - 0xad: createSymbolObject("extend_u/i32", "i64"), - 0xae: createSymbolObject("trunc_s/f32", "i64"), - 0xaf: createSymbolObject("trunc_u/f32", "i64"), - 0xb0: createSymbolObject("trunc_s/f64", "i64"), - 0xb1: createSymbolObject("trunc_u/f64", "i64"), - 0xb2: createSymbolObject("convert_s/i32", "f32"), - 0xb3: createSymbolObject("convert_u/i32", "f32"), - 0xb4: createSymbolObject("convert_s/i64", "f32"), - 0xb5: createSymbolObject("convert_u/i64", "f32"), - 0xb6: createSymbolObject("demote/f64", "f32"), - 0xb7: createSymbolObject("convert_s/i32", "f64"), - 0xb8: createSymbolObject("convert_u/i32", "f64"), - 0xb9: createSymbolObject("convert_s/i64", "f64"), - 0xba: createSymbolObject("convert_u/i64", "f64"), - 0xbb: createSymbolObject("promote/f32", "f64"), - 0xbc: createSymbolObject("reinterpret/f32", "i32"), - 0xbd: createSymbolObject("reinterpret/f64", "i64"), - 0xbe: createSymbolObject("reinterpret/i32", "f32"), - 0xbf: createSymbolObject("reinterpret/i64", "f64") -}; -var symbolsByName = invertMap(symbolsByByte, function (obj) { - if (typeof obj.object === "string") { - return "".concat(obj.object, ".").concat(obj.name); - } + var _startLoc18 = getPosition(); - return obj.name; -}); -var _default = { - symbolsByByte: symbolsByByte, - sections: sections, - magicModuleHeader: magicModuleHeader, - moduleVersion: moduleVersion, - types: types, - valtypes: valtypes, - exportTypes: exportTypes, - blockTypes: blockTypes, - tableTypes: tableTypes, - globalTypes: globalTypes, - importTypes: importTypes, - valtypesByString: valtypesByString, - globalTypesByString: globalTypesByString, - exportTypesByName: exportTypesByName, - symbolsByName: symbolsByName -}; -exports.default = _default; + var _u4 = readU32(); -/***/ }), + var numberOfFuncs = _u4.value; + eatBytes(_u4.nextIndex); -/***/ 79348: -/***/ (function(__unused_webpack_module, exports) { + var _metadata6 = t.sectionMetadata("code", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfFuncs), endLoc, _startLoc18); + }()); -"use strict"; + if (opts.ignoreCodeSection === true) { + var remainingBytes = sectionSizeInBytes - _u4.nextIndex; + eatBytes(remainingBytes); // eat the entire section + } else { + parseCodeSection(numberOfFuncs); + } + var _nodes6 = []; + return { + nodes: _nodes6, + metadata: _metadata6, + nextSectionIndex: nextSectionIndex + }; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getSectionForNode = getSectionForNode; + case _helperWasmBytecode.default.sections.start: + { + dumpSep("section Start"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); -function getSectionForNode(n) { - switch (n.type) { - case "ModuleImport": - return "import"; + var _metadata7 = t.sectionMetadata("start", startOffset, sectionSizeInBytesNode); - case "CallInstruction": - case "CallIndirectInstruction": - case "Func": - case "Instr": - return "code"; + var _nodes7 = [parseStartSection()]; + return { + nodes: _nodes7, + metadata: _metadata7, + nextSectionIndex: nextSectionIndex + }; + } - case "ModuleExport": - return "export"; + case _helperWasmBytecode.default.sections.element: + { + dumpSep("section Element"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); - case "Start": - return "start"; + var _startLoc19 = getPosition(); - case "TypeInstruction": - return "type"; + var numberOfElementsu32 = readU32(); + var numberOfElements = numberOfElementsu32.value; + eatBytes(numberOfElementsu32.nextIndex); - case "IndexInFuncSection": - return "func"; + var _metadata8 = t.sectionMetadata("element", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfElements), endLoc, _startLoc19); + }()); - case "Global": - return "global"; - // No section + var _nodes8 = parseElemSection(numberOfElements); - default: - return; - } -} + return { + nodes: _nodes8, + metadata: _metadata8, + nextSectionIndex: nextSectionIndex + }; + } -/***/ }), + case _helperWasmBytecode.default.sections.global: + { + dumpSep("section Global"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); -/***/ 57732: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + var _startLoc20 = getPosition(); -"use strict"; + var numberOfGlobalsu32 = readU32(); + var numberOfGlobals = numberOfGlobalsu32.value; + eatBytes(numberOfGlobalsu32.nextIndex); + var _metadata9 = t.sectionMetadata("global", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(numberOfGlobals), endLoc, _startLoc20); + }()); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.encodeF32 = encodeF32; -exports.encodeF64 = encodeF64; -exports.decodeF32 = decodeF32; -exports.decodeF64 = decodeF64; -exports.DOUBLE_PRECISION_MANTISSA = exports.SINGLE_PRECISION_MANTISSA = exports.NUMBER_OF_BYTE_F64 = exports.NUMBER_OF_BYTE_F32 = void 0; + var _nodes9 = parseGlobalSection(numberOfGlobals); -var _ieee = __webpack_require__(30848); + return { + nodes: _nodes9, + metadata: _metadata9, + nextSectionIndex: nextSectionIndex + }; + } -/** - * According to https://webassembly.github.io/spec/binary/values.html#binary-float - * n = 32/8 - */ -var NUMBER_OF_BYTE_F32 = 4; -/** - * According to https://webassembly.github.io/spec/binary/values.html#binary-float - * n = 64/8 - */ + case _helperWasmBytecode.default.sections.memory: + { + dumpSep("section Memory"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); -exports.NUMBER_OF_BYTE_F32 = NUMBER_OF_BYTE_F32; -var NUMBER_OF_BYTE_F64 = 8; -exports.NUMBER_OF_BYTE_F64 = NUMBER_OF_BYTE_F64; -var SINGLE_PRECISION_MANTISSA = 23; -exports.SINGLE_PRECISION_MANTISSA = SINGLE_PRECISION_MANTISSA; -var DOUBLE_PRECISION_MANTISSA = 52; -exports.DOUBLE_PRECISION_MANTISSA = DOUBLE_PRECISION_MANTISSA; + var _startLoc21 = getPosition(); -function encodeF32(v) { - var buffer = []; - (0, _ieee.write)(buffer, v, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); - return buffer; -} + var _numberOfElementsu = readU32(); -function encodeF64(v) { - var buffer = []; - (0, _ieee.write)(buffer, v, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); - return buffer; -} + var _numberOfElements = _numberOfElementsu.value; + eatBytes(_numberOfElementsu.nextIndex); -function decodeF32(bytes) { - var buffer = Buffer.from(bytes); - return (0, _ieee.read)(buffer, 0, true, SINGLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F32); -} + var _metadata10 = t.sectionMetadata("memory", startOffset, sectionSizeInBytesNode, function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(_numberOfElements), endLoc, _startLoc21); + }()); -function decodeF64(bytes) { - var buffer = Buffer.from(bytes); - return (0, _ieee.read)(buffer, 0, true, DOUBLE_PRECISION_MANTISSA, NUMBER_OF_BYTE_F64); -} + var _nodes10 = parseMemorySection(_numberOfElements); -/***/ }), + return { + nodes: _nodes10, + metadata: _metadata10, + nextSectionIndex: nextSectionIndex + }; + } -/***/ 62904: -/***/ (function(__unused_webpack_module, exports) { + case _helperWasmBytecode.default.sections.data: + { + dumpSep("section Data"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); -"use strict"; -// Copyright 2012 The Obvious Corporation. + var _metadata11 = t.sectionMetadata("data", startOffset, sectionSizeInBytesNode); -/* - * bits: Bitwise buffer utilities. The utilities here treat a buffer - * as a little-endian bigint, so the lowest-order bit is bit #0 of - * `buffer[0]`, and the highest-order bit is bit #7 of - * `buffer[buffer.length - 1]`. - */ + var _startLoc22 = getPosition(); -/* - * Modules used - */ + var _numberOfElementsu2 = readU32(); -/* - * Exported bindings - */ + var _numberOfElements2 = _numberOfElementsu2.value; + eatBytes(_numberOfElementsu2.nextIndex); -/** - * Extracts the given number of bits from the buffer at the indicated - * index, returning a simple number as the result. If bits are requested - * that aren't covered by the buffer, the `defaultBit` is used as their - * value. - * - * The `bitLength` must be no more than 32. The `defaultBit` if not - * specified is taken to be `0`. - */ + _metadata11.vectorOfSize = function () { + var endLoc = getPosition(); + return t.withLoc(t.numberLiteralFromRaw(_numberOfElements2), endLoc, _startLoc22); + }(); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.extract = extract; -exports.inject = inject; -exports.getSign = getSign; -exports.highOrder = highOrder; + if (opts.ignoreDataSection === true) { + var _remainingBytes = sectionSizeInBytes - _numberOfElementsu2.nextIndex; -function extract(buffer, bitIndex, bitLength, defaultBit) { - if (bitLength < 0 || bitLength > 32) { - throw new Error("Bad value for bitLength."); - } + eatBytes(_remainingBytes); // eat the entire section - if (defaultBit === undefined) { - defaultBit = 0; - } else if (defaultBit !== 0 && defaultBit !== 1) { - throw new Error("Bad value for defaultBit."); - } + dumpSep("ignore data (" + sectionSizeInBytes + " bytes)"); + return { + nodes: [], + metadata: _metadata11, + nextSectionIndex: nextSectionIndex + }; + } else { + var _nodes11 = parseDataSection(_numberOfElements2); - var defaultByte = defaultBit * 0xff; - var result = 0; // All starts are inclusive. The {endByte, endBit} pair is exclusive, but - // if endBit !== 0, then endByte is inclusive. + return { + nodes: _nodes11, + metadata: _metadata11, + nextSectionIndex: nextSectionIndex + }; + } + } - var lastBit = bitIndex + bitLength; - var startByte = Math.floor(bitIndex / 8); - var startBit = bitIndex % 8; - var endByte = Math.floor(lastBit / 8); - var endBit = lastBit % 8; + case _helperWasmBytecode.default.sections.custom: + { + dumpSep("section Custom"); + dump([sectionId], "section code"); + dump([sectionSizeInBytes], "section size"); + var _metadata12 = [t.sectionMetadata("custom", startOffset, sectionSizeInBytesNode)]; + var sectionName = readUTF8String(); + eatBytes(sectionName.nextIndex); + dump([], "section name (".concat(sectionName.value, ")")); - if (endBit !== 0) { - // `(1 << endBit) - 1` is the mask of all bits up to but not including - // the endBit. - result = get(endByte) & (1 << endBit) - 1; - } + var _remainingBytes2 = sectionSizeInBytes - sectionName.nextIndex; - while (endByte > startByte) { - endByte--; - result = result << 8 | get(endByte); - } + if (sectionName.value === "name") { + var initialOffset = offset; - result >>>= startBit; - return result; + try { + _metadata12.push.apply(_metadata12, _toConsumableArray(parseNameSection(_remainingBytes2))); + } catch (e) { + console.warn("Failed to decode custom \"name\" section @".concat(offset, "; ignoring (").concat(e.message, ").")); + eatBytes(offset - (initialOffset + _remainingBytes2)); + } + } else if (sectionName.value === "producers") { + var _initialOffset = offset; - function get(index) { - var result = buffer[index]; - return result === undefined ? defaultByte : result; - } -} -/** - * Injects the given bits into the given buffer at the given index. Any - * bits in the value beyond the length to set are ignored. - */ + try { + _metadata12.push(parseProducersSection()); + } catch (e) { + console.warn("Failed to decode custom \"producers\" section @".concat(offset, "; ignoring (").concat(e.message, ").")); + eatBytes(offset - (_initialOffset + _remainingBytes2)); + } + } else { + // We don't parse the custom section + eatBytes(_remainingBytes2); + dumpSep("ignore custom " + JSON.stringify(sectionName.value) + " section (" + _remainingBytes2 + " bytes)"); + } + return { + nodes: [], + metadata: _metadata12, + nextSectionIndex: nextSectionIndex + }; + } + } -function inject(buffer, bitIndex, bitLength, value) { - if (bitLength < 0 || bitLength > 32) { - throw new Error("Bad value for bitLength."); + throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId)); } - var lastByte = Math.floor((bitIndex + bitLength - 1) / 8); - - if (bitIndex < 0 || lastByte >= buffer.length) { - throw new Error("Index out of range."); - } // Just keeping it simple, until / unless profiling shows that this - // is a problem. + parseModuleHeader(); + parseVersion(); + var moduleFields = []; + var sectionIndex = 0; + var moduleMetadata = { + sections: [], + functionNames: [], + localNames: [], + producers: [] + }; + /** + * All the generate declaration are going to be stored in our state + */ + while (offset < buf.length) { + var _parseSection = parseSection(sectionIndex), + _nodes12 = _parseSection.nodes, + _metadata13 = _parseSection.metadata, + nextSectionIndex = _parseSection.nextSectionIndex; - var atByte = Math.floor(bitIndex / 8); - var atBit = bitIndex % 8; + moduleFields.push.apply(moduleFields, _toConsumableArray(_nodes12)); + var metadataArray = Array.isArray(_metadata13) ? _metadata13 : [_metadata13]; + metadataArray.forEach(function (metadataItem) { + if (metadataItem.type === "FunctionNameMetadata") { + moduleMetadata.functionNames.push(metadataItem); + } else if (metadataItem.type === "LocalNameMetadata") { + moduleMetadata.localNames.push(metadataItem); + } else if (metadataItem.type === "ProducersSectionMetadata") { + moduleMetadata.producers.push(metadataItem); + } else { + moduleMetadata.sections.push(metadataItem); + } + }); // Ignore custom section - while (bitLength > 0) { - if (value & 1) { - buffer[atByte] |= 1 << atBit; - } else { - buffer[atByte] &= ~(1 << atBit); + if (nextSectionIndex) { + sectionIndex = nextSectionIndex; } + } + /** + * Transform the state into AST nodes + */ - value >>= 1; - bitLength--; - atBit = (atBit + 1) % 8; - if (atBit === 0) { - atByte++; - } - } -} -/** - * Gets the sign bit of the given buffer. - */ + var funcIndex = 0; + state.functionsInModule.forEach(function (func) { + var params = func.signature.params; + var result = func.signature.result; + var body = []; // External functions doesn't provide any code, can skip it here + if (func.isExternal === true) { + return; + } -function getSign(buffer) { - return buffer[buffer.length - 1] >>> 7; -} -/** - * Gets the zero-based bit number of the highest-order bit with the - * given value in the given buffer. - * - * If the buffer consists entirely of the other bit value, then this returns - * `-1`. - */ + var decodedElementInCodeSection = state.elementsInCodeSection[funcIndex]; + if (opts.ignoreCodeSection === false) { + if (typeof decodedElementInCodeSection === "undefined") { + throw new _helperApiError.CompileError("func " + toHex(funcIndex) + " code not found"); + } -function highOrder(bit, buffer) { - var length = buffer.length; - var fullyWrongByte = (bit ^ 1) * 0xff; // the other-bit extended to a full byte + body = decodedElementInCodeSection.code; + } - while (length > 0 && buffer[length - 1] === fullyWrongByte) { - length--; - } + funcIndex++; + var funcNode = t.func(func.id, t.signature(params, result), body); - if (length === 0) { - // Degenerate case. The buffer consists entirely of ~bit. - return -1; - } + if (func.isExternal === true) { + funcNode.isExternal = func.isExternal; + } // Add function position in the binary if possible - var byteToCheck = buffer[length - 1]; - var result = length * 8 - 1; - for (var i = 7; i > 0; i--) { - if ((byteToCheck >> i & 1) === bit) { - break; + if (opts.ignoreCodeSection === false) { + var _startLoc23 = decodedElementInCodeSection.startLoc, + endLoc = decodedElementInCodeSection.endLoc, + bodySize = decodedElementInCodeSection.bodySize; + funcNode = t.withLoc(funcNode, endLoc, _startLoc23); + funcNode.metadata = { + bodySize: bodySize + }; } - result--; - } - - return result; + moduleFields.push(funcNode); + }); + state.elementsInExportSection.forEach(function (moduleExport) { + /** + * If the export has no id, we won't be able to call it from the outside + * so we can omit it + */ + if (moduleExport.id != null) { + moduleFields.push(t.withLoc(t.moduleExport(moduleExport.name, t.moduleExportDescr(moduleExport.type, moduleExport.id)), moduleExport.endLoc, moduleExport.startLoc)); + } + }); + dumpSep("end of program"); + var module = t.module(null, moduleFields, t.moduleMetadata(moduleMetadata.sections, moduleMetadata.functionNames, moduleMetadata.localNames, moduleMetadata.producers)); + return t.program([module]); } /***/ }), -/***/ 7276: -/***/ (function(__unused_webpack_module, exports) { +/***/ 27352: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; @@ -118278,7888 +117159,8292 @@ function highOrder(bit, buffer) { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.alloc = alloc; -exports.free = free; -exports.resize = resize; -exports.readInt = readInt; -exports.readUInt = readUInt; -exports.writeInt64 = writeInt64; -exports.writeUInt64 = writeUInt64; -// Copyright 2012 The Obvious Corporation. - -/* - * bufs: Buffer utilities. - */ - -/* - * Module variables - */ - -/** Pool of buffers, where `bufPool[x].length === x`. */ -var bufPool = []; -/** Maximum length of kept temporary buffers. */ - -var TEMP_BUF_MAXIMUM_LENGTH = 20; -/** Minimum exactly-representable 64-bit int. */ - -var MIN_EXACT_INT64 = -0x8000000000000000; -/** Maximum exactly-representable 64-bit int. */ - -var MAX_EXACT_INT64 = 0x7ffffffffffffc00; -/** Maximum exactly-representable 64-bit uint. */ - -var MAX_EXACT_UINT64 = 0xfffffffffffff800; -/** - * The int value consisting just of a 1 in bit #32 (that is, one more - * than the maximum 32-bit unsigned value). - */ +exports.decode = decode; -var BIT_32 = 0x100000000; -/** - * The int value consisting just of a 1 in bit #64 (that is, one more - * than the maximum 64-bit unsigned value). - */ +var decoder = _interopRequireWildcard(__webpack_require__(28458)); -var BIT_64 = 0x10000000000000000; -/* - * Helper functions - */ +var t = _interopRequireWildcard(__webpack_require__(81875)); -/** - * Masks off all but the lowest bit set of the given number. - */ +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 lowestBit(num) { - return num & -num; -} /** - * Gets whether trying to add the second number to the first is lossy - * (inexact). The first number is meant to be an accumulated result. + * TODO(sven): I added initial props, but we should rather fix + * https://github.com/xtuc/webassemblyjs/issues/405 */ +var defaultDecoderOpts = { + dump: false, + ignoreCodeSection: false, + ignoreDataSection: false, + ignoreCustomNameSection: false +}; // traverses the AST, locating function name metadata, which is then +// used to update index-based identifiers with function names +function restoreFunctionNames(ast) { + var functionNames = []; + t.traverse(ast, { + FunctionNameMetadata: function FunctionNameMetadata(_ref) { + var node = _ref.node; + functionNames.push({ + name: node.value, + index: node.index + }); + } + }); -function isLossyToAdd(accum, num) { - if (num === 0) { - return false; + if (functionNames.length === 0) { + return; } - var lowBit = lowestBit(num); - var added = accum + lowBit; + t.traverse(ast, { + Func: function (_Func) { + function Func(_x) { + return _Func.apply(this, arguments); + } - if (added === accum) { - return true; - } + Func.toString = function () { + return _Func.toString(); + }; - if (added - lowBit !== accum) { - return true; - } + return Func; + }(function (_ref2) { + var node = _ref2.node; + // $FlowIgnore + var nodeName = node.name; + var indexBasedFunctionName = nodeName.value; + var index = Number(indexBasedFunctionName.replace("func_", "")); + var functionName = functionNames.find(function (f) { + return f.index === index; + }); - return false; -} -/* - * Exported functions - */ + if (functionName) { + var oldValue = nodeName.value; + nodeName.value = functionName.name; + nodeName.numeric = oldValue; // $FlowIgnore -/** - * Allocates a buffer of the given length, which is initialized - * with all zeroes. This returns a buffer from the pool if it is - * available, or a freshly-allocated buffer if not. - */ + delete nodeName.raw; + } + }), + // Also update the reference in the export + ModuleExport: function (_ModuleExport) { + function ModuleExport(_x2) { + return _ModuleExport.apply(this, arguments); + } + ModuleExport.toString = function () { + return _ModuleExport.toString(); + }; -function alloc(length) { - var result = bufPool[length]; + return ModuleExport; + }(function (_ref3) { + var node = _ref3.node; - if (result) { - bufPool[length] = undefined; - } else { - result = new Buffer(length); - } + if (node.descr.exportType === "Func") { + // $FlowIgnore + var nodeName = node.descr.id; + var index = nodeName.value; + var functionName = functionNames.find(function (f) { + return f.index === index; + }); - result.fill(0); - return result; -} -/** - * Releases a buffer back to the pool. - */ + if (functionName) { + node.descr.id = t.identifier(functionName.name); + } + } + }), + ModuleImport: function (_ModuleImport) { + function ModuleImport(_x3) { + return _ModuleImport.apply(this, arguments); + } + ModuleImport.toString = function () { + return _ModuleImport.toString(); + }; -function free(buffer) { - var length = buffer.length; + return ModuleImport; + }(function (_ref4) { + var node = _ref4.node; - if (length < TEMP_BUF_MAXIMUM_LENGTH) { - bufPool[length] = buffer; - } -} -/** - * Resizes a buffer, returning a new buffer. Returns the argument if - * the length wouldn't actually change. This function is only safe to - * use if the given buffer was allocated within this module (since - * otherwise the buffer might possibly be shared externally). - */ + if (node.descr.type === "FuncImportDescr") { + // $FlowIgnore + var indexBasedFunctionName = node.descr.id; + var index = Number(indexBasedFunctionName.replace("func_", "")); + var functionName = functionNames.find(function (f) { + return f.index === index; + }); + if (functionName) { + // $FlowIgnore + node.descr.id = t.identifier(functionName.name); + } + } + }), + CallInstruction: function (_CallInstruction) { + function CallInstruction(_x4) { + return _CallInstruction.apply(this, arguments); + } -function resize(buffer, length) { - if (length === buffer.length) { - return buffer; - } + CallInstruction.toString = function () { + return _CallInstruction.toString(); + }; - var newBuf = alloc(length); - buffer.copy(newBuf); - free(buffer); - return newBuf; -} -/** - * Reads an arbitrary signed int from a buffer. - */ + return CallInstruction; + }(function (nodePath) { + var node = nodePath.node; + var index = node.index.value; + var functionName = functionNames.find(function (f) { + return f.index === index; + }); + if (functionName) { + var oldValue = node.index; + node.index = t.identifier(functionName.name); + node.numeric = oldValue; // $FlowIgnore -function readInt(buffer) { - var length = buffer.length; - var positive = buffer[length - 1] < 0x80; - var result = positive ? 0 : -1; - var lossy = false; // Note: We can't use bit manipulation here, since that stops - // working if the result won't fit in a 32-bit int. + delete node.raw; + } + }) + }); +} - if (length < 7) { - // Common case which can't possibly be lossy (because the result has - // no more than 48 bits, and loss only happens with 54 or more). - for (var i = length - 1; i >= 0; i--) { - result = result * 0x100 + buffer[i]; +function restoreLocalNames(ast) { + var localNames = []; + t.traverse(ast, { + LocalNameMetadata: function LocalNameMetadata(_ref5) { + var node = _ref5.node; + localNames.push({ + name: node.value, + localIndex: node.localIndex, + functionIndex: node.functionIndex + }); } - } else { - for (var _i = length - 1; _i >= 0; _i--) { - var one = buffer[_i]; - result *= 0x100; + }); - if (isLossyToAdd(result, one)) { - lossy = true; + if (localNames.length === 0) { + return; + } + + t.traverse(ast, { + Func: function (_Func2) { + function Func(_x5) { + return _Func2.apply(this, arguments); } - result += one; - } - } + Func.toString = function () { + return _Func2.toString(); + }; - return { - value: result, - lossy: lossy - }; -} -/** - * Reads an arbitrary unsigned int from a buffer. - */ + return Func; + }(function (_ref6) { + var node = _ref6.node; + var signature = node.signature; + if (signature.type !== "Signature") { + return; + } // $FlowIgnore -function readUInt(buffer) { - var length = buffer.length; - var result = 0; - var lossy = false; // Note: See above in re bit manipulation. - if (length < 7) { - // Common case which can't possibly be lossy (see above). - for (var i = length - 1; i >= 0; i--) { - result = result * 0x100 + buffer[i]; - } - } else { - for (var _i2 = length - 1; _i2 >= 0; _i2--) { - var one = buffer[_i2]; - result *= 0x100; + var nodeName = node.name; + var indexBasedFunctionName = nodeName.value; + var functionIndex = Number(indexBasedFunctionName.replace("func_", "")); + signature.params.forEach(function (param, paramIndex) { + var paramName = localNames.find(function (f) { + return f.localIndex === paramIndex && f.functionIndex === functionIndex; + }); - if (isLossyToAdd(result, one)) { - lossy = true; + if (paramName && paramName.name !== "") { + param.id = paramName.name; + } + }); + }) + }); +} + +function restoreModuleName(ast) { + t.traverse(ast, { + ModuleNameMetadata: function (_ModuleNameMetadata) { + function ModuleNameMetadata(_x6) { + return _ModuleNameMetadata.apply(this, arguments); } - result += one; - } - } + ModuleNameMetadata.toString = function () { + return _ModuleNameMetadata.toString(); + }; - return { - value: result, - lossy: lossy - }; -} -/** - * Writes a little-endian 64-bit signed int into a buffer. - */ + return ModuleNameMetadata; + }(function (moduleNameMetadataPath) { + // update module + t.traverse(ast, { + Module: function (_Module) { + function Module(_x7) { + return _Module.apply(this, arguments); + } + Module.toString = function () { + return _Module.toString(); + }; -function writeInt64(value, buffer) { - if (value < MIN_EXACT_INT64 || value > MAX_EXACT_INT64) { - throw new Error("Value out of range."); - } + return Module; + }(function (_ref7) { + var node = _ref7.node; + var name = moduleNameMetadataPath.node.value; // compatiblity with wast-parser - if (value < 0) { - value += BIT_64; - } + if (name === "") { + name = null; + } - writeUInt64(value, buffer); + node.id = name; + }) + }); + }) + }); } -/** - * Writes a little-endian 64-bit unsigned int into a buffer. - */ +function decode(buf, customOpts) { + var opts = Object.assign({}, defaultDecoderOpts, customOpts); + var ast = decoder.decode(buf, opts); -function writeUInt64(value, buffer) { - if (value < 0 || value > MAX_EXACT_UINT64) { - throw new Error("Value out of range."); + if (opts.ignoreCustomNameSection === false) { + restoreFunctionNames(ast); + restoreLocalNames(ast); + restoreModuleName(ast); } - var lowWord = value % BIT_32; - var highWord = Math.floor(value / BIT_32); - buffer.writeUInt32LE(lowWord, 0); - buffer.writeUInt32LE(highWord, 4); + return ast; } /***/ }), -/***/ 89943: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.decodeInt64 = decodeInt64; -exports.decodeUInt64 = decodeUInt64; -exports.decodeInt32 = decodeInt32; -exports.decodeUInt32 = decodeUInt32; -exports.encodeU32 = encodeU32; -exports.encodeI32 = encodeI32; -exports.encodeI64 = encodeI64; -exports.MAX_NUMBER_OF_BYTE_U64 = exports.MAX_NUMBER_OF_BYTE_U32 = void 0; - -var _leb = _interopRequireDefault(__webpack_require__(80881)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * According to https://webassembly.github.io/spec/core/binary/values.html#binary-int - * max = ceil(32/7) - */ -var MAX_NUMBER_OF_BYTE_U32 = 5; -/** - * According to https://webassembly.github.io/spec/core/binary/values.html#binary-int - * max = ceil(64/7) - */ +/***/ 77087: +/***/ (function(__unused_webpack_module, exports) { -exports.MAX_NUMBER_OF_BYTE_U32 = MAX_NUMBER_OF_BYTE_U32; -var MAX_NUMBER_OF_BYTE_U64 = 10; -exports.MAX_NUMBER_OF_BYTE_U64 = MAX_NUMBER_OF_BYTE_U64; +(function (global, factory) { + true ? factory(exports) : + 0; +}(this, function (exports) { 'use strict'; -function decodeInt64(encodedBuffer, index) { - return _leb.default.decodeInt64(encodedBuffer, index); -} + // Reserved word lists for various dialects of the language -function decodeUInt64(encodedBuffer, index) { - return _leb.default.decodeUInt64(encodedBuffer, index); -} + 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" + }; -function decodeInt32(encodedBuffer, index) { - return _leb.default.decodeInt32(encodedBuffer, index); -} + // And the keywords -function decodeUInt32(encodedBuffer, index) { - return _leb.default.decodeUInt32(encodedBuffer, index); -} + 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"; -function encodeU32(v) { - return _leb.default.encodeUInt32(v); -} + var keywords = { + 5: ecma5AndLessKeywords, + "5module": ecma5AndLessKeywords + " export import", + 6: ecma5AndLessKeywords + " const class extends export import super" + }; -function encodeI32(v) { - return _leb.default.encodeInt32(v); -} + var keywordRelationalOperator = /^in(stanceof)?$/; -function encodeI64(v) { - return _leb.default.encodeInt64(v); -} + // ## 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-\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\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\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\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-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7c6\ua7f7-\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-\uab67\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\u0b56\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\u0d82\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\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\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"; -/***/ 80881: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); -"use strict"; -// Copyright 2012 The Obvious Corporation. + nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; -/* - * leb: LEB128 utilities. - */ + // 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 -/* - * Modules used - */ + // 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,477,28,11,0,9,21,155,22,13,52,76,44,33,24,27,35,30,0,12,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,0,33,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,0,161,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,270,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,754,9486,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,42710,42,4148,12,221,3,5761,15,7472,3104,541]; + // 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,525,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,4,9,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,232,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,19723,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,792487,239]; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.default = void 0; + // 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 } + } + } -var _long = _interopRequireDefault(__webpack_require__(77960)); + // Test whether a given character code starts an identifier. -var bits = _interopRequireWildcard(__webpack_require__(62904)); + 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) + } -var bufs = _interopRequireWildcard(__webpack_require__(7276)); + // Test whether a given character is part of an identifier. -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 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) + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // ## Token types -/* - * Module variables - */ + // 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. -/** The minimum possible 32-bit signed int. */ -var MIN_INT32 = -0x80000000; -/** The maximum possible 32-bit signed int. */ + // All token type variables start with an underscore, to make them + // easy to recognize. -var MAX_INT32 = 0x7fffffff; -/** The maximum possible 32-bit unsigned int. */ + // 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 MAX_UINT32 = 0xffffffff; -/** The minimum possible 64-bit signed int. */ -// const MIN_INT64 = -0x8000000000000000; + var TokenType = function TokenType(label, conf) { + if ( conf === void 0 ) conf = {}; -/** - * The maximum possible 64-bit signed int that is representable as a - * JavaScript number. - */ -// const MAX_INT64 = 0x7ffffffffffffc00; + 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; + }; -/** - * The maximum possible 64-bit unsigned int that is representable as a - * JavaScript number. - */ -// const MAX_UINT64 = 0xfffffffffffff800; + function binop(name, prec) { + return new TokenType(name, {beforeExpr: true, binop: prec}) + } + var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; -/* - * Helper functions - */ + // Map keyword names to token types. -/** - * Determines the number of bits required to encode the number - * represented in the given buffer as a signed value. The buffer is - * taken to represent a signed number in little-endian form. - * - * The number of bits to encode is the (zero-based) bit number of the - * highest-order non-sign-matching bit, plus two. For example: - * - * 11111011 01110101 - * high low - * - * The sign bit here is 1 (that is, it's a negative number). The highest - * bit number that doesn't match the sign is bit #10 (where the lowest-order - * bit is bit #0). So, we have to encode at least 12 bits total. - * - * As a special degenerate case, the numbers 0 and -1 each require just one bit. - */ + var keywords$1 = {}; -function signedBitCount(buffer) { - return bits.highOrder(bits.getSign(buffer) ^ 1, buffer) + 2; -} -/** - * Determines the number of bits required to encode the number - * represented in the given buffer as an unsigned value. The buffer is - * taken to represent an unsigned number in little-endian form. - * - * The number of bits to encode is the (zero-based) bit number of the - * highest-order 1 bit, plus one. For example: - * - * 00011000 01010011 - * high low - * - * The highest-order 1 bit here is bit #12 (where the lowest-order bit - * is bit #0). So, we have to encode at least 13 bits total. - * - * As a special degenerate case, the number 0 requires 1 bit. - */ + // 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) + } -function unsignedBitCount(buffer) { - var result = bits.highOrder(1, buffer) + 1; - return result ? result : 1; -} -/** - * Common encoder for both signed and unsigned ints. This takes a - * bigint-ish buffer, returning an LEB128-encoded buffer. - */ + 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), + 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}), -function encodeBufferCommon(buffer, signed) { - var signBit; - var bitCount; + // 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. - if (signed) { - signBit = bits.getSign(buffer); - bitCount = signedBitCount(buffer); - } else { - signBit = 0; - bitCount = unsignedBitCount(buffer); - } + 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}), - var byteCount = Math.ceil(bitCount / 7); - var result = bufs.alloc(byteCount); + // 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}) + }; - for (var i = 0; i < byteCount; i++) { - var payload = bits.extract(buffer, i * 7, 7, signBit); - result[i] = payload | 0x80; - } // Mask off the top bit of the last byte, to indicate the end of the - // encoding. + // 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"); - result[byteCount - 1] &= 0x7f; - return result; -} -/** - * Gets the byte-length of the value encoded in the given buffer at - * the given index. - */ + function isNewLine(code, ecma2019String) { + return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) + } + var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; -function encodedLength(encodedBuffer, index) { - var result = 0; + var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; - while (encodedBuffer[index + result] >= 0x80) { - result++; - } + var ref = Object.prototype; + var hasOwnProperty = ref.hasOwnProperty; + var toString = ref.toString; - result++; // to account for the last byte + // Checks if an object has a property. - if (index + result > encodedBuffer.length) {// FIXME(sven): seems to cause false positives - // throw new Error("integer representation too long"); + function has(obj, propName) { + return hasOwnProperty.call(obj, propName) } - return result; -} -/** - * Common decoder for both signed and unsigned ints. This takes an - * LEB128-encoded buffer, returning a bigint-ish buffer. - */ + var isArray = Array.isArray || (function (obj) { return ( + toString.call(obj) === "[object Array]" + ); }); + function wordsRegexp(words) { + return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") + } -function decodeBufferCommon(encodedBuffer, index, signed) { - index = index === undefined ? 0 : index; - var length = encodedLength(encodedBuffer, index); - var bitLength = length * 7; - var byteLength = Math.ceil(bitLength / 8); - var result = bufs.alloc(byteLength); - var outIndex = 0; + // These are used when `options.locations` is on, for the + // `startLoc` and `endLoc` properties. - while (length > 0) { - bits.inject(result, outIndex, 7, encodedBuffer[index]); - outIndex += 7; - index++; - length--; - } + var Position = function Position(line, col) { + this.line = line; + this.column = col; + }; - var signBit; - var signByte; + Position.prototype.offset = function offset (n) { + return new Position(this.line, this.column + n) + }; - if (signed) { - // Sign-extend the last byte. - var lastByte = result[byteLength - 1]; - var endBit = outIndex % 8; + var SourceLocation = function SourceLocation(p, start, end) { + this.start = start; + this.end = end; + if (p.sourceFile !== null) { this.source = p.sourceFile; } + }; - if (endBit !== 0) { - var shift = 32 - endBit; // 32 because JS bit ops work on 32-bit ints. + // 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. - lastByte = result[byteLength - 1] = lastByte << shift >> shift & 0xff; + 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) + } } + } - signBit = lastByte >> 7; - signByte = signBit * 0xff; - } else { - signBit = 0; - signByte = 0; - } // Slice off any superfluous bytes, that is, ones that add no meaningful - // bits (because the value would be the same if they were removed). + // A second optional argument can be given to further configure + // the parser process. These options are recognized: + var defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must be + // either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10 + // (2019). This influences support for strict mode, the set of + // reserved words, and support for new syntax features. The default + // is 9. + ecmaVersion: 9, + // `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. + 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 + }; - while (byteLength > 1 && result[byteLength - 1] === signByte && (!signed || result[byteLength - 2] >> 7 === signBit)) { - byteLength--; - } + // Interpret and default an options object - result = bufs.resize(result, byteLength); - return { - value: result, - nextIndex: index - }; -} -/* - * Exported bindings - */ + function getOptions(opts) { + var options = {}; + for (var opt in defaultOptions) + { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } -function encodeIntBuffer(buffer) { - return encodeBufferCommon(buffer, true); -} + if (options.ecmaVersion >= 2015) + { options.ecmaVersion -= 2009; } -function decodeIntBuffer(encodedBuffer, index) { - return decodeBufferCommon(encodedBuffer, index, true); -} + if (options.allowReserved == null) + { options.allowReserved = options.ecmaVersion < 5; } -function encodeInt32(num) { - var buf = bufs.alloc(4); - buf.writeInt32LE(num, 0); - var result = encodeIntBuffer(buf); - bufs.free(buf); - return result; -} + 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); } -function decodeInt32(encodedBuffer, index) { - var result = decodeIntBuffer(encodedBuffer, index); - var parsed = bufs.readInt(result.value); - var value = parsed.value; - bufs.free(result.value); + return options + } - if (value < MIN_INT32 || value > MAX_INT32) { - throw new Error("integer too large"); + 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); + } } - return { - value: value, - nextIndex: result.nextIndex - }; -} + // 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 encodeInt64(num) { - var buf = bufs.alloc(8); - bufs.writeInt64(num, buf); - var result = encodeIntBuffer(buf); - bufs.free(buf); - return result; -} + function functionFlags(async, generator) { + return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) + } -function decodeInt64(encodedBuffer, index) { - var result = decodeIntBuffer(encodedBuffer, index); + // 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 value = _long.default.fromBytesLE(result.value, false); + 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) { + for (var v = options.ecmaVersion;; v--) + { if (reserved = reservedWords[v]) { break } } + 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); - bufs.free(result.value); - return { - value: value, - nextIndex: result.nextIndex, - lossy: false - }; -} + // 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; -function encodeUIntBuffer(buffer) { - return encodeBufferCommon(buffer, false); -} + // Set up token state -function decodeUIntBuffer(encodedBuffer, index) { - return decodeBufferCommon(encodedBuffer, index, false); -} + // 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(); -function encodeUInt32(num) { - var buf = bufs.alloc(4); - buf.writeUInt32LE(num, 0); - var result = encodeUIntBuffer(buf); - bufs.free(buf); - return result; -} + // Position information for the previous token + this.lastTokEndLoc = this.lastTokStartLoc = null; + this.lastTokStart = this.lastTokEnd = this.pos; -function decodeUInt32(encodedBuffer, index) { - var result = decodeUIntBuffer(encodedBuffer, index); - var parsed = bufs.readUInt(result.value); - var value = parsed.value; - bufs.free(result.value); + // 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; - if (value > MAX_UINT32) { - throw new Error("integer too large"); - } + // Figure out if it's a module code. + this.inModule = options.sourceType === "module"; + this.strict = this.inModule || this.strictDirective(this.pos); - return { - value: value, - nextIndex: result.nextIndex - }; -} + // Used to signify the start of a potential arrow function + this.potentialArrowAt = -1; -function encodeUInt64(num) { - var buf = bufs.alloc(8); - bufs.writeUInt64(num, buf); - var result = encodeUIntBuffer(buf); - bufs.free(buf); - return result; -} + // 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 = {}; -function decodeUInt64(encodedBuffer, index) { - var result = decodeUIntBuffer(encodedBuffer, index); + // If enabled, skip leading hashbang line. + if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") + { this.skipLineComment(2); } - var value = _long.default.fromBytesLE(result.value, true); + // Scope tracking for duplicate variable names (see scope.js) + this.scopeStack = []; + this.enterScope(SCOPE_TOP); - bufs.free(result.value); - return { - value: value, - nextIndex: result.nextIndex, - lossy: false + // For RegExp validation + this.regexpState = null; }; -} - -var _default = { - decodeInt32: decodeInt32, - decodeInt64: decodeInt64, - decodeIntBuffer: decodeIntBuffer, - decodeUInt32: decodeUInt32, - decodeUInt64: decodeUInt64, - decodeUIntBuffer: decodeUIntBuffer, - encodeInt32: encodeInt32, - encodeInt64: encodeInt64, - encodeIntBuffer: encodeIntBuffer, - encodeUInt32: encodeUInt32, - encodeUInt64: encodeUInt64, - encodeUIntBuffer: encodeUIntBuffer -}; -exports.default = _default; - -/***/ }), -/***/ 19418: -/***/ (function(__unused_webpack_module, exports) { + var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } }; -"use strict"; + 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()) }; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.decode = decode; + // Switch to a getter for 7.0.0. + Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }; -function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + Parser.extend = function extend () { + var plugins = [], len = arguments.length; + while ( len-- ) plugins[ len ] = arguments[ len ]; -function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } + var cls = this; + for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } + return cls + }; -function con(b) { - if ((b & 0xc0) === 0x80) { - return b & 0x3f; - } else { - throw new Error("invalid UTF-8 encoding"); - } -} + Parser.parse = function parse (input, options) { + return new this(options, input).parse() + }; -function code(min, n) { - if (n < min || 0xd800 <= n && n < 0xe000 || n >= 0x10000) { - throw new Error("invalid UTF-8 encoding"); - } else { - return n; - } -} + Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { + var parser = new this(options, input, pos); + parser.nextToken(); + return parser.parseExpression() + }; -function decode(bytes) { - return _decode(bytes).map(function (x) { - return String.fromCharCode(x); - }).join(""); -} + Parser.tokenizer = function tokenizer (input, options) { + return new this(options, input) + }; -function _decode(bytes) { - if (bytes.length === 0) { - return []; - } - /** - * 1 byte - */ + Object.defineProperties( Parser.prototype, prototypeAccessors ); + var pp = Parser.prototype; - { - var _bytes = _toArray(bytes), - b1 = _bytes[0], - bs = _bytes.slice(1); + // ## Parser utilities - if (b1 < 0x80) { - return [code(0x0, b1)].concat(_toConsumableArray(_decode(bs))); - } + 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") { return true } + start += match[0].length; - if (b1 < 0xc0) { - throw new Error("invalid UTF-8 encoding"); + // Skip semicolon, if any. + skipWhiteSpace.lastIndex = start; + start += skipWhiteSpace.exec(this.input)[0].length; + if (this.input[start] === ";") + { start++; } } - } - /** - * 2 bytes - */ + }; - { - var _bytes2 = _toArray(bytes), - _b = _bytes2[0], - b2 = _bytes2[1], - _bs = _bytes2.slice(2); + // Predicate that tests whether the next token is of the given + // type, and if yes, consumes it as a side effect. - if (_b < 0xe0) { - return [code(0x80, ((_b & 0x1f) << 6) + con(b2))].concat(_toConsumableArray(_decode(_bs))); + pp.eat = function(type) { + if (this.type === type) { + this.next(); + return true + } else { + return false } - } - /** - * 3 bytes - */ + }; - { - var _bytes3 = _toArray(bytes), - _b2 = _bytes3[0], - _b3 = _bytes3[1], - b3 = _bytes3[2], - _bs2 = _bytes3.slice(3); + // Tests whether parsed token is a contextual keyword. - if (_b2 < 0xf0) { - return [code(0x800, ((_b2 & 0x0f) << 12) + (con(_b3) << 6) + con(b3))].concat(_toConsumableArray(_decode(_bs2))); - } - } - /** - * 4 bytes - */ + pp.isContextual = function(name) { + return this.type === types.name && this.value === name && !this.containsEsc + }; - { - var _bytes4 = _toArray(bytes), - _b4 = _bytes4[0], - _b5 = _bytes4[1], - _b6 = _bytes4[2], - b4 = _bytes4[3], - _bs3 = _bytes4.slice(4); + // Consumes contextual keyword if possible. - if (_b4 < 0xf8) { - return [code(0x10000, (((_b4 & 0x07) << 18) + con(_b5) << 12) + (con(_b6) << 6) + con(b4))].concat(_toConsumableArray(_decode(_bs3))); - } - } - throw new Error("invalid UTF-8 encoding"); -} + pp.eatContextual = function(name) { + if (!this.isContextual(name)) { return false } + this.next(); + return true + }; -/***/ }), + // Asserts that following token is given contextual keyword. -/***/ 43882: -/***/ (function(__unused_webpack_module, exports) { + pp.expectContextual = function(name) { + if (!this.eatContextual(name)) { this.unexpected(); } + }; -"use strict"; + // 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)) + }; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.encode = encode; + pp.insertSemicolon = function() { + if (this.canInsertSemicolon()) { + if (this.options.onInsertedSemicolon) + { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } + return true + } + }; -function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + // Consume a semicolon, or, failing that, see if we are allowed to + // pretend that there is a semicolon at this position. -function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } + pp.semicolon = function() { + if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } + }; -function con(n) { - return 0x80 | n & 0x3f; -} + 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 + } + }; -function encode(str) { - var arr = str.split("").map(function (x) { - return x.charCodeAt(0); - }); - return _encode(arr); -} + // Expect a token of a given type. If found, consume it, otherwise, + // raise an unexpected token error. -function _encode(arr) { - if (arr.length === 0) { - return []; - } + pp.expect = function(type) { + this.eat(type) || this.unexpected(); + }; - var _arr = _toArray(arr), - n = _arr[0], - ns = _arr.slice(1); + // Raise an unexpected token error. - if (n < 0) { - throw new Error("utf8"); - } + pp.unexpected = function(pos) { + this.raise(pos != null ? pos : this.start, "Unexpected token"); + }; - if (n < 0x80) { - return [n].concat(_toConsumableArray(_encode(ns))); + function DestructuringErrors() { + this.shorthandAssign = + this.trailingComma = + this.parenthesizedAssign = + this.parenthesizedBind = + this.doubleProto = + -1; } - if (n < 0x800) { - return [0xc0 | n >>> 6, con(n)].concat(_toConsumableArray(_encode(ns))); - } + 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"); } + }; - if (n < 0x10000) { - return [0xe0 | n >>> 12, con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); - } + 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"); } + }; - if (n < 0x110000) { - return [0xf0 | n >>> 18, con(n >>> 12), con(n >>> 6), con(n)].concat(_toConsumableArray(_encode(ns))); - } + 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"); } + }; - throw new Error("utf8"); -} + 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; -/***/ 81637: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // ### Statement parsing -"use strict"; + // 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 = {}; + 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]; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "decode", ({ - enumerable: true, - get: function get() { - return _decoder.decode; - } -})); -Object.defineProperty(exports, "encode", ({ - enumerable: true, - get: function get() { - return _encoder.encode; - } -})); + 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 _decoder = __webpack_require__(19418); + var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; -var _encoder = __webpack_require__(43882); + 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 + }; -/***/ 28458: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + // 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 } -"use strict"; + 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. -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.decode = decode; + pp$1.parseStatement = function(context, topLevel, exports) { + var starttype = this.type, node = this.startNode(), kind; -var _helperApiError = __webpack_require__(20193); + if (this.isLet(context)) { + starttype = types._var; + kind = "let"; + } -var ieee754 = _interopRequireWildcard(__webpack_require__(57732)); + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. -var utf8 = _interopRequireWildcard(__webpack_require__(81637)); + 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) // '(' + { return this.parseExpressionStatement(node, this.parseExpression()) } + } -var t = _interopRequireWildcard(__webpack_require__(81875)); + 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) -var _leb = __webpack_require__(89943); + // 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 _helperWasmBytecode = _interopRequireDefault(__webpack_require__(66921)); + 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) } + } + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + 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(); + } -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; } } + // 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") + }; -function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + pp$1.parseDebuggerStatement = function(node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement") + }; -function toHex(n) { - return "0x" + Number(n).toString(16); -} + 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") + }; -function byteArrayEq(l, r) { - if (l.length !== r.length) { - return false; - } + // 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. - for (var i = 0; i < l.length; i++) { - if (l[i] !== r[i]) { - return false; + 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.checkLVal(init); + return this.parseForIn(node, init) + } else { + this.checkExpressionErrors(refDestructuringErrors, true); + } + if (awaitAt > -1) { this.unexpected(awaitAt); } + return this.parseFor(node, init) + }; - return true; -} + pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { + this.next(); + return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) + }; -function decode(ab, opts) { - var buf = new Uint8Array(ab); - var getUniqueName = t.getUniqueNameGenerator(); - var offset = 0; + 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") + }; - function getPosition() { - return { - line: -1, - column: offset - }; - } + pp$1.parseReturnStatement = function(node) { + if (!this.inFunction && !this.options.allowReturnOutsideFunction) + { this.raise(this.start, "'return' outside of function"); } + this.next(); - function dump(b, msg) { - if (opts.dump === false) return; - var pad = "\t\t\t\t\t\t\t\t\t\t"; - var str = ""; + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. - if (b.length < 5) { - str = b.map(toHex).join(" "); - } else { - str = "..."; - } + if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } + else { node.argument = this.parseExpression(); this.semicolon(); } + return this.finishNode(node, "ReturnStatement") + }; - console.log(toHex(offset) + ":\t", str, pad, ";", msg); - } + pp$1.parseSwitchStatement = function(node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(types.braceL); + this.labels.push(switchLabel); + this.enterScope(0); - function dumpSep(msg) { - if (opts.dump === false) return; - console.log(";", msg); - } - /** - * TODO(sven): we can atually use a same structure - * we are adding incrementally new features - */ + // 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") + }; - var state = { - elementsInFuncSection: [], - elementsInExportSection: [], - elementsInCodeSection: [], + 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") + }; - /** - * Decode memory from: - * - Memory section - */ - memoriesInModule: [], + // Reused empty array added for node fields that are always empty. - /** - * Decoded types from: - * - Type section - */ - typesInModule: [], + var empty = []; - /** - * Decoded functions from: - * - Function section - * - Import section - */ - functionsInModule: [], + 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.checkLVal(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") + }; - /** - * Decoded tables from: - * - Table section - */ - tablesInModule: [], + pp$1.parseVarStatement = function(node, kind) { + this.next(); + this.parseVar(node, false, kind); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration") + }; - /** - * Decoded globals from: - * - Global section - */ - globalsInModule: [] + 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") }; - function isEOF() { - return offset >= buf.length; - } + 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") + }; - function eatBytes(n) { - offset = offset + n; - } + pp$1.parseEmptyStatement = function(node) { + this.next(); + return this.finishNode(node, "EmptyStatement") + }; - function readBytesAtOffset(_offset, numberOfBytes) { - var arr = []; + 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]; - for (var i = 0; i < numberOfBytes; i++) { - arr.push(buf[_offset + i]); + 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") + }; - return arr; - } + pp$1.parseExpressionStatement = function(node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement") + }; - function readBytes(numberOfBytes) { - return readBytesAtOffset(offset, numberOfBytes); - } + // Parse a semicolon-enclosed block of statements, handling `"use + // strict"` declarations when `allowStrict` is true (used for + // function bodies). - function readF64() { - var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F64); - var value = ieee754.decodeF64(bytes); + pp$1.parseBlock = function(createNewLexicalScope, node) { + if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; + if ( node === void 0 ) node = this.startNode(); - if (Math.sign(value) * value === Infinity) { - return { - value: Math.sign(value), - inf: true, - nextIndex: ieee754.NUMBER_OF_BYTE_F64 - }; + node.body = []; + this.expect(types.braceL); + if (createNewLexicalScope) { this.enterScope(0); } + while (!this.eat(types.braceR)) { + var stmt = this.parseStatement(null); + node.body.push(stmt); } + if (createNewLexicalScope) { this.exitScope(); } + return this.finishNode(node, "BlockStatement") + }; - if (isNaN(value)) { - var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1; - var mantissa = 0; - - for (var i = 0; i < bytes.length - 2; ++i) { - mantissa += bytes[i] * Math.pow(256, i); - } + // Parse a regular `for` loop. The disambiguation code in + // `parseStatement` will already have parsed the init statement or + // expression. - mantissa += bytes[bytes.length - 2] % 16 * Math.pow(256, bytes.length - 2); - return { - value: sign * mantissa, - nan: true, - nextIndex: ieee754.NUMBER_OF_BYTE_F64 - }; - } + 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") + }; - return { - value: value, - nextIndex: ieee754.NUMBER_OF_BYTE_F64 - }; - } + // Parse a `for`/`in` and `for`/`of` loop, which are almost + // same from parser's perspective. - function readF32() { - var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F32); - var value = ieee754.decodeF32(bytes); + pp$1.parseForIn = function(node, init) { + var isForIn = this.type === types._in; + this.next(); - if (Math.sign(value) * value === Infinity) { - return { - value: Math.sign(value), - inf: true, - nextIndex: ieee754.NUMBER_OF_BYTE_F32 - }; + 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") + ); + } else if (init.type === "AssignmentPattern") { + this.raise(init.start, "Invalid left-hand side in for-loop"); } + 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") + }; - if (isNaN(value)) { - var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1; - var mantissa = 0; + // Parse a list of variable declarations. - for (var i = 0; i < bytes.length - 2; ++i) { - mantissa += bytes[i] * Math.pow(256, i); + 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; } - - mantissa += bytes[bytes.length - 2] % 128 * Math.pow(256, bytes.length - 2); - return { - value: sign * mantissa, - nan: true, - nextIndex: ieee754.NUMBER_OF_BYTE_F32 - }; + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(types.comma)) { break } } + return node + }; - return { - value: value, - nextIndex: ieee754.NUMBER_OF_BYTE_F32 - }; - } - - function readUTF8String() { - var lenu32 = readU32(); // Don't eat any bytes. Instead, peek ahead of the current offset using - // readBytesAtOffset below. This keeps readUTF8String neutral with respect - // to the current offset, just like the other readX functions. + pp$1.parseVarId = function(decl, kind) { + decl.id = this.parseBindingAtom(); + this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); + }; - var strlen = lenu32.value; - dump([strlen], "string length"); - var bytes = readBytesAtOffset(offset + lenu32.nextIndex, strlen); - var value = utf8.decode(bytes); - return { - value: value, - nextIndex: strlen + lenu32.nextIndex - }; - } - /** - * Decode an unsigned 32bits integer - * - * The length will be handled by the leb librairy, we pass the max number of - * byte. - */ + var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; + // Parse a function declaration or literal (depending on the + // `statement & FUNC_STATEMENT`). - function readU32() { - var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32); - var buffer = Buffer.from(bytes); - return (0, _leb.decodeUInt32)(buffer); - } + // 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; } - function readVaruint32() { - // where 32 bits = max 4 bytes - var bytes = readBytes(4); - var buffer = Buffer.from(bytes); - return (0, _leb.decodeUInt32)(buffer); - } + 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.checkLVal(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } + } - function readVaruint7() { - // where 7 bits = max 1 bytes - var bytes = readBytes(1); - var buffer = Buffer.from(bytes); - return (0, _leb.decodeUInt32)(buffer); - } - /** - * Decode a signed 32bits interger - */ + 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; } - function read32() { - var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32); - var buffer = Buffer.from(bytes); - return (0, _leb.decodeInt32)(buffer); - } - /** - * Decode a signed 64bits integer - */ + 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") + }; - function read64() { - var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); - var buffer = Buffer.from(bytes); - return (0, _leb.decodeInt64)(buffer); - } + pp$1.parseFunctionParams = function(node) { + this.expect(types.parenL); + node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + }; - function readU64() { - var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64); - var buffer = Buffer.from(bytes); - return (0, _leb.decodeUInt64)(buffer); - } + // Parse a class declaration or literal (depending on the + // `isStatement` parameter). - function readByte() { - return readBytes(1)[0]; - } + pp$1.parseClass = function(node, isStatement) { + this.next(); - function parseModuleHeader() { - if (isEOF() === true || offset + 4 > buf.length) { - throw new Error("unexpected end"); + // 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.eat(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; + } + } } + node.body = this.finishNode(classBody, "ClassBody"); + this.strict = oldStrict; + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") + }; - var header = readBytes(4); + pp$1.parseClassElement = function(constructorAllowsSuper) { + var this$1 = this; - if (byteArrayEq(_helperWasmBytecode.default.magicModuleHeader, header) === false) { - throw new _helperApiError.CompileError("magic header not detected"); - } + if (this.eat(types.semi)) { return null } - dump(header, "wasm magic header"); - eatBytes(4); - } + var method = this.startNode(); + var tryContextual = function (k, noLineBreak) { + if ( noLineBreak === void 0 ) noLineBreak = false; - function parseVersion() { - if (isEOF() === true || offset + 4 > buf.length) { - throw new Error("unexpected end"); + 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 + }; - var version = readBytes(4); + pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { + method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); + return this.finishNode(method, "MethodDefinition") + }; - if (byteArrayEq(_helperWasmBytecode.default.moduleVersion, version) === false) { - throw new _helperApiError.CompileError("unknown binary version"); + pp$1.parseClassId = function(node, isStatement) { + if (this.type === types.name) { + node.id = this.parseIdent(); + if (isStatement) + { this.checkLVal(node.id, BIND_LEXICAL, false); } + } else { + if (isStatement === true) + { this.unexpected(); } + node.id = null; } + }; - dump(version, "wasm version"); - eatBytes(4); - } + pp$1.parseClassSuper = function(node) { + node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; + }; - function parseVec(cast) { - var u32 = readU32(); - var length = u32.value; - eatBytes(u32.nextIndex); - dump([length], "number"); + // Parses module export declaration. - if (length === 0) { - return []; + pp$1.parseExport = function(node, exports) { + this.next(); + // export * from '...' + if (this.eat(types.star)) { + 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]; - var elements = []; - - for (var i = 0; i < length; i++) { - var byte = readByte(); - eatBytes(1); - var value = cast(byte); - dump([byte], value); + this.checkUnreserved(spec.local); + // check if export is defined + this.checkLocalExport(spec.local); + } - if (typeof value === "undefined") { - throw new _helperApiError.CompileError("Internal failure: parseVec could not cast the value"); + node.source = null; } - - elements.push(value); + this.semicolon(); } + return this.finishNode(node, "ExportNamedDeclaration") + }; - return elements; - } // Type section - // https://webassembly.github.io/spec/binary/modules.html#binary-typesec + 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]; - function parseTypeSection(numberOfTypes) { - var typeInstructionNodes = []; - dump([numberOfTypes], "num types"); + 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]; - for (var i = 0; i < numberOfTypes; i++) { - var _startLoc = getPosition(); + 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); } + }; - dumpSep("type " + i); - var type = readByte(); - eatBytes(1); + pp$1.checkVariableExport = function(exports, decls) { + if (!exports) { return } + for (var i = 0, list = decls; i < list.length; i += 1) + { + var decl = list[i]; - if (type == _helperWasmBytecode.default.types.func) { - dump([type], "func"); - var paramValtypes = parseVec(function (b) { - return _helperWasmBytecode.default.valtypes[b]; - }); - var params = paramValtypes.map(function (v) { - return t.funcParam( - /*valtype*/ - v); - }); - var result = parseVec(function (b) { - return _helperWasmBytecode.default.valtypes[b]; - }); - typeInstructionNodes.push(function () { - var endLoc = getPosition(); - return t.withLoc(t.typeInstruction(undefined, t.signature(params, result)), endLoc, _startLoc); - }()); - state.typesInModule.push({ - params: params, - result: result - }); - } else { - throw new Error("Unsupported type: " + toHex(type)); - } + this.checkPatternExport(exports, decl.id); } + }; - return typeInstructionNodes; - } // Import section - // https://webassembly.github.io/spec/binary/modules.html#binary-importsec - + 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() + }; - function parseImportSection(numberOfImports) { - var imports = []; + // Parses a comma-separated list of module exports. - for (var i = 0; i < numberOfImports; i++) { - dumpSep("import header " + i); + 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 _startLoc2 = getPosition(); - /** - * Module name - */ + 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. - var moduleName = readUTF8String(); - eatBytes(moduleName.nextIndex); - dump([], "module name (".concat(moduleName.value, ")")); - /** - * Name - */ + 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") + }; - var name = readUTF8String(); - eatBytes(name.nextIndex); - dump([], "name (".concat(name.value, ")")); - /** - * Import descr - */ + // Parses a comma-separated list of module imports. - var descrTypeByte = readByte(); - eatBytes(1); - var descrType = _helperWasmBytecode.default.importTypes[descrTypeByte]; - dump([descrTypeByte], "import kind"); + 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.checkLVal(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.checkLVal(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; } - if (typeof descrType === "undefined") { - throw new _helperApiError.CompileError("Unknown import description type: " + toHex(descrTypeByte)); + 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.checkLVal(node$2.local, BIND_LEXICAL); + nodes.push(this.finishNode(node$2, "ImportSpecifier")); + } + return nodes + }; - var importDescr = void 0; + // 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] === "'") + ) + }; - if (descrType === "func") { - var indexU32 = readU32(); - var typeindex = indexU32.value; - eatBytes(indexU32.nextIndex); - dump([typeindex], "type index"); - var signature = state.typesInModule[typeindex]; + var pp$2 = Parser.prototype; - if (typeof signature === "undefined") { - throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")")); - } + // Convert existing expression atom to assignable pattern + // if possible. - var id = getUniqueName("func"); - importDescr = t.funcImportDescr(id, t.signature(signature.params, signature.result)); - state.functionsInModule.push({ - id: t.identifier(name.value), - signature: signature, - isExternal: true - }); - } else if (descrType === "global") { - importDescr = parseGlobalType(); - var globalNode = t.global(importDescr, []); - state.globalsInModule.push(globalNode); - } else if (descrType === "table") { - importDescr = parseTableType(i); - } else if (descrType === "mem") { - var memoryNode = parseMemoryType(0); - state.memoriesInModule.push(memoryNode); - importDescr = memoryNode; - } else { - throw new _helperApiError.CompileError("Unsupported import of type: " + descrType); - } + 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 - imports.push(function () { - var endLoc = getPosition(); - return t.withLoc(t.moduleImport(moduleName.value, name.value, importDescr), endLoc, _startLoc2); - }()); - } + case "ObjectPattern": + case "ArrayPattern": + case "RestElement": + break - return imports; - } // Function section - // https://webassembly.github.io/spec/binary/modules.html#function-section + 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 - function parseFuncSection(numberOfFunctions) { - dump([numberOfFunctions], "num funcs"); + 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 - for (var i = 0; i < numberOfFunctions; i++) { - var indexU32 = readU32(); - var typeindex = indexU32.value; - eatBytes(indexU32.nextIndex); - dump([typeindex], "type index"); - var signature = state.typesInModule[typeindex]; + case "ArrayExpression": + node.type = "ArrayPattern"; + if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } + this.toAssignableList(node.elements, isBinding); + break - if (typeof signature === "undefined") { - throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")")); - } // preserve anonymous, a name might be resolved later + 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); + // falls through to AssignmentPattern - var id = t.withRaw(t.identifier(getUniqueName("func")), ""); - state.functionsInModule.push({ - id: id, - signature: signature, - isExternal: false - }); - } - } // Export section - // https://webassembly.github.io/spec/binary/modules.html#export-section + case "AssignmentPattern": + break + case "ParenthesizedExpression": + this.toAssignable(node.expression, isBinding, refDestructuringErrors); + break - function parseExportSection(numberOfExport) { - dump([numberOfExport], "num exports"); // Parse vector of exports + case "MemberExpression": + if (!isBinding) { break } - for (var i = 0; i < numberOfExport; i++) { - var _startLoc3 = getPosition(); - /** - * Name - */ + 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. - var name = readUTF8String(); - eatBytes(name.nextIndex); - dump([], "export name (".concat(name.value, ")")); - /** - * exportdescr - */ + 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 + }; - var typeIndex = readByte(); - eatBytes(1); - dump([typeIndex], "export kind"); - var indexu32 = readU32(); - var index = indexu32.value; - eatBytes(indexu32.nextIndex); - dump([index], "export index"); - var id = void 0, - signature = void 0; + // Parses spread element. - if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Func") { - var func = state.functionsInModule[index]; + pp$2.parseSpread = function(refDestructuringErrors) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refDestructuringErrors); + return this.finishNode(node, "SpreadElement") + }; - if (typeof func === "undefined") { - throw new _helperApiError.CompileError("unknown function (".concat(index, ")")); - } + pp$2.parseRestBinding = function() { + var node = this.startNode(); + this.next(); - id = t.numberLiteralFromRaw(index, String(index)); - signature = func.signature; - } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Table") { - var table = state.tablesInModule[index]; + // RestElement inside of a function parameter must be an identifier + if (this.options.ecmaVersion === 6 && this.type !== types.name) + { this.unexpected(); } - if (typeof table === "undefined") { - throw new _helperApiError.CompileError("unknown table ".concat(index)); - } + node.argument = this.parseBindingAtom(); - id = t.numberLiteralFromRaw(index, String(index)); - signature = null; - } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Mem") { - var memNode = state.memoriesInModule[index]; + return this.finishNode(node, "RestElement") + }; - if (typeof memNode === "undefined") { - throw new _helperApiError.CompileError("unknown memory ".concat(index)); - } + // Parses lvalue (assignable) atom. - id = t.numberLiteralFromRaw(index, String(index)); - signature = null; - } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Global") { - var global = state.globalsInModule[index]; + 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") - if (typeof global === "undefined") { - throw new _helperApiError.CompileError("unknown global ".concat(index)); - } + case types.braceL: + return this.parseObj(true) + } + } + return this.parseIdent() + }; - id = t.numberLiteralFromRaw(index, String(index)); - signature = null; + 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 { - console.warn("Unsupported export type: " + toHex(typeIndex)); - return; + var elem = this.parseMaybeDefault(this.start, this.startLoc); + this.parseBindingListItem(elem); + elts.push(elem); } - - var endLoc = getPosition(); - state.elementsInExportSection.push({ - name: name.value, - type: _helperWasmBytecode.default.exportTypes[typeIndex], - signature: signature, - id: id, - index: index, - endLoc: endLoc, - startLoc: _startLoc3 - }); } - } // Code section - // https://webassembly.github.io/spec/binary/modules.html#code-section + return elts + }; + pp$2.parseBindingListItem = function(param) { + return param + }; - function parseCodeSection(numberOfFuncs) { - dump([numberOfFuncs], "number functions"); // Parse vector of function + // Parses assignment pattern around given atom if possible. - for (var i = 0; i < numberOfFuncs; i++) { - var _startLoc4 = getPosition(); + 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") + }; - dumpSep("function body " + i); // the u32 size of the function code in bytes - // Ignore it for now + // Verify that a node is an lval — something that can be assigned + // to. + // bindingType can be either: + // 'var' indicating that the lval creates a 'var' binding + // 'let' indicating that the lval creates a lexical ('let' or 'const') binding + // 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references - var bodySizeU32 = readU32(); - eatBytes(bodySizeU32.nextIndex); - dump([bodySizeU32.value], "function body size"); - var code = []; - /** - * Parse locals - */ + pp$2.checkLVal = function(expr, bindingType, checkClashes) { + if ( bindingType === void 0 ) bindingType = BIND_NONE; - var funcLocalNumU32 = readU32(); - var funcLocalNum = funcLocalNumU32.value; - eatBytes(funcLocalNumU32.nextIndex); - dump([funcLocalNum], "num locals"); - var locals = []; + switch (expr.type) { + case "Identifier": + if (bindingType === BIND_LEXICAL && expr.name === "let") + { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } + if (this.strict && this.reservedWordsStrictBind.test(expr.name)) + { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } + if (checkClashes) { + if (has(checkClashes, expr.name)) + { this.raiseRecoverable(expr.start, "Argument name clash"); } + checkClashes[expr.name] = true; + } + if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } + break - for (var _i = 0; _i < funcLocalNum; _i++) { - var _startLoc5 = getPosition(); + case "MemberExpression": + if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); } + break - var localCountU32 = readU32(); - var localCount = localCountU32.value; - eatBytes(localCountU32.nextIndex); - dump([localCount], "num local"); - var valtypeByte = readByte(); - eatBytes(1); - var type = _helperWasmBytecode.default.valtypes[valtypeByte]; - var args = []; + case "ObjectPattern": + for (var i = 0, list = expr.properties; i < list.length; i += 1) + { + var prop = list[i]; - for (var _i2 = 0; _i2 < localCount; _i2++) { - args.push(t.valtypeLiteral(type)); - } + this.checkLVal(prop, bindingType, checkClashes); + } + break - var localNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.instruction("local", args), endLoc, _startLoc5); - }(); + case "Property": + // AssignmentProperty has type === "Property" + this.checkLVal(expr.value, bindingType, checkClashes); + break - locals.push(localNode); - dump([valtypeByte], type); + 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 (typeof type === "undefined") { - throw new _helperApiError.CompileError("Unexpected valtype: " + toHex(valtypeByte)); - } + if (elem) { this.checkLVal(elem, bindingType, checkClashes); } } + break - code.push.apply(code, locals); // Decode instructions until the end + case "AssignmentPattern": + this.checkLVal(expr.left, bindingType, checkClashes); + break - parseInstructionBlock(code); - var endLoc = getPosition(); - state.elementsInCodeSection.push({ - code: code, - locals: locals, - endLoc: endLoc, - startLoc: _startLoc4, - bodySize: bodySizeU32.value - }); - } - } + case "RestElement": + this.checkLVal(expr.argument, bindingType, checkClashes); + break - function parseInstructionBlock(code) { - while (true) { - var _startLoc6 = getPosition(); + case "ParenthesizedExpression": + this.checkLVal(expr.expression, bindingType, checkClashes); + break - var instructionAlreadyCreated = false; - var instructionByte = readByte(); - eatBytes(1); + default: + this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue"); + } + }; - if (instructionByte === 0xfe) { - throw new _helperApiError.CompileError("Atomic instructions are not implemented"); - } + // A recursive descent parser operates by defining functions for all - var instruction = _helperWasmBytecode.default.symbolsByByte[instructionByte]; + var pp$3 = Parser.prototype; - if (typeof instruction === "undefined") { - throw new _helperApiError.CompileError("Unexpected instruction: " + toHex(instructionByte)); - } + // 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. - if (typeof instruction.object === "string") { - dump([instructionByte], "".concat(instruction.object, ".").concat(instruction.name)); - } else { - dump([instructionByte], instruction.name); + 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 && 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; } - /** - * End of the function - */ - - - if (instruction.name === "end") { - var node = function () { - var endLoc = getPosition(); - return t.withLoc(t.instruction(instruction.name), endLoc, _startLoc6); - }(); - - code.push(node); - break; + 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; + }; - var args = []; + // ### Expression parsing - if (instruction.name === "loop") { - var _startLoc7 = getPosition(); + // 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. - var blocktypeByte = readByte(); - eatBytes(1); - var blocktype = _helperWasmBytecode.default.blockTypes[blocktypeByte]; - dump([blocktypeByte], "blocktype"); + // 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). - if (typeof blocktype === "undefined") { - throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(blocktypeByte)); - } + 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 + }; - var instr = []; - parseInstructionBlock(instr); // preserve anonymous + // Parse an assignment expression. This includes applications of + // operators like `+=`. - var label = t.withRaw(t.identifier(getUniqueName("loop")), ""); + 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 loopNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.loopInstruction(label, blocktype, instr), endLoc, _startLoc7); - }(); + var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldShorthandAssign = -1; + if (refDestructuringErrors) { + oldParenAssign = refDestructuringErrors.parenthesizedAssign; + oldTrailingComma = refDestructuringErrors.trailingComma; + oldShorthandAssign = refDestructuringErrors.shorthandAssign; + refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.shorthandAssign = -1; + } else { + refDestructuringErrors = new DestructuringErrors; + ownDestructuringErrors = true; + } - code.push(loopNode); - instructionAlreadyCreated = true; - } else if (instruction.name === "if") { - var _startLoc8 = getPosition(); + 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; + node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left; + if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); } + refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly + this.checkLVal(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; } + if (oldShorthandAssign > -1) { refDestructuringErrors.shorthandAssign = oldShorthandAssign; } + return left + }; - var _blocktypeByte = readByte(); + // Parse a ternary conditional (`?:`) operator. - eatBytes(1); - var _blocktype = _helperWasmBytecode.default.blockTypes[_blocktypeByte]; - dump([_blocktypeByte], "blocktype"); + 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 + }; - if (typeof _blocktype === "undefined") { - throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte)); - } + // Start the precedence parser. - var testIndex = t.withRaw(t.identifier(getUniqueName("if")), ""); - var ifBody = []; - parseInstructionBlock(ifBody); // Defaults to no alternate + 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) + }; - var elseIndex = 0; + // 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. - for (elseIndex = 0; elseIndex < ifBody.length; ++elseIndex) { - var _instr = ifBody[elseIndex]; + 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 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); + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) + } + } + return left + }; - if (_instr.type === "Instr" && _instr.id === "else") { - break; - } - } + 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") + }; - var consequentInstr = ifBody.slice(0, elseIndex); - var alternate = ifBody.slice(elseIndex + 1); // wast sugar + // Parse unary operators, both prefix and postfix. - var testInstrs = []; + 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.checkLVal(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.checkLVal(expr); + this.next(); + expr = this.finishNode(node$1, "UpdateExpression"); + } + } - var ifNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.ifInstruction(testIndex, testInstrs, _blocktype, consequentInstr, alternate), endLoc, _startLoc8); - }(); + if (!sawUnary && this.eat(types.starstar)) + { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } + else + { return expr } + }; - code.push(ifNode); - instructionAlreadyCreated = true; - } else if (instruction.name === "block") { - var _startLoc9 = getPosition(); + // Parse call, dot, and `[]`-subscript expressions. - var _blocktypeByte2 = readByte(); + pp$3.parseExprSubscripts = function(refDestructuringErrors) { + var startPos = this.start, startLoc = this.startLoc; + var expr = this.parseExprAtom(refDestructuringErrors); + var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"; + if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { 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; } + } + return result + }; - eatBytes(1); - var _blocktype2 = _helperWasmBytecode.default.blockTypes[_blocktypeByte2]; - dump([_blocktypeByte2], "blocktype"); + 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() && this.input.slice(base.start, base.end) === "async"; + while (true) { + var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow); + if (element === base || element.type === "ArrowFunctionExpression") { return element } + base = element; + } + }; - if (typeof _blocktype2 === "undefined") { - throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte2)); + pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow) { + var computed = this.eat(types.bracketL); + if (computed || 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); } + 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 && base.type !== "Import", false, refDestructuringErrors); + if (maybeAsyncArrow && !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 (node$1.callee.type === "Import") { + if (node$1.arguments.length !== 1) { + this.raise(node$1.start, "import() requires exactly one argument"); } - var _instr2 = []; - parseInstructionBlock(_instr2); // preserve anonymous - - var _label = t.withRaw(t.identifier(getUniqueName("block")), ""); - - var blockNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.blockInstruction(_label, _instr2, _blocktype2), endLoc, _startLoc9); - }(); + var importArg = node$1.arguments[0]; + if (importArg && importArg.type === "SpreadElement") { + this.raise(importArg.start, "... is not allowed in import()"); + } + } + base = this.finishNode(node$1, "CallExpression"); + } else if (this.type === types.backQuote) { + 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 + }; - code.push(blockNode); - instructionAlreadyCreated = true; - } else if (instruction.name === "call") { - var indexu32 = readU32(); - var index = indexu32.value; - eatBytes(indexu32.nextIndex); - dump([index], "index"); + // 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 `{}`. - var callNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.callInstruction(t.indexLiteral(index)), endLoc, _startLoc6); - }(); + 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(); } - code.push(callNode); - instructionAlreadyCreated = true; - } else if (instruction.name === "call_indirect") { - var _startLoc10 = getPosition(); + 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") - var indexU32 = readU32(); - var typeindex = indexU32.value; - eatBytes(indexU32.nextIndex); - dump([typeindex], "type index"); - var signature = state.typesInModule[typeindex]; + case types._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression") - if (typeof signature === "undefined") { - throw new _helperApiError.CompileError("call_indirect signature not found (".concat(typeindex, ")")); + 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 - var _callNode = t.callIndirectInstruction(t.signature(signature.params, signature.result), []); + case types.regexp: + var value = this.value; + node = this.parseLiteral(value.value); + node.regex = {pattern: value.pattern, flags: value.flags}; + return node - var flagU32 = readU32(); - var flag = flagU32.value; // 0x00 - reserved byte + case types.num: case types.string: + return this.parseLiteral(this.value) - eatBytes(flagU32.nextIndex); + 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") - if (flag !== 0) { - throw new _helperApiError.CompileError("zero flag expected"); - } + 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 - code.push(function () { - var endLoc = getPosition(); - return t.withLoc(_callNode, endLoc, _startLoc10); - }()); - instructionAlreadyCreated = true; - } else if (instruction.name === "br_table") { - var indicesu32 = readU32(); - var indices = indicesu32.value; - eatBytes(indicesu32.nextIndex); - dump([indices], "num indices"); + case types.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); + return this.finishNode(node, "ArrayExpression") - for (var i = 0; i <= indices; i++) { - var _indexu = readU32(); + case types.braceL: + return this.parseObj(false, refDestructuringErrors) - var _index = _indexu.value; - eatBytes(_indexu.nextIndex); - dump([_index], "index"); - args.push(t.numberLiteralFromRaw(_indexu.value.toString(), "u32")); - } - } else if (instructionByte >= 0x28 && instructionByte <= 0x40) { - /** - * Memory instructions - */ - if (instruction.name === "grow_memory" || instruction.name === "current_memory") { - var _indexU = readU32(); + case types._function: + node = this.startNode(); + this.next(); + return this.parseFunction(node, 0) - var _index2 = _indexU.value; - eatBytes(_indexU.nextIndex); + case types._class: + return this.parseClass(this.startNode(), false) - if (_index2 !== 0) { - throw new Error("zero flag expected"); - } + case types._new: + return this.parseNew() - dump([_index2], "index"); - } else { - var aligun32 = readU32(); - var align = aligun32.value; - eatBytes(aligun32.nextIndex); - dump([align], "align"); - var offsetu32 = readU32(); - var _offset2 = offsetu32.value; - eatBytes(offsetu32.nextIndex); - dump([_offset2], "offset"); - } - } else if (instructionByte >= 0x41 && instructionByte <= 0x44) { - /** - * Numeric instructions - */ - if (instruction.object === "i32") { - var value32 = read32(); - var value = value32.value; - eatBytes(value32.nextIndex); - dump([value], "i32 value"); - args.push(t.numberLiteralFromRaw(value)); - } + case types.backQuote: + return this.parseTemplate() - if (instruction.object === "u32") { - var valueu32 = readU32(); - var _value = valueu32.value; - eatBytes(valueu32.nextIndex); - dump([_value], "u32 value"); - args.push(t.numberLiteralFromRaw(_value)); - } + case types._import: + if (this.options.ecmaVersion > 10) { + return this.parseDynamicImport() + } else { + return this.unexpected() + } - if (instruction.object === "i64") { - var value64 = read64(); - var _value2 = value64.value; - eatBytes(value64.nextIndex); - dump([Number(_value2.toString())], "i64 value"); - var high = _value2.high, - low = _value2.low; - var _node = { - type: "LongNumberLiteral", - value: { - high: high, - low: low - } - }; - args.push(_node); - } + default: + this.unexpected(); + } + }; - if (instruction.object === "u64") { - var valueu64 = readU64(); - var _value3 = valueu64.value; - eatBytes(valueu64.nextIndex); - dump([Number(_value3.toString())], "u64 value"); - var _high = _value3.high, - _low = _value3.low; - var _node2 = { - type: "LongNumberLiteral", - value: { - high: _high, - low: _low - } - }; - args.push(_node2); - } + pp$3.parseDynamicImport = function() { + var node = this.startNode(); + this.next(); + if (this.type !== types.parenL) { + this.unexpected(); + } + return this.finishNode(node, "Import") + }; - if (instruction.object === "f32") { - var valuef32 = readF32(); - var _value4 = valuef32.value; - eatBytes(valuef32.nextIndex); - dump([_value4], "f32 value"); - args.push( // $FlowIgnore - t.floatLiteral(_value4, valuef32.nan, valuef32.inf, String(_value4))); - } + 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); } + this.next(); + return this.finishNode(node, "Literal") + }; - if (instruction.object === "f64") { - var valuef64 = readF64(); - var _value5 = valuef64.value; - eatBytes(valuef64.nextIndex); - dump([_value5], "f64 value"); - args.push( // $FlowIgnore - t.floatLiteral(_value5, valuef64.nan, valuef64.inf, String(_value5))); - } - } else { - for (var _i3 = 0; _i3 < instruction.numberOfArgs; _i3++) { - var u32 = readU32(); - eatBytes(u32.nextIndex); - dump([u32.value], "argument " + _i3); - args.push(t.numberLiteralFromRaw(u32.value)); - } - } + pp$3.parseParenExpression = function() { + this.expect(types.parenL); + var val = this.parseExpression(); + this.expect(types.parenR); + return val + }; - if (instructionAlreadyCreated === false) { - if (typeof instruction.object === "string") { - var _node3 = function () { - var endLoc = getPosition(); - return t.withLoc(t.objectInstruction(instruction.name, instruction.object, args), endLoc, _startLoc6); - }(); + 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(); - code.push(_node3); + 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 { - var _node4 = function () { - var endLoc = getPosition(); - return t.withLoc(t.instruction(instruction.name, args), endLoc, _startLoc6); - }(); - - code.push(_node4); + exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); } } - } - } // https://webassembly.github.io/spec/core/binary/types.html#limits + 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) + } - function parseLimits() { - var limitType = readByte(); - eatBytes(1); - dump([limitType], "limit type"); - var min, max; + 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 (limitType === 0x01 || limitType === 0x03 // shared limits - ) { - var u32min = readU32(); - min = parseInt(u32min.value); - eatBytes(u32min.nextIndex); - dump([min], "min"); - var u32max = readU32(); - max = parseInt(u32max.value); - eatBytes(u32max.nextIndex); - dump([max], "max"); + 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 (limitType === 0x00) { - var _u32min = readU32(); - - min = parseInt(_u32min.value); - eatBytes(_u32min.nextIndex); - dump([min], "min"); + 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 + }; - return t.limit(min, max); - } // https://webassembly.github.io/spec/core/binary/types.html#binary-tabletype + 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. - function parseTableType(index) { - var name = t.withRaw(t.identifier(getUniqueName("table")), String(index)); - var elementTypeByte = readByte(); - eatBytes(1); - dump([elementTypeByte], "element type"); - var elementType = _helperWasmBytecode.default.tableTypes[elementTypeByte]; + var empty$1 = []; - if (typeof elementType === "undefined") { - throw new _helperApiError.CompileError("Unknown element type in table: " + toHex(elementType)); + pp$3.parseNew = function() { + 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" || containsEsc) + { this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); } + 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; + node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); + if (this.options.ecmaVersion > 10 && node.callee.type === "Import") { + this.raise(node.callee.start, "Cannot use new with import(...)"); + } + if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8 && node.callee.type !== "Import", false); } + else { node.arguments = empty$1; } + return this.finishNode(node, "NewExpression") + }; - var limits = parseLimits(); - return t.table(elementType, limits, name); - } // https://webassembly.github.io/spec/binary/types.html#global-types - + // Parse template expression. - function parseGlobalType() { - var valtypeByte = readByte(); - eatBytes(1); - var type = _helperWasmBytecode.default.valtypes[valtypeByte]; - dump([valtypeByte], type); + pp$3.parseTemplateElement = function(ref) { + var isTagged = ref.isTagged; - if (typeof type === "undefined") { - throw new _helperApiError.CompileError("Unknown valtype: " + toHex(valtypeByte)); + 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") + }; - var globalTypeByte = readByte(); - eatBytes(1); - var globalType = _helperWasmBytecode.default.globalTypes[globalTypeByte]; - dump([globalTypeByte], "global type (".concat(globalType, ")")); + pp$3.parseTemplate = function(ref) { + if ( ref === void 0 ) ref = {}; + var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; - if (typeof globalType === "undefined") { - throw new _helperApiError.CompileError("Invalid mutability: " + toHex(globalTypeByte)); + 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") + }; - return t.globalType(type, globalType); - } // function parseNameModule() { - // const lenu32 = readVaruint32(); - // eatBytes(lenu32.nextIndex); - // console.log("len", lenu32); - // const strlen = lenu32.value; - // dump([strlen], "string length"); - // const bytes = readBytes(strlen); - // eatBytes(strlen); - // const value = utf8.decode(bytes); - // return [t.moduleNameMetadata(value)]; - // } - // this section contains an array of function names and indices + 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. - function parseNameSectionFunctions() { - var functionNames = []; - var numberOfFunctionsu32 = readU32(); - var numbeOfFunctions = numberOfFunctionsu32.value; - eatBytes(numberOfFunctionsu32.nextIndex); + 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.afterTrailingComma(types.braceR)) { break } + } else { first = false; } - for (var i = 0; i < numbeOfFunctions; i++) { - var indexu32 = readU32(); - var index = indexu32.value; - eatBytes(indexu32.nextIndex); - var name = readUTF8String(); - eatBytes(name.nextIndex); - functionNames.push(t.functionNameMetadata(name.value, index)); + var prop = this.parseProperty(isPattern, refDestructuringErrors); + if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } + node.properties.push(prop); } + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") + }; - return functionNames; - } - - function parseNameSectionLocals() { - var localNames = []; - var numbeOfFunctionsu32 = readU32(); - var numbeOfFunctions = numbeOfFunctionsu32.value; - eatBytes(numbeOfFunctionsu32.nextIndex); - - for (var i = 0; i < numbeOfFunctions; i++) { - var functionIndexu32 = readU32(); - var functionIndex = functionIndexu32.value; - eatBytes(functionIndexu32.nextIndex); - var numLocalsu32 = readU32(); - var numLocals = numLocalsu32.value; - eatBytes(numLocalsu32.nextIndex); - - for (var _i4 = 0; _i4 < numLocals; _i4++) { - var localIndexu32 = readU32(); - var localIndex = localIndexu32.value; - eatBytes(localIndexu32.nextIndex); - var name = readUTF8String(); - eatBytes(name.nextIndex); - localNames.push(t.localNameMetadata(name.value, localIndex, functionIndex)); + 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") + }; - return localNames; - } // this is a custom section used for name resolution - // https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section - - - function parseNameSection(remainingBytes) { - var nameMetadata = []; - var initialOffset = offset; + pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { + if ((isGenerator || isAsync) && this.type === types.colon) + { this.unexpected(); } - while (offset - initialOffset < remainingBytes) { - // name_type - var sectionTypeByte = readVaruint7(); - eatBytes(sectionTypeByte.nextIndex); // name_payload_len + 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)) { + 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, prop.key); + } else if (this.type === types.eq && refDestructuringErrors) { + if (refDestructuringErrors.shorthandAssign < 0) + { refDestructuringErrors.shorthandAssign = this.start; } + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); + } else { + prop.value = prop.key; + } + prop.shorthand = true; + } else { this.unexpected(); } + }; - var subSectionSizeInBytesu32 = readVaruint32(); - eatBytes(subSectionSizeInBytesu32.nextIndex); + 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") + }; - switch (sectionTypeByte.value) { - // case 0: { - // TODO(sven): re-enable that - // Current status: it seems that when we decode the module's name - // no name_payload_len is used. - // - // See https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section - // - // nameMetadata.push(...parseNameModule()); - // break; - // } - case 1: - { - nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionFunctions())); - break; - } + // Initialize empty function node. - case 2: - { - nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionLocals())); - break; - } + 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; } + }; - default: - { - // skip unknown subsection - eatBytes(subSectionSizeInBytesu32.value); - } - } - } + // Parse object or class method. - return nameMetadata; - } // this is a custom section used for information about the producers - // https://github.com/WebAssembly/tool-conventions/blob/master/ProducersSection.md + 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; } - function parseProducersSection() { - var metadata = t.producersSectionMetadata([]); // field_count + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; + this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); - var sectionTypeByte = readVaruint32(); - eatBytes(sectionTypeByte.nextIndex); - dump([sectionTypeByte.value], "num of producers"); - var fields = { - language: [], - "processed-by": [], - sdk: [] - }; // fields + this.expect(types.parenL); + node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); + this.checkYieldAwaitInDefaultParams(); + this.parseFunctionBody(node, false, true); - for (var fieldI = 0; fieldI < sectionTypeByte.value; fieldI++) { - // field_name - var fieldName = readUTF8String(); - eatBytes(fieldName.nextIndex); // field_value_count + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "FunctionExpression") + }; - var valueCount = readVaruint32(); - eatBytes(valueCount.nextIndex); // field_values + // Parse arrow function expression with given parameters. - for (var producerI = 0; producerI < valueCount.value; producerI++) { - var producerName = readUTF8String(); - eatBytes(producerName.nextIndex); - var producerVersion = readUTF8String(); - eatBytes(producerVersion.nextIndex); - fields[fieldName.value].push(t.producerMetadataVersionedName(producerName.value, producerVersion.value)); - } + pp$3.parseArrowExpression = function(node, params, isAsync) { + var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; - metadata.producers.push(fields[fieldName.value]); - } + this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); + this.initFunction(node); + if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } - return metadata; - } + this.yieldPos = 0; + this.awaitPos = 0; + this.awaitIdentPos = 0; - function parseGlobalSection(numberOfGlobals) { - var globals = []; - dump([numberOfGlobals], "num globals"); + node.params = this.toAssignableList(params, true); + this.parseFunctionBody(node, true, false); - for (var i = 0; i < numberOfGlobals; i++) { - var _startLoc11 = getPosition(); + this.yieldPos = oldYieldPos; + this.awaitPos = oldAwaitPos; + this.awaitIdentPos = oldAwaitIdentPos; + return this.finishNode(node, "ArrowFunctionExpression") + }; - var globalType = parseGlobalType(); - /** - * Global expressions - */ + // Parse function body and check parameters. - var init = []; - parseInstructionBlock(init); + pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { + var isExpression = isArrowFunction && this.type !== types.braceL; + var oldStrict = this.strict, useStrict = false; - var node = function () { - var endLoc = getPosition(); - return t.withLoc(t.global(globalType, init), endLoc, _startLoc11); - }(); + 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; } - globals.push(node); - state.globalsInModule.push(node); + // 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)); + node.body = this.parseBlock(false); + node.expression = false; + this.adaptDirectivePrologue(node.body.body); + this.labels = oldLabels; } + this.exitScope(); - return globals; - } + // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' + if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); } + this.strict = oldStrict; + }; - function parseElemSection(numberOfElements) { - var elems = []; - dump([numberOfElements], "num elements"); + pp$3.isSimpleParamList = function(params) { + for (var i = 0, list = params; i < list.length; i += 1) + { + var param = list[i]; - for (var i = 0; i < numberOfElements; i++) { - var _startLoc12 = getPosition(); + if (param.type !== "Identifier") { return false + } } + return true + }; - var tableindexu32 = readU32(); - var tableindex = tableindexu32.value; - eatBytes(tableindexu32.nextIndex); - dump([tableindex], "table index"); - /** - * Parse instructions - */ + // Checks function params for various disallowed patterns such as using "eval" + // or "arguments" and duplicate parameters. - var instr = []; - parseInstructionBlock(instr); - /** - * Parse ( vector function index ) * - */ + pp$3.checkParams = function(node, allowDuplicates) { + var nameHash = {}; + for (var i = 0, list = node.params; i < list.length; i += 1) + { + var param = list[i]; - var indicesu32 = readU32(); - var indices = indicesu32.value; - eatBytes(indicesu32.nextIndex); - dump([indices], "num indices"); - var indexValues = []; + this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash); + } + }; - for (var _i5 = 0; _i5 < indices; _i5++) { - var indexu32 = readU32(); - var index = indexu32.value; - eatBytes(indexu32.nextIndex); - dump([index], "index"); - indexValues.push(t.indexLiteral(index)); - } + // 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). - var elemNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.elem(t.indexLiteral(tableindex), instr, indexValues), endLoc, _startLoc12); - }(); + 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; } - elems.push(elemNode); + 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 + }; - return elems; - } // https://webassembly.github.io/spec/core/binary/types.html#memory-types - + pp$3.checkUnreserved = function(ref) { + var start = ref.start; + var end = ref.end; + var name = ref.name; - function parseMemoryType(i) { - var limits = parseLimits(); - return t.memory(limits, t.indexLiteral(i)); - } // https://webassembly.github.io/spec/binary/modules.html#table-section + 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. - function parseTableSection(numberOfElements) { - var tables = []; - dump([numberOfElements], "num elements"); + 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; - for (var i = 0; i < numberOfElements; i++) { - var tablesNode = parseTableType(i); - state.tablesInModule.push(tablesNode); - tables.push(tablesNode); + // 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(); + this.finishNode(node, "Identifier"); + if (!liberal) { + this.checkUnreserved(node); + if (node.name === "await" && !this.awaitIdentPos) + { this.awaitIdentPos = node.start; } + } + return node + }; - return tables; - } // https://webassembly.github.io/spec/binary/modules.html#memory-section - + // Parses yield expression inside generator. - function parseMemorySection(numberOfElements) { - var memories = []; - dump([numberOfElements], "num elements"); + pp$3.parseYield = function(noIn) { + if (!this.yieldPos) { this.yieldPos = this.start; } - for (var i = 0; i < numberOfElements; i++) { - var memoryNode = parseMemoryType(i); - state.memoriesInModule.push(memoryNode); - memories.push(memoryNode); + 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") + }; - return memories; - } // https://webassembly.github.io/spec/binary/modules.html#binary-startsec - + pp$3.parseAwait = function() { + if (!this.awaitPos) { this.awaitPos = this.start; } - function parseStartSection() { - var startLoc = getPosition(); - var u32 = readU32(); - var startFuncIndex = u32.value; - eatBytes(u32.nextIndex); - dump([startFuncIndex], "index"); - return function () { - var endLoc = getPosition(); - return t.withLoc(t.start(t.indexLiteral(startFuncIndex)), endLoc, startLoc); - }(); - } // https://webassembly.github.io/spec/binary/modules.html#data-section + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeUnary(null, true); + return this.finishNode(node, "AwaitExpression") + }; + var pp$4 = Parser.prototype; - function parseDataSection(numberOfElements) { - var dataEntries = []; - dump([numberOfElements], "num elements"); + // 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. - for (var i = 0; i < numberOfElements; i++) { - var memoryIndexu32 = readU32(); - var memoryIndex = memoryIndexu32.value; - eatBytes(memoryIndexu32.nextIndex); - dump([memoryIndex], "memory index"); - var instrs = []; - parseInstructionBlock(instrs); - var hasExtraInstrs = instrs.filter(function (i) { - return i.id !== "end"; - }).length !== 1; + 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 + }; - if (hasExtraInstrs) { - throw new _helperApiError.CompileError("data section offset must be a single instruction"); - } + pp$4.raiseRecoverable = pp$4.raise; - var bytes = parseVec(function (b) { - return b; - }); - dump([], "init"); - dataEntries.push(t.data(t.memIndexLiteral(memoryIndex), instrs[0], t.byteArray(bytes))); + pp$4.curPosition = function() { + if (this.options.locations) { + return new Position(this.curLine, this.pos - this.lineStart) } + }; - return dataEntries; - } // https://webassembly.github.io/spec/binary/modules.html#binary-section - + var pp$5 = Parser.prototype; - function parseSection(sectionIndex) { - var sectionId = readByte(); - eatBytes(1); + 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 = []; + }; - if (sectionId >= sectionIndex || sectionIndex === _helperWasmBytecode.default.sections.custom) { - sectionIndex = sectionId + 1; - } else { - if (sectionId !== _helperWasmBytecode.default.sections.custom) throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId)); - } + // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. - var nextSectionIndex = sectionIndex; - var startOffset = offset; - var startLoc = getPosition(); - var u32 = readU32(); - var sectionSizeInBytes = u32.value; - eatBytes(u32.nextIndex); + pp$5.enterScope = function(flags) { + this.scopeStack.push(new Scope(flags)); + }; - var sectionSizeInBytesNode = function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(sectionSizeInBytes), endLoc, startLoc); - }(); + pp$5.exitScope = function() { + this.scopeStack.pop(); + }; - switch (sectionId) { - case _helperWasmBytecode.default.sections.type: - { - dumpSep("section Type"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + // 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) + }; - var _startLoc13 = getPosition(); + 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")); } + }; - var _u = readU32(); + 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; + } + }; - var numberOfTypes = _u.value; - eatBytes(_u.nextIndex); + pp$5.currentScope = function() { + return this.scopeStack[this.scopeStack.length - 1] + }; - var _metadata = t.sectionMetadata("type", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfTypes), endLoc, _startLoc13); - }()); + pp$5.currentVarScope = function() { + for (var i = this.scopeStack.length - 1;; i--) { + var scope = this.scopeStack[i]; + if (scope.flags & SCOPE_VAR) { return scope } + } + }; - var _nodes = parseTypeSection(numberOfTypes); + // 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 } + } + }; - return { - nodes: _nodes, - metadata: _metadata, - nextSectionIndex: nextSectionIndex - }; - } + 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]; } + }; - case _helperWasmBytecode.default.sections.table: - { - dumpSep("section Table"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + // Start an AST node, attaching a start offset. - var _startLoc14 = getPosition(); + var pp$6 = Parser.prototype; - var _u2 = readU32(); + pp$6.startNode = function() { + return new Node(this, this.start, this.startLoc) + }; - var numberOfTable = _u2.value; - eatBytes(_u2.nextIndex); - dump([numberOfTable], "num tables"); + pp$6.startNodeAt = function(pos, loc) { + return new Node(this, pos, loc) + }; - var _metadata2 = t.sectionMetadata("table", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfTable), endLoc, _startLoc14); - }()); + // Finish an AST node, adding `type` and `end` properties. - var _nodes2 = parseTableSection(numberOfTable); + 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 + } - return { - nodes: _nodes2, - metadata: _metadata2, - nextSectionIndex: nextSectionIndex - }; - } + pp$6.finishNode = function(node, type) { + return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) + }; - case _helperWasmBytecode.default.sections.import: - { - dumpSep("section Import"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + // Finish node at given position - var _startLoc15 = getPosition(); + pp$6.finishNodeAt = function(node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc) + }; - var numberOfImportsu32 = readU32(); - var numberOfImports = numberOfImportsu32.value; - eatBytes(numberOfImportsu32.nextIndex); - dump([numberOfImports], "number of imports"); + // The algorithm used to determine whether a regexp can appear at a - var _metadata3 = t.sectionMetadata("import", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfImports), endLoc, _startLoc15); - }()); + 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 _nodes3 = parseImportSection(numberOfImports); + 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) + }; - return { - nodes: _nodes3, - metadata: _metadata3, - nextSectionIndex: nextSectionIndex - }; - } + var pp$7 = Parser.prototype; - case _helperWasmBytecode.default.sections.func: - { - dumpSep("section Function"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + pp$7.initialContext = function() { + return [types$1.b_stat] + }; - var _startLoc16 = getPosition(); + 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 } - var numberOfFunctionsu32 = readU32(); - var numberOfFunctions = numberOfFunctionsu32.value; - eatBytes(numberOfFunctionsu32.nextIndex); + // 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 + }; - var _metadata4 = t.sectionMetadata("func", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfFunctions), endLoc, _startLoc16); - }()); + 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 + }; - parseFuncSection(numberOfFunctions); - var _nodes4 = []; - return { - nodes: _nodes4, - metadata: _metadata4, - nextSectionIndex: nextSectionIndex - }; - } + 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; } + }; - case _helperWasmBytecode.default.sections.export: - { - dumpSep("section Export"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + // Token-specific context update code - var _startLoc17 = getPosition(); + 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; + }; - var _u3 = readU32(); + types.braceL.updateContext = function(prevType) { + this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); + this.exprAllowed = true; + }; - var numberOfExport = _u3.value; - eatBytes(_u3.nextIndex); + types.dollarBraceL.updateContext = function() { + this.context.push(types$1.b_tmpl); + this.exprAllowed = true; + }; - var _metadata5 = t.sectionMetadata("export", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfExport), endLoc, _startLoc17); - }()); + 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; + }; - parseExportSection(numberOfExport); - var _nodes5 = []; - return { - nodes: _nodes5, - metadata: _metadata5, - nextSectionIndex: nextSectionIndex - }; - } + types.incDec.updateContext = function() { + // tokExprAllowed stays unchanged + }; - case _helperWasmBytecode.default.sections.code: - { - dumpSep("section Code"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + types._function.updateContext = types._class.updateContext = function(prevType) { + if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && + !(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; + }; - var _startLoc18 = getPosition(); + 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; + }; - var _u4 = readU32(); + 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; + }; - var numberOfFuncs = _u4.value; - eatBytes(_u4.nextIndex); + 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; + }; - var _metadata6 = t.sectionMetadata("code", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfFuncs), endLoc, _startLoc18); - }()); + // 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) - if (opts.ignoreCodeSection === true) { - var remainingBytes = sectionSizeInBytes - _u4.nextIndex; - eatBytes(remainingBytes); // eat the entire section - } else { - parseCodeSection(numberOfFuncs); - } + // #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 unicodeBinaryProperties = { + 9: ecma9BinaryProperties, + 10: ecma10BinaryProperties, + 11: ecma11BinaryProperties + }; - var _nodes6 = []; - return { - nodes: _nodes6, - metadata: _metadata6, - nextSectionIndex: nextSectionIndex - }; - } + // #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"; - case _helperWasmBytecode.default.sections.start: - { - dumpSep("section Start"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + // #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 unicodeScriptValues = { + 9: ecma9ScriptValues, + 10: ecma10ScriptValues, + 11: ecma11ScriptValues + }; - var _metadata7 = t.sectionMetadata("start", startOffset, sectionSizeInBytesNode); + 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; - var _nodes7 = [parseStartSection()]; - return { - nodes: _nodes7, - metadata: _metadata7, - nextSectionIndex: nextSectionIndex - }; - } + 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); - case _helperWasmBytecode.default.sections.element: - { - dumpSep("section Element"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + var pp$8 = Parser.prototype; - var _startLoc19 = getPosition(); + 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 >= 11 ? 11 : 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 = []; + }; - var numberOfElementsu32 = readU32(); - var numberOfElements = numberOfElementsu32.value; - eatBytes(numberOfElementsu32.nextIndex); + 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; + }; - var _metadata8 = t.sectionMetadata("element", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfElements), endLoc, _startLoc19); - }()); + RegExpValidationState.prototype.raise = function raise (message) { + this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); + }; - var _nodes8 = parseElemSection(numberOfElements); + // 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) { + var s = this.source; + var l = s.length; + if (i >= l) { + return -1 + } + var c = s.charCodeAt(i); + if (!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 + }; - return { - nodes: _nodes8, - metadata: _metadata8, - nextSectionIndex: nextSectionIndex - }; - } + RegExpValidationState.prototype.nextIndex = function nextIndex (i) { + var s = this.source; + var l = s.length; + if (i >= l) { + return l + } + var c = s.charCodeAt(i), next; + if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || + (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { + return i + 1 + } + return i + 2 + }; - case _helperWasmBytecode.default.sections.global: - { - dumpSep("section Global"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + RegExpValidationState.prototype.current = function current () { + return this.at(this.pos) + }; - var _startLoc20 = getPosition(); + RegExpValidationState.prototype.lookahead = function lookahead () { + return this.at(this.nextIndex(this.pos)) + }; - var numberOfGlobalsu32 = readU32(); - var numberOfGlobals = numberOfGlobalsu32.value; - eatBytes(numberOfGlobalsu32.nextIndex); + RegExpValidationState.prototype.advance = function advance () { + this.pos = this.nextIndex(this.pos); + }; - var _metadata9 = t.sectionMetadata("global", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(numberOfGlobals), endLoc, _startLoc20); - }()); + RegExpValidationState.prototype.eat = function eat (ch) { + if (this.current() === ch) { + this.advance(); + return true + } + return false + }; - var _nodes9 = parseGlobalSection(numberOfGlobals); + function codePointToString(ch) { + if (ch <= 0xFFFF) { return String.fromCharCode(ch) } + ch -= 0x10000; + return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) + } - return { - nodes: _nodes9, - metadata: _metadata9, - nextSectionIndex: nextSectionIndex - }; - } + /** + * 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; - case _helperWasmBytecode.default.sections.memory: - { - dumpSep("section Memory"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + 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"); + } + } + }; - var _startLoc21 = getPosition(); + /** + * 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); - var _numberOfElementsu = readU32(); + // 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); + } + }; - var _numberOfElements = _numberOfElementsu.value; - eatBytes(_numberOfElementsu.nextIndex); + // 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; - var _metadata10 = t.sectionMetadata("memory", startOffset, sectionSizeInBytesNode, function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(_numberOfElements), endLoc, _startLoc21); - }()); + this.regexp_disjunction(state); - var _nodes10 = parseMemorySection(_numberOfElements); + 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]; - return { - nodes: _nodes10, - metadata: _metadata10, - nextSectionIndex: nextSectionIndex - }; - } + if (state.groupNames.indexOf(name) === -1) { + state.raise("Invalid named capture referenced"); + } + } + }; - case _helperWasmBytecode.default.sections.data: - { - dumpSep("section Data"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); + // 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); + } - var _metadata11 = t.sectionMetadata("data", startOffset, sectionSizeInBytesNode); + // 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"); + } + }; - var _startLoc22 = getPosition(); + // 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)) + { } + }; - var _numberOfElementsu2 = readU32(); + // 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 + } - var _numberOfElements2 = _numberOfElementsu2.value; - eatBytes(_numberOfElementsu2.nextIndex); + if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { + this.regexp_eatQuantifier(state); + return true + } - _metadata11.vectorOfSize = function () { - var endLoc = getPosition(); - return t.withLoc(t.numberLiteralFromRaw(_numberOfElements2), endLoc, _startLoc22); - }(); + return false + }; - if (opts.ignoreDataSection === true) { - var _remainingBytes = sectionSizeInBytes - _numberOfElementsu2.nextIndex; + // 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; - eatBytes(_remainingBytes); // eat the entire section + // ^, $ + if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { + return true + } - dumpSep("ignore data (" + sectionSizeInBytes + " bytes)"); - return { - nodes: [], - metadata: _metadata11, - nextSectionIndex: nextSectionIndex - }; - } else { - var _nodes11 = parseDataSection(_numberOfElements2); + // \b \B + if (state.eat(0x5C /* \ */)) { + if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { + return true + } + state.pos = start; + } - return { - nodes: _nodes11, - metadata: _metadata11, - nextSectionIndex: nextSectionIndex - }; - } + // 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 + } + } - case _helperWasmBytecode.default.sections.custom: - { - dumpSep("section Custom"); - dump([sectionId], "section code"); - dump([sectionSizeInBytes], "section size"); - var _metadata12 = [t.sectionMetadata("custom", startOffset, sectionSizeInBytesNode)]; - var sectionName = readUTF8String(); - eatBytes(sectionName.nextIndex); - dump([], "section name (".concat(sectionName.value, ")")); - - var _remainingBytes2 = sectionSizeInBytes - sectionName.nextIndex; + state.pos = start; + return false + }; - if (sectionName.value === "name") { - var initialOffset = offset; + // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier + pp$8.regexp_eatQuantifier = function(state, noError) { + if ( noError === void 0 ) noError = false; - try { - _metadata12.push.apply(_metadata12, _toConsumableArray(parseNameSection(_remainingBytes2))); - } catch (e) { - console.warn("Failed to decode custom \"name\" section @".concat(offset, "; ignoring (").concat(e.message, ").")); - eatBytes(offset - (initialOffset + _remainingBytes2)); - } - } else if (sectionName.value === "producers") { - var _initialOffset = offset; + if (this.regexp_eatQuantifierPrefix(state, noError)) { + state.eat(0x3F /* ? */); + return true + } + return false + }; - try { - _metadata12.push(parseProducersSection()); - } catch (e) { - console.warn("Failed to decode custom \"producers\" section @".concat(offset, "; ignoring (").concat(e.message, ").")); - eatBytes(offset - (_initialOffset + _remainingBytes2)); - } - } else { - // We don't parse the custom section - eatBytes(_remainingBytes2); - dumpSep("ignore custom " + JSON.stringify(sectionName.value) + " section (" + _remainingBytes2 + " bytes)"); + // 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 + }; - return { - nodes: [], - metadata: _metadata12, - nextSectionIndex: nextSectionIndex - }; + // 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"); } - - throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId)); - } - - parseModuleHeader(); - parseVersion(); - var moduleFields = []; - var sectionIndex = 0; - var moduleMetadata = { - sections: [], - functionNames: [], - localNames: [], - producers: [] + return false }; - /** - * All the generate declaration are going to be stored in our state - */ - while (offset < buf.length) { - var _parseSection = parseSection(sectionIndex), - _nodes12 = _parseSection.nodes, - _metadata13 = _parseSection.metadata, - nextSectionIndex = _parseSection.nextSectionIndex; + // 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) + ) + }; - moduleFields.push.apply(moduleFields, _toConsumableArray(_nodes12)); - var metadataArray = Array.isArray(_metadata13) ? _metadata13 : [_metadata13]; - metadataArray.forEach(function (metadataItem) { - if (metadataItem.type === "FunctionNameMetadata") { - moduleMetadata.functionNames.push(metadataItem); - } else if (metadataItem.type === "LocalNameMetadata") { - moduleMetadata.localNames.push(metadataItem); - } else if (metadataItem.type === "ProducersSectionMetadata") { - moduleMetadata.producers.push(metadataItem); - } else { - moduleMetadata.sections.push(metadataItem); - } - }); // Ignore custom section + // 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 + }; - if (nextSectionIndex) { - sectionIndex = nextSectionIndex; + // 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 /* } */ + ) } - /** - * Transform the state into AST nodes - */ - - var funcIndex = 0; - state.functionsInModule.forEach(function (func) { - var params = func.signature.params; - var result = func.signature.result; - var body = []; // External functions doesn't provide any code, can skip it here - - if (func.isExternal === true) { - return; + // 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 + }; - var decodedElementInCodeSection = state.elementsInCodeSection[funcIndex]; + // 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 + }; - if (opts.ignoreCodeSection === false) { - if (typeof decodedElementInCodeSection === "undefined") { - throw new _helperApiError.CompileError("func " + toHex(funcIndex) + " code not found"); + // GroupSpecifier[U] :: + // [empty] + // `?` GroupName[?U] + 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 } - - body = decodedElementInCodeSection.code; + state.raise("Invalid group"); } + }; - funcIndex++; - var funcNode = t.func(func.id, t.signature(params, result), body); - - if (func.isExternal === true) { - funcNode.isExternal = func.isExternal; - } // Add function position in the binary if possible - - - if (opts.ignoreCodeSection === false) { - var _startLoc23 = decodedElementInCodeSection.startLoc, - endLoc = decodedElementInCodeSection.endLoc, - bodySize = decodedElementInCodeSection.bodySize; - funcNode = t.withLoc(funcNode, endLoc, _startLoc23); - funcNode.metadata = { - bodySize: bodySize - }; + // GroupName[U] :: + // `<` RegExpIdentifierName[?U] `>` + // 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 + }; - moduleFields.push(funcNode); - }); - state.elementsInExportSection.forEach(function (moduleExport) { - /** - * If the export has no id, we won't be able to call it from the outside - * so we can omit it - */ - if (moduleExport.id != null) { - moduleFields.push(t.withLoc(t.moduleExport(moduleExport.name, t.moduleExportDescr(moduleExport.type, moduleExport.id)), moduleExport.endLoc, moduleExport.startLoc)); + // RegExpIdentifierName[U] :: + // RegExpIdentifierStart[?U] + // RegExpIdentifierName[?U] RegExpIdentifierPart[?U] + // 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 } - }); - dumpSep("end of program"); - var module = t.module(null, moduleFields, t.moduleMetadata(moduleMetadata.sections, moduleMetadata.functionNames, moduleMetadata.localNames, moduleMetadata.producers)); - return t.program([module]); -} - -/***/ }), - -/***/ 27352: -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.decode = decode; + return false + }; -var decoder = _interopRequireWildcard(__webpack_require__(28458)); + // RegExpIdentifierStart[U] :: + // UnicodeIDStart + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[?U] + pp$8.regexp_eatRegExpIdentifierStart = function(state) { + var start = state.pos; + var ch = state.current(); + state.advance(); -var t = _interopRequireWildcard(__webpack_require__(81875)); + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierStart(ch)) { + state.lastIntValue = ch; + return true + } -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; } } + state.pos = start; + return false + }; + function isRegExpIdentifierStart(ch) { + return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ + } -/** - * TODO(sven): I added initial props, but we should rather fix - * https://github.com/xtuc/webassemblyjs/issues/405 - */ -var defaultDecoderOpts = { - dump: false, - ignoreCodeSection: false, - ignoreDataSection: false, - ignoreCustomNameSection: false -}; // traverses the AST, locating function name metadata, which is then -// used to update index-based identifiers with function names + // RegExpIdentifierPart[U] :: + // UnicodeIDContinue + // `$` + // `_` + // `\` RegExpUnicodeEscapeSequence[?U] + // + // + pp$8.regexp_eatRegExpIdentifierPart = function(state) { + var start = state.pos; + var ch = state.current(); + state.advance(); -function restoreFunctionNames(ast) { - var functionNames = []; - t.traverse(ast, { - FunctionNameMetadata: function FunctionNameMetadata(_ref) { - var node = _ref.node; - functionNames.push({ - name: node.value, - index: node.index - }); + if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { + ch = state.lastIntValue; + } + if (isRegExpIdentifierPart(ch)) { + state.lastIntValue = ch; + return true } - }); - if (functionNames.length === 0) { - return; + state.pos = start; + return false + }; + function isRegExpIdentifierPart(ch) { + return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ } - t.traverse(ast, { - Func: function (_Func) { - function Func(_x) { - return _Func.apply(this, arguments); + // 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"); } - - Func.toString = function () { - return _Func.toString(); - }; - - return Func; - }(function (_ref2) { - var node = _ref2.node; - // $FlowIgnore - var nodeName = node.name; - var indexBasedFunctionName = nodeName.value; - var index = Number(indexBasedFunctionName.replace("func_", "")); - var functionName = functionNames.find(function (f) { - return f.index === index; - }); - - if (functionName) { - var oldValue = nodeName.value; - nodeName.value = functionName.name; - nodeName.numeric = oldValue; // $FlowIgnore - - delete nodeName.raw; + 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 } - }), - // Also update the reference in the export - ModuleExport: function (_ModuleExport) { - function ModuleExport(_x2) { - return _ModuleExport.apply(this, arguments); + if (n <= state.numCapturingParens) { + return true } - - ModuleExport.toString = function () { - return _ModuleExport.toString(); - }; - - return ModuleExport; - }(function (_ref3) { - var node = _ref3.node; - - if (node.descr.exportType === "Func") { - // $FlowIgnore - var nodeName = node.descr.id; - var index = nodeName.value; - var functionName = functionNames.find(function (f) { - return f.index === index; - }); - - if (functionName) { - node.descr.id = t.identifier(functionName.name); - } + 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 } - }), - ModuleImport: function (_ModuleImport) { - function ModuleImport(_x3) { - return _ModuleImport.apply(this, arguments); + 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) || + (!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 + }; - ModuleImport.toString = function () { - return _ModuleImport.toString(); - }; + // 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 + }; - return ModuleImport; - }(function (_ref4) { - var node = _ref4.node; + // 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 */) + ) + } - if (node.descr.type === "FuncImportDescr") { - // $FlowIgnore - var indexBasedFunctionName = node.descr.id; - var index = Number(indexBasedFunctionName.replace("func_", "")); - var functionName = functionNames.find(function (f) { - return f.index === index; - }); + // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence + pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state) { + var start = state.pos; - if (functionName) { - // $FlowIgnore - node.descr.id = t.identifier(functionName.name); + if (state.eat(0x75 /* u */)) { + if (this.regexp_eatFixedHexDigits(state, 4)) { + var lead = state.lastIntValue; + if (state.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 } - }), - CallInstruction: function (_CallInstruction) { - function CallInstruction(_x4) { - return _CallInstruction.apply(this, arguments); - } - - CallInstruction.toString = function () { - return _CallInstruction.toString(); - }; - - return CallInstruction; - }(function (nodePath) { - var node = nodePath.node; - var index = node.index.value; - var functionName = functionNames.find(function (f) { - return f.index === index; - }); - - if (functionName) { - var oldValue = node.index; - node.index = t.identifier(functionName.name); - node.numeric = oldValue; // $FlowIgnore - - delete node.raw; + if ( + state.switchU && + state.eat(0x7B /* { */) && + this.regexp_eatHexDigits(state) && + state.eat(0x7D /* } */) && + isValidUnicode(state.lastIntValue) + ) { + return true } - }) - }); -} - -function restoreLocalNames(ast) { - var localNames = []; - t.traverse(ast, { - LocalNameMetadata: function LocalNameMetadata(_ref5) { - var node = _ref5.node; - localNames.push({ - name: node.value, - localIndex: node.localIndex, - functionIndex: node.functionIndex - }); + if (state.switchU) { + state.raise("Invalid unicode escape"); + } + state.pos = start; } - }); - if (localNames.length === 0) { - return; + return false + }; + function isValidUnicode(ch) { + return ch >= 0 && ch <= 0x10FFFF } - t.traverse(ast, { - Func: function (_Func2) { - function Func(_x5) { - return _Func2.apply(this, arguments); + // 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 + } - Func.toString = function () { - return _Func2.toString(); - }; - - return Func; - }(function (_ref6) { - var node = _ref6.node; - var signature = node.signature; + var ch = state.current(); + if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { + state.lastIntValue = ch; + state.advance(); + return true + } - if (signature.type !== "Signature") { - return; - } // $FlowIgnore + 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 + }; - var nodeName = node.name; - var indexBasedFunctionName = nodeName.value; - var functionIndex = Number(indexBasedFunctionName.replace("func_", "")); - signature.params.forEach(function (param, paramIndex) { - var paramName = localNames.find(function (f) { - return f.localIndex === paramIndex && f.functionIndex === functionIndex; - }); + // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape + pp$8.regexp_eatCharacterClassEscape = function(state) { + var ch = state.current(); - if (paramName && paramName.name !== "") { - param.id = paramName.name; - } - }); - }) - }); -} + if (isCharacterClassEscape(ch)) { + state.lastIntValue = -1; + state.advance(); + return true + } -function restoreModuleName(ast) { - t.traverse(ast, { - ModuleNameMetadata: function (_ModuleNameMetadata) { - function ModuleNameMetadata(_x6) { - return _ModuleNameMetadata.apply(this, arguments); + 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"); + } - ModuleNameMetadata.toString = function () { - return _ModuleNameMetadata.toString(); - }; - - return ModuleNameMetadata; - }(function (moduleNameMetadataPath) { - // update module - t.traverse(ast, { - Module: function (_Module) { - function Module(_x7) { - return _Module.apply(this, arguments); - } - - Module.toString = function () { - return _Module.toString(); - }; - - return Module; - }(function (_ref7) { - var node = _ref7.node; - var name = moduleNameMetadataPath.node.value; // compatiblity with wast-parser + return false + }; + function isCharacterClassEscape(ch) { + return ( + ch === 0x64 /* d */ || + ch === 0x44 /* D */ || + ch === 0x73 /* s */ || + ch === 0x53 /* S */ || + ch === 0x77 /* w */ || + ch === 0x57 /* W */ + ) + } - if (name === "") { - name = null; - } + // UnicodePropertyValueExpression :: + // UnicodePropertyName `=` UnicodePropertyValue + // LoneUnicodePropertyNameOrValue + pp$8.regexp_eatUnicodePropertyValueExpression = function(state) { + var start = state.pos; - node.id = name; - }) - }); - }) - }); -} + // 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; -function decode(buf, customOpts) { - var opts = Object.assign({}, defaultDecoderOpts, customOpts); - var ast = decoder.decode(buf, opts); + // 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"); } + }; - if (opts.ignoreCustomNameSection === false) { - restoreFunctionNames(ast); - restoreLocalNames(ast); - restoreModuleName(ast); + // 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 /* _ */ } - return ast; -} - -/***/ }), - -/***/ 77087: -/***/ (function(__unused_webpack_module, exports) { + // 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) + } -(function (global, factory) { - true ? factory(exports) : - 0; -}(this, function (exports) { 'use strict'; + // LoneUnicodePropertyNameOrValue :: + // UnicodePropertyValueCharacters + pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { + return this.regexp_eatUnicodePropertyValue(state) + }; - // Reserved word lists for various dialects of the language + // 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 + }; - 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" + // 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"); + } + } + } }; - // And the keywords + // 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; - 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"; + 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 keywords = { - 5: ecma5AndLessKeywords, - "5module": ecma5AndLessKeywords + " export import", - 6: ecma5AndLessKeywords + " const class extends export import super" + var ch = state.current(); + if (ch !== 0x5D /* [ */) { + state.lastIntValue = ch; + state.advance(); + return true + } + + return false }; - var keywordRelationalOperator = /^in(stanceof)?$/; + // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape + pp$8.regexp_eatClassEscape = function(state) { + var start = state.pos; - // ## Character categories + if (state.eat(0x62 /* b */)) { + state.lastIntValue = 0x08; /* */ + return true + } - // 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-\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\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\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\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-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7c6\ua7f7-\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-\uab67\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\u0b56\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\u0d82\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\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\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"; + if (state.switchU && state.eat(0x2D /* - */)) { + state.lastIntValue = 0x2D; /* - */ + return true + } - var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); - var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + if (!state.switchU && state.eat(0x63 /* c */)) { + if (this.regexp_eatClassControlLetter(state)) { + return true + } + state.pos = start; + } - nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + return ( + this.regexp_eatCharacterClassEscape(state) || + this.regexp_eatCharacterEscape(state) + ) + }; - // 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 + // 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 + }; - // 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,477,28,11,0,9,21,155,22,13,52,76,44,33,24,27,35,30,0,12,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,0,33,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,0,161,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,270,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,754,9486,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,42710,42,4148,12,221,3,5761,15,7472,3104,541]; + // 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 + }; - // 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,525,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,4,9,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,232,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,19723,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,792487,239]; + // 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 */ + } - // 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 } + // 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 */ } - // Test whether a given character code starts an identifier. + // 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 + }; - 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) + // 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 */ } - // Test whether a given character is part of an identifier. + // 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 + }; - 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) - } + // 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. - // ## Token types + 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]; } + }; - // 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. + // ## Tokenizer - // All token type variables start with an underscore, to make them - // easy to recognize. + var pp$9 = Parser.prototype; - // 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. + // Move to the next token - var TokenType = function TokenType(label, conf) { - if ( conf === void 0 ) conf = {}; + pp$9.next = function() { + if (this.options.onToken) + { this.options.onToken(new Token(this)); } - 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; + this.lastTokEnd = this.end; + this.lastTokStart = this.start; + this.lastTokEndLoc = this.endLoc; + this.lastTokStartLoc = this.startLoc; + this.nextToken(); }; - 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. + pp$9.getToken = function() { + this.next(); + return new Token(this) + }; - var keywords$1 = {}; + // If we're in an ES6 environment, make parsers iterable + if (typeof Symbol !== "undefined") + { pp$9[Symbol.iterator] = function() { + var this$1 = this; - // Succinct definitions of keyword token types - function kw(name, options) { - if ( options === void 0 ) options = {}; + return { + next: function () { + var token = this$1.getToken(); + return { + done: token.type === types.eof, + value: token + } + } + } + }; } - options.keyword = name; - return keywords$1[name] = new TokenType(name, options) - } + // Toggle strict mode. Re-reads the next number or string to please + // pedantic tests (`"use strict"; 010;` should fail). - 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"), + pp$9.curContext = function() { + return this.context[this.context.length - 1] + }; - // 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), - 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}), + // Read a single token, updating the parser object's token-related + // properties. - // 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. + pp$9.nextToken = function() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } - 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}), + this.start = this.pos; + if (this.options.locations) { this.startLoc = this.curPosition(); } + if (this.pos >= this.input.length) { return this.finishToken(types.eof) } - // 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}) + if (curContext.override) { return curContext.override(this) } + else { this.readToken(this.fullCharCodeAtPos()); } }; - // Matches a whole line break (where CRLF is considered a single - // line break). Used to count lines. + 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() } - var lineBreak = /\r\n?|\n|\u2028|\u2029/; - var lineBreakG = new RegExp(lineBreak.source, "g"); + return this.getTokenFromCode(code) + }; - function isNewLine(code, ecma2019String) { - return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) - } + 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 + }; - var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; + 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()); } + }; - var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; + 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()); } + }; - var ref = Object.prototype; - var hasOwnProperty = ref.hasOwnProperty; - var toString = ref.toString; + // Called at the start of the parse and after every token. Skips + // whitespace and comments, and. - // Checks if an object has a property. + 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 + } + } + } + }; - function has(obj, propName) { - return hasOwnProperty.call(obj, propName) - } + // 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. - var isArray = Array.isArray || (function (obj) { return ( - toString.call(obj) === "[object Array]" - ); }); + 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; - function wordsRegexp(words) { - return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") - } + this.updateContext(prevType); + }; - // These are used when `options.locations` is on, for the - // `startLoc` and `endLoc` properties. + // ### Token reading - var Position = function Position(line, col) { - this.line = line; - this.column = col; + // 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) + } }; - Position.prototype.offset = function offset (n) { - return new Position(this.line, this.column + n) + 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) }; - var SourceLocation = function SourceLocation(p, start, end) { - this.start = start; - this.end = end; - if (p.sourceFile !== null) { this.source = p.sourceFile; } + 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) }; - // 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. + pp$9.readToken_pipe_amp = function(code) { // '|&' + var next = this.input.charCodeAt(this.pos + 1); + if (next === code) { 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) + }; - 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) + 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) + }; - // A second optional argument can be given to further configure - // the parser process. These options are recognized: + 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) + // Check this is direct call to eval + if (!this.scopeManager.__ignoreEval() && node.callee.type === Syntax.Identifier && node.callee.name === "eval") { + + // NOTE: This should be `variableScope`. Since direct eval call always creates Lexical environment and + // let / const should be enclosed into it. Only VariableDeclaration affects on the caller's environment. + this.currentScope().variableScope.__detectEval(); + } + this.visitChildren(node); } - 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) + BlockStatement(node) { + if (this.scopeManager.__isES6()) { + this.scopeManager.__nestBlockScope(node); + } + + this.visitChildren(node); + + this.close(node); } - if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && - this.input.charCodeAt(this.pos + 3) === 45) { - // `